glyphengine

package module
v0.0.0-...-61f5c44 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 30 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

GlyphEngine

A 3D game engine for Go, built on Vulkan.

Go has no living 3D engine — Ebitengine is 2D, g3n is quiet, Azul3D is gone. This is an attempt at one, extracted from a working Vulkan MMO rather than written speculatively.

It is a library. Your program owns main(); there is no editor and no runtime that loads your game.

Status: v0.x. APIs break without notice. Pin a commit if you build on it.

A rigged character running across procedural terrain through instanced grass, with a text overlay

task example:15-kitchen-sink — a rigged glTF character with GPU skinning, running over a procedural heightmap that is both the collision surface and the geometry, through instanced grass scattered from that same heightmap, under cascaded shadow maps and the day/night sky from x/sky, with MSDF text over the top. Every image in this README is captured by the engine itself with -screenshot, not taken by hand.

The showcase game

Vesper 3 — a colony builder on a hex grid, in true 3D, on a planet that is not Earth.

It is the engine's proving ground as much as its shop window. Translucent placement ghosts, instanced props, glTF loading and a HUD that survives being looked at through water are all here because building Vesper 3 needed them, and a good share of the engine's sharper edges were found there first rather than in an example.

Install

go get github.com/derekmwright/glyphengine

Prerequisites

  • Go 1.26+
  • CGo enabled and a C compiler. CGO_ENABLED=0 will not build.
  • Vulkan runtime and a GPU/driver supporting VK_KHR_dynamic_rendering, its dynamicRendering feature and extension dependencies (see ADR 0009)
  • go-task, for the repo's build targets
  • Optional: the Vulkan SDK, for the validation layer and for recompiling shaders
Platform Status
Windows Supported, and where development happens
Linux Blocked upstream. vkngwrapper/core v3.1.1 is missing an unsafe import in system_nonwindows.go and does not compile. The fix is merged on main; tracking a tag in vkngwrapper/core#13.
macOS Untested. MoltenVK portability enumeration/subset handling is present; its driver must support the required dynamic-rendering capabilities.

Hello, triangle

git clone https://github.com/derekmwright/glyphengine
cd glyphengine
task example:01-triangle

If a tri-color triangle appears, your whole toolchain works — CGo, the C compiler, the Vulkan loader, the driver, GLFW, and the entire instance → device → swapchain → pipeline → present path. Debug there first when anything breaks.

A minimal game

package main

import (
	"log"
	"runtime"

	"github.com/go-gl/mathgl/mgl32"
	glyph "github.com/derekmwright/glyphengine"
	"github.com/derekmwright/glyphengine/input"
	"github.com/derekmwright/glyphengine/x/sky"
)

func init() {
	runtime.LockOSThread() // GLFW must stay on the thread that initialized it
}

type game struct{ camera *glyph.Camera }

func (g *game) Init(e *glyph.Engine) error {
	cube, err := e.Renderer().CreateCube(1.0)
	if err != nil {
		return err
	}

	ent := e.Spawn()
	e.C.Transform.Set(ent, &glyph.Transform{
		Position: mgl32.Vec3{0, 1, 0},
		Scale:    mgl32.Vec3{1, 1, 1},
	})
	e.C.MeshRef.Set(ent, &glyph.MeshRef{Mesh: cube})

	// A sky, a sun and some haze. The engine has no environment of its own
	// beyond flat light and air, so a scene that wants one says which: x/sky is
	// the day/night sky the engine used to ship. Leave this out and the frame
	// is black with an unlit cube in it.
	e.Scene.Env = sky.DefaultEnvironment()

	g.camera = glyph.NewCamera(8)
	g.camera.Target = mgl32.Vec3{0, 1, 0}
	return nil
}

func (g *game) Update(e *glyph.Engine, dt float32) {
	if e.Input().KeyPressed(input.KeyEscape) {
		e.Close()
	}
	g.camera.Update(e.Input())
	e.SetCamera(g.camera.ViewVectors())
}

func main() {
	// WithShaders is the other half of the sky: the source above decides where
	// the sun is, and these three shader stages are what draw a dome, stars and
	// clouds from it. The engine embeds none of them.
	e, err := glyph.New(&game{},
		glyph.WithTitle("My Game"),
		glyph.WithShaders(sky.Shaders()),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer e.Destroy()
	e.Run()
}

Loading assets

Every loader takes an fs.FS, so the same call works against an embed.FS baked into the binary, an os.DirFS pointing at a mod folder, or a test fixture. The working directory never decides whether your game finds its assets.

//go:embed assets
var assetsFS embed.FS

tex, err := r.LoadTexture(assetsFS, "assets/crate.png")
model, err := r.LoadGLTFSkinned(assetsFS, "assets/character.glb")
hm, err := glyph.LoadHeightmap(assetsFS, "assets/island.heightmap")

.heightmap files come from cmd/heightmapconv — rasterised from a sculpted Blender mesh, or converted from a heightmap image/raw grid — or from (*glyph.Heightmap).WriteTo in a game's own pipeline. See docs/agents/terrain-heightmap.md.

Moving a character

Simulation runs on a fixed tick; rendering runs at the display rate and interpolates between ticks. Read input per frame in Update, move per tick in FixedUpdate:

func (g *game) Update(e *glyph.Engine, dt float32) {
	in := e.Input()
	g.intent = glyph.MoveIntent{Yaw: g.camera.Yaw}
	if in.KeyDown(input.KeyW) { g.intent.Forward++ }
	if in.KeyPressed(input.KeySpace) { g.jumpQueued = true } // latch the edge
}

func (g *game) FixedUpdate(e *glyph.Engine, dt float32) {
	intent := g.intent
	intent.Jump = g.jumpQueued
	g.jumpQueued = false
	e.MoveCharacter(g.player, intent, dt)
}

That split is why movement is reproducible: identical inputs give bit-identical results at 60Hz and at 300Hz.

Packages

Package What it does
glyphengine Root. Engine (window, frame loop), Scene (simulation), components, physics, terrain, water, environment, cameras, character controller; .heightmap encoder/decoder, with a Blender-mesh/image/raw-to-.heightmap conversion CLI at cmd/heightmapconv
glyphengine/ecs Generic ECS — typed Store[T], Query2/3/4
glyphengine/renderer Vulkan renderer: forward + reverse-Z, cascaded shadows, GPU skinning, MSDF text, instanced grass, water, particles
glyphengine/window GLFW window and Vulkan surface
glyphengine/input Keyboard, mouse, cursor capture
glyphengine/audio 3D positional audio (miniaudio)
glyphengine/ui Immediate-mode widgets
glyphengine/ui/yamlui Declarative YAML UI with data bindings
glyphengine/shaders Embedded SPIR-V, overridable via renderer.ShaderSet
glyphengine/msdf MSDF font atlas generation in pure Go; CLI at cmd/msdfatlas

A second published module, github.com/derekmwright/glyphengine/x, holds the systems that have a look rather than a mechanism, one package per system. It depends on the engine and the engine depends on neither it nor the examples.

Package What it does
glyphengine/x/sky The day/night sky: the cycle and its palette curves, the dome, the sun and moon discs, the stars and the cloud layers
glyphengine/x/water The underwater volume: absorption, the water's own colour, sun shafts
glyphengine/x/terrainfield An island heightmap from value-noise fBm

See x/README.md and ADR 0012 for why there are two modules and what may go in the second.

Examples

One concept each. Examples 01–04 and 07 load nothing from disk. Every one takes -screenshot out.png to capture its last frame.

02-cube 03-physics
05-textures 06-skinned
08-grass 09-water
11-lights 21-streetlights
24-custom-passes Additive light patterns, compute smoothing and depth-aware fog
task example:01-triangle      # window, renderer, input loop
task example:02-cube          # Game, Scene, entities, orbit camera, day/night
task example:03-physics       # colliders, gravity, spatial grids, picking
task example:04-first-person  # FP camera, MoveIntent, character controller
task example:05-textures      # loading assets from an embedded filesystem
task example:06-skinned       # rigged glTF character, GPU skinning, clip blending
task example:07-terrain       # heightmap as both collision and geometry
task example:08-grass         # instanced flora scattered across terrain
task example:09-water         # animated lake: waves, refraction, Fresnel reflection
task example:10-text          # MSDF text, one atlas from caption to headline size
task example:11-lights        # point lights, cube shadow maps, emissive markers
task example:12-particles     # CPU-simulated emitters, one instanced draw
task example:13-ui            # immediate-mode HUD: panels, bars, MSDF labels
task example:15-kitchen-sink  # all of the above at once
task example:16-materials     # normal, metallic-roughness, occlusion and emissive maps
task example:17-input         # named actions across keyboard, mouse and gamepad
task example:18-translucent   # blended geometry: placement ghosts and glass
task example:19-instanced     # 900 props one draw call at a time, or all at once
task example:20-screens       # main menu, pause menu, scene swapping, keyboard menus
task example:21-streetlights  # clustered spot and point lights on terrain at night
task example:22-level         # a level loaded from one glTF: extras, KHR_lights_punctual, per-node placement
task example:23-shadow-coverage # distant off-camera casters with independent shadow coverage/depth
task example:24-custom-passes # application render targets, graphics/compute passes and depth-aware fog
task example:25-lod-forest     # per-instance culling, distance levels, dithered fades and baked impostors
task example:26-mesh-ranges    # distinct patches as separate meshes, shared arena ranges or indirect batches
task example:27-streaming      # patches uploaded while frames render: synchronous, dynamic or batched
task example:28-overdraw       # the overdraw baseline: a field that hides itself, and a control that does not

Building

task build     # engine and examples
task test      # unit tests, no GPU needed
task lint      # gofmt, then go vet
task smoke     # render real frames of every example
task validate  # every example under the Vulkan validation layer
task ci        # lint, build, test, race

Documentation

  • docs/adr/ — architecture decisions, their rationale, and the process for recording new ones
  • docs/agents/ — one page per capability, with working code and the failure modes that matter
  • AGENTS.md — architecture, invariants, and the rules that are expensive to get wrong
  • examples/ — runnable programs

License

MIT. See LICENSE, and THIRD_PARTY.md for vendored code.

Documentation

Index

Constants

View Source
const DefaultBlendDuration = float32(0.15)

DefaultBlendDuration is the cross-fade time in seconds applied when a clip changes and AnimationState.BlendDuration is zero.

View Source
const DefaultFogDensity = 0.0075

DefaultFogDensity gives about 35% fog at the 80-unit grass cull distance, which is enough to hide where the scatter stops without flattening the view.

View Source
const DefaultGravity = float32(20.0)

DefaultGravity is the downward acceleration applied by IntegrateBodies and the character controller, in world units per second squared.

View Source
const DefaultMaxCatchUp = 250 * time.Millisecond

DefaultMaxCatchUp is how much simulation time one frame may make up after a stall. See WithMaxCatchUp.

View Source
const DefaultTickRate = 60

DefaultTickRate is the fixed simulation rate in ticks per second.

View Source
const GroundEpsilon = float32(0.05)

GroundEpsilon is the vertical slack, in world units, within which a body is still considered to be standing on a surface.

View Source
const SplatTiles = float32(10)

SplatTiles is how many times a terrain mesh's UVs repeat across its full extent. The terrain splat shader divides fragUV by this to recover the 0–1 top-down coordinate for the splat weight map, so terrain geometry built for that pipeline must use this tiling factor. TerrainMesh uses it by default.

Variables

This section is empty.

Functions

func ExtractGLTFPositions

func ExtractGLTFPositions(fsys fs.FS, name string) ([][3]float32, error)

ExtractGLTFPositions reads a glTF/GLB document from fsys and returns all vertex positions across all meshes and primitives. No GPU or Renderer required, so hull generation can run as a build step.

func FindClip

func FindClip(model *renderer.SkinnedModel, name string) int

FindClip returns the index of the first animation clip whose name matches name, case-insensitively, or -1 if there is none.

func FindClipAny

func FindClipAny(model *renderer.SkinnedModel, names ...string) int

FindClipAny returns the index of the first clip matching any of names, tried in order, or -1 if none match. Useful for models that spell a clip differently: FindClipAny(m, "sprint", "run", "walk").

func GJKOverlapAABB

func GJKOverlapAABB(hull *ConvexHullCollider, t *Transform, box AABB) bool

GJKOverlapAABB returns true if the convex hull (in local space, transformed by t) overlaps the given world-space AABB.

func HullBounds

func HullBounds(hull *ConvexHullCollider) (min, max mgl32.Vec3)

HullBounds returns the axis-aligned bounding box of a hull in local space.

func HullFootprintOverlapsCell

func HullFootprintOverlapsCell(hull *ConvexHullCollider, t *Transform, cellMinX, cellMinZ, cellMaxX, cellMaxZ float32) bool

HullFootprintOverlapsCell returns true if the XZ projection of a transformed hull overlaps the given grid cell rectangle.

func IntegrateBodies

func IntegrateBodies(s *Scene, dt float32)

IntegrateBodies applies gravity and integrates velocity into position for every entity with a Transform and a Velocity. Entities that also have a Collider are additionally snapped to the ground — the terrain heightmap when there is one, a downward raycast otherwise.

Bodies are resolved against the world, not against each other: this is not a rigid-body solver and does no body-to-body response. Entities with a CharacterController are skipped entirely, since MoveCharacter already does its own gravity, grounding, and swept collision — integrating them here too would apply gravity twice per tick.

func LerpAngle

func LerpAngle(a, b, alpha float32) float32

LerpAngle interpolates between two angles in radians along the shortest arc.

Plain linear interpolation is wrong for angles: a character turning from 179° to -179° has moved 2°, but lerping the raw numbers sweeps it 358° the other way. At 144Hz that is a visible spin every time facing crosses the wrap point.

func RaycastHull

func RaycastHull(hull *ConvexHullCollider, t *Transform, origin, dir mgl32.Vec3, maxDist float32) (float32, mgl32.Vec3, bool)

RaycastHull tests a ray against a convex hull. The ray and hull are in world space. Transforms the ray to hull local space for efficiency, then tests each face triangle. Returns the nearest hit distance, the world-space outward normal, and whether it hit.

func SerializeHull

func SerializeHull(hull *ConvexHullCollider) []byte

SerializeHull encodes a convex hull into a compact binary blob. Format: [uint8 version][uint16 vertCount][float32×3 verts...][uint16 faceCount][uint16×3 faces...]

func TerrainMesh

func TerrainMesh(h *Heightmap, opts *TerrainOptions) ([]renderer.Vertex, []uint32, error)

TerrainMesh builds renderable geometry from a heightmap: one vertex per grid point, with normals from the heightmap's central differences so lighting is smooth across cell boundaries.

It returns 32-bit indices because terrain grids routinely exceed 65,536 vertices — a 256×256 heightmap is already 65,536 exactly. Feed the result to Renderer.CreateIndexedMesh32.

func WaterMesh

func WaterMesh(h *Heightmap, opts WaterOptions) ([]renderer.Vertex, []uint32, error)

WaterMesh builds a surface grid covering the submerged parts of a heightmap.

Quads whose four corners are all above Level are dropped, so the mesh follows the shape of the lake instead of covering the whole map. That is worth doing for more than the triangle count: a surface stretched over dry land would z-fight with the ground it sits inside.

Each vertex carries the still-water depth beneath it, sampled from the heightmap. Baking it at build time means the shader gets the depth of the real lake bed without a depth buffer read, which is what lets the shore fade, the colour absorption, and the wave shoaling all work in the first pass.

Types

type AABB

type AABB struct {
	Min, Max mgl32.Vec3
}

AABB is a world-space axis-aligned bounding box.

func WorldAABB

func WorldAABB(t *Transform, c *Collider) AABB

WorldAABB computes the world-space AABB for an entity given its transform and collider. Rotation is ignored (axis-aligned assumption).

func (AABB) Overlaps

func (a AABB) Overlaps(other AABB) bool

Overlaps returns true if two AABBs overlap (touching counts as overlap).

func (AABB) OverlapsXZ

func (a AABB) OverlapsXZ(b AABB) bool

OverlapsXZ tests if two AABBs overlap on the XZ plane only (ignoring Y).

func (AABB) Raycast

func (a AABB) Raycast(origin, dir mgl32.Vec3, maxDist float32) (t float32, normal mgl32.Vec3, hit bool)

Raycast tests a ray against the AABB using the slab method. Returns the hit distance t, outward normal at the entry face, and whether the ray hit. A ray originating inside the box is not considered a hit.

type AmbientLight

type AmbientLight struct {
	Color [3]float32
}

AmbientLight is uniform fill light with no direction.

type AnimationState

type AnimationState struct {
	Clip    int     // index into SkeletonRef.Model.Animations
	Time    float32 // seconds into the clip
	Speed   float32 // playback rate multiplier
	Loop    bool
	Playing bool

	// BlendDuration is the cross-fade time in seconds used on the next clip
	// change. Zero means DefaultBlendDuration.
	BlendDuration float32
	// contains filtered or unexported fields
}

AnimationState holds skeletal animation playback state for one entity.

This is playback only — which clip, where in it, how fast. Choosing the clip is game policy (an idle/walk/run speed ladder, a jump state machine, a death override) and belongs in a game-side system that calls PlayLoop and PlayOnce. The engine deliberately ships no locomotion controller.

func (*AnimationState) Finished

func (a *AnimationState) Finished() bool

Finished reports whether a non-looping clip has played to its end.

func (*AnimationState) PlayLoop

func (a *AnimationState) PlayLoop(clip int, speed float32)

PlayLoop plays clip on a loop at the given playback speed, cross-fading from the current pose. Playback time is reset only on an actual clip change, so calling it every frame with the same clip does not stutter. A negative clip index is ignored, which makes FindClip's -1 miss safe to pass straight in.

func (*AnimationState) PlayOnce

func (a *AnimationState) PlayOnce(clip int)

PlayOnce plays clip from the start at normal speed without looping, cross-fading from the current pose on a clip change. Playing goes false when the clip reaches its end. A negative clip index is ignored.

func (*AnimationState) Stop

func (a *AnimationState) Stop()

Stop freezes playback at the current pose.

type CPUPhase

type CPUPhase int

CPUPhase names a slice of the frame's CPU work.

The split is chosen so each entry points at something a game can actually change. "The frame takes 8 ms" is not actionable; "6 ms of it is waiting for the GPU" and "4 ms of it is building the draw list" lead to opposite fixes.

const (
	// CPUPoll is input sampling and window event pumping.
	CPUPoll CPUPhase = iota
	// CPUUpdate is Game.Update.
	CPUUpdate
	// CPUTick is Scene.Tick plus FixedUpdate, summed over however many ticks
	// the frame ran — which is zero on most frames at a high refresh rate.
	CPUTick
	// CPUAnimate is skeletal animation sampling.
	CPUAnimate
	// CPULateUpdate is Game.LateUpdate.
	CPULateUpdate
	// CPUDrawList is building and culling the draw list.
	CPUDrawList
	// CPUDrawSort is ordering it: building the sort keys and running the sort.
	//
	// Split out of CPUDrawList because what the sort costs is a question of its
	// own -- see drawOrder, where the answer was a microbenchmark and nothing
	// else -- and a column that also carried the component walk and the frustum
	// tests cannot answer it. It is a slice of CPUDrawList's old value rather
	// than work added beside it, so the phases still sum to the frame.
	CPUDrawSort
	// CPUCluster is binning the unshadowed lights into the froxel grid:
	// gathering them, culling them against the frustum, and filling the cells.
	//
	// It scales with the light count rather than with the scene, so it is the
	// phase that answers "what are those thousand lamps costing me on the CPU"
	// -- a question the GPU table cannot answer, since clustering is what
	// keeps the GPU cost from scaling with them at all.
	CPUCluster
	// CPUGPUWait is time blocked on the previous frame's fence and on acquiring
	// a swapchain image.
	//
	// The most useful number here. Large means the CPU is ahead and the GPU is
	// the limit — or, with vsync on, simply that the frame is being paced, which
	// is what a healthy capped frame looks like. Near zero while the frame is
	// long means the CPU is the limit and the rest of this table says where.
	CPUGPUWait
	// CPUSubmit is whatever else DrawFrame does: staged uploads, descriptor
	// writes, the submit call itself. Small when healthy; a large value means
	// per-frame work has crept in somewhere unattributed.
	CPUSubmit
	// CPURecord is building and submitting the command buffer. Genuine CPU work,
	// unlike the waits either side of it.
	CPURecord
	// CPUPresent is time inside QueuePresent, which with vsync on can block for
	// most of a frame. Split out from record because lumping the two together
	// reports a busy CPU on a frame that is only being paced.
	CPUPresent

	// CPULODCull and CPULODUpload measure CPU distance selection and buffer writes.
	CPULODCull
	CPULODUpload
)

func (CPUPhase) String

func (p CPUPhase) String() string

String is the label used in reports.

type CPUTimings

type CPUTimings struct {
	Phase [cpuPhaseCount]float32
	Total float32
	Valid bool
}

CPUTimings is one frame's CPU cost in milliseconds, per phase.

Total is the whole loop body measured directly, so it can be compared against the sum the same way GPUTimings.Total can. Unlike the GPU passes these run strictly in sequence, so a gap between total and sum is unmeasured work rather than overlap — which makes it a useful check that the phases still cover the loop after it is edited.

type Camera

type Camera struct {
	Target     mgl32.Vec3 // position to orbit around (set from player)
	LookOffset float32    // vertical offset above target for look-at point (pushes character down on screen)
	Yaw        float32    // radians, 0 = looking along -Z
	Pitch      float32    // radians, positive = eye above target, looking down
	Distance   float32    // orbit distance from target

	LookSensitivity float32 // radians per pixel of mouse delta
	EditorMode      bool    // when true, only right-drag orbits (left-click reserved for editor)

	// StickLookRate is radians per second at full thumbstick deflection, and
	// ZoomRate is orbit units per second at full trigger or bumper deflection.
	// Both are used by LookStick and ZoomBy.
	//
	// Rates, where LookSensitivity is a ratio: a mouse reports displacement since
	// last frame, a stick reports only how far it is pushed. Scaling a stick like
	// a mouse gives a camera that orbits faster the higher the frame rate.
	StickLookRate float32
	ZoomRate      float32
	// contains filtered or unexported fields
}

Camera is a third-person orbit camera that follows a target position.

func NewCamera

func NewCamera(distance float32) *Camera

NewCamera creates an orbit camera at the given distance behind the target.

func (*Camera) FirstPerson

func (c *Camera) FirstPerson() bool

FirstPerson returns true when the camera is in first-person mode.

func (*Camera) GetYaw

func (c *Camera) GetYaw() float32

GetYaw returns the camera yaw so player movement can be relative to camera facing.

func (*Camera) LookStick

func (c *Camera) LookStick(x, y, dt float32)

LookStick applies one frame of thumbstick orbit, in the convention Bindings.Direction returns: +x orbits right, +y raises the camera.

Call it alongside Update, not instead of it, so mouse drag and stick both work. dt is required because deflection is a rate; see StickLookRate.

func (*Camera) ResolveCollision

func (c *Camera) ResolveCollision(rc Raycaster, exclude ecs.Entity, dt float32)

ResolveCollision raycasts from the target toward the ideal eye position and pulls the camera forward if geometry blocks the line of sight. dt is the frame delta in seconds; the pull-in is fast and the ease-out is slow, so the camera snaps away from walls but drifts back smoothly.

func (*Camera) Update

func (c *Camera) Update(inp *input.Input)

Update processes mouse look (left- or right-click drag) and scroll zoom for one tick. Left-drag orbits and turns the character; right-drag orbits without turning.

func (*Camera) ViewVectors

func (c *Camera) ViewVectors() (eye, center, up mgl32.Vec3)

ViewVectors returns the eye, center, and up vectors for SetCamera.

func (*Camera) WasClick

func (c *Camera) WasClick(inp *input.Input) bool

WasClick returns true if the left mouse button was released without significant dragging, distinguishing a target-pick click from a camera-orbit drag.

func (*Camera) ZoomBy

func (c *Camera) ZoomBy(amount, dt float32)

ZoomBy changes the orbit distance at ZoomRate, for a trigger or bumper pair. Positive pulls the camera in.

Separate from the scroll wheel Update consumes, because a wheel delivers discrete notches already scaled per frame while a held button is a rate.

type CharacterController

type CharacterController struct {
	WalkSpeed float32 // world units per second
	RunSpeed  float32 // world units per second while MoveIntent.Sprint is set
	JumpSpeed float32 // upward velocity applied on a grounded jump
	TurnRate  float32 // radians per second applied by MoveIntent.Turn

	// Grounded reports whether the character was standing on something after
	// the last MoveCharacter call. Read-only for callers; games use it to
	// gate jump input and to select airborne animations.
	Grounded bool
}

CharacterController marks an entity as driven by MoveCharacter and holds its movement tuning. Entities with this component are skipped by IntegrateBodies — the controller does its own gravity, grounding, and swept collision.

func NewCharacterController

func NewCharacterController() CharacterController

NewCharacterController returns a controller with the engine's default tuning: 4/8 units per second walk/run, a 7 unit-per-second jump, and a ~200°/s keyboard turn rate.

type CharacterState

type CharacterState struct {
	Position mgl32.Vec3
	Rotation mgl32.Vec3
	Velocity mgl32.Vec3
	Grounded bool
}

CharacterState is everything MoveCharacter reads and writes for one character — and deliberately nothing else.

It exists for client-side prediction against an authoritative server: the client rewinds a character to the last state the server confirmed, then replays the inputs the server has not acknowledged yet. That works because MoveCharacter is a pure function of (state, intent, dt) plus the static world, so replaying the same intents from the same state reproduces the same result exactly.

This is not a save format and not a general scene snapshot. It captures one entity's movement state, ignores every other component, and will silently fail to preserve anything a game layers on top.

type Collider

type Collider struct {
	HalfExtents mgl32.Vec3
}

Collider is an ECS component that defines an axis-aligned bounding volume in local space via half-extents (half the width on each axis).

type Color

type Color struct {
	R, G, B float32
}

Color holds an RGB tint for an entity.

type Components

type Components struct {
	// Physics & spatial
	Transform           *ecs.Store[Transform]
	PrevTransform       *ecs.Store[PrevTransform]
	Velocity            *ecs.Store[Velocity]
	Collider            *ecs.Store[Collider]
	ConvexHullCollider  *ecs.Store[ConvexHullCollider]
	CharacterController *ecs.Store[CharacterController]
	Static              *ecs.Store[Static]

	// Animation & rendering
	AnimationState *ecs.Store[AnimationState]
	SkeletonRef    *ecs.Store[SkeletonRef]
	MeshRef        *ecs.Store[MeshRef]
	Water          *ecs.Store[Water]
	MaterialRef    *ecs.Store[MaterialRef]
	Color          *ecs.Store[Color]

	// Render flags
	Hidden        *ecs.Store[Hidden]
	Highlighted   *ecs.Store[Highlighted]
	DoubleSided   *ecs.Store[DoubleSided]
	Emissive      *ecs.Store[Emissive]
	Translucent   *ecs.Store[Translucent]
	InstancedMesh *ecs.Store[InstancedMesh]
	NoCastShadow  *ecs.Store[NoCastShadow]
}

Components holds the engine's typed component stores. Access via Scene.C (e.g. scene.C.Transform.Get(entity)).

This is deliberately only what the engine itself reads: spatial and physics queries, draw-list building, and animation sampling. Game-specific stores belong in a struct the game owns — the engine never sees them, so the engine/game boundary is enforced by the compiler rather than by convention.

func NewComponents

func NewComponents(w *ecs.World) *Components

NewComponents creates the engine component stores and registers them with the given World. Call once per World, before spawning any entities.

type ConvexHullCollider

type ConvexHullCollider struct {
	Vertices []mgl32.Vec3
	Faces    []HullFace
}

ConvexHullCollider is an ECS component that stores a convex hull in model-local space. Vertices are the hull points; Faces are triangulated with outward normals. The entity's Transform (position + Y rotation + uniform scale) is applied at runtime. The regular Collider (AABB) remains for broad-phase culling.

func ComputeConvexHull

func ComputeConvexHull(points [][3]float32) *ConvexHullCollider

ComputeConvexHull computes the convex hull of a 3D point cloud. Uses the quickhull-go library for a correct, closed mesh. Returns a ConvexHullCollider with hull vertices and triangulated faces.

func DeserializeHull

func DeserializeHull(data []byte) (*ConvexHullCollider, error)

DeserializeHull decodes a binary blob into a ConvexHullCollider. Face normals are recomputed from vertex positions.

type DirectionalLight

type DirectionalLight struct {
	// Direction points *toward* the light, matching DayNight.SunDir.
	Direction [3]float32
	Color     [3]float32
}

DirectionalLight is a fixed sun: one direction, one colour, no clock.

type DoubleSided

type DoubleSided struct{}

DoubleSided is a tag component that disables backface culling for this entity.

type Emissive

type Emissive struct{}

Emissive is a tag component that bypasses lighting (always full-bright).

type EmitterConfig

type EmitterConfig struct {
	// Spawning
	Spawn        SpawnMode
	SpawnRate    float32 // particles per second (continuous mode)
	BurstCount   int     // number of particles (burst mode)
	MaxParticles int

	// Lifetime
	LifeMin, LifeMax float32

	// Size
	SizeMin, SizeMax float32

	// Color ranges (random per particle at spawn)
	RMin, RMax float32
	GMin, GMax float32
	BMin, BMax float32

	// Movement
	Move           MoveMode
	InitialSpeedXZ float32 // half-range for random initial XZ velocity
	InitialSpeedY  float32 // half-range for random initial Y velocity
	MaxSpeed       float32
	TurbulenceXZ   float32 // per-second random velocity perturbation in XZ
	TurbulenceY    float32 // per-second random velocity perturbation in Y
	Gravity        float32 // downward acceleration (positive = down)
	RadialSpeed    float32 // outward speed for radial mode
	BounceAtBounds bool

	// Visuals
	Fade        FadeMode
	FadeInTime  float32
	FadeOutTime float32
	PulseSpeed  float32
	AlphaMax    float32

	// Conditions
	NightOnly bool
	NightMin  float32 // minimum nightFactor to be active

	// Lifecycle
	Loop bool // continuous emitters loop; one-shot burst emitters set Done when empty
}

EmitterConfig defines all behavior parameters for a particle emitter.

func FireflyConfig

func FireflyConfig() *EmitterConfig

FireflyConfig returns an emitter config matching the original hardcoded firefly behavior.

func SparkConfig

func SparkConfig() *EmitterConfig

SparkConfig returns an emitter config for fire spark particles.

func SpellImpactConfig

func SpellImpactConfig() *EmitterConfig

SpellImpactConfig returns an emitter config for a burst of spell impact particles.

type Engine

type Engine struct {
	*Scene
	// contains filtered or unexported fields
}

Engine owns the window, renderer, input, and frame loop, and drives a Scene. The embedded *Scene means engine.C, engine.Raycast, engine.Spawn and friends are reachable directly from a *Engine.

func New

func New(g Game, opts ...Option) (*Engine, error)

New creates the window, renderer, and input system, then calls g.Init so the game can build its scene. Call Destroy when Run returns.

func (*Engine) Alpha

func (e *Engine) Alpha() float32

Alpha returns how far the current frame sits between the last simulation tick and the next, in [0,1). Rendering uses it to blend transforms; games need it only for their own interpolation of non-Transform state.

func (*Engine) CPUTimings

func (e *Engine) CPUTimings() CPUTimings

CPUTimings returns the mean per-phase CPU cost in milliseconds.

Pair it with GPUTimings: together they say whether a frame is CPU-bound, GPU-bound, or simply paced by vsync, which the three look identical without.

func (*Engine) CameraEye

func (e *Engine) CameraEye() mgl32.Vec3

CameraEye returns the current camera eye position.

func (*Engine) Capabilities

func (e *Engine) Capabilities() renderer.Capabilities

Capabilities returns what the GPU and driver granted this renderer: the negotiated MSAA count, the anisotropy level, which optional features are present, and who the device is. Fixed once the engine is built.

Read it to choose between two techniques whose results are not the same picture — the engine has already taken every fallback that produces the same one, and says in here which it took. See renderer.Capabilities, renderer.ErrCapabilityUnavailable and docs/agents/game-loop.md.

func (*Engine) Close

func (e *Engine) Close()

Close signals the engine to shut down at the end of the current frame.

func (*Engine) CreateTerrainMesh

func (e *Engine) CreateTerrainMesh(h *Heightmap, opts *TerrainOptions) (*renderer.Mesh, error)

CreateTerrainMesh builds terrain geometry from a heightmap and uploads it to the GPU. The returned mesh is owned by the caller — pass it to a MeshRef and release it with Renderer.DestroyMesh.

func (*Engine) CreateWaterMesh

func (e *Engine) CreateWaterMesh(h *Heightmap, opts WaterOptions) (*renderer.Mesh, error)

CreateWaterMesh builds a water surface over the heightmap and uploads it.

Give the returned mesh to an entity with a Water component:

mesh, err := e.CreateWaterMesh(hm, opts)
ent := e.Spawn()
e.C.Transform.Set(ent, &glyph.Transform{Scale: mgl32.Vec3{1, 1, 1}})
e.C.MeshRef.Set(ent, &glyph.MeshRef{Mesh: mesh})
e.C.Water.Set(ent, &glyph.Water{Options: opts})
e.C.Static.Set(ent, &glyph.Static{})

With opts.Foam.Decay above zero the mesh also gets its foam target, laid over the same grid; the target is released with the mesh.

func (*Engine) Debugf

func (e *Engine) Debugf(format string, args ...any)

Debugf queues a line of text for the top-left corner of this frame.

e.Debugf("ToD %.4f", e.Scene.TimeOfDay())
e.Debugf("sun %+.4f", e.Scene.Environment().SunElevation)

Lines are cleared every frame, so calling it from Update or LateUpdate shows the current value and calling it from nowhere shows nothing. Order is call order, top to bottom.

It exists because the alternative is what this repo kept doing instead: screenshotting a frame that looks wrong and then guessing which time of day, sun elevation or setting produced it. A number in the corner turns "the glow lingers too long" into "the glow is still warm at sun -0.14", which is a bug report that can be acted on.

The font is Go Mono, generated on first use rather than loaded, so this needs no asset and no setup. Generation costs a few hundred milliseconds once; if that matters in a shipping build, do not call Debugf in one.

It draws over everything, in a channel of its own, so it neither disturbs nor is disturbed by SetMSDFOverlays.

func (*Engine) Destroy

func (e *Engine) Destroy()

Destroy runs the game's Shutdown hook, then releases renderer and window resources. Call once, after Run returns.

func (*Engine) Elapsed

func (e *Engine) Elapsed() float32

Elapsed returns the running SIMULATION time in seconds since Run started.

It is scaled by SetTimeScale: at scale 0 it stops, at 0.5 it advances at half the rate of the wall clock, and it can never be read as a wall-clock reading. That is deliberate -- it is the clock the shaders animate on, so pausing the game has to stop the grass moving -- but it used to be documented as wall-clock time, which is how a paused menu animation gets written against the wrong clock and then never runs.

For time that keeps going while the world is stopped, use UnscaledElapsed.

func (*Engine) FPS

func (e *Engine) FPS() float64

FPS returns a smoothed frames-per-second measurement.

func (*Engine) FogDensity

func (e *Engine) FogDensity() float32

FogDensity returns the current fog density.

func (*Engine) FrameCount

func (e *Engine) FrameCount() int

FrameCount returns the number of frames rendered so far, counted the same way WithMaxFrames counts them.

func (*Engine) GPUTimings

func (e *Engine) GPUTimings() renderer.GPUTimings

GPUTimings returns the most recent per-pass GPU cost in milliseconds.

Measured with timestamp queries on the GPU's own clock, so the numbers are real GPU time whether or not vsync is capping the frame. That is what makes them the right tool for deciding where rendering time goes: whole-frame timing has to run unlocked to show anything, and even then cannot say which pass to look at.

The reading is a couple of frames old — collecting a fresher one would need a pipeline flush, which would change what was being measured. Check Valid: it is false for the first frames and on devices without timestamp support.

func (*Engine) Input

func (e *Engine) Input() *input.Input

Input returns the input system.

func (*Engine) InterpolatedTransform

func (e *Engine) InterpolatedTransform(entity ecs.Entity) (Transform, bool)

InterpolatedTransform returns the transform an entity is being drawn at this frame — its last two tick transforms blended by Alpha.

Use it for anything that must line up with what is on screen, a camera above all. A first-person camera reading the raw Transform sits at the last simulated position while the world renders between ticks, so the view lurches at the tick rate even though everything else is smooth.

func (*Engine) LightStats

func (e *Engine) LightStats() lightcluster.Stats

LightStats reports what the last frame's light binning did.

Four of the fields are the ones a game should watch, because each is a way light can go missing that nothing else will report:

  • DroppedOverBudget: more lights passed the frustum test than renderer.MaxLights. The furthest-from-lighting-anything are dropped.
  • CellsOverflowed: a froxel wanted more lights than it can hold. It keeps the ones nearest the camera; the rest do not light that cell.
  • CellsTruncated: the whole index buffer filled up. Worse than an overflowed cell, because it takes whole cells in cell order rather than the tail of one list.
  • ScreenWideLights: lights that reached every tile of a slice. These are the ones clustering did not help with, so a scene where this grows is a scene drifting back towards the every-light loop.

The rest are for tuning the grid; see lightcluster.Stats.

func (*Engine) LogGPUTimings

func (e *Engine) LogGPUTimings()

LogGPUTimings prints one line per pass plus the measured frame total, averaged over every frame collected.

The passes are not expected to sum to the total. The GPU overlaps work across pass boundaries, and a gap between two passes belongs to neither, so a total well above the sum is a bubble worth knowing about rather than an error.

func (*Engine) LogPipelineStats

func (e *Engine) LogPipelineStats()

LogPipelineStats prints the fragment-shader invocations and post-clip primitives per pass, averaged over every frame collected, and says nothing at all on a build that is not recording them.

Only the passes with something in them are printed, because sixteen rows of zeroes buries the two that matter. The header says how many frames the mean covers and names the counter's open question, so a number copied out of this block carries the caveat with it rather than leaving it behind in a document.

Every application row is printed, including the ones with no number, and that asymmetry is deliberate: an engine pass is always there and a zero on it says "shaded nothing", while an application row's absence of a number is the information -- a dispatch that cannot be counted, or a pass that was off when the frame was recorded. A row omitted would read as a pass that costs nothing.

func (*Engine) LogTimings

func (e *Engine) LogTimings()

LogTimings prints the CPU and GPU breakdowns together, which is the only way to read either of them.

A frame that is slow with a large gpuwait is GPU-bound or vsync-paced; the GPU table says which pass. A frame that is slow with gpuwait near zero is CPU-bound and the GPU table is a distraction. Printing one without the other invites exactly the wrong conclusion.

func (*Engine) LogTimingsTSV

func (e *Engine) LogTimingsTSV(label string)

LogTimingsTSV prints one tab-separated line of every timing, for collecting runs into a table.

Deliberately one line rather than the human-readable block: a benchmark comparing twelve scenes wants columns it can align, and a format that survives being pasted into a spreadsheet or diffed between commits.

func (*Engine) MSDFOverlays

func (e *Engine) MSDFOverlays() []renderer.RenderObject

MSDFOverlays returns the current MSDF text overlay render objects.

func (*Engine) MeanGPUTimings

func (e *Engine) MeanGPUTimings() renderer.GPUTimings

MeanGPUTimings averages every frame measured so far; see Renderer.MeanGPUTimings.

func (*Engine) MeanPipelineStats

func (e *Engine) MeanPipelineStats() (renderer.PipelineStats, error)

MeanPipelineStats averages every frame collected so far; see Renderer.MeanPipelineStats. Prefer it over PipelineStats for any comparison.

func (*Engine) Paused

func (e *Engine) Paused() bool

Paused reports whether the simulation clock is stopped.

func (*Engine) PickEntity

func (e *Engine) PickEntity(screenX, screenY float64, maxDist float32, exclude ecs.Entity) (RayHit, bool)

PickEntity casts a ray from a screen-space mouse position into the world and returns the nearest collider hit within maxDist.

func (*Engine) PipelineStats

func (e *Engine) PipelineStats() (renderer.PipelineStats, error)

PipelineStats returns the most recent per-pass fragment-invocation and post-clip primitive counts; see renderer.PipelineStats for what the fragment counter includes, which is implementation-defined and has to be established before a ratio taken from it means anything.

The error is renderer.ErrStatisticsNotEnabled without WithPipelineStatistics and wraps renderer.ErrCapabilityUnavailable on a device without the feature.

func (*Engine) Renderer

func (e *Engine) Renderer() *renderer.Renderer

Renderer returns the Vulkan renderer.

func (*Engine) ResetTimings

func (e *Engine) ResetTimings()

ResetTimings discards the CPU, GPU and pipeline-statistics accumulated means, for measuring one phase of a run without its startup frames.

All three, because they are read together: a mean invocation count over frames the mean gpu_opaque does not cover is a ratio of two different runs.

func (*Engine) Run

func (e *Engine) Run()

Run enters the main loop. Each frame, in order:

  1. poll input
  2. Game.Update - frame delta; sample input, latch edges
  3. Scene.Tick + FixedUpdate - tick delta, zero or more times
  4. TickAnimations - frame delta
  5. Game.LateUpdate - frame delta; final transforms and poses
  6. render

It returns when the window closes or the WithMaxFrames budget is spent.

Frame pacing belongs to the presentation engine, not to this loop. With vsync on (the default) the swapchain blocks at the refresh rate of whatever display the window is on; with it off the loop runs unbounded. There is deliberately no software frame limiter here — see WithVSync.

func (*Engine) ScreenRay

func (e *Engine) ScreenRay(screenX, screenY float64) (origin, dir mgl32.Vec3)

ScreenRay converts a screen-space position in pixels into a world-space ray.

func (*Engine) SetCamera

func (e *Engine) SetCamera(eye, center, up mgl32.Vec3)

SetCamera sets the camera eye, center, and up vectors used for rendering. Both Camera and FPCamera return these three from ViewVectors.

func (*Engine) SetLightDebugMode

func (e *Engine) SetLightDebugMode(mode LightDebugMode)

SetLightDebugMode selects how the fragment shader evaluates the light list: normal, the per-cell light-count heatmap, or the brute-force reference path. See LightDebugMode.

func (*Engine) SetMSDFOverlays

func (e *Engine) SetMSDFOverlays(objs []renderer.RenderObject)

SetMSDFOverlays sets the MSDF text overlay render objects.

func (*Engine) SetOverlays

func (e *Engine) SetOverlays(overlays []renderer.RenderObject)

SetOverlays sets the overlay render objects drawn on top of the 3D scene.

func (*Engine) SetShadowCoverage

func (e *Engine) SetShadowCoverage(coverage renderer.ShadowCoverage) error

SetShadowCoverage sets directional shadow volumes without reallocating maps. Call on the frame thread (Init or Update). Invalid input leaves the previous setting intact; zero restores the historical defaults. The setting belongs to Engine, so swapping Scene preserves it, like other renderer settings.

The coverage must describe as many cascades as WithShadowCascades allocated: a count that disagrees is refused like any other invalid input. The zero value is renderer.DefaultShadowCoverageFor that count.

func (*Engine) SetTimeScale

func (e *Engine) SetTimeScale(s float32)

SetTimeScale multiplies the rate of the simulation clock.

1 is real time. 0 pauses: Scene.Tick and FixedUpdate stop being called, animation stops advancing, and the wind and waves stop moving. Values between run slow motion, and above 1 runs fast — a difficulty setting, a bullet-time effect, or stepping through a bug at a tenth speed.

func (g *game) Update(e *glyph.Engine, dt float32) {
    if e.Input().KeyPressed(input.KeyEscape) {
        g.paused = !g.paused
        if g.paused {
            e.SetTimeScale(0)
        } else {
            e.SetTimeScale(1)
        }
    }
}

What keeps running is everything a paused game needs to still be a program: Update, LateUpdate, and rendering. They receive the real frame delta, not the scaled one, so a menu animates and a camera moves at full speed while the world behind them is stopped. A game that wants its camera slowed too can multiply by TimeScale itself.

Pausing is not something a game can do for itself. Returning early from FixedUpdate stops the game's own simulation and none of the engine's: rigid bodies keep integrating, character controllers keep moving, the transform snapshots interpolation reads keep being taken, and animation keeps playing. A game with no physics and no skinned meshes gets away with it by luck.

Negative values are clamped to zero. Running a fixed-timestep simulation backwards is not a thing this engine can do — the integrator is not reversible — and the useful reading of a negative scale is "stopped".

func (*Engine) SetUIOverlays

func (e *Engine) SetUIOverlays(objs []renderer.UIRenderObject)

SetUIOverlays sets the UI panel render objects (alpha-blended, textured 9-slice).

func (*Engine) TickAnimations

func (e *Engine) TickAnimations(dt float32)

TickAnimations advances and uploads skeletal animations for every animated entity. dt is the real frame delta: animation is sampled once per rendered frame rather than per simulation tick, so poses stay smooth independently of the tick rate.

func (*Engine) TimeScale

func (e *Engine) TimeScale() float32

TimeScale returns the current simulation rate; see SetTimeScale.

func (*Engine) UIOverlays

func (e *Engine) UIOverlays() []renderer.UIRenderObject

UIOverlays returns the current UI panel render objects.

func (*Engine) UnscaledElapsed

func (e *Engine) UnscaledElapsed() float32

UnscaledElapsed returns the running wall-clock time in seconds since Run started, unaffected by SetTimeScale.

This is the clock anything that must keep moving while the game is paused runs on: a modal fading in, a menu sliding, a spinner on a loading screen. Elapsed cannot serve them, because a game pauses by setting the scale to 0 and a transition driven off Elapsed then never finishes -- a dialog that opens only when the game is running is a dialog that never opens.

tree.SetTime(e.UnscaledElapsed())   // ui/yamlui transitions

Under WithFixedFrameTime (or GLYPHENGINE_FIXED_FRAME_TIME) it advances by the fixed delta, exactly as Elapsed does before scaling, so a transition lands on the same frame in every run and a capture of it is comparable.

func (*Engine) ViewProjection

func (e *Engine) ViewProjection() mgl32.Mat4

ViewProjection returns the current view-projection matrix.

func (*Engine) Window

func (e *Engine) Window() *window.Window

Window returns the underlying window.

type Entity

type Entity = ecs.Entity

Entity is a handle to a thing in the world.

Aliased from the ecs package so a game that only touches the engine's own API does not have to import ecs for a single type. It is the same type, so the two are interchangeable wherever both are in scope.

type EnvironmentSource

type EnvironmentSource interface {
	// Advance moves the environment forward on the simulation tick. It runs
	// at the fixed rate, so anything driven from it is frame-rate independent.
	// Implementations with nothing to advance can leave it empty.
	Advance(dt float32)

	// State returns the current environment. It is called once per rendered
	// frame and must not mutate anything — Advance is where change belongs.
	State() EnvironmentState
}

EnvironmentSource supplies the sky, the light, and the air for a frame.

The engine holds one of these on the Scene and asks it for state each frame. That makes the whole environment replaceable: a game that wants weather, scripted lighting, an interior, or a sky that owes nothing to a sun can implement this and plug it in, without the engine needing to know.

type stormy struct{ intensity float32 }

func (s *stormy) Advance(dt float32) { s.intensity = ... }

func (s *stormy) State() EnvironmentState {
    return glyph.EnvironmentState{
        SunDir:     [3]float32{0.3, 0.5, 0.2},
        SunColor:   [3]float32{0.35, 0.36, 0.40},
        Ambient:    [3]float32{0.10, 0.11, 0.13},
        FogDensity: 0.02 + s.intensity*0.05,
        DrawSky:    true,
    }
}

scene.Env = &stormy{}

This governs the values. What *draws* a dome, stars or clouds from them is the sky slot in renderer.ShaderSet, supplied through renderer.WithShaders — the two are deliberately separate, so a custom sky does not force a custom lighting model or the reverse. The engine ships neither half: x/sky is the built-in Earth sky, and it is both a source and the three shaders.

type EnvironmentState

type EnvironmentState struct {
	// SunDir points *toward* the directional light. SunColor is its colour;
	// black means no directional light at all.
	SunDir   [3]float32
	SunColor [3]float32

	// RealSunDir points toward the real sun, and SunElevation is its height,
	// -1 to 1. Together they are what the atmosphere derives its palette and
	// its scattering from.
	//
	// They are separate from SunDir because SunDir is whichever body is
	// currently lighting the scene. At night that is the moon, which rides
	// highest exactly when the sky should be darkest, so driving the sky from
	// the light direction paints a noon sky at midnight — and hangs the warm
	// sunset halo on the moon, which is the other half of the same mistake.
	//
	// SunElevation is RealSunDir's y. It stays a separate field because most
	// of the atmosphere only needs the height, and because a fixed sun can set
	// an elevation for the sky without the two having to agree.
	RealSunDir   [3]float32
	SunElevation float32

	// Ambient is uniform fill light.
	Ambient [3]float32

	// FogDensity blends distant geometry toward the horizon colour. Zero
	// disables it.
	FogDensity float32

	// FogHeight and FogBaseHeight describe the vertical falloff; see Fog.
	// A zero FogHeight selects uniform density.
	FogHeight     float32
	FogBaseHeight float32

	// ClearColor is used when DrawSky is false. With a sky it is unused: the
	// dome is opaque and drawn first.
	ClearColor [3]float32

	// StarFade is how visible the stars are, 0 to 1.
	StarFade float32

	// MilkyWay is the galactic band's strength, 0 to 1. The star pass reads it;
	// what it means is the source's, not the engine's.
	MilkyWay float32

	// StarDensity scales the star count, 1 being whatever the star shader calls
	// its own default and 0 leaving an empty sky.
	StarDensity float32

	// DrawSky draws the procedural dome. DrawStars, DrawSun and DrawMoon add
	// the stars and the celestial billboards.
	DrawSky   bool
	DrawStars bool
	DrawSun   bool
	DrawMoon  bool

	// SunDiscDir and SunDiscColor place and colour the sun billboard;
	// MoonDiscDir and MoonDiscColor do the same for the moon. Ignored unless
	// DrawSun/DrawMoon.
	//
	// Both colours arrive with their horizon fade and their brightness boost
	// already applied, because a disc is a light source rather than a surface
	// and how bright it is at a given elevation is a look. The moon's used to
	// be three constants and a fade inside buildMoonObject, which left the
	// engine owning a colour after the environment was meant to own all of
	// them: a replacement sky could move the moon and not tint it.
	SunDiscDir    [3]float32
	SunDiscColor  [3]float32
	MoonDiscDir   [3]float32
	MoonDiscColor [3]float32

	// CloudSteps is the volumetric cloud sample count; zero disables cumulus.
	CloudSteps int

	// Cirrus is the high, thin cloud layer strength, 0 to 1. Zero disables it.
	// Independent of CloudSteps.
	Cirrus float32

	// LightShafts is the god-ray strength; zero disables them. It carries the
	// fade with the sun disc's elevation already applied, so a sun on its way
	// down arrives here weaker rather than being cut off at the horizon.
	LightShafts float32

	// LightShaftShape is the shape the source asked the shaft pass for, passed
	// through untouched. Zero fields mean the engine's defaults; see
	// LightShaftShape.
	LightShaftShape LightShaftShape

	// CastShadows enables the shadow pass. Turning it off when the only light
	// is a dim moon saves the cascades for shadows nobody can see.
	CastShadows bool

	// SkyPalette is the six colours the dome, the fog and the water's
	// reflection all blend between; NightGrade is the scotopic grade lit
	// surfaces take on as daylight goes. Both are here because the fog, the
	// water and the clouds read them every frame, so a source that replaces the
	// sky has to be able to say what colour the air is -- otherwise an alien
	// sky still hazes into Earth-blue.
	//
	// An all-zero value means "the scene's", which Scene.SetSkyPalette and
	// Scene.SetNightGrade write and NewScene initialises to the engine's
	// defaults. That sentinel is what makes these safe to have here at all: a
	// source written before the field existed returns the zero value and its
	// sky, haze and water stay exactly as they were, instead of the six black
	// endpoints a plain value field would have handed them. Scene.Environment
	// is the one place it is resolved.
	//
	// The cost is two values that cannot be asked for: a palette of six exact
	// blacks, and a grade with Strength 0 *and* a zero Tint. For a night with
	// no scotopic shift set Strength 0 and any tint -- the tint is unread at
	// zero strength -- and for a black world set Sky nil and ClearColor black,
	// which is what an empty environment already means.
	SkyPalette SkyPalette
	NightGrade NightGrade
}

EnvironmentState is the per-frame contract between an environment and the renderer. Its zero value is an empty world: no sky, no light, no fog.

type FPCamera

type FPCamera struct {
	// Target is the position the eye is anchored to, normally the character's
	// Transform.Position. Set it with Follow.
	Target mgl32.Vec3

	// EyeHeight raises the eye above Target — roughly the character's eye
	// level above its origin.
	EyeHeight float32

	Yaw   float32 // radians, 0 = looking along -Z
	Pitch float32 // radians, positive = looking down

	// LookSensitivity is radians of rotation per pixel of mouse movement.
	LookSensitivity float32

	// StickLookRate is radians per second at full thumbstick deflection, used by
	// LookStick.
	//
	// It is a rate where LookSensitivity is a ratio, and that difference is the
	// whole reason the two are separate numbers. A mouse reports how far it moved
	// since the last frame, so the frame's displacement is already the answer. A
	// stick reports how far it is pushed, which says nothing about how long it has
	// been pushed — turning that into rotation needs dt. Treating a stick like a
	// mouse gives a camera that spins faster the higher the frame rate.
	StickLookRate float32

	// InvertY flips vertical look, for both mouse and stick.
	InvertY bool

	// MaxPitch clamps how far up and down the camera can look, in radians.
	// Zero means just under a right angle, which avoids gimbal flip at
	// straight up and straight down.
	MaxPitch float32
}

FPCamera is a first-person camera: the eye sits at the target position plus EyeHeight and looks along Yaw/Pitch. It shares the orbit Camera's angle convention — yaw 0 looks down -Z, positive pitch looks down — so MoveIntent.Yaw can be fed from either camera unchanged.

func NewFPCamera

func NewFPCamera() *FPCamera

NewFPCamera returns a first-person camera with sensible defaults: a 1.6 unit eye height and the same look sensitivity as the orbit camera.

func (*FPCamera) Eye

func (c *FPCamera) Eye() mgl32.Vec3

Eye returns the world-space eye position.

func (*FPCamera) Follow

func (c *FPCamera) Follow(t *Transform)

Follow anchors the camera to an entity transform.

func (*FPCamera) Forward

func (c *FPCamera) Forward() mgl32.Vec3

Forward returns the normalized look direction.

func (*FPCamera) GetYaw

func (c *FPCamera) GetYaw() float32

GetYaw returns the camera yaw, for use as MoveIntent.Yaw.

func (*FPCamera) LookStick

func (c *FPCamera) LookStick(x, y, dt float32)

LookStick applies one frame of thumbstick look, in the same convention Bindings.Direction returns: +x turns right, +y looks up.

Call it alongside Update rather than instead of it. Update handles the mouse and LookStick handles the stick, so both work at once and a player can reach for either without the game switching modes.

dt is required because deflection is a rate; see StickLookRate.

func (*FPCamera) Update

func (c *FPCamera) Update(inp *input.Input)

Update applies mouse movement to yaw and pitch. It only looks when the cursor is locked, so a game can release the cursor for menus by calling inp.SetCursorLocked(false) and the camera holds still.

func (*FPCamera) ViewVectors

func (c *FPCamera) ViewVectors() (eye, center, up mgl32.Vec3)

ViewVectors returns the eye, look-at center, and up vectors for Engine.SetCamera.

type FadeMode

type FadeMode uint8

FadeMode controls how particle alpha changes over lifetime.

const (
	FadePulse FadeMode = iota // sinusoidal pulsing with fade in/out
	FadePlain                 // linear fade in and fade out
	FadeFlash                 // instant bright, rapid quadratic decay
)

type FixedUpdateGame

type FixedUpdateGame interface {
	FixedUpdate(e *Engine, dt float32)
}

FixedUpdateGame is an optional Game interface. FixedUpdate runs on the fixed simulation tick, immediately after Scene.Tick, with the tick delta — never the frame delta. Put anything that must be deterministic here: character movement, physics-driven gameplay, anything a server also simulates.

It runs zero, one, or several times per frame depending on how the frame rate divides into the tick rate. On a 144Hz display against a 60Hz tick, roughly 59% of frames run no tick at all.

That is why input must not be read here. A KeyPressed edge inside FixedUpdate is silently dropped on a zero-tick frame and fired twice on a two-tick frame. Sample input in Update, latch the edges, and consume the latch here:

func (g *game) Update(e *glyphengine.Engine, dt float32) {
	g.intent.Right, g.intent.Forward = g.binds.Direction(g.move)
	if g.binds.Pressed(g.jump) {
		g.jumpQueued = true // latch the edge
	}
}

func (g *game) FixedUpdate(e *glyphengine.Engine, dt float32) {
	intent := g.intent
	intent.Jump = g.jumpQueued
	g.jumpQueued = false // consume exactly once
	e.MoveCharacter(g.player, intent, dt)
}

type Fog

type Fog struct {
	// Density in inverse world units. Around 0.008 fades over a few hundred
	// units; zero is the same as no Fog at all.
	Density float32

	// Height is the altitude over which density falls to 1/e of its value at
	// BaseHeight. Zero means uniform fog at every altitude.
	//
	// Real fog settles, and a uniform one cannot express that at any density:
	// a valley floor has the same haze as the ridge above it, so nothing reads
	// as low-lying. With a Height set, mist pools in the low ground and peaks
	// rise out of it.
	//
	// Sensible values are on the order of the terrain's vertical scale — a
	// Height of 8 over a 15-unit landscape puts most of the fog in the bottom
	// third of it.
	Height float32

	// BaseHeight is the world Y at which density equals Density. Above it fog
	// thins, below it thickens. Usually the ground or water level.
	BaseHeight float32
}

Fog blends geometry toward the horizon colour with distance.

type Frustum

type Frustum = renderer.Frustum

Frustum holds the six clip planes extracted from a view-projection matrix. The implementation lives in the renderer package so command recording can cull GPU work (grass tiles, point-light shadow faces) without importing engine.

func ExtractFrustum

func ExtractFrustum(vp mgl32.Mat4) Frustum

ExtractFrustum extracts 6 normalized clip planes from a view-projection matrix using the Gribb-Hartmann method.

type Game

type Game interface {
	Init(e *Engine) error
	Update(e *Engine, dt float32)
}

Game is implemented by the game to set up its scene and run per-frame logic.

Init runs once, after the window and renderer exist and before the first frame. Update runs once per rendered frame with the real frame delta in seconds, which makes it the only correct place to read input: GLFW events are polled per frame, so edge-triggered queries like KeyPressed are meaningful exactly once per frame.

Implement the optional interfaces below for fixed-timestep simulation, post-simulation work, shutdown, and resize.

type Heightmap

type Heightmap struct {
	GridW, GridH     int
	WorldW, WorldD   float32 // total world-space dimensions
	OriginX, OriginZ float32 // world-space origin (min corner)
	Heights          []float32
}

Heightmap stores a grid of height values for terrain collision. Heights are indexed [z*GridW + x] in row-major order.

func LoadHeightmap

func LoadHeightmap(fsys fs.FS, name string) (*Heightmap, error)

LoadHeightmap reads a .heightmap binary file from fsys.

Format: gridW(u32) gridH(u32) worldW(f32) worldD(f32) originX(f32) originZ(f32) then gridW*gridH little-endian f32 heights.

func NewHeightmap

func NewHeightmap(gridW, gridH int, worldW, worldD, originX, originZ float32, heights []float32) (*Heightmap, error)

NewHeightmap wraps an existing grid of heights, which must hold exactly gridW*gridH values in row-major order ([z*gridW + x]). The grid covers the world-space rectangle from (originX, originZ) to (originX+worldW, originZ+worldD).

This is the constructor for procedurally generated terrain; LoadHeightmap reads the same structure from a file.

func (*Heightmap) Bounds

func (h *Heightmap) Bounds() (minX, minZ, maxX, maxZ float32)

Bounds returns the world-space extent covered by the heightmap.

func (*Heightmap) HeightAt

func (h *Heightmap) HeightAt(x, z float32) (float32, bool)

HeightAt returns the interpolated terrain height at world position (x, z). Points outside the heightmap return -infinity (no ground).

func (*Heightmap) HeightAtRayDown

func (h *Heightmap) HeightAtRayDown(originX, originY, originZ, maxDist float32) (dist float32, hitY float32, ok bool)

HeightAtRayDown performs a downward raycast against the heightmap. Returns the distance along the ray and the hit Y position, or false if no hit.

func (*Heightmap) NormalAt

func (h *Heightmap) NormalAt(x, z float32) [3]float32

NormalAt computes an approximate surface normal at world position (x, z) using central differences.

func (*Heightmap) WriteTo

func (h *Heightmap) WriteTo(w io.Writer) (int64, error)

WriteTo writes h in the format LoadHeightmap reads: gridW(u32) gridH(u32) worldW(f32) worldD(f32) originX(f32) originZ(f32), then gridW*gridH little-endian f32 heights in row-major order ([z*gridW+x]). It is LoadHeightmap run backwards, so a tool or a game-side generator that wants to persist a Heightmap has exactly one encoder to share rather than each reimplementing this layout.

This is (*Heightmap).WriteTo rather than a path-taking SaveHeightmap: LoadHeightmap takes an fs.FS because the engine has no business choosing where a file lives, and the same reasoning applies on the way out -- io.WriterTo lets a caller hand it an *os.File, a bytes.Buffer, or anything else that implements io.Writer.

type Hidden

type Hidden struct{}

Hidden is a tag component that prevents an entity from being rendered.

type Highlighted

type Highlighted struct{}

Highlighted is a tag component that additively brightens an entity's color.

type HullColliderInfo

type HullColliderInfo struct {
	Hull      *ConvexHullCollider
	Transform *Transform
}

HullColliderInfo pairs a hull with its transform for NavGrid building.

type HullFace

type HullFace struct {
	A, B, C int        // indices into Vertices
	Normal  mgl32.Vec3 // precomputed outward unit normal
}

HullFace is a single triangulated face of the convex hull.

type InstancedMesh

type InstancedMesh struct {
	Set *renderer.InstanceSet
	LOD *renderer.InstanceSetLOD // mutually exclusive with Set; per-placement culling and distance levels
}

InstancedMesh draws one mesh at many placements in a single draw call.

It is for the case a builder-style game hits early: 900 identical habitat domes are 900 draw calls of a 200-triangle mesh on the ordinary MeshRef path — no GPU cost worth the name, and all of the cost in CPU-side command recording. One InstancedMesh is one CmdDrawIndexed, one push-constant upload and one frustum test, however many placements it holds.

set, err := e.Renderer().CreateInstanceSet(domeMesh, 1000, placements)
colony := e.Spawn()
e.C.InstancedMesh.Set(colony, &glyph.InstancedMesh{Set: set})

The entity needs no Transform: every placement carries its own model matrix, which is what separates this from merging props into one mesh per chunk. Add a placement with Renderer.UpdateInstanceSet rather than rebuilding geometry.

Color on the entity tints the whole set; MeshInstance.Tint tints one placement. Emissive, DoubleSided and NoCastShadow all apply to the set as a whole. Translucent does not — there is no blended instanced pipeline, and the set stays opaque rather than silently losing its placements.

Set culls as one group; LOD culls each placement and selects distance levels. See docs/agents/instancing.md and docs/agents/lod-instancing.md for the costs.

type LateUpdateGame

type LateUpdateGame interface {
	LateUpdate(e *Engine, dt float32)
}

LateUpdateGame is an optional Game interface. LateUpdate runs once per frame with the frame delta, after every fixed tick and after animation sampling — so it sees final transforms and final poses for this frame.

This is where a camera follows its target. Following in Update instead would read positions from before this frame's simulation, leaving the camera a tick behind whatever it is tracking.

type LightDebugMode

type LightDebugMode int

LightDebugMode selects what the fragment shader does with the clustered light data; see Engine.SetLightDebugMode.

const (
	// LightDebugOff renders normally: every fragment evaluates the lights its
	// froxel lists, which is the path games ship.
	LightDebugOff LightDebugMode = iota
	// LightDebugHeatmap replaces the lit colour with a ramp of each fragment's
	// cluster cell light count, for inspecting how lights distribute across
	// the grid.
	LightDebugHeatmap
	// LightDebugBruteForce forces the reference loop-every-light path
	// regardless of the cluster grid.
	//
	// It is the same lights in the same order as the clustered path -- only
	// the iteration differs -- so the two must render pixel for pixel alike,
	// and `task lights` requires exactly that. A difference between them is a
	// binning bug and nothing else, which is what makes this worth carrying in
	// the shipped shader rather than in a test build.
	LightDebugBruteForce
)

type LightShaftShape

type LightShaftShape struct {
	// Radius is how far from the sun the shafts reach, in screen heights.
	// Default 0.90. Wider reaches further and starts to haze ground a few
	// metres from the eye: the pass has no depth buffer, and distance from the
	// sun on screen is what stands in for it.
	Radius float32

	// Decay is the weight each of the 48 steps toward the sun keeps from the
	// one before, in (0, 1]. Default 0.96. Lower gives an occluder a harder
	// streak and the shafts less reach; 1 is an even wash.
	Decay float32

	// Threshold is the linear-luminance window a pixel has to clear to count as
	// a source, as {low, high}. Default {0.62, 0.88}: on the default palette
	// that admits cloud, the sunset glow and the disc, and rejects plain sky
	// and everything on the ground. A palette with a much brighter sky wants it
	// raised, or the whole dome smears into itself; a much dimmer one wants it
	// lowered, or nothing clears it and the pass draws nothing. {0, 0} is the
	// default -- for a window that really starts at zero, give high a value.
	Threshold [2]float32
}

LightShaftShape tunes the look of the light shafts: how far they reach, how hard a streak an occluder casts, and what counts as bright enough to be a source. Each field's zero value keeps the engine's default for that field, so a game sets the one it cares about:

sky.LightShaftShape.Radius = 1.2 // reach further across the frame

The defaults were measured on the default sky at dusk (the tables are beside the constants in renderer/commands.go). They are defaults and not constants because they are a look, and because Threshold in particular is a statement about how bright the sky is -- which, since SetSkyPalette, is the game's to decide.

func DefaultLightShaftShape

func DefaultLightShaftShape() LightShaftShape

DefaultLightShaftShape is the shape a zero LightShaftShape resolves to, spelled out for a game that wants to start from the numbers.

type MaterialRef

type MaterialRef struct {
	// PBR routes the entity through the material pipeline: albedo plus normal,
	// metallic-roughness, and occlusion maps. Build one with
	// Renderer.CreateMaterial. It takes precedence over Texture, whose job the
	// material's own albedo slot does.
	//
	// MeshRef.Metallic and .Roughness still apply — the maps multiply them, so
	// they keep working as per-object factors.
	//
	// Ignored on skinned meshes; see renderer.RenderObject.Material.
	PBR *renderer.Material

	// Texture is a single albedo map, lit as one uniform material.
	Texture *renderer.Texture

	// Terrain routes the entity through the terrain splat pipeline
	// (multi-texture blend) instead of the single-texture lit pipeline.
	Terrain *renderer.TerrainMaterial
}

MaterialRef links an entity to the GPU resources that describe its surface. Exactly one of the three is used, in the order they are listed here.

type MeshRef

type MeshRef struct {
	Mesh      *renderer.Mesh
	Metallic  float32 // 0 = dielectric, 1 = metal (from glTF PBR)
	Roughness float32 // 0 = mirror, 1 = matte (from glTF PBR)
}

MeshRef links an entity to a GPU mesh resource.

type MoveBatchEntry

type MoveBatchEntry struct {
	Entity ecs.Entity
	Intent MoveIntent
}

MoveBatchEntry pairs a character entity with one frame of input.

type MoveIntent

type MoveIntent struct {
	// Forward and Right are movement on the XZ plane in [-1, 1], relative to
	// Yaw.
	//
	// The magnitude scales speed, so a thumbstick at a third of its travel walks
	// at a third of WalkSpeed. Digital sources pass ±1 and get full speed;
	// diagonals are clamped to unit length, so holding two keys is not faster
	// than holding one.
	Forward float32
	Right   float32

	// Turn rotates the character in place at CharacterController.TurnRate,
	// in [-1, 1], positive turning right. Non-zero Turn also makes Forward and
	// Right relative to the character's new facing rather than to Yaw, so
	// keyboard turning and camera-relative movement compose.
	Turn float32

	// Yaw is the reference heading in radians that Forward and Right are
	// relative to — normally the camera yaw.
	Yaw float32

	// Sprint selects RunSpeed instead of WalkSpeed.
	Sprint bool

	// Jump applies JumpSpeed when the character is grounded.
	Jump bool

	// SpeedScale multiplies the final horizontal speed, for game-side effects
	// like haste buffs, snares, or roots. Zero is treated as 1.
	SpeedScale float32
}

MoveIntent is one frame of movement input for a character. It is deliberately device- and network-agnostic: a keyboard, a gamepad, an AI controller, or a decoded network packet all produce the same struct.

type MoveMode

type MoveMode uint8

MoveMode controls particle movement behavior.

const (
	MoveDrift   MoveMode = iota // random walk with turbulence
	MoveGravity                 // upward burst, falls back down
	MoveRadial                  // expand outward from center
)
type NavGrid struct {
	Width, Height int
	CellSize      float32
	OriginX       float32
	OriginZ       float32
	Walkable      []bool
}

NavGrid is a walkability grid derived from the heightmap and scene colliders. Cells are indexed [z*Width + x].

func BuildNavGrid

func BuildNavGrid(hm *Heightmap, colliders []AABB, hulls []HullColliderInfo, cellSize float32, slopeThreshold float32) *NavGrid

BuildNavGrid creates a NavGrid from a heightmap and scene collider AABBs. slopeThreshold is the minimum Y-component of the surface normal for a cell to be walkable (0.707 ~ 45 degrees). Cells overlapping any collider AABB are blocked.

func (g *NavGrid) FindPath(fx, fz, tx, tz float32, maxNodes int) []Vec2

FindPath finds a path from (fx, fz) to (tx, tz) using A* with 8-connected neighbors. maxNodes caps the number of nodes expanded to prevent runaway searches. Returns nil if no path exists or the budget is exceeded.

func (g *NavGrid) GridToWorld(gx, gz int) (float32, float32)

GridToWorld converts grid cell indices to world XZ center coordinates.

func (g *NavGrid) IsWalkable(gx, gz int) bool

IsWalkable returns whether grid cell (gx, gz) is walkable.

func (g *NavGrid) SmoothPath(path []Vec2) []Vec2

SmoothPath removes redundant intermediate waypoints using line-of-sight checks.

func (g *NavGrid) WalkableCount() int

WalkableCount returns the number of walkable cells (for logging).

func (g *NavGrid) WorldToGrid(x, z float32) (int, int)

WorldToGrid converts world XZ coordinates to grid cell indices.

type NightGrade

type NightGrade struct {
	// Strength 0 turns the shift off completely, leaving night dim but
	// otherwise ungraded.
	Strength float32
	Tint     mgl32.Vec3
}

NightGrade is the colour grade lit surfaces take on as daylight goes: the scotopic shift that stops a night scene being a dimmed day scene. Strength is how far a surface with no lamp on it goes toward that grade at full night, and Tint is what its luminance is multiplied by to get there — blue-biased, because rods are.

These are look decisions, not physics. The defaults are what this engine has always used and are documented in docs/agents/day-night.md; a game with a different artistic direction is meant to change them rather than vendor the lighting chain to get at two constants.

func DefaultNightGrade

func DefaultNightGrade() NightGrade

DefaultNightGrade is the grade every scene had before it was tunable.

type NoCastShadow

type NoCastShadow struct{}

NoCastShadow is a tag component that excludes an entity from the shadow pass. The entity still receives shadows but does not cast them.

type Option

type Option func(*config)

Option configures an Engine at construction.

func WithAppTimingCapacity

func WithAppTimingCapacity(count int) Option

WithAppTimingCapacity sets the named application GPU timing budget. Zero keeps sixteen; the maximum is renderer.MaxAppTimingCapacity.

func WithApplicationName

func WithApplicationName(name string, major, minor, patch int) Option

WithApplicationName overrides the application name and version reported to Vulkan, which otherwise default to the window title at version 0.1.0.

Driver tools, GPU profilers, and vendor control panels display this, and some drivers key per-application optimizations off it — so a shipping game should set a stable name here even if its window title changes at runtime.

func WithBackgroundWindow

func WithBackgroundWindow() Option

WithBackgroundWindow opens a visible window without requesting input focus. Use it for captures or tools running while another application is in use. GLYPHENGINE_BACKGROUND=1 enables it for any engine or window.New caller. It cannot be combined with WithFullscreen.

func WithDebugKeys

func WithDebugKeys() Option

WithDebugKeys binds F1 to toggle bloom and F2 to cycle the tonemap curve.

The second exception to "the engine never reads input on the game's behalf", and admitted for the same reason as the first: judging a post-process means looking at the same frame with it on and off, and restarting the program between the two comparisons is not looking at the same frame. That is a harness concern, exactly like getting out of a window.

Opt-in, so nothing takes F1 and F2 away from a game that wants them. F-keys because they do not collide with movement.

F1 turns bloom on even in a scene that never called SetBloom, using the defaults documented in bloom.md. That is deliberate -- most scenes have never asked for bloom, and those are the interesting ones to try it on.

func WithDepthPrepass

func WithDepthPrepass(mode renderer.DepthPrepassMode) Option

WithDepthPrepass renders depth only for the qualifying opaque draws before the scene pass, so a fragment hidden behind another never reaches the lit or material fragment shader.

renderer.DepthPrepassOff is the default and is free. renderer.DepthPrepassAuto runs the prepass only on the frames whose estimated depth complexity says it will pay, and is the mode a game that wants this at all should want. renderer.DepthPrepassOn runs it unconditionally, which is for measuring.

A straight passthrough to renderer.WithDepthPrepass, and it exists for the reason WithUIGlow does: the pipelines are built at construction and the frame graph is compiled around the node once, so the seam is unreachable from a game that only has an Engine.

Whether it is worth turning on is a property of the scene, not of the engine. Read renderer.WithDepthPrepass, ADR 0013 and the measurements in docs/agents/game-loop.md before switching it on in a shipping game; Renderer().Capabilities().DepthPrepass reports which mode the build went with and Renderer().Stats() carries the per-frame estimate and decision.

func WithFixedFrameTime

func WithFixedFrameTime(d time.Duration) Option

WithFixedFrameTime makes every frame advance the clock by exactly d instead of by however long the frame took, so a run is a function of its frame count rather than of the machine it ran on. Zero, the default, uses the real delta.

This is a diagnostic setting, not a pacing one: it does not slow the loop down to d, it lies to the simulation about how much time passed. Wind, clouds, water, particles, animation and the day-night cycle all read that clock, so with it set two runs at the same -frames produce the same image, bit for bit.

Without it they do not, and that is expensive when you are hunting an artifact. Comparing two renders means comparing them against a noise floor measured from two identical runs, and anything smaller than the floor is invisible -- a single-pixel sparkle counted 7 times in one run and 14 in the next is not a measurement, and a fix judged by one run of each is a coin toss. It also makes bisecting a visual bug possible at all: without a fixed clock, "it looks different now" cannot be told from "the wind moved".

Set GLYPHENGINE_FIXED_FRAME_TIME to a Go duration ("16.667ms") to force it on a binary you did not compile, the way GLYPHENGINE_TIMING and GLYPHENGINE_VALIDATION work. The environment wins over this option.

func WithFullscreen

func WithFullscreen() Option

WithFullscreen opens fullscreen on the primary monitor at its native resolution, ignoring WithWindowSize.

func WithInterpolation

func WithInterpolation(enabled bool) Option

WithInterpolation controls whether rendering blends between simulation ticks. It defaults to true.

Simulation runs at a fixed rate (60Hz by default) while rendering runs at the display rate. Without interpolation a 144Hz monitor draws each simulated position for two or three frames and then jumps, which reads as stutter on anything the tick moves. With it on, each frame draws the transform blended between the last two ticks.

The cost is one transform copy per non-Static entity per tick. Turn it off for a game that moves nothing on the tick, or when profiling the simulation in isolation.

func WithMSAA

func WithMSAA(n int) Option

WithMSAA requests an MSAA sample count (1, 2, 4, or 8); the renderer clamps it to what the GPU supports. Zero keeps the renderer default.

func WithMaxCatchUp

func WithMaxCatchUp(d time.Duration) Option

WithMaxCatchUp bounds how much simulation time a single frame may make up after a stall — an alt-tab, a breakpoint, a hitch. Defaults to DefaultMaxCatchUp. Values below one tick are raised to one tick.

It is a *duration*, not a tick count, because the two stop being equivalent the moment a game changes its tick rate. A budget of two ticks is 33ms at 60Hz but only 16ms at 128Hz — less than one frame at 60fps — so every frame would discard time it could never make up and the whole game would run in slow motion for anyone below ~120fps.

The size of the budget is a genre decision:

  • A large budget keeps in-game time tracking wall-clock time. After a stall the next frame simulates the backlog, so a fast-paced or single-player game stays honest about how much time passed. The cost is a burst of movement when a stalled client resumes.
  • A small budget makes a struggling client run in slow motion instead of bursting. That is often what a server-authoritative game wants: the server is the truth and will correct the client anyway, and a smooth slow client beats a lurching one.

Whatever the budget, exceeding it means the simulation falls behind rather than trying to repay a debt it cannot — which is what stops the classic spiral where catch-up work makes the next frame slower still.

func WithMaxFrames

func WithMaxFrames(n int) Option

WithMaxFrames stops the main loop after n frames. Zero, the default, runs until the window closes. This is what makes the engine testable on CI and profilable over a fixed workload.

It counts iterations that got as far as rendering, which is all but the ones skipped while minimized. Almost always that is also the number of frames presented; the exception is a swapchain rebuilt at a new size, where the frame already built for the old one is dropped. Under a fixed clock the difference matters -- see Repeatable renders in docs/agents/game-loop.md.

func WithPipelineStatistics

func WithPipelineStatistics() Option

WithPipelineStatistics counts fragment-shader invocations and post-clip primitives per pass, beside the per-pass timestamps, and reports them through Engine.MeanPipelineStats and the GLYPHENGINE_TIMING block.

Off by default and free when off. A straight passthrough to renderer.WithPipelineStatistics, which exists for the reason WithUIGlow does: the query pool is sized for every frame slot at construction, so the seam is unreachable from a game that only has an Engine.

GLYPHENGINE_PIPELINE_STATS=1 turns it on for any build without this option. Read renderer.PipelineStats on what the fragment counter does and does not include before taking a ratio from it; docs/agents/profiling.md records what it was measured to count.

func WithProjection

func WithProjection(fovDegrees, near, far float32) Option

WithProjection overrides the vertical field of view in degrees and the near and far clip planes. Defaults are 45°, 0.1, and 500.

func WithQuitKey

func WithQuitKey(key input.Key) Option

WithQuitKey closes the window when that key is pressed.

The engine otherwise never reads input on the game's behalf, and this is a deliberate exception rather than the start of a pattern: getting out of a window is a harness concern, not a gameplay one. It is also not optional in practice, because WithFullscreen leaves no close button, so every example that offers fullscreen has to handle a quit key or trap whoever runs it.

Hand-rolling it costs four lines and an import of the input package in every example, which is four lines of noise in front of whatever the example is actually there to show. A game that wants quitting to mean something more -- a confirmation prompt, saving first -- should leave this unset and bind its own action.

func WithResizable

func WithResizable(resizable bool) Option

WithResizable controls whether a windowed-mode window can be resized. Defaults to true.

func WithScene

func WithScene(s *Scene) Option

WithScene injects an externally created Scene instead of building a fresh one — for a game that loads or replicates its world before the window opens.

func WithScreenshot

func WithScreenshot(path string) Option

WithScreenshot writes a PNG of the last rendered frame to path when Run finishes, then returns.

Pair it with WithMaxFrames so the run is deterministic: render a fixed number of frames, capture, exit. That is how the images in the README are produced, and it is reproducible rather than a hand-taken grab.

Capture reads the presented swapchain image back from the GPU, so it costs a device-idle wait — fine once at the end of a run, not something to do per frame.

func WithShaderTextureSlots

func WithShaderTextureSlots(count int) Option

WithShaderTextureSlots opts into additional shared application samplers. See renderer.WithShaderTextureSlots for the binding contract and limits.

func WithShaders

func WithShaders(set renderer.ShaderSet) Option

WithShaders replaces the SPIR-V the renderer builds its pipelines from.

Fields left nil fall back to the engine's embedded shader for that stage, so a game can override one pipeline without supplying all of them:

custom := renderer.DefaultShaders()
custom.LitFrag = myLitFragSpv
e, err := glyph.New(&game{}, glyph.WithShaders(custom))

It is also how a sky gets drawn at all. Three stages -- SkyFrag, StarsFrag and CloudsFrag -- are the sky slot, and the engine embeds none of them, so an engine with no shader option has no dome, no stars and no clouds. x/sky is the sky the engine used to ship:

e, err := glyph.New(&game{}, glyph.WithShaders(sky.Shaders()))

See the sky slot on renderer.ShaderSet.

This is a straight passthrough to renderer.WithShaders, and exists because without it the seam was unreachable from Engine. A game that wanted a sky that is not Earth's had to call renderer.New directly and then reimplement the frame loop, the fixed timestep, interpolation, the draw-list build and the environment resolve that Run already provides -- a steep price for one field.

See renderer.ShaderSet for what a replacement has to match. A mismatch is a pipeline-creation failure at startup or, worse, a shader that links and draws nothing, so develop one with WithValidation on.

func WithShadowCascades

func WithShadowCascades(n int) Option

WithShadowCascades allocates n directional shadow cascades instead of two, up to renderer.MaxShadowCascades. Zero keeps two, and two keeps the allocation and recorded frame a renderer without the option has.

A straight passthrough to renderer.WithShadowCascades, which exists for the reason WithUIGlow does: the count sizes the shadow array at construction, so the seam is unreachable from a game that only has an Engine. What the extra cascades cover is SetShadowCoverage's to say; until it is said, the engine draws renderer.DefaultShadowCoverageFor(n), so shadows are never silently missing.

func WithTickRate

func WithTickRate(hz int) Option

WithTickRate sets the fixed simulation rate in ticks per second. Defaults to DefaultTickRate.

func WithTitle

func WithTitle(title string) Option

WithTitle sets the window title. Unless WithApplicationName overrides it, the title is also what the engine reports to Vulkan as the application name.

func WithUIGlow

func WithUIGlow() Option

WithUIGlow gives the screen-space UI its own HDR layer, so a UI element can be brighter than 1 and bloom across the elements around it.

Off by default and free when off. An element asks for glow through renderer.UIRenderObject.Glow or renderer.TextLine.Glow, both of which are inert without this; how the glow looks is tuned at run time through Renderer().SetUIGlow and Renderer().SetUIExposure, which are the game's to set rather than the engine's to decide.

A straight passthrough to renderer.WithUIGlowLayer, and it exists for the same reason WithShaders does: the layer allocates targets at construction and on resize, so it cannot be reached by a game that only has an Engine otherwise. See docs/agents/overlay-composite.md.

func WithVSync

func WithVSync(enabled bool) Option

WithVSync controls frame pacing. It defaults to true.

On, the presentation engine blocks at the refresh rate of the display the window is actually on — the right place for a frame limit, since it costs no CPU, follows the window between monitors, and cannot disagree with the hardware. A 144Hz display gets 144fps; a 60Hz one gets 60.

Off, rendering runs unbounded. Use it for benchmarking, profiling, or latency-sensitive input, and expect a pegged GPU.

Note that the simulation rate is independent either way — see WithTickRate.

func WithValidation

func WithValidation(enabled bool) Option

WithValidation enables the Vulkan validation layer, which reports API misuse through the standard logger. Off by default — it costs frame time and needs the Vulkan SDK, which players do not have. A missing layer logs a warning instead of failing to start.

GLYPHENGINE_VALIDATION=1 in the environment turns it on for any build, which is how to get validation out of a binary you did not compile.

func WithWindowSize

func WithWindowSize(width, height int) Option

WithWindowSize sets the windowed-mode size in screen coordinates.

type OverlapResult

type OverlapResult struct {
	Entity ecs.Entity
	Box    AABB
}

OverlapResult describes an entity whose collider overlaps a query AABB.

type Particle

type Particle struct {
	X, Y, Z    float32
	VX, VY, VZ float32
	Phase      float32 // random offset for pulsing
	Life       float32 // remaining life in seconds
	MaxLife    float32 // total life in seconds
	Size       float32
	R, G, B    float32
}

Particle is a single simulated particle.

type ParticleEmitter

type ParticleEmitter struct {
	Config *EmitterConfig

	MinX, MaxX float32
	MinZ, MaxZ float32
	BaseY      float32
	HeightMin  float32
	HeightMax  float32

	Particles []Particle

	Done bool
	// contains filtered or unexported fields
}

ParticleEmitter spawns and manages particles within a bounding region.

func NewParticleEmitter

func NewParticleEmitter(cfg *EmitterConfig, minX, maxX, minZ, maxZ, baseY, heightMin, heightMax float32) *ParticleEmitter

NewParticleEmitter creates an emitter with the given config and bounding region.

func (*ParticleEmitter) BuildInstances

func (em *ParticleEmitter) BuildInstances(nightFactor float32) []renderer.ParticleInstance

BuildInstances converts live particles into GPU instance data.

func (*ParticleEmitter) Reset

func (em *ParticleEmitter) Reset()

Reset clears all particles and resets burst state for reuse.

func (*ParticleEmitter) SetPosition

func (em *ParticleEmitter) SetPosition(cx, baseY, cz float32)

func (*ParticleEmitter) Tick

func (em *ParticleEmitter) Tick(dt, nightFactor float32)

Tick advances the emitter by dt seconds. nightFactor is 0 (day) to 1 (night).

type PathFinder

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

PathFinder processes path requests in an amortized queue, computing up to maxPerTick paths per Tick so a burst of requests spreads its CPU cost across frames instead of spiking one.

Request and Cancel are safe to call from any goroutine — AI systems commonly request paths off the tick. Tick itself is not: it invokes callbacks that typically write ECS components, so it must run on the goroutine that owns the world. Scene.Tick calls it for you.

func NewPathFinder

func NewPathFinder(grid *NavGrid, maxPerTick int) *PathFinder

NewPathFinder creates a PathFinder backed by the given NavGrid.

func (*PathFinder) Cancel

func (pf *PathFinder) Cancel(id uint64)

Cancel removes a pending request by ID. It is a no-op if the request has already been processed.

func (*PathFinder) Pending

func (pf *PathFinder) Pending() int

Pending returns the number of queued path requests.

func (*PathFinder) Request

func (pf *PathFinder) Request(from, to Vec2, callback func([]Vec2)) uint64

Request enqueues a path request and returns its ID. The callback runs on a future Tick with the resulting path, which is nil when no path exists.

func (*PathFinder) Tick

func (pf *PathFinder) Tick()

Tick processes up to maxPerTick queued path requests, invoking each callback on the calling goroutine.

type PathRequest

type PathRequest struct {
	ID       uint64
	From, To Vec2
	Callback func([]Vec2)
}

PathRequest is a queued pathfinding request.

type PointLight

type PointLight struct {
	Pos   mgl32.Vec3
	Range float32
	Color mgl32.Vec3

	// Volumetric is how much of this light the air itself sends back toward
	// the eye -- Unreal's "volumetric scattering intensity". 0, the default,
	// means none: the light still lights surfaces exactly as it always did
	// and the in-scattering march skips it entirely, so a scene that does not
	// ask pays nothing and renders byte-identically.
	//
	// Above 0 the lamp gets a glow in the air around it, integrated along the
	// view ray through the froxel grid. What it scatters off is the scene's
	// FOG, so a scene with Fog nil or Density 0 sees nothing however high
	// this goes -- there is no medium. Scene.SetVolumetrics tunes the medium;
	// this is per light, so one lamp in a scene can have a visible halo and
	// the rest not.
	//
	// It is not shadowed: no local light in this engine casts a shadow, and
	// the glow is consistent with the light it belongs to. See
	// docs/agents/lights.md.
	Volumetric float32
}

PointLight describes an unshadowed point light for the renderer.

Scatter as many as the scene wants. They are binned into a view-space froxel grid every frame (renderer/lightcluster), so a fragment evaluates the lights whose range reaches it rather than every light in the scene, and Range is what decides that -- a light with a range far larger than it visibly needs is a light in every cell it crosses. renderer.MaxLights is the ceiling on how many reach the GPU in one frame; past it the binner drops the ones furthest from lighting anything and says so in Engine.LightStats.

type PrevTransform

type PrevTransform Transform

PrevTransform holds an entity's Transform as it was at the start of the current tick, so rendering can interpolate between ticks instead of showing simulation steps.

Written by the engine at the top of Scene.Tick when Scene.Interpolate is on. Games do not set this; they call Scene.ClearInterpolation after a teleport.

type QueryBackend

type QueryBackend interface {
	Raycaster
	OverlapAABB(box AABB, exclude ecs.Entity) []OverlapResult
}

QueryBackend answers the two collision queries every internal engine system runs against the world: a nearest-hit raycast and a box-overlap query. Scene.Queries is nil by default, which keeps this file's spatial-grid implementation; setting it replaces BOTH Scene.Raycast and Scene.OverlapAABB in one step, because every engine call site goes through those two methods and nothing else — IntegrateBodies, MoveCharacter, Unstick, Camera.ResolveCollision (via the Raycaster embedded below), and Engine.PickEntity. A game backing collision queries with its own broadphase — a BVH, say — implements this once instead of leaving OverlapAABB stuck on the built-in grid while only Raycast is swapped.

A replacement must honour the order contracts #57 gave the built-in implementation, because engine code is written against them:

  • OverlapAABB's results are ordered by ascending entity id, and hold each entity at most once (#141).
  • Raycast breaks an exact-distance tie on the lower entity id; a terrain hit (Entity == 0, since no real entity ever has id 0) always wins a tie against any real entity.

Both are about reproducibility, not the specific ordering: the same query against the same frozen state must return the same answer on every call, not whichever candidate a map walk or a goroutine happened to reach first. Measured, not assumed: scrambling OverlapAABB's result order does not currently break Unstick or MoveCharacter — Unstick scans the whole result list itself and picks the smallest-push entry with its own tie-break (below), and MoveCharacter's "does anything block this move" check is an OR over the list, so neither reads a positional index. See TestUnstickToleratesScrambledOverlapOrder and TestMoveCharacterToleratesScrambledOverlapOrder in query_backend_test.go. The contract is required of a replacement anyway, because OverlapAABB documents it to ITS OWN callers (physics-queries.md) and a game may depend on it exactly the way Unstick used to.

The collision snapshot is the other half of the contract, and deliberately is not a method here — there is no lifecycle hook to freeze or unfreeze a replacement, because Raycast and OverlapAABB are the whole of what this seam is for. During Scene.MoveCharactersParallel, both are called from multiple goroutines while other goroutines concurrently write Transform and Velocity through MoveCharacter. The built-in implementation is exposed to that race only because it reads those same live components, and it survives by freezing a copy of every collider's AABB before the phase starts (colliderAABB, buildCollisionSnapshot) and answering from the copy for the phase's duration. A replacement backed by its own index — rebuilt once per tick, which is the normal shape of a broadphase — satisfies the same requirement for free, because nothing in its index changes mid-phase in the first place. A replacement that instead queries Scene's live Transform/Velocity itself needs the same freeze the built-in one has, and Scene.FrozenQueries is that freeze, exported: it hands back this same implementation bound to a snapshot taken on the spot, for a game whose own movement integrator runs a parallel phase of its own (#133).

Concurrency: Raycast and OverlapAABB are called from multiple goroutines during the parallel phase, so neither may keep scratch state shared across calls. The built-in implementation visits the frozen grid cells directly; SpatialGrid.QueryRadius reuses a buffer and is NOT safe for this. Each call must be independent or internally synchronized.

A replacement must never call Scene.Raycast or Scene.OverlapAABB on the scene it is installed in: with Queries set those ARE the replacement, and the call recurses until the stack runs out. The built-in implementation is reached through Scene.BuiltinQueries instead.

type RayHit

type RayHit struct {
	Entity ecs.Entity
	T      float32    // distance along ray
	Point  mgl32.Vec3 // world-space hit point
	Normal mgl32.Vec3 // outward face normal at hit
}

RayHit describes the result of a raycast against the world.

type Raycaster

type Raycaster interface {
	Raycast(origin, dir mgl32.Vec3, maxDist float32, exclude ecs.Entity) (RayHit, bool)
}

Raycaster is the world-query capability the camera needs to keep itself out of walls. Scene implements it. Taking an interface rather than *Scene or *Engine keeps the camera usable in tests and against a game's own broadphase.

type ResizeGame

type ResizeGame interface {
	OnResize(e *Engine, width, height int)
}

ResizeGame is an optional Game interface. OnResize is called when the framebuffer size changes, after the renderer has been notified.

type Scene

type Scene struct {

	// C holds the engine component stores. Games keep their own component
	// structs; the engine never sees them.
	C *Components

	// Env is the sky, light and air around the scene. It is an interface so a
	// game can replace the whole model; see EnvironmentSource. Nil means an
	// empty world -- no sky, no directional light, no fog -- and nil is what
	// NewScene leaves here.
	//
	// It used to be DefaultEnvironment(): a day cycle, a dome, clouds and
	// stars, handed to every scene whether it asked or not. That environment is
	// an opinion and it now lives in x/sky, so the engine has nothing to put
	// here that would not be one. A scene that wants the sky the engine used to
	// give it says so:
	//
	//	scene.Env = sky.DefaultEnvironment()
	//
	// and passes sky.Shaders() to WithShaders, which is the other half -- the
	// source asks for a dome and the sky slot is what draws it. An interior or
	// a diagnostic scene wants StaticSource instead, and a black world wants
	// this left nil.
	Env EnvironmentSource

	// Gravity is the downward acceleration used by IntegrateBodies and
	// MoveCharacter. Defaults to DefaultGravity.
	Gravity float32

	// Integrator advances rigid bodies — everything with a Transform and a
	// Velocity, minus character controllers — once per Tick, in
	// IntegrateBodies's place. NewScene sets it to IntegrateBodies, and a
	// custom one is free to call IntegrateBodies itself for the bodies it
	// does not want to handle differently.
	//
	// nil does NOT mean "integrate nothing." Unlike Env, Terrain, PathFinder,
	// and SpatialGrid — where nil is a real, supported "off" — Tick treats a
	// nil Integrator as "use IntegrateBodies," and only that function decides
	// per-entity whether there is anything to do. The reason is the failure
	// mode: an empty sky or a missing pathfinder is obviously absent, but a
	// Scene built some way other than NewScene (a struct literal, an
	// embedding game type that forgot to call it) that quietly stopped
	// applying gravity would look like nothing was wrong until something
	// floated. A game that wants no built-in integration says so with a real
	// function value instead of leaving the zero value in place:
	//
	//	scene.Integrator = func(*glyphengine.Scene, float32) {}
	//
	// That is "off," deliberately, the same way an EnvironmentSource that
	// returns an empty EnvironmentState is deliberately no sky rather than an
	// oversight.
	Integrator func(s *Scene, dt float32)

	// Interpolate makes Tick record each non-Static entity's transform before
	// simulating, so a renderer can blend between ticks instead of showing
	// 60Hz steps on a faster display.
	//
	// Off by default, because it is pure cost for anything that does not draw:
	// a headless server ticking the same Scene has no use for it. Engine turns
	// it on — see WithInterpolation.
	Interpolate bool

	// Terrain, when set, provides O(1) ground height for movement and is
	// tested first by downward raycasts.
	Terrain *Heightmap

	// SpatialGrid indexes moving entities for broad-phase queries. Rebuild it
	// with UpdateSpatialGrid. Nil falls back to a linear scan.
	SpatialGrid *SpatialGrid

	// StaticGrid indexes entities tagged Static. Built once by RebuildStatics.
	StaticGrid *SpatialGrid

	// Queries replaces the built-in spatial-grid collision queries — Raycast
	// and OverlapAABB — with a game's own broadphase. Nil keeps the built-in
	// implementation; NewScene leaves it nil, the same way it leaves Terrain,
	// PathFinder, and SpatialGrid nil for "use the built-in or fallback
	// behavior" rather than setting a default the way it does for Env and
	// Integrator. See QueryBackend for what a replacement must honour: the
	// #57 order contracts, the collision snapshot, and the concurrency
	// requirement.
	Queries QueryBackend

	// NavGrid and PathFinder are optional A* pathfinding over the terrain.
	NavGrid    *NavGrid
	PathFinder *PathFinder
	// contains filtered or unexported fields
}

Scene owns simulation state: the ECS world, component stores, physics acceleration structures, terrain, and the day/night cycle. It has no renderer or window dependency, so a headless tool or test can drive one directly — Engine adds the frame loop and drawing on top.

func NewScene

func NewScene() *Scene

NewScene creates a Scene with an empty ECS world and default state.

Env is nil: the engine has no environment of its own beyond StaticSource, so a scene straight out of here is unlit and clears to black until something is put in Scene.Env. See that field.

func (*Scene) AddSystem

func (s *Scene) AddSystem(fn System)

AddSystem registers a per-tick callback. Systems run in registration order at the end of Tick.

func (*Scene) BuiltinQueries

func (s *Scene) BuiltinQueries() QueryBackend

BuiltinQueries returns the spatial-grid implementation as a QueryBackend, whatever Scene.Queries is set to. It is to Queries what the exported IntegrateBodies is to Integrator: a replacement that only wants to change part of the answer -- its own BVH for the static buildings and the engine's grid for everything that moves, a filter, a counter -- delegates the rest here rather than reimplementing the terrain fast path and the hull narrow phase, and it cannot delegate to Scene.Raycast, which is itself.

It inherits the collision snapshot, so a backend built on it is safe in MoveCharactersParallel without a freeze of its own.

func (*Scene) ClearInterpolation

func (s *Scene) ClearInterpolation(entity ecs.Entity)

ClearInterpolation makes an entity render at its current transform on the next frame instead of blending from its previous one.

Call it after teleporting: a warp, a respawn, a scene load. Without it the entity is drawn sliding from where it used to be to where it now is, which across a level is a smear all the way over the map.

RestoreCharacter already does this, so prediction corrections do not smear.

func (*Scene) Despawn

func (s *Scene) Despawn(entity ecs.Entity)

Despawn removes an entity and every component attached to it, including components in stores the game registered on the same World.

Do not call this from inside a query over a store you are iterating — collect the entities first, then despawn after the query returns.

func (*Scene) Environment

func (s *Scene) Environment() EnvironmentState

Environment returns the scene's environment, resolved for this frame.

This is the one place the state's two sentinel fields are filled in. A source that leaves SkyPalette or NightGrade at its zero value -- which is every source written before they existed, and every source that has no opinion about the colour of the air -- gets the scene's, which NewScene initialises to the engine's defaults and SetSkyPalette and SetNightGrade change. Resolving here rather than at each reader is what keeps "a source writes it, or the scene does" from becoming two answers in two places: by the time anything reads the state, there is one answer in it.

func (*Scene) FrozenQueries

func (s *Scene) FrozenQueries() QueryBackend

FrozenQueries returns a QueryBackend that answers Raycast and OverlapAABB from a snapshot of every collider's current world AABB, taken now. Safe to call from many goroutines while Transforms are being written, which is how MoveCharactersParallel uses it: a game running its own movement integrator in a parallel phase freezes once on the calling goroutine, then queries the returned backend from all of them.

frozen := scene.FrozenQueries()
// ... goroutines calling frozen.Raycast and frozen.OverlapAABB while
// other goroutines write Transforms, under scene.World().EnableLocking()
// the way MoveCharactersParallel does ...

The answers are BuiltinQueries' answers, ordering and tie-breaks included — it is that same implementation reading AABBs from the snapshot instead of from live components, which is exactly what MoveCharactersParallel does.

The snapshot holds the world AABB of every entity that had both a Transform and a Collider when it was taken, moving and Static alike, so a character sees its neighbours where they stood before the phase began. It copies nothing else: the terrain heightmap, convex hulls and the Transforms the hull narrow phase reads, and the two spatial grids that supply broad-phase candidates are all still read live. That is sound for the same reason MoveCharactersParallel is — hull entities are Static, and terrain and the grids are rebuilt between phases rather than during one.

A snapshot goes stale the moment anything writes a Transform or a Collider, or spawns or despawns a collider entity: those writes are invisible to it by design. Take a new one each tick — holding one across ticks answers with last tick's world.

func (*Scene) InterpolatedTransform

func (s *Scene) InterpolatedTransform(entity ecs.Entity, alpha float32) (Transform, bool)

InterpolatedTransform returns where an entity should be drawn this frame: its previous tick transform blended toward its current one by alpha.

It falls back to the current transform when interpolation is off, when the entity has no previous transform yet (just spawned, or just teleported), or when the entity is Static.

func (*Scene) MoveCharacter

func (s *Scene) MoveCharacter(entity ecs.Entity, intent MoveIntent, dt float32)

MoveCharacter advances one character entity by dt seconds: turning, gravity, ground detection, jumping, and axis-separated slide collision.

The entity must have Transform, Collider, Velocity, and CharacterController. Missing any of them makes this a no-op.

func (*Scene) MoveCharactersParallel

func (s *Scene) MoveCharactersParallel(batch []MoveBatchEntry, dt float32)

MoveCharactersParallel moves many characters concurrently against a frozen collision snapshot. It exists for servers stepping hundreds of characters per tick; a single-player game should just call MoveCharacter in a loop.

The snapshot is what makes this safe: OverlapAABB and Raycast read every collider's world AABB as it was before the phase began, so no goroutine can observe a neighbor mid-write. Two invariants come with it:

  • Convex-hull narrow-phase reads live Transforms while the AABB broad phase reads the snapshot. That is only sound because hull entities are Static and therefore never move during the phase. Attaching a hull to a moving entity breaks it.
  • Work is partitioned by entity hash, not by batch position. A caller that delivers two intents for the SAME entity in one batch needs them applied sequentially in order; a positional split would race on that entity's own Transform and silently drop a frame of movement.

func (*Scene) NightGrade

func (s *Scene) NightGrade() NightGrade

NightGrade returns the scene's scotopic grade. It is not necessarily the one this frame used: a source that returns its own on EnvironmentState wins. Read Environment().NightGrade for the frame's.

func (*Scene) OverlapAABB

func (s *Scene) OverlapAABB(box AABB, exclude ecs.Entity) []OverlapResult

OverlapAABB queries the world for all collider entities whose AABB overlaps the given box. The exclude entity (if non-zero) is skipped.

Results are sorted by ascending entity id — that is part of the contract, not an incidental detail. Candidates arrive from the spatial grid, whose cell lists are filled by a Go map walk (SpatialGrid.Update), so without an explicit sort a caller reading results[0] would get a different entity on every call. Unstick used to do exactly that (#57).

Strictly ascending: an entity is in the results at most once, even though a Static collider is in both spatial grids and the broad phase walks both (#141, eachBroadPhaseCandidate).

When Scene.Queries is set, this and Raycast delegate to it instead of the spatial-grid implementation below — see QueryBackend for the contract a replacement has to honour.

func (*Scene) PlayClip

func (s *Scene) PlayClip(entity ecs.Entity, name string, loop bool) bool

PlayClip looks up a clip by name on the entity's skinned model and starts it. It reports false if the entity has no AnimationState and SkeletonRef, or if the model has no clip by that name.

func (*Scene) PointLights

func (s *Scene) PointLights() []PointLight

PointLights returns the current unshadowed point lights.

func (*Scene) Raycast

func (s *Scene) Raycast(origin, dir mgl32.Vec3, maxDist float32, exclude ecs.Entity) (RayHit, bool)

Raycast finds the nearest collider entity hit by a ray. The exclude entity (if non-zero) is skipped. Also tests the terrain heightmap for downward rays (checked first). Uses the SpatialGrid when available to reduce candidate entities from O(all) to O(nearby).

When Scene.Queries is set, this delegates to it instead of the built-in implementation below — see QueryBackend for the contract a replacement has to honour.

func (*Scene) RebuildStatics

func (s *Scene) RebuildStatics()

RebuildStatics rebuilds the static spatial grid and the cached XZ position list from every entity tagged Static that also has a Collider. Call after loading or reloading world geometry.

func (*Scene) RestoreCharacter

func (s *Scene) RestoreCharacter(entity ecs.Entity, st CharacterState) bool

RestoreCharacter writes a snapshot back onto a character, rewinding it to that exact movement state. It reports false if the entity is not a character controller.

Restoring does not move the character through the world — it teleports it. Nothing is swept, so a state captured somewhere the character can no longer legally stand will leave it intersecting geometry; Unstick recovers from that if a game needs to be defensive about it.

func (*Scene) SetNightGrade

func (s *Scene) SetNightGrade(g NightGrade)

SetNightGrade sets the scotopic grade for this scene.

This is the scene's grade, and it is what a frame gets whenever the environment does not name one of its own — which is every built-in source and every source that has no opinion about it. EnvironmentState.NightGrade is where a source that does have one puts it, and Scene.Environment is where the two meet: an all-zero grade on the state means "the scene's".

Both halves are load-bearing. The state needs the field because the night shift is part of the look a replacement sky owns, and the engine cannot read it off a day cycle it no longer has. The scene needs to keep the value because EnvironmentState is produced wholesale by EnvironmentSource.State, so a game that replaced the environment model returns a struct written before the field existed and the field arrives as Strength 0 — no night shift at all — and that game's nights would change on a dependency bump with nobody choosing it.

The cost of the sentinel is that Strength 0 with a zero Tint cannot be asked for on the state. Strength 0 with any other tint is the way to turn the shift off, and the tint is unread at zero strength, so nothing expressible is lost.

A source that wants the grade to move — moon phase, a storm — can either return it from State or call this from Update, the same place SetPointLights is called from.

func (*Scene) SetPointLight

func (s *Scene) SetPointLight(pos, color mgl32.Vec3, r float32)

SetPointLight sets the single shadow-casting point light's position, color, and falloff range.

func (*Scene) SetPointLights

func (s *Scene) SetPointLights(lights []PointLight)

SetPointLights sets the unshadowed point lights. Combined with the spot lights (see SetSpotLights), at most renderer.MaxLights of them reach the GPU in a frame; the rest are dropped nearest-surface-last and counted in Engine.LightStats. renderer.MaxPointLights is an alias for the same number and no longer the 32 it once was.

The slice is not copied. Reusing one buffer across frames is the way to drive hundreds of lights without allocating for them.

func (*Scene) SetSkyPalette

func (s *Scene) SetSkyPalette(p SkyPalette)

SetSkyPalette sets the atmosphere's colours for this scene.

This is the scene's palette, and it is what a frame gets whenever the environment does not name one of its own — which is every built-in source. EnvironmentState.SkyPalette is where a source that owns the atmosphere puts its own, and Scene.Environment is where the two meet: an all-zero palette on the state means "the scene's". SetNightGrade records the same arrangement.

It is deliberately not on Sky. `applyFog` blends distant geometry toward the horizon colour whether or not a dome is drawn, and water reflects the dome, so a scene with Sky nil still uses this. It is the whole atmosphere's palette, not the dome's, which makes Sky the wrong home for it.

The sentinel is what makes the state's field safe: a game that replaced the environment model returns a struct written before the field existed, and the field arrives as six black colours. Without the sentinel that game's sky, haze and water reflections all go black on a dependency bump with nobody choosing it. The one thing it costs is a palette of six exact blacks, which is not a palette anybody wants — Sky nil and a black ClearColor is how to get a black frame.

It does not cover a half-filled palette: a source that sets ZenithDay and leaves the other five alone gets five black endpoints and no warning. That trap is real and is the reason the scene keeps the value at all — a source either owns the palette or says nothing about it, and saying nothing is the zero value.

A source that wants the palette to move — a storm, an eclipse, a second moon — can either return it from State or call this from Update, where SetPointLights is called from.

func (*Scene) SetSpotLights

func (s *Scene) SetSpotLights(lights []SpotLight)

SetSpotLights sets the unshadowed spot lights. Combined with the point lights, at most renderer.MaxLights of them reach the GPU in a frame, points first then spots -- see Engine.gatherLights. Not copied, like SetPointLights.

func (*Scene) SetTerrain

func (s *Scene) SetTerrain(hm *Heightmap)

SetTerrain installs a heightmap used for ground snapping and downward raycasts. Pass nil to remove it.

func (*Scene) SetVolumetrics

func (s *Scene) SetVolumetrics(v Volumetrics)

SetVolumetrics sets the scattering medium for this scene.

On Scene, initialised by NewScene, for exactly the reasons SetSkyPalette records: EnvironmentState is produced wholesale by EnvironmentSource.State, so a game that has replaced the environment model returns a struct written before this field existed and it would arrive zero -- and a zero Steps marches nothing, so every beam in that game would disappear on a dependency bump with nobody choosing it.

Density is the exception and stays on Fog, because it is not a volumetrics setting: it is the fog, and a game that animates fog rolling in wants the beams to thicken with it without touching this at all.

func (*Scene) SkyPalette

func (s *Scene) SkyPalette() SkyPalette

SkyPalette returns the scene's atmosphere palette. It is not necessarily the one this frame used: a source that returns its own on EnvironmentState wins. Read Environment().SkyPalette for the frame's.

func (*Scene) SnapshotCharacter

func (s *Scene) SnapshotCharacter(entity ecs.Entity) (CharacterState, bool)

SnapshotCharacter captures a character's movement state. It reports false if the entity is not a character controller.

Pair the result with Scene.TickCount to know which tick it describes — that number, not wall-clock time, is what a client and server agree on.

func (*Scene) Spawn

func (s *Scene) Spawn() ecs.Entity

Spawn creates a new entity with no components.

func (*Scene) SpotLights

func (s *Scene) SpotLights() []SpotLight

SpotLights returns the current unshadowed spot lights.

func (*Scene) StarVisibility

func (s *Scene) StarVisibility() float32

StarVisibility returns a 0–1 factor for night visibility (0=day, 1=night).

func (*Scene) Tick

func (s *Scene) Tick(dt float32)

Tick advances the scene by dt seconds: day/night, rigid-body integration, queued pathfinding, then registered systems in order.

Character controller entities are driven by MoveCharacter instead, and are skipped by the integrator — see IntegrateBodies.

func (*Scene) TickCount

func (s *Scene) TickCount() uint64

TickCount returns the number of ticks this scene has run. It increments once per Scene.Tick and never resets.

This is the scene's simulation clock, and the thing to stamp on anything that has to be correlated across machines: a client and an authoritative server running the same tick rate agree on what "tick 4213" means, where wall-clock time and frame numbers do not.

func (*Scene) Unstick

func (s *Scene) Unstick(entity ecs.Entity)

Unstick nudges an entity out of any overlapping colliders on the XZ plane. Call after spawning or teleporting to prevent getting stuck inside obstacles.

func (*Scene) UpdateSpatialGrid

func (s *Scene) UpdateSpatialGrid()

UpdateSpatialGrid rebuilds the moving-entity spatial grid from every entity with a Transform. Call once per tick before physics queries; without it, OverlapAABB and Raycast fall back to a linear scan of all colliders.

func (*Scene) Volumetrics

func (s *Scene) Volumetrics() Volumetrics

Volumetrics returns the scene's scattering medium.

func (*Scene) World

func (s *Scene) World() *ecs.World

World returns the ECS world.

type ShutdownGame

type ShutdownGame interface {
	Shutdown(e *Engine)
}

ShutdownGame is an optional Game interface. Shutdown is called once after the main loop exits and before renderer and window teardown, so a game can save state while its resources are still valid.

type SkeletonRef

type SkeletonRef struct {
	Model       *renderer.SkinnedModel
	JointBuffer *renderer.JointBuffer
	Skinned     bool
}

SkeletonRef links an entity to a skinned model and its GPU joint buffer.

type SkyPalette

type SkyPalette struct {
	ZenithDay, HorizonDay           mgl32.Vec3
	ZenithTwilight, HorizonTwilight mgl32.Vec3
	ZenithNight, HorizonNight       mgl32.Vec3
}

SkyPalette is the six colours the atmosphere blends between: zenith and horizon for day, for twilight and for night. `shaders/include/atmosphere.inc` mixes night toward day on the daylight curve and then toward twilight on the twilight curve, so these are endpoints rather than a gradient to sample.

It is the whole atmosphere's palette, not the dome's. Distant geometry fades toward the same horizon colour and water reflects the dome, so changing only the sky would give a violet sky over a landscape still hazing into Earth-blue — which is exactly what replacing `sky.frag` through `WithShaders` used to do, and the reason these are data now.

What it does not cover: Rayleigh-versus-Mie behaviour, a different scattering model, two suns, the cloud and star colours, and the sun's own glow ember are all still shader work, and `WithShaders` is the right escape hatch for them. This is the case that is pure palette, which is most of what "another planet" means in practice.

func DefaultSkyPalette

func DefaultSkyPalette() SkyPalette

DefaultSkyPalette is Earth's sky, and is exactly the constants that used to be compiled into atmSkyPalette.

The horizon is pale because that is what looking through more atmosphere does, but not white: distant geometry fades into this colour, so a washed-out horizon washes out the whole landscape with it. The night endpoints are deliberately very dark for the same reason — they are what the dome, the fog and the water all reach at midnight, so lifting them to make the sky legible washes out the entire landscape. Brighten the moon instead.

type SpatialGrid

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

SpatialGrid is a flat-cell spatial hash for 2D (XZ) entity lookups. Rebuilt every snapshot tick.

func NewSpatialGrid

func NewSpatialGrid(cellSize float32) *SpatialGrid

NewSpatialGrid creates an empty grid with the given cell size.

func (*SpatialGrid) Clear

func (g *SpatialGrid) Clear()

Clear resets the grid without reallocating the map.

func (*SpatialGrid) HasAnyInRadius

func (g *SpatialGrid) HasAnyInRadius(x, z, radius float32) bool

HasAnyInRadius returns true if any cell within radius of (x,z) has entities. This is a coarse check (cell-level, not per-entity distance) suitable for cheap proximity heuristics.

func (*SpatialGrid) Insert

func (g *SpatialGrid) Insert(entity ecs.Entity, x, z float32)

Insert adds an entity to the grid at the given world XZ position.

func (*SpatialGrid) QueryRadius

func (g *SpatialGrid) QueryRadius(x, z, radius float32) []ecs.Entity

QueryRadius returns all entities within radius of (x, z) on the XZ plane. The returned slice is reused across calls — callers must not retain it. NOT safe for concurrent use — use QueryRadiusAlloc for parallel paths.

func (*SpatialGrid) QueryRadiusAlloc

func (g *SpatialGrid) QueryRadiusAlloc(x, z, radius float32) []ecs.Entity

QueryRadiusAlloc returns entities within radius, allocating a fresh slice. Safe for concurrent use from multiple goroutines.

func (*SpatialGrid) Update

func (g *SpatialGrid) Update(w *ecs.World, transforms *ecs.Store[Transform])

Update rebuilds the grid from every living entity with a Transform.

type SpawnMode

type SpawnMode uint8

SpawnMode controls how particles are emitted.

const (
	SpawnContinuous SpawnMode = iota
	SpawnBurst
)

type SpotLight

type SpotLight struct {
	Pos   mgl32.Vec3
	Dir   mgl32.Vec3
	Range float32
	Color mgl32.Vec3
	Inner float32
	Outer float32

	// Volumetric turns the cone into a visible beam: the air inside it
	// scatters the light back toward the eye instead of only the surface the
	// cone lands on. 0, the default, means none, and costs nothing. See
	// PointLight.Volumetric for what the number means and what it scatters
	// off -- the scene's fog, so a scene with no fog shows no beam.
	//
	// The beam is the same cone the surface lighting uses, evaluated in the
	// air rather than on a surface, so the shaft and the pool it lands in
	// agree by construction. It is not shadowed: a beam crossing a wall keeps
	// glowing on the far side, exactly as the light does.
	Volumetric float32
}

SpotLight describes an unshadowed spot light for the renderer: a point light narrowed to a cone. Dir is the direction the light points (need not be unit length -- the engine normalizes it).

A zero Dir has no cone to aim and is treated as omnidirectional, i.e. an ordinary point light, rather than as an error. That is deliberate: it turns a caller's uninitialized or mistakenly-zeroed Dir into a visibly wrong light -- unexpectedly lighting everything around it -- rather than a silently missing one, which is easier to notice and debug.

Inner and Outer are half-angles in radians measured from Dir: full intensity inside Inner, a smooth falloff to zero between Inner and Outer, and nothing beyond Outer. Inner greater than Outer is clamped down to Outer rather than rejected, producing a hard-edged cone instead of flooding the scene with an unbounded point light -- the opposite of what asking for a narrower inner cone means.

type Static

type Static struct{}

Static is a tag component marking an entity as world geometry that never moves — rocks, walls, buildings. Static entities go into Scene.StaticGrid, which is rebuilt on demand rather than every tick.

The tag is load-bearing, not just an optimization: the parallel movement phase runs convex-hull narrow-phase tests against *live* Transforms while AABB queries read a frozen snapshot, which is only sound because hull entities do not move during that phase. Attaching ConvexHullCollider to an entity that moves breaks that invariant.

type StaticSource

type StaticSource struct {
	// Sun is the directional light. Nil means none: only ambient and the
	// scene's own point and spot lights.
	Sun *DirectionalLight

	// Ambient is uniform fill light. Nil means none.
	Ambient *AmbientLight

	// Fog blends distant geometry toward the horizon. Nil disables it.
	Fog *Fog

	// ClearColor is what the frame clears to. It is what the frame clears to
	// unconditionally here, since this source never draws a dome over it.
	ClearColor [3]float32
}

StaticSource is light and air that do not move: one direction, one colour, no clock. It is the whole of the environment the engine itself has, now that the day cycle and the dome are in x/sky — flat colours, a sun that stays where it is put, and fog.

scene.Env = &glyph.StaticSource{
    Sun:     &glyph.DirectionalLight{Direction: [3]float32{0.4, 0.8, 0.3}, Color: [3]float32{0.7, 0.68, 0.62}},
    Ambient: &glyph.AmbientLight{Color: [3]float32{0.18, 0.17, 0.20}},
}

It draws no sky. DrawSky stays false, so the frame keeps ClearColor: an interior, a diagnostic scene, or a world whose sky comes from somewhere else. For a dome — fixed at one hour or on a clock — use a package that supplies one; x/sky's Environment takes exactly these pieces and adds a Sky to them.

It is also the one resolution of fixed light the engine still owns, which is why x/sky's fixed-light path calls it rather than repeating it. The rules are small but they are rules: a sun with a black colour casts no shadows, and without a cycle there is no handover, so the light and the real sun are the same vector.

func (*StaticSource) Advance

func (s *StaticSource) Advance(float32)

Advance does nothing: nothing here moves. The method exists because the interface needs it, and an empty one is the honest implementation.

func (*StaticSource) State

func (s *StaticSource) State() EnvironmentState

State resolves this frame's environment from the fixed pieces.

The arithmetic is kept in the order it was written in when this shared a resolver with the day cycle. Nothing here is subtle enough for that to matter on its own, but every committed capture of a fixed-light scene was taken through it, and a reassociated float32 is a moved low bit.

type System

type System func(s *Scene, dt float32)

System is a per-tick callback registered on a Scene. Systems run in registration order, after the built-in day/night, integration, and pathfinding steps.

type TerrainOptions

type TerrainOptions struct {
	// UVTiles is how many times UVs repeat across the terrain. Zero means
	// SplatTiles, which is what the terrain splat pipeline expects.
	UVTiles float32

	// Tint colors each vertex. Nil means flat white, which the lit pipeline
	// renders as untinted.
	Tint TerrainTint
}

TerrainOptions configures TerrainMesh. The zero value is valid.

type TerrainTint

type TerrainTint func(height float32, normal [3]float32) [3]float32

TerrainTint colors a terrain vertex from its world height and surface normal — the usual grass-in-the-valleys, rock-on-the-cliffs rule. Return linear RGB in 0–1.

type Transform

type Transform struct {
	Position mgl32.Vec3
	Rotation mgl32.Vec3 // Euler angles in radians
	Scale    mgl32.Vec3
}

Transform holds position, rotation, and scale for an entity.

func LerpTransform

func LerpTransform(a, b Transform, alpha float32) Transform

LerpTransform blends two transforms by alpha in [0,1]. Position and scale interpolate linearly; each Euler rotation component takes the shortest arc.

func TransformFromMatrix

func TransformFromMatrix(m mgl32.Mat4) (t Transform, exact bool)

TransformFromMatrix is Transform.ModelMatrix run backwards: the Position, Euler Rotation and Scale whose ModelMatrix is m.

It is here because ModelMatrix's order is this engine's own -- Translate * RotY * RotX * RotZ * Scale -- and a matrix from anywhere else (a glTF node's World, a physics library, a parent's matrix times a child's) has to be taken apart against that same product or the entity comes out rotated about the wrong axes. A game cannot know the order without reading ModelMatrix, and a copy of this function in a game does not find out when ModelMatrix changes. TestTransformFromMatrixRoundTrips is what ties the two together: it asserts on matrices, not on angles, because several Euler triples describe one rotation and only the matrix is the fact.

exact is false when no Transform can reproduce m, and the Transform returned is then the closest one that ignores the part that cannot be kept:

  • Shear. A rotated child under a non-uniformly scaled parent is sheared in world space, and Position/Rotation/Scale has nowhere to put that. In a level exported from an editor it means an object was rotated inside a parent that was stretched; applying the parent's scale in the editor before exporting removes it.
  • A scale of zero on an axis, which leaves that axis's direction unknown.

A mirrored matrix (negative determinant, which is what a mirror modifier or a negative scale in an editor exports as) IS representable and comes back exact, with the mirror on Scale's X.

func (*Transform) ModelMatrix

func (t *Transform) ModelMatrix() mgl32.Mat4

ModelMatrix computes the model matrix from the transform.

type Translucent

type Translucent struct {
	// Alpha is opacity from 0 to 1. At or below 0 the entity is not drawn at
	// all; at or above 1 it is drawn opaque, through the ordinary lit path.
	Alpha float32
}

Translucent draws an entity blended over the scene instead of opaque.

It is a component rather than a field on MeshRef because MeshRef's zero value has to stay opaque. An Alpha field there would make every existing MeshRef read as fully transparent unless zero were special-cased to mean one, and "0 means opaque except when it means invisible" is the kind of quiet surprise that costs an afternoon.

ghost := e.Spawn()
e.C.Transform.Set(ghost, &glyph.Transform{Position: at, Scale: one})
e.C.MeshRef.Set(ghost, &glyph.MeshRef{Mesh: dome})
e.C.Translucent.Set(ghost, &glyph.Translucent{Alpha: 0.4})

Translucent entities are drawn after everything opaque, back to front, and do not cast shadows — a placement preview that threw a solid shadow would read as a real building. They compose with Emissive and DoubleSided.

Not supported on entities that also carry a MaterialRef.PBR or a skinned SkeletonRef: those route through their own pipelines, which have no blended variant, so the engine leaves such an entity opaque rather than silently dropping its maps or its skinning. See docs/agents/translucency.md.

type Vec2

type Vec2 struct {
	X, Z float32
}

Vec2 is a 2D position on the XZ plane.

type Velocity

type Velocity struct {
	Vec mgl32.Vec3
}

Velocity holds linear velocity in world units per second.

type Volumetrics

type Volumetrics struct {
	// Anisotropy is the Henyey-Greenstein g. 0 scatters equally in every
	// direction; positive scatters forward, so a beam coming toward the eye
	// is brighter than the same beam crossing it. Clamped to (-1, 1).
	Anisotropy float32

	// Steps is how many samples each pixel's march takes: the cost knob and
	// the banding knob at once. 0 turns the march off for the whole scene,
	// whatever the lights ask for. Capped at renderer.MaxVolumetricSteps.
	Steps int
}

Volumetrics is the scattering medium a light's beam is made of: how forward-scattering the air is, and how many steps the per-pixel march spends crossing it.

It is deliberately NOT the medium's density. That is the scene's fog (Fog.Density and the height profile beside it) and it stays there, because the air that hazes the hills is the air a lamp lights -- one medium, one place to tune it. A scene with no fog therefore sees no beams, which is the right answer rather than a missing feature: there is nothing in the air to light.

func DefaultVolumetrics

func DefaultVolumetrics() Volumetrics

DefaultVolumetrics is the medium a scene gets by saying nothing.

The numbers are repeated from renderer.DefaultVolumetrics rather than read from it, because Scene has no renderer dependency -- that is what lets a headless tool or test drive one -- and the same is already true of DefaultNightGrade and DefaultSkyPalette above. The measurements behind them are on the renderer side, next to the shader they configure; TestDefaultsMatchTheRenderers is what keeps the two copies from drifting, which nothing did for the grade or the palette until now.

type Water

type Water struct {
	Options WaterOptions
}

Water routes an entity's mesh through the water pipeline: Gerstner wave displacement, a Fresnel-weighted sky reflection, and refraction of whatever was drawn behind it. Build the mesh with Engine.CreateWaterMesh, and pass the same options here so the shader agrees with the geometry.

type WaterFoam

type WaterFoam struct {
	// Threshold is the Jacobian below which a crest makes foam; new foam
	// ramps from none at the threshold to full 0.1 below it.
	Threshold float32
	// Decay is how many seconds full foam takes to fade to nothing, in
	// shader time (Engine.Elapsed). Zero, the default, is no foam at all.
	Decay float32
	// Color is the foam's albedo, lit by the sun and the ambient.
	Color [3]float32
}

WaterFoam is whitecap foam: marked where the wave sum squeezes the surface together hard enough to break, kept in a persistent target over the surface grid, and faded out over Decay seconds, so a crest leaves foam behind it rather than carrying a highlight along.

Where the surface is squeezed is the Jacobian of the Gerstner sum's horizontal displacement, evaluated by the same shader code that displaces the vertices and builds their normal: one on calm water, falling toward zero under a sharp crest. WaterOptions.SurfaceAt reports it at any point.

The target is one R16F texel per grid vertex, stepped by one compute dispatch per surface per frame the surface is drawn, and the foam is blended over the water as a matte layer lit by the sun and the ambient. See docs/agents/water.md for what it costs and how the defaults were measured.

func DefaultWaterFoam

func DefaultWaterFoam() WaterFoam

DefaultWaterFoam is the measured starting point for WaterOptions.Foam. DefaultWaterOptions leaves foam off: whether the engine's lake has whitecaps by default is a decision for someone looking at it.

type WaterGrid

type WaterGrid struct {
	// Origin is the rest X and Z of point (0, 0), Step the spacing along X and
	// Z, and Width and Height the point counts -- Resolution+1 each way.
	Origin, Step  [2]float32
	Width, Height int
	// Depth is the still-water depth under each point, in rows along X; zero
	// over dry land.
	Depth []float32
}

WaterGrid is the still grid a water surface is built on: the rest position of every vertex and the depth of still water under it. WaterMesh emits the underwater part of it as a mesh; the foam target is laid out over all of it, one texel per point; and WaterOptions.SurfaceAt evaluates the waves at any of its points as the vertex stage displaces the vertex there.

func NewWaterGrid

func NewWaterGrid(h *Heightmap, opts WaterOptions) (WaterGrid, error)

NewWaterGrid lays out the grid WaterMesh builds over a heightmap.

func (WaterGrid) Point

func (g WaterGrid) Point(ix, iz int) (x, z, depth float32)

Point returns the rest X and Z of grid point (ix, iz) and the depth under it.

func (WaterGrid) Spacing

func (g WaterGrid) Spacing() float32

Spacing is the coarser of the two steps, which is what the water shader judges which wave components the grid can carry by; see water.vert. It is the spacing SurfaceAt wants for a point of this grid.

type WaterOptions

type WaterOptions struct {
	// Level is the world Y of the still surface. Terrain below it is
	// underwater, terrain above it is dry land and gets no surface built over
	// it at all.
	Level float32

	// Resolution is the number of grid divisions along each axis. Waves are
	// displaced per vertex, so this bounds the shortest wavelength the surface
	// can actually show. 160 is comfortable for a lake a couple of hundred
	// units wide.
	//
	// It interacts with WaveLength, and the interaction is worth knowing about.
	// The shortest of the five wave components is WaveLength * 0.26, and a
	// wavelength needs at least two vertices across it to be a wave at all
	// rather than a beat pattern the grid invented. Below that the shader fades
	// the component out rather than rendering it, so asking for short waves on a
	// coarse grid gets smooth water rather than choppy water — never faceted
	// water, which is what it used to get.
	//
	// The rule, given a surface w world units wide:
	//
	//	WaveLength * 0.26 >= 2 * w / Resolution
	//
	// The defaults sit just below that, so the finest component is faded at
	// Resolution 160 over a 200-unit lake. Raise Resolution to about 256 to get
	// it as a real wave.
	Resolution int

	// ShallowColor and DeepColor are the water's own colour at the surface and
	// at AbsorptionDepth. Real water absorbs red first, so a deep colour that
	// is bluer and darker than the shallow one reads correctly.
	ShallowColor [3]float32
	DeepColor    [3]float32

	// AbsorptionDepth is how far light travels through the water before it is
	// fully absorbed, in world units. It sets both how quickly the colour
	// reaches DeepColor and how quickly the bottom stops being visible, which
	// is why it is one number rather than two: in real water they are the same
	// physical process.
	AbsorptionDepth float32

	// WaveAmplitude is the surface's maximum crest height above still water, in
	// world units — the five components' amplitudes sum to it. Waves are scaled
	// down in shallow water so they vanish at the shoreline rather than cutting
	// through it.
	//
	// Amplitude tall relative to WaveLength is self-limiting: a Gerstner surface
	// stops being a function once its crests would fold over, and the shader
	// clamps steepness to keep it just short of that. Past roughly
	// WaveLength / 11 the crests stop getting sharper and only get taller.
	WaveAmplitude float32

	// WaveLength is the wavelength of the longest wave component, in world
	// units. Four shorter ones ride on top of it, down to 0.26 of it. See
	// Resolution for the shortest wavelength a given grid can carry.
	WaveLength float32

	// WaveNoise is how much of WaveAmplitude arrives as drifting fractal noise
	// rather than as one of the five wave components, from 0 to about 1.
	//
	// A sum of sinusoids is exactly periodic, so without this the surface tiles
	// at a glancing angle — the same crest pattern marching away from you to the
	// horizon. The noise gives the field variation no sum of sinusoids can:
	// patches of chop, stretches of calm, and crests that do not all agree.
	//
	// Zero disables it and restores the pure Gerstner sum. Its octaves are
	// bounded by the grid exactly as the wave components are, so raising it on a
	// coarse mesh makes the water lumpier, never faceted.
	WaveNoise float32

	// RefractStrength scales how far the surface displaces the view of the
	// lake bed. Zero disables refraction entirely and falls back to ordinary
	// alpha blending, which costs nothing but shows an undistorted bottom.
	RefractStrength float32

	// Subsurface is light let through a backlit crest. The zero value is no
	// term at all, and a surface without it renders byte for byte what it
	// rendered before the option existed. DefaultWaterSubsurface is the
	// measured starting point.
	Subsurface WaterSubsurface

	// Foam is whitecap foam on crests that are close to breaking. The zero
	// value is no foam and costs nothing: CreateWaterMesh makes no target and
	// the frame has no dispatch for it. Unlike the other options it has to be
	// decided when the mesh is created, because that is when the target is.
	// DefaultWaterFoam is the measured starting point.
	Foam WaterFoam
}

WaterOptions configures a water surface built over a heightmap.

The zero value is not useful; use DefaultWaterOptions and adjust.

func DefaultWaterOptions

func DefaultWaterOptions(level float32) WaterOptions

DefaultWaterOptions is a calm freshwater lake.

func (WaterOptions) SurfaceAt

func (o WaterOptions) SurfaceAt(x, z, depth, spacing, t float32) WaterSample

SurfaceAt evaluates the surface the water vertex stage draws, at the rest point (x, z) with depth of still water under it, at shader time t (the engine's Elapsed). spacing is the surface grid's vertex spacing, which decides which wave components the mesh can carry -- WaterSpacing gives it for a mesh built over a heightmap -- and zero keeps them all.

It is a mirror for checks and for gameplay that needs to know where the water is, not a second implementation: GPU sines are not Go's, so expect agreement to a few parts in ten thousand rather than to the bit.

type WaterSample

type WaterSample struct {
	// Position is where the vertex stage moves the rest point (x, Level, z)
	// to, before the entity's model matrix.
	Position [3]float32
	// Normal is the analytic normal of the displaced surface: the vertex
	// stage's, before the fragment stage adds its ripples.
	Normal [3]float32
	// Jacobian is the determinant of the horizontal Gerstner map at this rest
	// point. One is undisturbed water; it falls toward zero where neighbouring
	// points are pulled together under a crest, and would go negative where the
	// surface folds through itself, which the steepness clamp prevents. Foam is
	// marked where it falls below WaterFoam.Threshold.
	Jacobian float32
	// Crest is the height above still water as a fraction of WaveAmplitude:
	// about 1 on the tallest crests, negative in the troughs. It is what the
	// subsurface term is proportional to.
	Crest float32
}

WaterSample is the engine's water surface at one point of its still grid.

type WaterSubsurface

type WaterSubsurface struct {
	// Color is the water's colour in transmission. Light through a crest has
	// crossed centimetres of water rather than metres, so it is the shallow
	// colour rather than the deep one.
	Color [3]float32
	// Strength scales the whole term. Zero, the default, is no term.
	Strength float32
}

WaterSubsurface is the glow of a thin wave crest with the sun low behind it.

The fragment stage adds Color * Strength, times the sun's colour and the shadow the surface is already in, times three factors that say where the glow belongs: how far the crest rose above still water as a fraction of WaveAmplitude, how nearly the sun is behind the crest from the eye, and how edge-on the eye sees it. It is added under the Fresnel reflection, so a crest seen at a glancing angle shows the sky rather than the glow, as it would.

It reads the sun and nothing else: a lamp behind a wave does not light it through. See docs/agents/water.md.

func DefaultWaterSubsurface

func DefaultWaterSubsurface() WaterSubsurface

DefaultWaterSubsurface is the measured starting point for WaterOptions.Subsurface. DefaultWaterOptions leaves it off: whether the engine's lake glows by default is a decision for someone looking at it.

Directories

Path Synopsis
cmd
apppasscheck command
Command apppasscheck exercises application graphics nodes and their lifetime against a rendered control.
Command apppasscheck exercises application graphics nodes and their lifetime against a rendered control.
bench command
Command bench runs a fixed set of example scenes and prints one comparable table of CPU and GPU cost.
Command bench runs a fixed set of example scenes and prints one comparable table of CPU and GPU cost.
blendcheck command
Command blendcheck asserts that a blended effect standing in front of water is still on screen where the water is.
Command blendcheck asserts that a blended effect standing in front of water is still on screen where the water is.
cloudcheck command
Command cloudcheck checks the fixed-clock captures made by task clouds.
Command cloudcheck checks the fixed-clock captures made by task clouds.
custompassescheck command
Command custompassescheck compares the worked example's fixed-camera captures.
Command custompassescheck compares the worked example's fixed-camera captures.
flatquadcheck command
Command flatquadcheck asserts that a flat yamlui quad reaches the colour its YAML asked for, rather than somewhere between that colour and whatever it was drawn over.
Command flatquadcheck asserts that a flat yamlui quad reaches the colour its YAML asked for, rather than somewhere between that colour and whatever it was drawn over.
heightmapconv command
Command heightmapconv is the encoder LoadHeightmap has never had a writer-side partner for: it turns a sculpted Blender terrain mesh, or a heightmap image from World Machine/Gaea/a displacement bake, into the .heightmap file glyphengine.LoadHeightmap reads.
Command heightmapconv is the encoder LoadHeightmap has never had a writer-side partner for: it turns a sculpted Blender terrain mesh, or a heightmap image from World Machine/Gaea/a displacement bake, into the .heightmap file glyphengine.LoadHeightmap reads.
hudcheck command
Command hudcheck measures how much of a HUD actually reached the screen.
Command hudcheck measures how much of a HUD actually reached the screen.
indicatorcheck command
Command indicatorcheck asserts that a yamlui `indicator:` block darkens the part of a widget it says it covers, leaves everything else alone, stays under the label that names the widget, and disappears completely when its value reaches zero.
Command indicatorcheck asserts that a yamlui `indicator:` block darkens the part of a widget it says it covers, leaves everything else alone, stays under the label that names the widget, and disappears completely when its value reaches zero.
instancecheck command
Command instancecheck pins that replacing an instance set's placements every frame never disturbs a frame that is still being drawn.
Command instancecheck pins that replacing an instance set's placements every frame never disturbs a frame that is still being drawn.
lampcheck command
Command lampcheck asserts that a lamp's pool of light still reads as the lamp's colour at night, and that the ground outside it still does not.
Command lampcheck asserts that a lamp's pool of light still reads as the lamp's colour at night, and that the ground outside it still does not.
lodcheck command
Command lodcheck verifies the forest's culling, transitions and far billboards.
Command lodcheck verifies the forest's culling, transitions and far billboards.
mipcheck command
Command mipcheck is issue #200's acceptance as a check: a render target with a full mip chain, filled level by level by application compute dispatches that each read level n and write level n+1 of the same image, sampled with hardware LOD and through a view restricted to one level -- with validation on, and through a resize, history rotation, a disabled and re-enabled reduction and a destroyed and recreated chain.
Command mipcheck is issue #200's acceptance as a check: a render target with a full mip chain, filled level by level by application compute dispatches that each read level n and write level n+1 of the same image, sampled with hardware LOD and through a view restricted to one level -- with validation on, and through a resize, history rotation, a disabled and re-enabled reduction and a destroyed and recreated chain.
msdfatlas command
Command msdfatlas generates a multi-channel signed distance field font atlas from a TTF or OTF file.
Command msdfatlas generates a multi-channel signed distance field font atlas from a TTF or OTF file.
normalcheck command
Command normalcheck renders supplied normals through the ordinary lit pipeline.
Command normalcheck renders supplied normals through the ordinary lit pipeline.
palettecheck command
Command palettecheck asserts that the sky palette reaches the whole atmosphere and not just the dome: the sky at the horizon, the fogged geometry beside it and the water reflecting both must all move together when the palette changes.
Command palettecheck asserts that the sky palette reaches the whole atmosphere and not just the dome: the sky at the horizon, the fogged geometry beside it and the water reflecting both must all move together when the palette changes.
pngsame command
Command pngsame reports whether two PNG files hold the same pixels.
Command pngsame reports whether two PNG files hold the same pixels.
quadcheck command
Command quadcheck establishes what this device's FRAGMENT_SHADER_INVOCATIONS counter counts, from geometry whose true quad factor is known.
Command quadcheck establishes what this device's FRAGMENT_SHADER_INVOCATIONS counter counts, from geometry whose true quad factor is known.
rangecheck command
Command rangecheck pins rendered equivalence of independent meshes and shared ranges, including offsets, index widths, transforms and retirement.
Command rangecheck pins rendered equivalence of independent meshes and shared ranges, including offsets, index widths, transforms and retirement.
scrollcheck command
Command scrollcheck asserts that a yamlui scroll_view clips what it holds to its own view rect: exactly up to the edge, and nothing past it.
Command scrollcheck asserts that a yamlui scroll_view clips what it holds to its own view rect: exactly up to the edge, and nothing past it.
shadowcheck command
Command shadowcheck checks the captures from task shadowcoverage: the three two-cascade captures, or with -planet the -cascades 3 arm and its probes.
Command shadowcheck checks the captures from task shadowcoverage: the three two-cascade captures, or with -planet the -cascades 3 arm and its probes.
shaftcheck command
Command shaftcheck asserts that the light-shaft pass draws light through the gaps between occluders and not a flat wash over everything.
Command shaftcheck asserts that the light-shaft pass draws light through the gaps between occluders and not a flat wash over everything.
skycheck command
Command skycheck asserts that nothing in a region of a capture is brighter than it should be.
Command skycheck asserts that nothing in a region of a capture is brighter than it should be.
skyshadowcheck command
Command skyshadowcheck compares a custom SkyFrag and LitFrag reading the same directional shadow map, including disabled shadows and swapchain rebuild.
Command skyshadowcheck compares a custom SkyFrag and LitFrag reading the same directional shadow map, including disabled shadows and swapchain rebuild.
streamcheck command
Command streamcheck renders a patch grid streamed in over 100 frames and requires the last frame to match, byte for byte, a capture of the same grid created synchronously.
Command streamcheck renders a patch grid streamed in over 100 frames and requires the last frame to match, byte for byte, a capture of the same grid created synchronously.
swapchainchurn command
Command swapchainchurn measures initial swapchain creation without building pipelines or rendering.
Command swapchainchurn measures initial swapchain creation without building pipelines or rendering.
tex3dcheck command
Command tex3dcheck is issue #190's acceptance as a check: a small known volume, sampled by an application graphics pass and by an application compute pass, interpolates along Z the way it does along X and Y, repeats continuously on every axis, holds its edge slice where Z clamps, and reads the right level out of both a supplied chain and a generated one -- while the volumes are replaced with a different extent, destroyed with frames in flight, resized under, and fed every unsupported input, with validation on.
Command tex3dcheck is issue #190's acceptance as a check: a small known volume, sampled by an application graphics pass and by an application compute pass, interpolates along Z the way it does along X and Y, repeats continuously on every axis, holds its edge slice where Z clamps, and reads the right level out of both a supplied chain and a generated one -- while the volumes are replaced with a different extent, destroyed with frames in flight, resized under, and fed every unsupported input, with validation on.
tracefield command
Command tracefield pulls one field out of a GLYPHENGINE_STATE_TRACE file so two runs can be diffed on it alone.
Command tracefield pulls one field out of a GLYPHENGINE_STATE_TRACE file so two runs can be diffed on it alone.
transitioncheck command
Command transitioncheck asserts that a yamlui `transition:` block actually moves a widget while the game is paused, lands exactly where a widget with no block lands, and moves nothing else.
Command transitioncheck asserts that a yamlui `transition:` block actually moves a widget while the game is paused, lands exactly where a widget with no block lands, and moves nothing else.
uiglowcheck command
Command uiglowcheck asserts that the screen-space UI's HDR layer glows where it is asked to, stays where it belongs, and changes nothing where it is not.
Command uiglowcheck asserts that the screen-space UI's HDR layer glows where it is asked to, stays where it belongs, and changes nothing where it is not.
volumetriccheck command
Command volumetriccheck asserts that a light asking for volumetric scattering puts light in the air INSIDE its cone and not outside it.
Command volumetriccheck asserts that a light asking for volumetric scattering puts light in the air INSIDE its cone and not outside it.
watercheck command
Command watercheck asserts that a lamp beside a lake reaches the water, in the lamp's own colour, and that water out of every lamp's range does not move at all.
Command watercheck asserts that a lamp beside a lake reaches the water, in the lamp's own colour, and that water out of every lamp's range does not move at all.
waterfxcheck command
Command waterfxcheck asserts the two water options -- whitecap foam and the subsurface crest term -- against what a real render of 09-water drew, by predicting both on the CPU from the same wave function.
Command waterfxcheck asserts the two water options -- whitecap foam and the subsurface crest term -- against what a real render of 09-water drew, by predicting both on the CPU from the same wave function.
widetexcheck command
Command widetexcheck measures what a CPU-uploaded half-float texture costs in precision against an eight-bit one, on the GPU, through the sampler.
Command widetexcheck measures what a CPU-uploaded half-float texture costs in precision against an eight-bit one, on the GPU, through the sampler.
Package msdf generates multi-channel signed distance field font atlases.
Package msdf generates multi-channel signed distance field font atlases.
framegraph
Package framegraph compiles ordered image and buffer uses without a device.
Package framegraph compiles ordered image and buffer uses without a device.
lightcluster
Package lightcluster bins point and spot lights into a view-space froxel grid so a fragment shader can loop over the lights that reach it instead of over every light in the scene.
Package lightcluster bins point and spot lights into a view-space froxel grid so a fragment shader can loop over the lights that reach it instead of over every light in the scene.
include
Package include exports the engine's shared GLSL include set.
Package include exports the engine's shared GLSL include set.
ui
ease
Package ease holds the interpolation curves the UI tweens on.
Package ease holds the interpolation curves the UI tweens on.
x module

Jump to

Keyboard shortcuts

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