sprite

package
v0.0.0-...-e938fac Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2024 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

A library for drawing sprites using OpenGL.

Index

Constants

View Source
const (
	MAX_DEPTH int = 1000
)
View Source
const NoopSprite = -1 //sprites with this Id dont get drawn

Variables

View Source
var DefaultBufferSize = 1024 // automatically allocated buffers can hold this number of sprites
View Source
var OpenGLInitialized bool

Functions

func GetGLError

func GetGLError() error

func Ortho

func Ortho(left, right, bottom, top, zNear, zFar float32) [16]float32

Ortho creates an orthographic projection matrix

Types

type Atlas

type Atlas struct {
	// contains filtered or unexported fields
}

Atlas stores a sprite atlas image and the corresponding gpu texture. It contains uv coordinates for the sprites it contains and operations to add sprites from images.

func NewAtlas

func NewAtlas(atlasImage *image.RGBA, spriteBoundingBoxes []math.Box2D[int]) (*Atlas, error)

NewSpriteAtlas initialises a sprite atlas given an atlas image. It also allocates the GPU texture for the altas (it depends on OpenGl being initialized). Param spriteBoundingBoxes is a list of bounding boxes in the atlas. Bounding boxes are defined as point pairs that specify the lower left and upper right corners of each sprite. Bounding boxes are given in pixels.

func NewAtlasFromFiles

func NewAtlasFromFiles(atlasImage, spriteBoundingBoxes string) (*Atlas, error)

Initialize from an image file and a JSON encoded list of bounding boxes.

func NewEmptyAtlas

func NewEmptyAtlas(width, height int) (*Atlas, error)

Initialize an empty atlas of given size

func (*Atlas) AddAtlasImage

func (s *Atlas) AddAtlasImage(img *image.RGBA, spriteBBoxes []math.Box2D[int]) (int, []int, error)

Add an image which is segmented into sprites. The existing sprite bounding boxes will be translated to the position where the image is placed. Returns the bounding box of the whole atlas and the individual bboxes for each sprite.

func (*Atlas) AddAtlasImageFromFiles

func (s *Atlas) AddAtlasImageFromFiles(img, spriteBBoxes string) (int, []int, error)

Same as AddAtlasImage but data is loaded from files.

func (*Atlas) AddBoundingBox

func (s *Atlas) AddBoundingBox(parentAtlas int, bbox math.Box2D[int]) int

Add a bounding box for an atlas. Because Atlas can contain multiple atlases, the id of the bounding box of the atlas must be given. The passed bounding box will be translated to the correct position. If the SpriteAtlas contains only one atlas, parentAtlas can be set to -1 and in which case translation occurs. Returns the index of the created bounding box.

func (*Atlas) AddBoundingBoxesFromFile

func (s *Atlas) AddBoundingBoxesFromFile(parentAtlas int, bbox string) []int

Loads a list of bounding boxes from a JSON file and adds them to the sprite store using AddBoundingBox.

func (*Atlas) AddFixedColorImage

func (s *Atlas) AddFixedColorImage(color color.RGBA, size math.Vector2[int]) (int, error)

Add a fixed color image. Useful for debugging.

func (*Atlas) AddImage

func (a *Atlas) AddImage(img *image.RGBA) (int, error)

Add an image to the atlas, if there is space. Returns the index for the sprite created out of img.

func (*Atlas) AddImageFromFile

func (a *Atlas) AddImageFromFile(filename string) (int, error)

Load a png image from disk and add it to the atlas.

func (*Atlas) AddImages

func (a *Atlas) AddImages(imgs []*image.RGBA) ([]int, error)

Add a list of images to the atlas. Returns a list of indices for the sprites added. AddImages is faster than calling AddImage repeatedly because it only triggers the GPU texture update when all sprites have been added.

func (*Atlas) AddImagesFromFiles

func (a *Atlas) AddImagesFromFiles(filenames []string) ([]int, error)

Load pngs from disk and add them to the atlas.

func (*Atlas) DumpAtlas

func (s *Atlas) DumpAtlas()

func (*Atlas) GenerateSpriteUVs

func (s *Atlas) GenerateSpriteUVs(index int) (uvs []float32)

Create and uv buffers for a sprite

func (*Atlas) GetBoundingBox

func (s *Atlas) GetBoundingBox(spriteId int) math.Box2D[int]

Get the bounding box of a sprite

func (*Atlas) GetSpriteUVs

func (s *Atlas) GetSpriteUVs(index int) [4]float32

Get UVs for a sprite. Normalizes and returns the bounding box coordinates in a single 4-vector.

func (*Atlas) UpdateGPUAtlas

func (s *Atlas) UpdateGPUAtlas() error

Update atlas image on gpu

type BufferList

type BufferList struct {
	RenderOrder int
	Shader      shaders.Shader
	CpuBuffers  [][]float32
	GpuBuffers  []uint32
	TypeSize    []int32 // fast access to Shader.Attributes[...].Type.Size
	NumSprites  int
	MaxSprites  int
	Texture     uint32
	VAO         uint32
}

BufferList is the cpu and gpu buffers needed to render with a shader. Cpu code updates the cpu buffers as many times as needed typically to add sprites for render. Cpu buffers are copied to the gpu in one go (typically once per frame). The buffers are preallocated to support a fixed amount of sprites (MaxSprites).

RenderOrder controls the order in which this buffer will be rendered. Although a Sprite's depth value controls its back-to-front order, renderOrder is important for transparent sprites. For transparency to work, opaque sprites need to be drawn before transparent ones and its up to the user to enforce this by drawing separating opaque and tranparent sprites into different buffers and setting renderOrder so that opaque sprites are drawn first. For cutout sprites (that only have 255 and 0 alpha values) the renderOrder can be ignored using this method https://www.khronos.org/opengl/wiki/Transparency_Sorting (up to the shader to implement this).

If the render order is rigid and known beforehand, you can disable depth testing in Renderer and rely on render order. This could result in a performance boost (benchmarking needed).

func NewBufferList

func NewBufferList(shader shaders.Shader, maxSprites, renderOrder int, texture uint32) (*BufferList, error)

Create a BufferList used to render using a specific shader.

func (*BufferList) AddSprite

func (bf *BufferList) AddSprite(sprite *Sprite) error

Adds a sprite to the cpu buffer.

func (*BufferList) Delete

func (bf *BufferList) Delete()

BufferList needs a destructor because gpu arrays must be manually deleted

func (*BufferList) Empty

func (sb *BufferList) Empty()

Clear all sprites from buffers

func (*BufferList) MoveCpuToGpu

func (bf *BufferList) MoveCpuToGpu() int

Copy all data from cpu buffers to gpu. Returns the number of floats moved.

func (*BufferList) UpdateBuffers

func (sb *BufferList) UpdateBuffers(buffer, index int, data []float32)

Update the data of a buffer. Can be used to add new data as well (since the buffers are preallocated) The index corresponds to the sprite number and is multiplied by the size (in floats) of the type of this buffer (given by Shader.Attributes[bufferName].Type.Size). Typically one would pass data in multiples of this size but this is not enforced.

type Renderer

type Renderer struct {

	// Stats
	SpritesRendered int
	DataMoved       int //float32s
	// contains filtered or unexported fields
}

A renderer holds a collection of BufferLists and renders them in a specific order

func NewRenderer

func NewRenderer() *Renderer

Create a new Renderer with the following default settings: alpha blending enabled, depth testing enabled, window size set to match the containing window size.

func (*Renderer) BufferStats

func (r *Renderer) BufferStats() string

Returns some data about the buffers renderer is using. For each buffer we report the number of sprites stored, the shader used and the render order. The number of sprites can only be read before Render is called because buffers are cleared after rendering.

func (*Renderer) DisableAlphaBlending

func (r *Renderer) DisableAlphaBlending()

func (*Renderer) DisableBackFaceCulling

func (r *Renderer) DisableBackFaceCulling()

func (*Renderer) DisableDepthTesting

func (r *Renderer) DisableDepthTesting()

Disable depth testing. You can still control front to back order for whole buffers with BufferList.RenderOrder.

func (*Renderer) EnableAlphaBlending

func (r *Renderer) EnableAlphaBlending()

func (*Renderer) EnableBackFaceCulling

func (r *Renderer) EnableBackFaceCulling()

func (*Renderer) EnableDepthTesting

func (r *Renderer) EnableDepthTesting()

Enable depth testing. A sprite's z value determines it's depth.

func (*Renderer) GetCamera

func (r *Renderer) GetCamera() math.Vector3[float32]

Get the camera position

func (*Renderer) GetScreenBoundingBox

func (r *Renderer) GetScreenBoundingBox() math.Box2D[float32]

Returns the screen bounding box. P1 is the lower-left and P2 is the upper-right.

func (*Renderer) Init

func (r *Renderer) Init()

Initialize rendering including opengl. Needs active opengl context (e.g. sdl.GLCreateContext) TODO: Deal with a opengl being already initialized (if the package is importerd in another rendering system)

func (*Renderer) QueueRender

func (r *Renderer) QueueRender(sprite *Sprite)

QueueRender adds a sprite to be rendered.

func (*Renderer) Render

func (r *Renderer) Render()

Renders all buffers in the order specified by ShaderBuffer.RenderOrder.

func (*Renderer) Resize

func (r *Renderer) Resize(w, h int)

Resize the render area. Called after the render window has been resized

func (*Renderer) SetBGColor

func (r *Renderer) SetBGColor(rgba [4]float32)

func (*Renderer) SetBufferSize

func (r *Renderer) SetBufferSize(s int)

Set the size for newly created buffers. If not set SetBufferSize, buffers are created with with DefaultBufferSize capacity. This sets the upper limit for sprites that can be drawn within each buffer. The total sprite upper limit depends on the number of shaders and render orders used. Each unique combination of shader-renderOrder gets its own buffer.

func (*Renderer) SetCamera

func (r *Renderer) SetCamera(position math.Vector3[float32])

Set the camera to position (translate the whole scene)

func (*Renderer) SetProjection

func (r *Renderer) SetProjection(center math.Vector2[float32], zNear, zFar float32)

Sets an orthographic projection and places the origin at the point specified by center. Center must be a point in the range (0,0) to (1,1) where (0,0) is the bottom-left of the view window and (1,1) is the upper right. Setting center to (0,0) will make it so that origin is at the lower-left of the screen. Setting it to (0.5, 0.5) will make it so that origin is at the center of the window. Parameters zNear, zFar define the depth range that sprites can take.

type Sprite

type Sprite struct {
	// contains filtered or unexported fields
}

Sprite holds info used to render a sprite. It exposes functions to manipulate sprite attributes such as position and scale and internally converts these into arrays suitable for rendering in OpenGL. Sprites are drawn from a sprite atlas stored in a sprite store and don't store pixel data on their own. To render a sprite it must be added to a Renderer using QueueRender.

func NewSprite

func NewSprite(spriteId int, spriteAtlas *Atlas, shader *shaders.Shader, renderOrder int) (Sprite, error)

func (*Sprite) GetAttribute

func (s *Sprite) GetAttribute(location int) []float32

General getter for sprite attributes. Does not copy so use with care.

func (*Sprite) GetColor

func (s *Sprite) GetColor() color.ColorRGBA

func (*Sprite) GetIndex

func (s *Sprite) GetIndex() int

func (*Sprite) GetOriginalSize

func (s *Sprite) GetOriginalSize() math.Vector2[int]

Get the sprite's original size which is its bounding box on the atlas map

func (*Sprite) GetPosition

func (s *Sprite) GetPosition() math.Vector3[float32]

func (*Sprite) GetRotation

func (s *Sprite) GetRotation() math.Vector3[float32]

func (*Sprite) GetScale

func (s *Sprite) GetScale() math.Vector2[float32]

func (*Sprite) SetAttribute

func (s *Sprite) SetAttribute(location int, data []float32)

General setter for sprite attributes.

func (*Sprite) SetColor

func (s *Sprite) SetColor(color color.ColorRGBA)

Set the sprite color. The same color is applied to every vertice.

func (*Sprite) SetIndex

func (s *Sprite) SetIndex(index int)

func (*Sprite) SetOriginalSize

func (s *Sprite) SetOriginalSize()

Sets the sprite size to its original value as it appears on the atlas map

func (*Sprite) SetPosition

func (s *Sprite) SetPosition(position math.Vector3[float32])

Setter for sprite position. Position is given in OpenGL coordinates, with the origin being in the center of the screen.

func (*Sprite) SetRotation

func (s *Sprite) SetRotation(rot math.Vector3[float32])

Setter for sprite rotation

func (*Sprite) SetScale

func (s *Sprite) SetScale(scale math.Vector2[float32])

Setter for sprite scale.

func (Sprite) String

func (s Sprite) String() string

type SpriteAtlasError

type SpriteAtlasError int
const (
	ErrorSpriteLimitReached SpriteAtlasError = iota
	ErrorAtlasFull
	ErrorMissingSpriteId
)

func (SpriteAtlasError) Error

func (s SpriteAtlasError) Error() string

type SpriteDrawer

type SpriteDrawer interface {
	Draw() // if the type has sprites, call their QueueRender
}

SpriteDrawer ensures that a type has the Draw method.

Jump to

Keyboard shortcuts

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