graphics

package
v0.0.0-...-16c05fb Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ColorBlack     = color.RGBA{R: 0, G: 0, B: 0, A: 255}
	ColorWhite     = color.RGBA{R: 255, G: 255, B: 255, A: 255}
	ColorRed       = color.RGBA{R: 255, G: 0, B: 0, A: 255}
	ColorGreen     = color.RGBA{R: 0, G: 255, B: 0, A: 255}
	ColorBlue      = color.RGBA{R: 0, G: 0, B: 255, A: 255}
	ColorYellow    = color.RGBA{R: 255, G: 255, B: 0, A: 255}
	ColorCyan      = color.RGBA{R: 0, G: 255, B: 255, A: 255}
	ColorMagenta   = color.RGBA{R: 255, G: 0, B: 255, A: 255}
	ColorGray      = color.RGBA{R: 128, G: 128, B: 128, A: 255}
	ColorDarkGray  = color.RGBA{R: 64, G: 64, B: 64, A: 255}
	ColorLightGray = color.RGBA{R: 192, G: 192, B: 192, A: 255}
)

Default colors using image/color types

Functions

func ColorToFloat32

func ColorToFloat32(c color.Color) [4]float32

ColorToFloat32 converts a color.Color to RGBA float32 values in the range [0, 1].

func GradientColorAt

func GradientColorAt(style ShapeStyle, px, py, x, y, width, height float32) [4]float32

GradientColorAt samples a ShapeStyle at px, py within the given bounds. It is useful when callers tessellate their own meshes: assign the returned color to Vertex.R/G/B/A and render with a nil texture for gradient fills.

func LoadImage

func LoadImage(data []byte) (image.Image, error)

LoadImage decodes PNG, JPEG, or GIF bytes into an image.Image.

func LoadImageURI

func LoadImageURI(uri string) (image.Image, error)

LoadImageURI loads an image from a filesystem path, file URI, or data URI.

func ResizeImageNearest

func ResizeImageNearest(src image.Image, width, height int) image.Image

ResizeImageNearest returns src resampled to width x height with nearest-neighbor sampling. It is intended for logical-size UI screenshots derived from backing pixel screenshots.

func RoundedRectIndexCount

func RoundedRectIndexCount(segments int) int

RoundedRectIndexCount returns the number of indices needed for a rounded rect.

func RoundedRectVertexCount

func RoundedRectVertexCount(segments int) int

RoundedRectVertexCount returns the number of vertices needed for a rounded rect.

func SegmentsForRadius

func SegmentsForRadius(radius float32) int

SegmentsForRadius returns appropriate tessellation quality based on radius. Larger radii need more segments for smooth curves.

Types

type ColorStop

type ColorStop struct {
	Position float32 // 0.0 to 1.0
	Color    color.Color
}

ColorStop defines a color at a specific position in a gradient.

type CornerRadius

type CornerRadius struct {
	TopLeft     float32
	TopRight    float32
	BottomRight float32
	BottomLeft  float32
}

CornerRadius specifies the radius for each corner of a rounded rectangle.

func UniformRadius

func UniformRadius(r float32) CornerRadius

UniformRadius creates a CornerRadius with the same value for all corners.

type Draw3DOptions

type Draw3DOptions struct {
	// Model places the mesh in world space. Zero value means identity.
	Model Mat4
	// View transforms world coordinates into camera space.
	View Mat4
	// Projection maps camera coordinates to clip space. Use PerspectiveMat4 or
	// Ortho3DMat4 for the common cases.
	Projection Mat4
	// Shader overrides the built-in lit vertex-color shader. Custom shaders must
	// use the Mesh3D vertex layout documented on Window.NewShader3D.
	Shader Shader3D
	// Textures binds sampler uniforms by name. The built-in 3D shader samples
	// u_texture and multiplies it by vertex color. When no texture is supplied,
	// a white texture is bound so vertex-color rendering still works.
	Textures map[string]Texture
	// Uniforms sets additional shader uniforms by name. Supported values are
	// float32/float64/int, Vec3, Mat4, and color.Color.
	Uniforms map[string]interface{}
	// Ambient controls minimum light contribution. Zero uses a small default.
	Ambient float32
	// LightDirection points from the surface toward the directional light.
	// Zero uses a camera/front-left default.
	LightDirection Vec3
	// FogStart/FogEnd enable distance fog when FogEnd is greater than FogStart.
	// FogColor defaults to transparent black when nil.
	FogStart float32
	FogEnd   float32
	FogColor color.Color
	// ClipDepthTest controls whether PushClipMesh3D depth-tests while writing
	// the stencil clip. The zero value is false, which is the recommended
	// projected-outline mode for flat surface clipping.
	ClipDepthTest bool
}

type DrawOptions

type DrawOptions struct {
	// Model is a column-major 4x4 model transform applied to vertex positions
	// before projection. If left as the zero value, Identity is assumed.
	Model Mat4
	// Mask multiplies rendered alpha by a mask texture sampled with the mesh UVs.
	// A render target texture works well for SVG-like masks.
	Mask Texture
}

type DynamicMesh

type DynamicMesh interface {
	Mesh
	// UpdateVertices updates a range of vertices starting at the given offset.
	UpdateVertices(offset int, vertices []Vertex)
	// UpdateAllVertices updates the entire vertex buffer.
	UpdateAllVertices(vertices []Vertex)
	// UpdateIndices updates the index buffer.
	UpdateIndices(indices []uint32)
	// Resize changes the buffer capacity (recreates GPU buffers).
	Resize(vertexCount, indexCount int)
	// VertexCount returns the current vertex capacity.
	VertexCount() int
}

DynamicMesh supports efficient partial vertex updates via BufferSubData.

type Frame

type Frame interface {
	// WindowSize returns the current logical window size. All Frame drawing
	// coordinates use this logical top-left origin coordinate space.
	WindowSize() (width, height int)
	// BackingSize returns the current physical framebuffer size in backing
	// pixels. On HiDPI displays this is typically WindowSize multiplied by Scale.
	BackingSize() (width, height int)
	// Scale returns the current backing-pixels-per-logical-pixel factor for this
	// frame. It can change when a window moves between displays.
	Scale() float32
	// CursorPos returns the cursor position in logical Frame coordinates.
	CursorPos() (x, y float32)

	GetKeyState(key window.Key) window.KeyState
	GetButtonState(button window.Button) window.ButtonState
	DrainInputEvents() []window.InputEvent
	// TextInput returns the UTF-8 text entered since the last call to TextInput.
	TextInput() string

	RenderQuad(x, y, width, height float32, tex Texture, color color.Color)
	// RenderFBOTexture renders an FBO texture with flipped V coordinates.
	// Use this for textures created by render-to-texture operations (like blur).
	RenderFBOTexture(x, y, width, height float32, tex Texture, color color.Color)
	// RenderMaskedQuad renders tex modulated by mask alpha. Mask and texture use
	// the same quad UVs; render masks into a RenderTarget and pass its Texture.
	RenderMaskedQuad(x, y, width, height float32, tex Texture, mask Texture, color color.Color)
	RenderMesh(mesh Mesh, opts DrawOptions)
	// RenderMesh3D draws a colored, lit 3D mesh. It temporarily enables depth
	// testing, then restores the 2D render state so UI/text can be drawn before
	// or after 3D content in the same frame.
	RenderMesh3D(mesh Mesh3D, opts Draw3DOptions)

	// PushClip intersects subsequent rendering with rect until PopClip is called.
	// Coordinates are logical pixels in the same top-left origin space as drawing.
	PushClip(rect Rect)
	// PopClip restores the previous clipping rectangle.
	PopClip()
	// PushClipMesh intersects subsequent rendering with the filled area of mesh
	// using the stencil buffer. Use meshes tessellated from clip paths.
	PushClipMesh(mesh Mesh, opts DrawOptions)
	// PopClipMesh restores the previous stencil clip mesh.
	PopClipMesh()
	// PushClipMesh3D intersects subsequent 3D and 2D rendering with the projected
	// stencil footprint of mesh. By default stencil writing ignores depth so it
	// can be pushed before or after drawing the clipped surface. Set
	// Draw3DOptions.ClipDepthTest for volume/depth-sensitive clip meshes.
	PushClipMesh3D(mesh Mesh3D, opts Draw3DOptions)
	// PopClipMesh3D restores the previous stencil clip mesh.
	PopClipMesh3D()

	// RenderToTarget renders into target using a top-left origin projection whose
	// logical size matches target.Size, then restores window rendering.
	RenderToTarget(target RenderTarget, opts RenderTargetOptions, draw func(Frame) error) error

	// Screenshot returns the current framebuffer in backing pixels. For logical
	// size UI test images, use ScreenshotLogical.
	Screenshot() (image.Image, error)
	// ScreenshotLogical returns a screenshot resampled to WindowSize.
	ScreenshotLogical() (image.Image, error)
}

type GradientDirection

type GradientDirection int

GradientDirection specifies the direction of a color gradient.

const (
	GradientNone       GradientDirection = iota
	GradientVertical                     // Top to bottom
	GradientHorizontal                   // Left to right
	GradientDiagonalTL                   // Top-left to bottom-right (135deg)
	GradientDiagonalTR                   // Top-right to bottom-left (45deg)
)

type Mat4

type Mat4 [16]float32

Mat4 is a column-major 4x4 matrix compatible with OpenGL uniforms.

func IdentityMat4

func IdentityMat4() Mat4

func LookAtMat4

func LookAtMat4(eye, center, up Vec3) Mat4

func MulMat4

func MulMat4(a, b Mat4) Mat4

MulMat4 returns a*b (column-major, vectors on the right).

func Ortho3DMat4

func Ortho3DMat4(left, right, bottom, top, near, far float32) Mat4

func PerspectiveMat4

func PerspectiveMat4(fovYRadians, aspect, near, far float32) Mat4

func RotateXMat4

func RotateXMat4(angle float32) Mat4

func RotateYMat4

func RotateYMat4(angle float32) Mat4

func RotateZMat4

func RotateZMat4(angle float32) Mat4

RotateZMat4 returns a rotation matrix around the Z axis (in radians).

func Scale3DMat4

func Scale3DMat4(x, y, z float32) Mat4

func ScaleMat4

func ScaleMat4(x, y float32) Mat4

func Translate3DMat4

func Translate3DMat4(x, y, z float32) Mat4

func TranslateMat4

func TranslateMat4(x, y float32) Mat4

type Mesh

type Mesh interface {

	// Destroy releases the GPU buffers owned by this mesh. Drawing a destroyed
	// mesh is a no-op. Destroy is idempotent.
	Destroy()
	// contains filtered or unexported methods
}

Mesh is an opaque GPU resource created by Window.NewMesh and drawn by Frame.RenderMesh.

type Mesh3D

type Mesh3D interface {

	// Destroy releases the GPU buffers owned by this mesh. Drawing a destroyed
	// mesh is a no-op. Destroy is idempotent.
	Destroy()
	// contains filtered or unexported methods
}

Mesh3D is an opaque GPU resource created by Window.NewMesh3D and drawn by Frame.RenderMesh3D.

type Point

type Point struct {
	X float32
	Y float32
}

Point is a logical-pixel coordinate in the top-left origin drawing space.

type Rect

type Rect struct {
	X      float32
	Y      float32
	Width  float32
	Height float32
}

Rect is a logical-pixel rectangle in the top-left origin coordinate space used by Frame drawing methods.

type RenderTarget

type RenderTarget interface {
	// Bind makes this render target the current drawing destination.
	// Call Unbind() when done to restore the default framebuffer.
	Bind()

	// Unbind restores the default framebuffer (screen).
	Unbind()

	// Texture returns the texture containing the rendered content.
	Texture() Texture

	// Size returns the dimensions of this render target.
	Size() (width, height int)

	// Resize changes the render target size (recreates GPU resources).
	Resize(width, height int) error

	// Destroy releases GPU resources.
	Destroy()
}

RenderTarget represents an off-screen render target (FBO + texture).

Prefer Frame.RenderToTarget over calling Bind/Unbind directly when drawing with Frame methods; it installs the correct target-sized projection and restores the window framebuffer afterward. To build an SVG-style vector mask, create a RenderTarget, call RenderToTarget with the default transparent clear, render the mask geometry in white, then use target.Texture() as DrawOptions.Mask or the mask argument to Frame.RenderMaskedQuad.

type RenderTargetOptions

type RenderTargetOptions struct {
	// NoClear leaves the previous render target contents intact. By default the
	// target is cleared before drawing.
	NoClear bool
	// ClearColor is used when clearing. Nil means transparent black, which is the
	// usual starting point for vector mask textures.
	ClearColor color.Color
}

RenderTargetOptions controls Frame.RenderToTarget.

type SVG

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

func LoadSVG

func LoadSVG(win Window, data []byte) (*SVG, error)

LoadSVG parses a minimal subset of SVG and uploads a compiled mesh to the GPU.

Supported for now (enough for internal/assets/logo-color-white.svg): - <svg viewBox="minX minY w h"> - <style> rules for "#id { fill: ... }" and "#id polygon { fill: ... }" - <g id="..."> grouping for style resolution - <polygon points="..." [fill="..."]>

func (*SVG) Draw

func (s *SVG) Draw(f Frame, x, y, w, h float32)

func (*SVG) DrawGroupRotated

func (s *SVG) DrawGroupRotated(f Frame, groupID string, x, y, w, h float32, angleRad float32)

DrawGroupRotated rotates a named group around its own bounds center (in viewBox space).

func (*SVG) DrawGroupWithOptions

func (s *SVG) DrawGroupWithOptions(f Frame, groupID string, x, y, w, h float32, opts DrawOptions)

DrawGroupWithOptions draws a specific named group mesh, applying opts.Model after the SVG-to-viewport transform.

func (*SVG) DrawWithOptions

func (s *SVG) DrawWithOptions(f Frame, x, y, w, h float32, opts DrawOptions)

DrawWithOptions draws the full SVG mesh, applying opts.Model in SVG local space (after viewBox translation).

func (*SVG) GroupBounds

func (s *SVG) GroupBounds(groupID string) (minX, minY, maxX, maxY float32, ok bool)

GroupBounds returns the viewBox-space bounds for a named <g id="..."> group.

func (*SVG) GroupCenter

func (s *SVG) GroupCenter(groupID string) (cx, cy float32, ok bool)

GroupCenter returns the area-weighted centroid for a named <g id="..."> group. The center is expressed in viewBox space.

func (*SVG) Height

func (s *SVG) Height() float32

Height returns the SVG viewBox height.

func (*SVG) Width

func (s *SVG) Width() float32

Width returns the SVG viewBox width.

type Shader3D

type Shader3D interface {

	// Destroy releases the shader program. Destroy is idempotent.
	Destroy()
	// contains filtered or unexported methods
}

Shader3D is an opaque shader resource created by Window.NewShader3D.

type ShapeBuilder

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

ShapeBuilder helps UI widgets manage dynamic shape meshes.

func NewShapeBuilder

func NewShapeBuilder(w Window, segments int) (*ShapeBuilder, error)

NewShapeBuilder creates a builder with pre-allocated capacity for a rounded rect.

func (*ShapeBuilder) Mesh

func (b *ShapeBuilder) Mesh() Mesh

Mesh returns the underlying mesh for rendering.

func (*ShapeBuilder) Segments

func (b *ShapeBuilder) Segments() int

Segments returns the tessellation quality.

func (*ShapeBuilder) UpdateCircle

func (b *ShapeBuilder) UpdateCircle(cx, cy, radius float32, style ShapeStyle)

UpdateCircle updates the mesh with circle geometry.

func (*ShapeBuilder) UpdatePill

func (b *ShapeBuilder) UpdatePill(x, y, width, height float32, style ShapeStyle)

UpdatePill updates the mesh with pill/capsule geometry.

func (*ShapeBuilder) UpdateRoundedRect

func (b *ShapeBuilder) UpdateRoundedRect(
	x, y, width, height float32,
	radius CornerRadius,
	style ShapeStyle,
)

UpdateRoundedRect updates the mesh with new rounded rect geometry.

type ShapeStyle

type ShapeStyle struct {
	// Fill color (used when GradientStops is empty)
	FillColor color.Color

	// Gradient colors (overrides FillColor if set)
	GradientDirection GradientDirection
	GradientStops     []ColorStop
}

ShapeStyle defines the visual appearance of a shape.

func DefaultShapeStyle

func DefaultShapeStyle() ShapeStyle

DefaultShapeStyle returns a white solid fill.

type StrokeCap

type StrokeCap int

StrokeCap describes how open stroke endpoints are rendered.

const (
	StrokeCapButt StrokeCap = iota
	StrokeCapSquare
	StrokeCapRound
)

type StrokeJoin

type StrokeJoin int

StrokeJoin describes how adjacent stroke segments are connected.

const (
	StrokeJoinMiter StrokeJoin = iota
	StrokeJoinBevel
	StrokeJoinRound
)

type StrokeStyle

type StrokeStyle struct {
	Width    float32
	Color    color.Color
	Join     StrokeJoin
	Cap      StrokeCap
	Segments int
}

StrokeStyle defines the visual appearance of stroked polyline geometry.

type Texture

type Texture interface {
	Size() (width, height int)
}

func NewTextureFromFile

func NewTextureFromFile(win Window, path string) (Texture, error)

NewTextureFromFile loads an image file and uploads it as a texture.

func NewTextureFromURI

func NewTextureFromURI(win Window, uri string) (Texture, error)

NewTextureFromURI loads a filesystem path, file URI, or data URI and uploads it. Callers that already hold a Texture can pass it directly to Frame.RenderQuad, Frame.RenderMaskedQuad, Window.NewMesh, or DrawOptions.Mask.

type Vec3

type Vec3 struct {
	X float32
	Y float32
	Z float32
}

type Vertex

type Vertex struct {
	X float32
	Y float32
	U float32
	V float32
	R float32
	G float32
	B float32
	A float32
}

Vertex matches the graphics shader input layout:

a_position: vec2
a_texCoord: vec2
a_color:    vec4

All values are in float32 and packed tightly in this order. With a nil mesh texture, vertex colors are multiplied by a built-in white texture, so per-vertex colors can be used directly for solid colors and tessellated linear/radial gradients.

func CircleGeometry

func CircleGeometry(cx, cy, radius float32, style ShapeStyle, segments int) ([]Vertex, []uint32)

CircleGeometry generates vertices/indices for a circle.

func PillGeometry

func PillGeometry(x, y, width, height float32, style ShapeStyle, segments int) ([]Vertex, []uint32)

PillGeometry generates vertices/indices for a pill/capsule shape.

func RoundedRectGeometry

func RoundedRectGeometry(
	x, y, width, height float32,
	radius CornerRadius,
	style ShapeStyle,
	segments int,
) ([]Vertex, []uint32)

RoundedRectGeometry generates vertices and indices for a rounded rectangle. The rectangle has its top-left corner at (x, y) with the given dimensions.

func StrokePolylineGeometry

func StrokePolylineGeometry(points []Point, style StrokeStyle) ([]Vertex, []uint32)

StrokePolylineGeometry creates triangle geometry for an open stroked polyline. The helper supports SVG-like butt, square, and round caps plus bevel/miter-ish joins. Round joins are approximated as bevel joins; use a higher-level path tessellator when exact SVG arc joins are required.

type Vertex3D

type Vertex3D struct {
	X  float32
	Y  float32
	Z  float32
	NX float32
	NY float32
	NZ float32
	U  float32
	V  float32
	R  float32
	G  float32
	B  float32
	A  float32
}

Vertex3D matches the built-in 3D shader input layout:

a_position: vec3
a_normal:   vec3
a_texCoord: vec2
a_color:    vec4

Positions are in caller-defined 3D units. The coordinate system is right-handed by convention: +X right, +Y up, and +Z toward the camera for the default LookAt-style cameras. Front faces use counter-clockwise winding.

func Cuboid3DGeometry

func Cuboid3DGeometry(width, height, depth float32, c color.Color) ([]Vertex3D, []uint32)

Cuboid3DGeometry returns a colored box centered on the origin. It is useful for slabs, blocks, and simple technical preview fixtures. Faces are emitted with counter-clockwise winding when viewed from outside.

func PlanarPolygon3DGeometry

func PlanarPolygon3DGeometry(points []Point, z float32, c color.Color) ([]Vertex3D, []uint32)

PlanarPolygon3DGeometry triangulates one planar XY contour at z using a triangle fan. It is intended for simple convex clip meshes and surface patches. For concave outlines or outlines with holes, tessellate externally and upload the result with Window.NewMesh3D.

func PlanarRect3DGeometry

func PlanarRect3DGeometry(width, height, z float32, c color.Color) ([]Vertex3D, []uint32)

PlanarRect3DGeometry returns a colored rectangle in the XY plane at z. It is useful for surface layers and stencil clip meshes projected onto flat faces.

type Window

type Window interface {
	// Return the platform-specific window implementation.
	PlatformWindow() window.Window

	// Create a new texture from an image.
	NewTexture(image.Image) (Texture, error)
	// NewMesh uploads a set of vertices/indices to the GPU for repeated rendering.
	NewMesh(vertices []Vertex, indices []uint32, tex Texture) (Mesh, error)
	// NewDynamicMesh creates a mesh that supports efficient partial vertex updates.
	NewDynamicMesh(maxVertices, maxIndices int, tex Texture) (DynamicMesh, error)
	// NewMesh3D uploads 3D vertices/indices for repeated lit rendering. 3D uses
	// a conventional right-handed coordinate system; vertex winding is
	// counter-clockwise when viewed from the front face.
	NewMesh3D(vertices []Vertex3D, indices []uint32) (Mesh3D, error)
	// NewShader3D compiles a shader program that can draw Mesh3D resources.
	//
	// Custom 3D shaders use the same vertex layout as Mesh3D:
	// a_position vec3, a_normal vec3, a_texCoord vec2, and a_color vec4.
	// They may declare u_model, u_view, u_projection, u_lightDirection, and
	// u_ambient uniforms to receive values from Draw3DOptions. Sampler uniforms
	// can be populated with Draw3DOptions.Textures.
	NewShader3D(vertexSource, fragmentSource string) (Shader3D, error)

	SetClear(enabled bool)
	SetClearColor(color color.Color)

	// Scale returns the most recently observed display scaling factor. During a
	// frame, prefer Frame.Scale so apps see the same scale used for drawing.
	Scale() float32

	// Call f for each frame until it returns an error.
	Loop(func(f Frame) error) error

	// GetShaderProgram returns the graphics shader program ID for state restoration.
	GetShaderProgram() uint32

	// NewRenderTarget creates an off-screen render target for render-to-texture.
	NewRenderTarget(width, height int) (RenderTarget, error)
}

func New

func New(title string, width, height int) (Window, error)

New returns a Window backed by OpenGL implementation.

width and height are logical pixels on every platform. Platform backends choose a backing framebuffer size from that logical size and the current display scale; use Frame.BackingSize and Frame.Scale to inspect it per frame.

Jump to

Keyboard shortcuts

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