render

package module
v0.0.0-...-a8da853 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 12, 2024 License: MIT Imports: 16 Imported by: 42

README

Render: Go Graphics Library

GoDoc

Render is a graphics rendering library for Go.

It supports SDL2 and HTML Canvas back-ends enabling its use for both desktop applications (Linux, Mac and Windows) and WebAssembly modules for running in the web browser.

Screenshot

Notice: github.com/SketchyMaze/render is a mirror to the upstream repository at git.kirsle.net/go/render. Issues and pull requests will be accepted at GitHub.

Example

package main

import (
    "git.kirsle.net/go/render"
    "git.kirsle.net/go/render/sdl"
)

func main() {
    mw := sdl.New("Hello World", 320, 240)

    if err := mw.Setup(); err != nil {
        panic(err)
    }

    // Text that we're gonna draw in the window.
    text := render.Text{
        Text:         "Hello, world!",
        Size:         24,
        Color:        render.SkyBlue,
        Shadow:       render.Blue,
        FontFilename: "DejaVuSans.ttf",
    }

    // Compute the rendered size of the text.
    rect, _ := mw.ComputeTextRect(text)

    for {
        // Blank the window.
        mw.Clear(render.White)

        // Poll for events (mouse clicks, keyboard keys, etc.)
        ev, err := mw.Poll()
        if err != nil {
            panic(err)
        }

        // Escape key closes the window.
        if ev.Escape {
            mw.Teardown()
            break
        }

        // Get the window size.
        w, h := mw.WindowSize()

        // Draw the text centered in the window.
        mw.DrawText(text, render.NewPoint(
            (w/2) - (rect.W/2),
            (h/2) - (rect.H/2),
        ))

        mw.Present()
    }
}

See the examples/ directory for examples. More will come eventually, including some WebAssembly examples.

Project Status: Alpha

This module was written as part of my drawing-based maze game, code named Project: Doodle. It is currently in alpha status and its API may change and be cleaned up in the future.

Drawing Methods (Engine)

This package provides some basic primitive drawing methods which are implemented for SDL2 (desktops) and HTML Canvas (WebAssembly). See the render.Engine interface. The drawing methods supported are:

  • Clear(Color): blank the window and fill it with this color.
  • DrawPoint(Color, Point): draw a single pixel at a coordinate.
  • DrawLine(Color, A Point, B Point): draw a line between two points.
  • DrawRect(Color, Rect): draw a rectangle outline between two points.
  • DrawBox(Color, Rect): draw a filled rectangle between two points.
  • DrawText(Text, Point): draw text at a location.
  • StoreTexture(name string, image.Image): load a Go image.Image object into the engine as a "texture" that can be re-used and pasted on the canvas.
  • LoadTexture(filename string): load an image from disk into a texture.
  • Copy(Texturer, src Rect, dst Rect): copy a texture onto the canvas.

Drawing Types

This package defines a handful of types useful for drawing operations. See the godoc for full details.

  • Color: an RGBA color holding uint8 values for each channel.
    • NewRGBA(red, green, blue, alpha uint8) to construct a new color.
  • Point: holds an X,Y pair of coordinates.
  • Rect: holds an X,Y and a W,H value.
  • Text: holds text and configuration for rendering (color, stroke, shadow, size, etc.)

Shape Generator Functions

The render package includes a few convenience functions for drawing complex shapes.

The generator functions return a channel that yields all of the Points that should be drawn to complete the shape. Example:

var (
    A Point = render.NewPoint(10, 10)
    B Point = render.NewPoint(15, 20)
)

for pt := range render.IterLine(A, B) {
    engine.DrawPoint(render.Red, pt)
}
  • IterLine(A Point, B Point): draw a line from A to B.
  • IterRect(A Point, B Point): iterate all the points to draw a rectangle.
  • IterEllipse(A Point, B Point): draw an elipse fitting inside the rectangle bounded by points A and B.

Multitouch Gesture Notes

Support for SDL2's MultiGestureEvent is added on October 6 2021. The event.State will have the property Touching=true while the engine believes multitouch gestures are afoot. This begins when the user touches the screen with two fingers, and then motion is detected.

SDL2 spams us with gesture events for each tiny change detected, and then just stops. The SDL driver in this repo doesn't set ev.State.Touching=false. One heuristic you may use in your program to detect when multitouch has ended is this:

SDL2 always emulates the mouse Button1 click for one of the fingers. Record the position at the first Touching=true event, and monitor for delta changes in position as the "mouse cursor" moves. When delta movements become stale and don't update, you can set State.Touching=false in your program.

License

MIT.

Documentation

Index

Constants

View Source
const Version = "0.1.0"

Version number of the render library.

Variables

View Source
var (
	Invisible  = Color{}
	White      = RGBA(255, 255, 255, 255)
	Grey       = RGBA(153, 153, 153, 255)
	DarkGrey   = RGBA(64, 64, 64, 255)
	Black      = RGBA(0, 0, 0, 255)
	SkyBlue    = RGBA(0, 153, 255, 255)
	Blue       = RGBA(0, 0, 255, 255)
	DarkBlue   = RGBA(0, 0, 153, 255)
	Red        = RGBA(255, 0, 0, 255)
	DarkRed    = RGBA(153, 0, 0, 255)
	Green      = RGBA(0, 255, 0, 255)
	DarkGreen  = RGBA(0, 153, 0, 255)
	Cyan       = RGBA(0, 255, 255, 255)
	DarkCyan   = RGBA(0, 153, 153, 255)
	Yellow     = RGBA(255, 255, 0, 255)
	Orange     = RGBA(255, 153, 0, 255)
	DarkYellow = RGBA(153, 153, 0, 255)
	Magenta    = RGBA(255, 0, 255, 255)
	Purple     = RGBA(153, 0, 153, 255)
	Pink       = RGBA(255, 153, 255, 255)
)

Common color names.

Functions

func AbsInt

func AbsInt(v int) int

AbsInt returns the absolute value of an integer.

func AbsInt32

func AbsInt32(v int32) int32

AbsInt32 returns the absolute value of an int32.

func ImageToRGBA

func ImageToRGBA(input image.Image) *image.RGBA

ImageToRGBA converts a Go image.Image into an image.RGBA.

func IterEllipse

func IterEllipse(A, B Point) chan Point

IterEllipse iterates an Ellipse using two Points as the top-left and bottom-right corners of a rectangle that encompasses the ellipse.

func IterLine

func IterLine(p1 Point, p2 Point) chan Point

IterLine is a generator that returns the X,Y coordinates to draw a line. https://en.wikipedia.org/wiki/Digital_differential_analyzer_(graphics_algorithm)

func IterRect

func IterRect(p1, p2 Point) chan Point

IterRect loops through all the points forming a rectangle between the top-left point and the bottom-right point.

func MidpointEllipse

func MidpointEllipse(center, radius Point) chan Point

MidpointEllipse implements an ellipse plotting algorithm.

func OpenImage

func OpenImage(filename string) (image.Image, error)

OpenImage opens an image file from disk.

Supported file types are: jpeg, gif, png, bmp.

func ParseResolution

func ParseResolution(resi string) (int, int, error)

ParseResolution turns a resolution string like "1024x768" and returns the width and height values.

func TrimBox

func TrimBox(src, dst *Rect, p Point, S Rect, thickness int)

TrimBox helps with Engine.Copy() to trim a destination box so that it won't overflow with the parent container.

Types

type Color

type Color struct {
	Red   uint8
	Green uint8
	Blue  uint8
	Alpha uint8
}

Color holds an RGBA color value.

func FromColor

func FromColor(from color.Color) Color

FromColor creates a render.Color from a Go color.Color

func HexColor

func HexColor(hex string) (Color, error)

HexColor parses a color from hexadecimal code.

func MustHexColor

func MustHexColor(hex string) Color

MustHexColor parses a color from hex code or panics.

func RGBA

func RGBA(r, g, b, a uint8) Color

RGBA creates a new Color.

func (Color) Add

func (c Color) Add(r, g, b, a int) Color

Add a relative color value to the color.

func (Color) AddColor

func (c Color) AddColor(other Color) Color

AddColor adds another Color to your Color.

func (Color) Darken

func (c Color) Darken(v int) Color

Darken a color value.

func (Color) IsZero

func (c Color) IsZero() bool

IsZero returns if the color is all zeroes (invisible).

func (Color) Lighten

func (c Color) Lighten(v int) Color

Lighten a color value.

func (Color) MarshalJSON

func (c Color) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Color for JSON.

func (Color) SetAlpha

func (c Color) SetAlpha(v uint8) Color

SetAlpha sets the alpha value to a specific setting.

func (Color) String

func (c Color) String() string

func (Color) ToColor

func (c Color) ToColor() color.RGBA

ToColor converts a render.Color into a Go standard color.Color

func (Color) ToHex

func (c Color) ToHex() string

ToHex converts a render.Color to standard #RRGGBB hexadecimal format.

func (Color) ToRGBA

func (c Color) ToRGBA() color.RGBA

ToRGBA converts to a standard Go color.Color

func (Color) Transparent

func (c Color) Transparent() bool

Transparent returns whether the alpha channel is zeroed out and the pixel won't appear as anything when rendered.

func (Color) Transparentize

func (c Color) Transparentize(v int) Color

Transparentize adjusts the alpha value.

func (*Color) UnmarshalJSON

func (c *Color) UnmarshalJSON(b []byte) error

UnmarshalJSON reloads the Color from JSON.

type Engine

type Engine interface {
	Setup() error

	// Poll for events like keypresses and mouse clicks.
	Poll() (*event.State, error)
	GetTicks() uint32
	WindowSize() (w, h int)

	// Present presents the current state to the screen.
	Present() error

	// Clear the full canvas and set this color.
	Clear(Color)
	SetTitle(string)
	DrawPoint(Color, Point)
	DrawLine(Color, Point, Point)
	DrawRect(Color, Rect)
	DrawBox(Color, Rect)
	DrawText(Text, Point) error
	ComputeTextRect(Text) (Rect, error)

	// Texture caching.
	StoreTexture(name string, img image.Image) (Texturer, error)
	LoadTexture(name string) (Texturer, error)
	Copy(t Texturer, src, dst Rect)

	// Teardown and free memory for all textures, returning the number
	// of textures that were freed.
	FreeTextures() int

	// Delay for a moment using the render engine's delay method,
	// implemented by sdl.Delay(uint32)
	Delay(uint32)

	// Tasks that the Setup function should defer until tear-down.
	Teardown()

	Loop() error // maybe?
}

Engine is the interface for the rendering engine, keeping SDL-specific stuff far away from the core of Doodle.

type Point

type Point struct {
	X int
	Y int
}

Point holds an X,Y coordinate value.

var (
	Origin Point
)

Common points.

func NewPoint

func NewPoint(x, y int) Point

NewPoint makes a new Point at an X,Y coordinate.

func ParsePoint

func ParsePoint(v string) (Point, error)

ParsePoint to parse a point from its string representation.

func (*Point) Add

func (p *Point) Add(other Point)

Add (or subtract) the other point to your current point.

func (*Point) Compare

func (p *Point) Compare(other Point) Point

Compare the point to another, returning a delta coordinate.

If the two points are equal the result has X=0 Y=0. Otherwise the X and Y return values will be positive or negative numbers of how you could modify the current Point to be equal to the other.

func (Point) Inside

func (p Point) Inside(r Rect) bool

Inside returns whether the Point falls inside the rect.

NOTICE: the W and H are zero-relative, so a 100x100 box at coordinate X,Y would still have W,H of 100.

func (Point) IsZero

func (p Point) IsZero() bool

IsZero returns if the point is the zero value.

func (*Point) MarshalText

func (p *Point) MarshalText() ([]byte, error)

MarshalText to convert the point into text so that a render.Point may be used as a map key and serialized to JSON.

func (Point) String

func (p Point) String() string

func (*Point) Subtract

func (p *Point) Subtract(other Point)

Subtract the other point from your current point.

func (*Point) UnmarshalText

func (p *Point) UnmarshalText(b []byte) error

UnmarshalText to restore it from text.

type Rect

type Rect struct {
	X int
	Y int
	W int
	H int
}

Rect has a coordinate and a width and height.

func NewRect

func NewRect(width, height int) Rect

NewRect creates a rectangle of size `width` and `height`. The X,Y values are initialized to zero.

func (Rect) Add

func (r Rect) Add(other Rect) Rect

Add another rect.

func (Rect) AddPoint

func (r Rect) AddPoint(other Point) Rect

Add a point to move the rect.

func (Rect) Bigger

func (r Rect) Bigger(other Rect) bool

Bigger returns if the given rect is larger than the current one.

func (Rect) Intersects

func (r Rect) Intersects(other Rect) bool

Intersects with the other rectangle in any way.

func (Rect) IsZero

func (r Rect) IsZero() bool

IsZero returns if the Rect is uninitialized.

func (Rect) Point

func (r Rect) Point() Point

Point returns the rectangle's X,Y values as a Point.

func (Rect) String

func (r Rect) String() string

func (Rect) SubtractPoint

func (r Rect) SubtractPoint(other Point) Rect

SubtractPoint is the inverse of AddPoint. Use this only if you need to invert the Point being added.

This does r.X - other.X, r.Y - other.Y and keeps the width/height the same.

type Text

type Text struct {
	Text         string
	Size         int
	Color        Color
	Padding      int
	PadX         int
	PadY         int
	Stroke       Color  // Stroke color (if not zero)
	Shadow       Color  // Drop shadow color (if not zero)
	FontFilename string // Path to *.ttf file on disk
}

Text holds information for drawing text.

func (Text) IsZero

func (t Text) IsZero() bool

IsZero returns if the Text is the zero value.

func (Text) String

func (t Text) String() string

func (Text) Update

func (t Text) Update(other Text) Text

Update properties on Text and return the updated copy. Only non-zerovalues will cause an update.

type Texturer

type Texturer interface {
	Size() Rect
	Image() image.Image
	Free() error // teardown and free memory
}

Texturer is a stored image texture used by the rendering engine while abstracting away its inner workings.

Directories

Path Synopsis
examples
Package sdl provides an SDL2 renderer for Doodle.
Package sdl provides an SDL2 renderer for Doodle.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL