API 레퍼런스는 소스 코드의 Go 문서 주석에서 추출되며 영어로 작성되어 있습니다.
package world3d
import "github.com/nsgo-dev/game/pkg/world3d"개요
Package world3d is experimental: its API and documented formats may change in a minor release. See the API stability policy. provides 3D world-building primitives for NSGo 3D games: heightmap terrain, 3D GridMaps of modular mesh tiles, procedural foliage/scattered instance fields, and large-world chunk streaming with floating-origin rebasing. Package pathfind3d builds 3D navigation meshes and path-corridor navigation agents on its chunk coordinates.
All positions, normals, rays, and bounding volumes follow package math3d's right-handed Y-up conventions (+X right, +Y up, -Z forward).
색인
- 상수
- 변수
- func BlendTerrainWeights(raw, heights [MaxTerrainLayers]float32, count int, contrast float32) [MaxTerrainLayers]float32
- func EncodeDensityMapPNG(d *DensityMap) ([]byte, error)
- func EncodeFoliage(doc *FoliageDoc) ([]byte, error)
- func EncodeGridMap(doc *GridMapDoc) ([]byte, error)
- func EncodeHeightmapPNG(h *Heightmap) ([]byte, error)
- func EncodeTerrain(doc *TerrainDoc) ([]byte, error)
- func FindGridOrientation(m math3d.Mat4) (uint8, bool)
- func GridOrientationMat4(orient uint8) math3d.Mat4
- func LoadGridMapFS(fsys fs.FS, name string) (*GridMap, *GridMapDoc, error)
- func LoadTerrainFS(fsys fs.FS, name string) (*Heightmap, *TerrainDoc, error)
- func PackLayerWeightMaps(weights ...image.Image) (splat0, splat1 *image.NRGBA, err error)
- func RebaseMat4(m math3d.Mat4, shift math3d.Vec3) math3d.Mat4
- func RotateGridOrientation(orient uint8, axis GridAxis, quarterTurns int) uint8
- func TerrainLODBiasFor(l quality.Level) float32
- func ValidateFoliage(doc *FoliageDoc) error
- func ValidateGridMap(doc *GridMapDoc) error
- func ValidateTerrain(doc *TerrainDoc) error
- type ChunkCoord
- type ChunkStreamer
- func NewChunkStreamer[T any](cfg ChunkStreamerConfig[T]) *ChunkStreamer[T]
- func (s *ChunkStreamer[T]) Close()
- func (s *ChunkStreamer[T]) Get(coord ChunkCoord) (T, bool)
- func (s *ChunkStreamer[T]) LoadedChunks() []ChunkCoord
- func (s *ChunkStreamer[T]) PendingCount() int
- func (s *ChunkStreamer[T]) ReadyCount() int
- func (s *ChunkStreamer[T]) Update(worldPos WorldPos64)
- type ChunkStreamerConfig
- type DensityMap
- func LoadDensityMapGray(img image.Image) *DensityMap
- func NewDensityMap(width, height int) *DensityMap
- func (d *DensityMap) At(x, y int) float32
- func (d *DensityMap) Clone() *DensityMap
- func (d *DensityMap) EncodePNG(w io.Writer) error
- func (d *DensityMap) Sample(u, v float32) float32
- func (d *DensityMap) Set(x, y int, v float32)
- func (d *DensityMap) ToGray() *image.Gray
- func (d *DensityMap) ToGray16() *image.Gray16
- type FloatingOrigin
- type FoliageBuildOptions
- type FoliageDoc
- func LoadFoliageFS(fsys fs.FS, name string) (*FoliageDoc, error)
- func ParseFoliage(data []byte) (*FoliageDoc, error)
- func ParseFoliageWith(data []byte, file string) (*FoliageDoc, error)
- func (d *FoliageDoc) BuildLayers(opts FoliageBuildOptions) ([]FoliageLayer, error)
- func (d *FoliageDoc) ScatterAll(hm *Heightmap, region math3d.AABB, opts FoliageBuildOptions) ([]*FoliageField, error)
- type FoliageField
- func Scatter(hm *Heightmap, layer FoliageLayer, region math3d.AABB) *FoliageField
- func (f *FoliageField) Bounds() math3d.AABB
- func (f *FoliageField) ChunkCount() int
- func (f *FoliageField) CollectVisible( camPos math3d.Vec3, frustum math3d.Frustum, quality QualityProfile, out []FoliageInstance, ) []FoliageInstance
- func (f *FoliageField) TotalCount() int
- type FoliageInstance
- type FoliageInstanceDoc
- type FoliageLayer
- type FoliageLayerDoc
- type GridAxis
- type GridBoxDoc
- type GridCell
- type GridCellDoc
- type GridColliderOptions
- type GridCoord
- type GridHit
- type GridInstanceBatch
- type GridMap
- func NewGridMap(cellSize math3d.Vec3, lib *MeshLibrary) *GridMap
- func (g *GridMap) AddCollidersToWorld(w *physics3d.World, opts GridColliderOptions) []*physics3d.Body
- func (g *GridMap) Bounds() math3d.AABB
- func (g *GridMap) BuildInstances(frustum *math3d.Frustum, out []GridInstanceBatch) []GridInstanceBatch
- func (g *GridMap) BuildStaticBodies(opts GridColliderOptions) []physics3d.Body
- func (g *GridMap) Cell(c GridCoord) (GridCell, bool)
- func (g *GridMap) CellBounds(c GridCoord) math3d.AABB
- func (g *GridMap) CellTransform(c GridCoord, orient uint8) math3d.Mat4
- func (g *GridMap) Clear()
- func (g *GridMap) ClearCell(c GridCoord)
- func (g *GridMap) ColliderBoxes() []math3d.AABB
- func (g *GridMap) CollisionBoxesIn(region math3d.AABB) []math3d.AABB
- func (g *GridMap) Count() int
- func (g *GridMap) EachCell(fn func(c GridCoord, cell GridCell) bool)
- func (g *GridMap) FillBox(minC, maxC GridCoord, tileID uint16, orient uint8)
- func (g *GridMap) MergedColliderBoxes() []math3d.AABB
- func (g *GridMap) Raycast(ray math3d.Ray, maxDist float32) (GridHit, bool)
- func (g *GridMap) SetCell(c GridCoord, tileID uint16, orient uint8)
- func (g *GridMap) ToDoc(name, meshLibrary string) (*GridMapDoc, error)
- type GridMapDoc
- func ParseGridMap(data []byte) (*GridMapDoc, error)
- func ParseGridMapWith(data []byte, file string) (*GridMapDoc, error)
- func (d *GridMapDoc) Build(lib *MeshLibrary) (*GridMap, error)
- func (d *GridMapDoc) EffectiveCellSize() math3d.Vec3
- func (d *GridMapDoc) EffectiveOrigin() math3d.Vec3
- func (d *GridMapDoc) Load(fsys fs.FS) (*GridMap, error)
- type Heightmap
- func DecodeHeightmapPNG(r io.Reader, cellSize, heightScale float32) (*Heightmap, error)
- func LoadHeightmapGray(img image.Image, cellSize, heightScale float32) *Heightmap
- func NewHeightmap(cols, rows int, cellSize, heightScale float32) *Heightmap
- func (h *Heightmap) Bounds() math3d.AABB
- func (h *Heightmap) BuildMesh(chunkCol, chunkRow, chunkCols, chunkRows int) TerrainMesh
- func (h *Heightmap) BuildMeshLOD(chunkCol, chunkRow, chunkCols, chunkRows int, lod int, neighbors TerrainEdgeLODs) TerrainMesh
- func (h *Heightmap) ChunkBounds(chunkCol, chunkRow, chunkCols, chunkRows int) math3d.AABB
- func (h *Heightmap) Collider() *physics3d.HeightfieldCollider
- func (h *Heightmap) EncodePNG(w io.Writer) error
- func (h *Heightmap) FoliageDensityAt(layer string, x, z float32) (float32, bool)
- func (h *Heightmap) HeightAt(x, z float32) (float32, bool)
- func (h *Heightmap) LayerAt(x, z float32) (TerrainLayerSample, bool)
- func (h *Heightmap) NormalAt(x, z float32) math3d.Vec3
- func (h *Heightmap) Raycast(ray math3d.Ray, maxDist float32) (TerrainHit, bool)
- func (h *Heightmap) SampleHeight(col, row int) float32
- func (h *Heightmap) ToGray16() *image.Gray16
- type MeshLibrary
- func LoadMeshLibraryFromGLTF(gltfJSON []byte) (*MeshLibrary, error)
- func NewMeshLibrary() *MeshLibrary
- func (l *MeshLibrary) Add(def MeshTileDef) uint16
- func (l *MeshLibrary) ByName(name string) (MeshTileDef, bool)
- func (l *MeshLibrary) Get(id uint16) (MeshTileDef, bool)
- func (l *MeshLibrary) Items() []MeshTileDef
- func (l *MeshLibrary) Len() int
- func (l *MeshLibrary) Revision() uint64
- type MeshTileDef
- type QualityLevel
- type QualityProfile
- type TerrainDoc
- func ParseTerrain(data []byte) (*TerrainDoc, error)
- func ParseTerrainWith(data []byte, file string) (*TerrainDoc, error)
- func (d *TerrainDoc) BuildFoliageLayers(opts FoliageBuildOptions) ([]FoliageLayer, error)
- func (d *TerrainDoc) BuildHeightmap(imgs TerrainImages) (*Heightmap, error)
- func (d *TerrainDoc) BuildLOD(hm *Heightmap) *TerrainLOD
- func (d *TerrainDoc) EffectiveCellSize() float32
- func (d *TerrainDoc) EffectiveChunkSize() int
- func (d *TerrainDoc) EffectiveOrigin() math3d.Vec3
- func (d *TerrainDoc) HasLayerWeightMaps() bool
- func (d *TerrainDoc) LODConfig() TerrainLODConfig
- func (d *TerrainDoc) LayerInfos() []TerrainLayerInfo
- func (d *TerrainDoc) LoadHeightmap(fsys fs.FS) (*Heightmap, error)
- func (d *TerrainDoc) ScatterFoliage(hm *Heightmap, region math3d.AABB, opts FoliageBuildOptions) ([]*FoliageField, error)
- type TerrainEdgeLODs
- type TerrainHeightLayer
- type TerrainHit
- type TerrainImages
- type TerrainLOD
- func NewTerrainLOD(hm *Heightmap, cfg TerrainLODConfig) *TerrainLOD
- func (t *TerrainLOD) ChunkBounds(coord ChunkCoord) (math3d.AABB, bool)
- func (t *TerrainLOD) ChunkCells() int
- func (t *TerrainLOD) ChunkCount() int
- func (t *TerrainLOD) ChunkLOD(coord ChunkCoord) (int, bool)
- func (t *TerrainLOD) ChunkWorldSize() float64
- func (t *TerrainLOD) EvictHiddenMeshes()
- func (t *TerrainLOD) GridSize() (cols, rows int)
- func (t *TerrainLOD) InvalidateAll()
- func (t *TerrainLOD) InvalidateChunk(coord ChunkCoord)
- func (t *TerrainLOD) IsChunkActive(coord ChunkCoord) bool
- func (t *TerrainLOD) LODBias() float32
- func (t *TerrainLOD) MaxLOD() int
- func (t *TerrainLOD) SetChunkActive(coord ChunkCoord, active bool)
- func (t *TerrainLOD) SetLODBias(bias float32)
- func (t *TerrainLOD) SetQualityLevel(level quality.Level)
- func (t *TerrainLOD) Stats() TerrainLODStats
- func (t *TerrainLOD) Update(camPos math3d.Vec3, frustum *math3d.Frustum) []TerrainLODChunk
- func (t *TerrainLOD) UpdateWithOrigin(camLocal math3d.Vec3, frustumLocal *math3d.Frustum, origin *FloatingOrigin) []TerrainLODChunk
- type TerrainLODChunk
- type TerrainLODConfig
- type TerrainLODStats
- type TerrainLayerDoc
- type TerrainLayerInfo
- type TerrainLayerSample
- type TerrainMesh
- type TerrainSplatMap
- func LoadTerrainSplatMap(layers []TerrainLayerInfo, maps ...image.Image) (*TerrainSplatMap, error)
- func LoadTerrainSplatMapFromWeights(layers []TerrainLayerInfo, weights []image.Image) (*TerrainSplatMap, error)
- func NewTerrainSplatMapFromRGBA(width, height int, layers []TerrainLayerInfo, splat0, splat1 []byte) (*TerrainSplatMap, error)
- func (s *TerrainSplatMap) Height() int
- func (s *TerrainSplatMap) LayerAt(x, z float32) TerrainLayerSample
- func (s *TerrainSplatMap) LayerCount() int
- func (s *TerrainSplatMap) LayerIndex(name string) int
- func (s *TerrainSplatMap) LayerName(index int) string
- func (s *TerrainSplatMap) LayerWeightImage(layer int) *image.Gray
- func (s *TerrainSplatMap) SampleUV(u, v float32) TerrainLayerSample
- func (s *TerrainSplatMap) SetTexelWeight(layer, x, y int, weight float32)
- func (s *TerrainSplatMap) SplatImages() (splat0, splat1 *image.NRGBA)
- func (s *TerrainSplatMap) TexelWeight(layer, x, y int) float32
- func (s *TerrainSplatMap) Width() int
- type TerrainTriplanarDoc
- type TilemapStreamer
- type TilemapStreamerConfig
- type WorldPos64
상수
const DefaultTerrainLayerRoughness float32 = 0.85DefaultTerrainLayerRoughness is the roughness factor used when a TerrainLayerDoc omits both roughness and a metallicRoughness texture.
const FoliageFormatVersion = 1FoliageFormatVersion is the current YAML foliage definition schema version.
const FoliageSchemaComment = "# yaml-language-server: $schema=" + FoliageSchemaURLFoliageSchemaComment is the first line EncodeFoliage writes so YAML language servers validate and complete foliage definition files automatically.
const FoliageSchemaURL = "https://nsgo.games/schemas/foliage.v1.json"FoliageSchemaURL is where the JSON Schema of version 1 foliage documents is published.
const GridMapSchemaComment = "# yaml-language-server: $schema=" + GridMapSchemaURLGridMapSchemaComment is the first line EncodeGridMap writes so YAML language servers validate and complete grid map files automatically.
const GridMapSchemaURL = "https://nsgo.games/schemas/gridmap.v1.json"GridMapSchemaURL is where the JSON Schema of version 1 grid map documents is published.
const GridOrientationCount = 24GridOrientationCount is the number of distinct proper 3D orthogonal 90-degree rotations supported by GridCell.Orientation (the 24 rotational symmetries of a cube). Orientations 0..3 are 0°, 90°, 180°, and 270° counter-clockwise quarter-turns around the +Y axis.
const MaxTerrainLayers = 8MaxTerrainLayers is the maximum number of PBR terrain material layers driven by splat maps (up to 2 RGBA weight maps × 4 channels per map).
const TerrainFormatVersion = 1TerrainFormatVersion is the current YAML terrain definition schema version.
const TerrainSchemaComment = "# yaml-language-server: $schema=" + TerrainSchemaURLTerrainSchemaComment is the first line EncodeTerrain writes so YAML language servers validate and complete terrain definition files automatically.
const TerrainSchemaURL = "https://nsgo.games/schemas/terrain.v1.json"TerrainSchemaURL is where the JSON Schema of version 1 terrain documents is published.
변수
var ErrInvalidTerrainSplat = errors.New("world3d: invalid terrain splat map")ErrInvalidTerrainSplat is wrapped by errors returned when constructing or validating a TerrainSplatMap.
함수
func BlendTerrainWeights(raw, heights [MaxTerrainLayers]float32, count int, contrast float32) [MaxTerrainLayers]float32BlendTerrainWeights normalizes raw splat weights across [0, count) and, when contrast > 0, applies height-based blending using each layer's effective height in [0, 1]. Higher contrast values (clamped to [0, 0.98]) produce sharper transitions while guaranteeing zero weights stay zero and the output always sums to 1 (falling back to layer 0 = 1 if all raw weights are <= 0).
This exact algebraic formula is shared with package render3d's GPU terrain shader and CPU reference evaluator.
func EncodeDensityMapPNG(d *DensityMap) ([]byte, error)EncodeDensityMapPNG encodes d as an 8-bit grayscale PNG byte slice.
func EncodeFoliage(doc *FoliageDoc) ([]byte, error)EncodeFoliage validates doc and serializes it as deterministic 2-space YAML prefixed with FoliageSchemaComment.
func EncodeGridMap(doc *GridMapDoc) ([]byte, error)EncodeGridMap validates doc and serializes it as deterministic 2-space YAML prefixed with GridMapSchemaComment, with boxes and cells sorted into canonical (y, z, x) order. The input doc is not modified.
func EncodeHeightmapPNG(h *Heightmap) ([]byte, error)EncodeHeightmapPNG encodes h as a 16-bit grayscale PNG byte slice.
func EncodeTerrain(doc *TerrainDoc) ([]byte, error)EncodeTerrain validates doc and serializes it as deterministic 2-space YAML prefixed with TerrainSchemaComment.
func FindGridOrientation(m math3d.Mat4) (uint8, bool)FindGridOrientation returns the orientation index (0..23) whose exact orthogonal rotation matrix matches the upper-left 3x3 of m, or (0, false) if none does.
func GridOrientationMat4(orient uint8) math3d.Mat4GridOrientationMat4 returns the exact orthogonal 4x4 rotation matrix for orientation index orient (modulo GridOrientationCount). Orientations 0..3 correspond to 0°, 90°, 180°, and 270° rotations around the +Y axis.
func LoadGridMapFS(fsys fs.FS, name string) (*GridMap, *GridMapDoc, error)LoadGridMapFS reads the YAML grid map at name in fsys, loads its referenced glTF mesh library from fsys, and returns the constructed *GridMap alongside the parsed *GridMapDoc.
func LoadTerrainFS(fsys fs.FS, name string) (*Heightmap, *TerrainDoc, error)LoadTerrainFS reads the YAML terrain definition at name in fsys, validates it, decodes its referenced heightmap and splat images from fsys, and returns the constructed *Heightmap alongside the parsed *TerrainDoc.
func PackLayerWeightMaps(weights ...image.Image) (splat0, splat1 *image.NRGBA, err error)PackLayerWeightMaps packs 1 to 8 per-layer grayscale weight-map images into 1 (for 1..4 layers) or 2 (for 5..8 layers) straight-alpha RGBA *image.NRGBA splat maps suitable for LoadTerrainSplatMap and GPU terrain shaders.
The output dimensions match the first non-nil weight image (or 1x1 when all images are nil, in which case layer 0 defaults to weight 255). Non-nil images with different dimensions are bilinearly resampled to match. Nil entries contribute zero weight to their channel.
func RebaseMat4(m math3d.Mat4, shift math3d.Vec3) math3d.Mat4RebaseMat4 applies a floating-origin shift to the translation column of m.
func RotateGridOrientation(orient uint8, axis GridAxis, quarterTurns int) uint8RotateGridOrientation applies quarterTurns 90-degree rotations around axis (world-space X, Y, or Z) to orient and returns the resulting orientation in 0..23. Composing X, Y, and Z quarter-turns reaches all 24 cube orientations.
func TerrainLODBiasFor(l quality.Level) float32TerrainLODBiasFor returns the recommended terrain LOD bias for a game-wide quality preset: +1.0 for quality.Low (one LOD coarser), +0.5 for quality.Medium, and 0.0 for quality.High (full detail distances). An invalid level maps to quality.Medium, matching quality.DefaultPreset and QualityLevelFor.
Positive bias shifts chunks toward coarser LODs by scaling distance thresholds by 2^(-bias); negative bias keeps finer LODs farther away.
func ValidateFoliage(doc *FoliageDoc) errorValidateFoliage checks that doc conforms to the version 1 foliage schema.
func ValidateGridMap(doc *GridMapDoc) errorValidateGridMap checks that doc conforms to the version 1 grid map schema.
func ValidateTerrain(doc *TerrainDoc) errorValidateTerrain checks that doc conforms to the version 1 terrain schema.
타입
type ChunkCoord struct {
X, Z int32
}ChunkCoord identifies a 2D streaming chunk in the XZ world plane.
type ChunkStreamer[T any] struct {
// contains filtered or unexported fields
}ChunkStreamer asynchronously streams 2D world chunks around a moving WorldPos64 with bounded worker concurrency, per-frame integration budgets, hysteresis unloading, and cancellation of stale in-flight loads.
Build one with NewChunkStreamer. A zero ChunkStreamer is usable too: it behaves like NewChunkStreamer with a zero config (synchronous, no loader, 64-unit chunks) instead of panicking (#546).
func NewChunkStreamer[T any](cfg ChunkStreamerConfig[T]) *ChunkStreamer[T]NewChunkStreamer constructs a ChunkStreamer and starts its worker goroutines when cfg.Workers > 0. Call Close when finished to stop workers and unload remaining chunks cleanly.
func (s *ChunkStreamer[T]) Close()Close cancels all in-flight loads, waits for worker goroutines to exit, and unloads all remaining loaded chunks via OnUnload. Calling Close multiple times is safe.
func (s *ChunkStreamer[T]) Get(coord ChunkCoord) (T, bool)Get returns the loaded chunk data for coord, or (zero, false) if not loaded.
func (s *ChunkStreamer[T]) LoadedChunks() []ChunkCoordLoadedChunks returns a sorted slice of all currently loaded chunk coordinates.
func (s *ChunkStreamer[T]) PendingCount() intPendingCount returns the number of chunks currently queued or loading in workers.
func (s *ChunkStreamer[T]) ReadyCount() intReadyCount returns the number of completed chunks awaiting integration on subsequent Update calls.
func (s *ChunkStreamer[T]) Update(worldPos WorldPos64)Update advances streaming for worldPos:
- Unloads loaded chunks beyond UnloadRadius and cancels stale in-flight loads.
- Integrates up to MaxIntegrationsPerFrame completed chunks (closest first).
- Enqueues missing chunks within LoadRadius (closest first).
When Workers == 0, missing chunks are loaded synchronously up to the remaining per-frame integration budget.
type ChunkStreamerConfig[T any] struct {
// ChunkSize is the width/depth of each square XZ chunk in world units.
// Defaults to 64 if <= 0.
ChunkSize float64
// LoadRadius is the Chebyshev chunk radius around the player chunk to load.
LoadRadius int
// UnloadRadius is the Chebyshev chunk radius beyond which loaded and
// in-flight chunks are unloaded/canceled. Defaults to LoadRadius + 1 if
// smaller than LoadRadius.
UnloadRadius int
// MaxIntegrationsPerFrame caps how many completed chunks are integrated
// into the active map per Update call to prevent frame-time hitches.
// Values <= 0 allow unlimited integrations per frame.
MaxIntegrationsPerFrame int
// Workers sets the number of background loader goroutines. When 0, Loader
// executes synchronously inside Update (useful for deterministic tests).
Workers int
// Loader loads chunk data for coord. It must respect ctx cancellation.
Loader func(ctx context.Context, coord ChunkCoord) (T, error)
// OnLoad is called on the Update goroutine after a chunk is integrated.
OnLoad func(coord ChunkCoord, data T)
// OnUnload is called on the Update/Close goroutine after a chunk is unloaded.
OnUnload func(coord ChunkCoord, data T)
// OnError is called on the Update goroutine when Loader returns a non-nil error.
OnError func(coord ChunkCoord, err error)
}ChunkStreamerConfig configures a ChunkStreamer.
type DensityMap struct {
Width int
Height int
Data []float32
}DensityMap stores normalized [0, 1] 2D scatter density weights in row-major order.
func LoadDensityMapGray(img image.Image) *DensityMapLoadDensityMapGray constructs a DensityMap from a grayscale (or color, converted to 16-bit luminance) image with pixel intensities normalized to [0, 1].
func NewDensityMap(width, height int) *DensityMapNewDensityMap allocates a zero-initialized DensityMap of width x height samples.
func (d *DensityMap) At(x, y int) float32At returns the density sample at texel (x, y), or 0 if out of range.
func (d *DensityMap) Clone() *DensityMapClone returns a deep copy of d, or nil if d is nil.
func (d *DensityMap) EncodePNG(w io.Writer) errorEncodePNG encodes d as an 8-bit grayscale PNG image into w.
func (d *DensityMap) Sample(u, v float32) float32Sample returns the bilinearly interpolated density weight in [0, 1] at normalized UV coordinates (u, v) in [0, 1]. If d is nil or empty, 1.0 is returned.
func (d *DensityMap) Set(x, y int, v float32)Set writes a clamped [0, 1] density value at texel (x, y); out-of-range coordinates are ignored.
func (d *DensityMap) ToGray() *image.GrayToGray converts d into an 8-bit grayscale image with values in [0, 255].
func (d *DensityMap) ToGray16() *image.Gray16ToGray16 converts d into a 16-bit grayscale image with values in [0, 65535].
type FloatingOrigin struct {
Origin WorldPos64
Threshold float64
}FloatingOrigin maintains a double-precision world origin offset so that local float32 physics, animation, and rendering coordinates stay near (0, 0, 0).
func NewFloatingOrigin(threshold float64) *FloatingOriginNewFloatingOrigin constructs a FloatingOrigin with the given rebase distance threshold (in world units). Non-positive thresholds default to 512.
func (f *FloatingOrigin) LocalToWorld(local math3d.Vec3) WorldPos64LocalToWorld converts a local float32 position back into double-precision world coordinates.
func (f *FloatingOrigin) Update(playerLocal math3d.Vec3) (rebased bool, shift math3d.Vec3)Update checks whether playerLocal has moved farther than Threshold from the local origin (0, 0, 0). When exceeded, Origin advances by playerLocal and Update returns (true, shift) where shift == -playerLocal is the additive offset to apply to every active local position/transform (pos = pos.Add(shift)) so playerLocal rebases back to (0, 0, 0) while preserving exact WorldPos64 coordinates.
func (f *FloatingOrigin) WorldToLocal(w WorldPos64) math3d.Vec3WorldToLocal converts double-precision world position w into local float32 space by subtracting Origin in float64 before narrowing to float32.
type FoliageBuildOptions struct {
// ResolveMesh maps a layer's Mesh asset path to a runtime MeshID. When nil, MeshID is 0.
ResolveMesh func(path string) (uint32, error)
// ResolveMaterial maps a layer's Material asset path (when non-empty) to a runtime MaterialID. When nil, MaterialID is 0.
ResolveMaterial func(path string) (uint32, error)
// LoadDensityMap loads a layer's DensityMap asset path (when non-empty) into a [*DensityMap].
// When nil and FS is non-nil, the image is decoded from FS with [LoadDensityMapGray].
LoadDensityMap func(path string) (*DensityMap, error)
// FS is an optional filesystem used to decode DensityMap images when LoadDensityMap is nil.
FS fs.FS
}FoliageBuildOptions supplies runtime mesh/material ID resolution and density map loading when converting a FoliageDoc into runtime FoliageLayer values.
type FoliageDoc struct {
// Version is the schema version; must be 1.
Version int `yaml:"version" schema:"required"`
// Name is an optional human-readable name for the foliage set.
Name string `yaml:"name,omitempty"`
// Terrain is an optional asset path to the terrain definition (*.terrain.yaml) these foliage layers scatter over.
Terrain string `yaml:"terrain,omitempty"`
// Layers lists 1 or more procedural foliage scatter layers in authoring order.
Layers []FoliageLayerDoc `yaml:"layers" schema:"required,minItems=1"`
}FoliageDoc is the root of a versioned YAML foliage definition declaring one or more procedural foliage scatter layers over a terrain heightmap.
func LoadFoliageFS(fsys fs.FS, name string) (*FoliageDoc, error)LoadFoliageFS reads and validates the YAML foliage definition at name in fsys.
func ParseFoliage(data []byte) (*FoliageDoc, error)ParseFoliage decodes and validates a YAML foliage definition document. Unknown fields and trailing YAML documents are rejected. Returned errors are *loaderr.Error values carrying line, column, field path, and a fix hint.
func ParseFoliageWith(data []byte, file string) (*FoliageDoc, error)ParseFoliageWith is ParseFoliage with an optional source file name attached to errors.
func (d *FoliageDoc) BuildLayers(opts FoliageBuildOptions) ([]FoliageLayer, error)BuildLayers validates d and converts every entry in d.Layers into a runtime FoliageLayer.
func (d *FoliageDoc) ScatterAll(hm *Heightmap, region math3d.AABB, opts FoliageBuildOptions) ([]*FoliageField, error)ScatterAll builds every foliage layer in d and scatters it across hm within region (or the full heightmap bounds when region is empty/zero).
type FoliageField struct {
Layer FoliageLayer
// contains filtered or unexported fields
}FoliageField holds deterministically scattered, spatially chunked foliage instances for fast frustum and distance culling.
func Scatter(hm *Heightmap, layer FoliageLayer, region math3d.AABB) *FoliageFieldScatter deterministically generates a chunked FoliageField across region on hm. If region is empty or zero, the full Heightmap bounds are used.
Instances within each spatial chunk are stored in deterministic pseudo-random order so runtime QualityProfile.DensityScale sub-sampling is spatially uniform, strictly nested across quality levels, and branch-free.
func (f *FoliageField) Bounds() math3d.AABBBounds returns the world-space AABB enclosing all scattered instances in f.
func (f *FoliageField) ChunkCount() intChunkCount returns the number of non-empty spatial chunks in f.
func (f *FoliageField) CollectVisible(
camPos math3d.Vec3,
frustum math3d.Frustum,
quality QualityProfile,
out []FoliageInstance,
) []FoliageInstanceCollectVisible culls f against frustum and effective draw distance from camPos, applies quality.DensityScale, computes smooth per-instance Fade factors (1.0 inside fade start -> 0.0 at MaxDistance), and appends visible instances into out[:0].
Passing back the slice returned on the previous frame avoids heap allocations in steady state.
func (f *FoliageField) TotalCount() intTotalCount returns the total number of scattered instances stored in f.
type FoliageInstance struct {
Transform math3d.Mat4
Fade float32 // 1.0 inside fade start distance, smoothly transitioning to 0.0 at MaxDistance
}FoliageInstance is a visible scattered instance ready for instanced rendering.
type FoliageInstanceDoc struct {
// Position is the instance's world X and Z; its Y is the terrain height there.
Position [2]float32 `yaml:"position" schema:"required"`
// Yaw is the rotation about +Y in radians.
Yaw float32 `yaml:"yaw,omitempty"`
// Scale is the uniform instance scale; omitted means 1.
Scale float32 `yaml:"scale,omitempty" schema:"exclusiveMinimum=0"`
}FoliageInstanceDoc is one deterministic hand-placed foliage transform.
type FoliageLayer struct {
Name string
MeshID uint32
MaterialID uint32
Density float32 // target candidate instances per square meter
MinScale float32 // minimum uniform instance scale (defaults to 1 if both <= 0)
MaxScale float32 // maximum uniform instance scale
AlignToNormal float32 // 0 = upright (+Y), 1 = fully aligned to terrain normal
MinSlopeDeg float32 // minimum terrain slope in degrees [0, 90]
MaxSlopeDeg float32 // maximum terrain slope in degrees [0, 90]; 0 with MinSlopeDeg==0 allows all slopes
MinHeight float32 // minimum world Y height (unconstrained if MinHeight == 0 && MaxHeight == 0)
MaxHeight float32 // maximum world Y height (unconstrained if MinHeight == 0 && MaxHeight == 0)
DensityMap *DensityMap // optional normalized density mask across terrain bounds
BaseMaxDistance float32 // default maximum draw distance in world units
Seed uint64 // deterministic PRNG seed
// BoundingRadius is the radius, at scale 1, of a sphere around the mesh pivot that encloses the mesh. When > 0, frustum culling uses each instance's scaled sphere and the draw distance and fade are measured from the sphere's nearest point, so a large tree is kept while any part of it is within range (#546). When <= 0, culling assumes a unit-radius mesh and distances are measured from the pivot.
BoundingRadius float32
// Instances are the layer's hand-placed instances, which ExplicitInstances resolves; Scatter does not include them.
Instances []FoliageInstanceDoc
}FoliageLayer configures deterministic procedural scattering of a foliage or prop mesh across a Heightmap.
func (l FoliageLayer) ExplicitInstances(hm *Heightmap) []FoliageInstanceExplicitInstances returns l.Instances as transforms standing on hm, in their listed order, with Fade 1. It depends only on the records and the heightmap, never on Seed or the procedural settings. An instance outside hm is skipped, and hm nil returns nil.
type FoliageLayerDoc struct {
// Name is the unique identifier for this foliage layer (such as "grass", "pine_tree", "boulder").
Name string `yaml:"name" schema:"required,minLength=1"`
// Mesh is the asset path to the foliage mesh (such as a .gltf or .glb model).
Mesh string `yaml:"mesh" schema:"required,minLength=1"`
// Material is an optional asset path to a material override for the foliage mesh.
Material string `yaml:"material,omitempty"`
// DensityMap is an optional asset path to a grayscale density mask image covering the terrain bounds.
DensityMap string `yaml:"densityMap,omitempty"`
// Density is the target candidate instances per square meter; set either density or spacing (not both).
Density float32 `yaml:"density,omitempty" schema:"exclusiveMinimum=0"`
// Spacing is the target average world-space spacing between instances in meters (equivalent to density = 1 / spacing^2); set either spacing or density (not both).
Spacing float32 `yaml:"spacing,omitempty" schema:"exclusiveMinimum=0"`
// MinScale is the minimum uniform instance scale; omitted defaults to 1 (or maxScale when only maxScale is set).
MinScale float32 `yaml:"minScale,omitempty" schema:"exclusiveMinimum=0"`
// MaxScale is the maximum uniform instance scale; omitted defaults to 1 (or minScale when only minScale is set).
MaxScale float32 `yaml:"maxScale,omitempty" schema:"exclusiveMinimum=0"`
// AlignToNormal blends instance up-axis alignment from upright (0) to terrain surface normal (1).
AlignToNormal float32 `yaml:"alignToNormal,omitempty" schema:"minimum=0,maximum=1"`
// MinSlopeDeg is the minimum terrain slope in degrees [0, 90] where instances may spawn.
MinSlopeDeg float32 `yaml:"minSlopeDeg,omitempty" schema:"minimum=0,maximum=90"`
// MaxSlopeDeg is the maximum terrain slope in degrees [0, 90] where instances may spawn; 0 with minSlopeDeg 0 allows all slopes.
MaxSlopeDeg float32 `yaml:"maxSlopeDeg,omitempty" schema:"minimum=0,maximum=90"`
// MinHeight is the minimum world-space Y elevation where instances may spawn.
MinHeight *float32 `yaml:"minHeight,omitempty"`
// MaxHeight is the maximum world-space Y elevation where instances may spawn.
MaxHeight *float32 `yaml:"maxHeight,omitempty"`
// BaseMaxDistance is the default maximum draw distance in world units; 0 means uncapped unless limited by QualityProfile.
BaseMaxDistance float32 `yaml:"baseMaxDistance,omitempty" schema:"minimum=0"`
// BoundingRadius is the bounding sphere radius at scale 1 around the mesh pivot for frustum culling and distance fade; 0 defaults to 1 around the pivot.
BoundingRadius float32 `yaml:"boundingRadius,omitempty" schema:"minimum=0"`
// Seed is the deterministic PRNG seed for repeatable scattering.
Seed uint64 `yaml:"seed,omitempty"`
// Instances lists hand-placed landmark instances in world X and Z, which seed, density and the density map do not move.
Instances []FoliageInstanceDoc `yaml:"instances,omitempty"`
}FoliageLayerDoc describes one procedural foliage scatter layer in a FoliageDoc.
func FoliageLayerToDoc(layer FoliageLayer, meshPath, materialPath, densityMapPath string) FoliageLayerDocFoliageLayerToDoc converts a runtime FoliageLayer and its asset paths into a FoliageLayerDoc suitable for deterministic YAML encoding.
func (l FoliageLayerDoc) EffectiveDensity() float32EffectiveDensity returns the candidate density in instances per square meter: l.Density when positive, or 1 / (l.Spacing * l.Spacing) when l.Spacing is positive.
func (l FoliageLayerDoc) ToLayer(opts FoliageBuildOptions) (FoliageLayer, error)ToLayer converts l into a runtime FoliageLayer using opts.
type GridAxis intGridAxis identifies a principal 3D axis for 90-degree GridMap item rotations.
const (
// GridAxisX is the world X axis.
GridAxisX GridAxis = iota
// GridAxisY is the world Y axis.
GridAxisY
// GridAxisZ is the world Z axis.
GridAxisZ
)type GridBoxDoc struct {
// Min is the inclusive minimum integer [x, y, z] grid coordinate of the filled box.
Min *[3]int `yaml:"min" schema:"required"`
// Max is the inclusive maximum integer [x, y, z] grid coordinate of the filled box; each axis must be >= min.
Max *[3]int `yaml:"max" schema:"required"`
// Tile is the name of the tile in the referenced mesh library.
Tile string `yaml:"tile" schema:"required,minLength=1"`
// Orientation is the orthogonal cube rotation index in 0..23 (0..3 are 0°, 90°, 180°, 270° around +Y); omitted defaults to 0.
Orientation uint8 `yaml:"orientation,omitempty" schema:"minimum=0,maximum=23"`
}GridBoxDoc describes an axis-aligned box run of identical tiles placed from Min to Max (inclusive).
type GridCell struct {
TileID uint16
Orientation uint8
}GridCell stores the tile ID and orthogonal orientation (0..23) of a GridMap cell.
type GridCellDoc struct {
// At is the discrete integer [x, y, z] grid coordinate of the cell.
At *[3]int `yaml:"at" schema:"required"`
// Tile is the name of the tile in the referenced mesh library.
Tile string `yaml:"tile" schema:"required,minLength=1"`
// Orientation is the orthogonal cube rotation index in 0..23 (0..3 are 0°, 90°, 180°, 270° around +Y); omitted defaults to 0.
Orientation uint8 `yaml:"orientation,omitempty" schema:"minimum=0,maximum=23"`
}GridCellDoc describes one occupied cell in a GridMapDoc.
type GridColliderOptions struct {
// DisableMerge emits one static body per cell ColliderBox instead of
// greedily merging adjacent aligned boxes along X, then Z, then Y.
DisableMerge bool
// MergeTolerance sets the face-alignment tolerance for greedy box merging
// (defaults to 1e-4 when <= 0).
MergeTolerance float32
// Friction is the Coulomb friction coefficient for created static bodies
// (defaults to 0.5 when <= 0).
Friction float32
// Restitution is the bounciness in [0, 1] for created static bodies.
Restitution float32
// Layer is the collision layer bitmask (0 defaults to physics3d.LayerAll).
Layer physics3d.LayerMask
// Mask is the collision filter bitmask (0 defaults to physics3d.LayerAll).
Mask physics3d.LayerMask
// Tag is an optional label assigned to every created static body.
Tag string
}GridColliderOptions configures static physics bodies created from a GridMap.
type GridCoord struct {
X, Y, Z int
}GridCoord identifies a discrete 3D cell coordinate in a GridMap.
type GridHit struct {
Coord GridCoord
Cell GridCell
Point math3d.Vec3
Normal math3d.Vec3
Distance float32
}GridHit describes the closest intersection between a ray and an occupied GridMap cell.
type GridInstanceBatch struct {
MeshID uint32
MaterialID uint32
Transforms []math3d.Mat4
}GridInstanceBatch groups world-space instance transforms sharing the same (MeshID, MaterialID) pair for instanced 3D rendering.
type GridMap struct {
Origin math3d.Vec3
CellSize math3d.Vec3
Library *MeshLibrary
// contains filtered or unexported fields
}GridMap is a sparse 3D grid of modular mesh tiles with runtime editing, frustum-culled instanced batch generation, AABB collision queries, and raycasting.
Each cell c spans [Origin + c*CellSize, Origin + (c+1)*CellSize] and places its tile's local origin at the center of that cell, rotated by GridOrientationMat4(cell.Orientation).
func NewGridMap(cellSize math3d.Vec3, lib *MeshLibrary) *GridMapNewGridMap creates an empty GridMap with the given cell dimensions and tile library. Any non-positive CellSize axis defaults to 1.0.
func (g *GridMap) AddCollidersToWorld(w *physics3d.World, opts GridColliderOptions) []*physics3d.BodyAddCollidersToWorld creates static bodies in w for g's ColliderBoxes (greedily merged along X, then Z, then Y unless opts.DisableMerge is true) and returns the added body pointers in deterministic order.
func (g *GridMap) Bounds() math3d.AABBBounds returns the tight world-space AABB enclosing all occupied cells.
func (g *GridMap) BuildInstances(frustum *math3d.Frustum, out []GridInstanceBatch) []GridInstanceBatchBuildInstances gathers world transforms for all visible occupied cells, grouped into instanced draw batches by (MeshID, MaterialID).
If frustum is non-nil, chunks and cells outside the view frustum are culled. To avoid steady-state heap allocations, callers can pass back the slice returned from the previous frame; its batch slots and Transforms backing arrays are reused in place.
func (g *GridMap) BuildStaticBodies(opts GridColliderOptions) []physics3d.BodyBuildStaticBodies builds static physics3d.Body values for g's ColliderBoxes. Adjacent aligned boxes are greedily merged along X, then Z, then Y unless opts.DisableMerge is true.
func (g *GridMap) Cell(c GridCoord) (GridCell, bool)Cell returns the GridCell at coordinate c, or (GridCell{}, false) if empty.
func (g *GridMap) CellBounds(c GridCoord) math3d.AABBCellBounds returns the world-space axis-aligned bounding box of cell c.
func (g *GridMap) CellTransform(c GridCoord, orient uint8) math3d.Mat4CellTransform returns the world-space transform matrix placing a tile at the center of cell c rotated by orient (0..23).
func (g *GridMap) ClearCell(c GridCoord)ClearCell removes any tile stored at grid coordinate c.
func (g *GridMap) ColliderBoxes() []math3d.AABBColliderBoxes returns all world-space collider AABBs from every occupied cell in g, in deterministic (Y, Z, X) cell order.
func (g *GridMap) CollisionBoxesIn(region math3d.AABB) []math3d.AABBCollisionBoxesIn returns all world-space collider AABBs from occupied cells that intersect region. Tiles with no ColliderBoxes emit no collision boxes.
func (g *GridMap) Count() intCount returns the number of occupied cells in the GridMap.
func (g *GridMap) EachCell(fn func(c GridCoord, cell GridCell) bool)EachCell calls fn for every occupied cell in the GridMap until fn returns false or all cells have been visited.
func (g *GridMap) FillBox(minC, maxC GridCoord, tileID uint16, orient uint8)FillBox sets every cell in the inclusive coordinate box [minC, maxC] to tileID with orientation orient. Component order is normalized automatically if any minC axis exceeds maxC. Setting tileID to 0 clears the box.
func (g *GridMap) MergedColliderBoxes() []math3d.AABBMergedColliderBoxes extracts all world-space ColliderBoxes from g's occupied cells and greedily merges adjacent aligned boxes along X, then Z, then Y using physics3d.MergeBoxes. The union of the returned AABBs equals the union of g.ColliderBoxes() while reducing collider count and eliminating internal cell seams.
func (g *GridMap) Raycast(ray math3d.Ray, maxDist float32) (GridHit, bool)Raycast intersects ray with occupied cells up to maxDist (in world-space Euclidean units; ray.Dir need not be unit-length). For each cell, Raycast tests its transformed ColliderBoxes when present, falling back to its transformed LocalBounds or CellBounds so non-colliding tiles remain pickable.
func (g *GridMap) SetCell(c GridCoord, tileID uint16, orient uint8)SetCell places tileID with orientation orient (0..23) at grid coordinate c. Setting tileID to 0 clears the cell.
func (g *GridMap) ToDoc(name, meshLibrary string) (*GridMapDoc, error)ToDoc exports g as a canonical deterministic *GridMapDoc, compressing contiguous axis-aligned runs of identical tiles into GridBoxDoc entries and emitting isolated cells as GridCellDoc entries in (y, z, x) order. Every occupied cell's TileID must resolve to a named MeshTileDef in g.Library.
type GridMapDoc struct {
// Version is the schema version; must be 1.
Version int `yaml:"version" schema:"required"`
// Name is an optional human-readable name for the grid map.
Name string `yaml:"name,omitempty"`
// Origin is the world-space [x, y, z] origin of grid cell (0, 0, 0); omitted defaults to [0, 0, 0].
Origin *[3]float32 `yaml:"origin,omitempty"`
// CellSize is the world-space [x, y, z] dimensions of one grid cell; omitted defaults to [1, 1, 1].
CellSize *[3]float32 `yaml:"cellSize,omitempty"`
// MeshLibrary is the optional asset path to the glTF 2.0 (.gltf) mesh library supplying named tiles.
MeshLibrary string `yaml:"meshLibrary,omitempty"`
// Boxes lists non-overlapping filled axis-aligned coordinate box runs placed before individual cells, written in canonical (y, z, x) order.
Boxes []GridBoxDoc `yaml:"boxes,omitempty"`
// Cells lists individual occupied cells placed in canonical (y, z, x) coordinate order.
Cells []GridCellDoc `yaml:"cells,omitempty"`
}GridMapDoc is the root of a versioned YAML modular 3D grid map document referencing a mesh library and placing tiles on an integer 3D lattice.
func ParseGridMap(data []byte) (*GridMapDoc, error)ParseGridMap decodes and validates a YAML grid map document. Unknown fields and trailing YAML documents are rejected. Returned errors are *loaderr.Error values carrying line, column, field path, and a fix hint.
func ParseGridMapWith(data []byte, file string) (*GridMapDoc, error)ParseGridMapWith is ParseGridMap with an optional source file name attached to errors.
func (d *GridMapDoc) Build(lib *MeshLibrary) (*GridMap, error)Build validates d and constructs a *GridMap populated with d's boxes and cells, resolving tile names against lib.
func (d *GridMapDoc) EffectiveCellSize() math3d.Vec3EffectiveCellSize returns d.CellSize as a math3d.Vec3, defaulting to (1, 1, 1) when omitted.
func (d *GridMapDoc) EffectiveOrigin() math3d.Vec3EffectiveOrigin returns d.Origin as a math3d.Vec3, defaulting to the zero vector when omitted.
func (d *GridMapDoc) Load(fsys fs.FS) (*GridMap, error)Load loads d.MeshLibrary from fsys (when set, as glTF 2.0) and builds a runtime *GridMap.
type Heightmap struct {
Cols int
Rows int
CellSize float32
HeightScale float32
Origin math3d.Vec3
Heights []float32
// Splat optionally attaches splat-map material layers for gameplay queries via [Heightmap.LayerAt].
Splat *TerrainSplatMap
// FoliageDensity optionally attaches per-layer foliage scatter density maps keyed by foliage layer name, queried via [Heightmap.FoliageDensityAt].
FoliageDensity map[string]*DensityMap
}Heightmap represents a regular grid terrain surface in the XZ plane with +Y elevation. Sample (col, row) lives at world position:
(Origin.X + col*CellSize, Origin.Y + Heights[row*Cols+col]*HeightScale, Origin.Z + row*CellSize)
Every quad cell (col, row) is triangulated consistently across HeightAt, NormalAt, Raycast, and BuildMesh along the diagonal from (col+1, row) to (col, row+1):
- Triangle 0 (fx+fz <= 1): (v00, v01, v10)
- Triangle 1 (fx+fz > 1): (v10, v01, v11)
func DecodeHeightmapPNG(r io.Reader, cellSize, heightScale float32) (*Heightmap, error)DecodeHeightmapPNG decodes a PNG image (preserving full 16-bit precision for 16-bit grayscale PNGs) from r and returns a *Heightmap with cellSize and heightScale.
func LoadHeightmapGray(img image.Image, cellSize, heightScale float32) *HeightmapLoadHeightmapGray constructs a Heightmap from a grayscale (or color, converted to 16-bit luminance) image. Pixel intensities are normalized to [0, 1] with full 16-bit precision for *image.Gray16 inputs and scaled by heightScale during height evaluation.
func NewHeightmap(cols, rows int, cellSize, heightScale float32) *HeightmapNewHeightmap allocates a flat (zero-elevation) Heightmap of cols x rows samples with the given cellSize and heightScale.
func (h *Heightmap) Bounds() math3d.AABBBounds returns the world-space axis-aligned bounding box enclosing the terrain.
func (h *Heightmap) BuildMesh(chunkCol, chunkRow, chunkCols, chunkRows int) TerrainMeshBuildMesh generates an indexed triangle mesh for the rectangular chunk of grid cells starting at (chunkCol, chunkRow) and spanning (chunkCols, chunkRows) cells. If chunkCols or chunkRows is <= 0, the chunk extends to the remaining edge of the heightmap.
func (h *Heightmap) BuildMeshLOD(chunkCol, chunkRow, chunkCols, chunkRows int, lod int, neighbors TerrainEdgeLODs) TerrainMeshBuildMeshLOD generates an indexed triangle mesh for the rectangular chunk of grid cells starting at (chunkCol, chunkRow) and spanning (chunkCols, chunkRows) cells at the given LOD level (vertex stride 1 << lod).
Whenever a neighbor in neighbors has a strictly coarser LOD (> lod), the shared border strip is re-triangulated to connect directly to that neighbor's coarser edge vertices, eliminating both height cracks and T-junctions across any pair of adjacent LOD levels (including partial border chunks). All triangles use counter-clockwise upward (+Y) winding and every emitted vertex is referenced by at least one triangle.
func (h *Heightmap) ChunkBounds(chunkCol, chunkRow, chunkCols, chunkRows int) math3d.AABBChunkBounds returns the world-space axis-aligned bounding box enclosing the rectangular chunk of grid cells starting at (chunkCol, chunkRow) and spanning (chunkCols, chunkRows) cells. If chunkCols or chunkRows is <= 0, the chunk extends to the remaining edge of the heightmap.
func (h *Heightmap) Collider() *physics3d.HeightfieldColliderCollider constructs a static physics3d.HeightfieldCollider matching h's grid dimensions, cell size, origin, and scaled vertex heights.
func (h *Heightmap) EncodePNG(w io.Writer) errorEncodePNG encodes h as a 16-bit grayscale PNG image into w.
func (h *Heightmap) FoliageDensityAt(layer string, x, z float32) (float32, bool)FoliageDensityAt samples the attached foliage density map for layer at world coordinates (x, z). The boolean reports whether (x, z) lies inside the heightmap's XZ footprint. Returns (0, false) when h is invalid or has no density map for layer.
func (h *Heightmap) HeightAt(x, z float32) (float32, bool)HeightAt returns the exact barycentric triangle-interpolated world Y height at world coordinates (x, z), or (0, false) if (x, z) lies outside the terrain.
func (h *Heightmap) LayerAt(x, z float32) (TerrainLayerSample, bool)LayerAt samples the terrain material layers attached to h.Splat at world coordinates (x, z). The boolean reports whether (x, z) lies inside the heightmap's XZ footprint; when (x, z) is outside the footprint but h and h.Splat are valid, LayerAt still clamps to the nearest terrain edge and returns the clamped edge sample alongside ok == false.
Returns (zero, false) when h is invalid or h.Splat is nil/empty.
func (h *Heightmap) NormalAt(x, z float32) math3d.Vec3NormalAt returns the unit upward (+Y) surface normal of the terrain triangle containing (x, z). If (x, z) lies outside the terrain, Vec3Up is returned.
func (h *Heightmap) Raycast(ray math3d.Ray, maxDist float32) (TerrainHit, bool)Raycast intersects ray with the heightmap using 2D grid DDA traversal paired with exact Möller-Trumbore triangle intersection. It visits only the cells under the ray, O(Cols+Rows) at most, and never scans the whole height grid. Distance and maxDist are measured in world-space Euclidean units (ray.Dir need not be unit-length).
func (h *Heightmap) SampleHeight(col, row int) float32SampleHeight returns the world-space Y height at grid sample (col, row), clamping col and row to valid sample indices.
func (h *Heightmap) ToGray16() *image.Gray16ToGray16 converts h's normalized [0, 1] heights into a 16-bit grayscale image suitable for lossless 16-bit PNG encoding without 8-bit banding. Values outside [0, 1] are clamped. Returns nil if h has non-positive dimensions or insufficient samples.
type MeshLibrary struct {
// contains filtered or unexported fields
}MeshLibrary is a registry of MeshTileDef entries indexed by ID and Name. Tile ID 0 is reserved to denote an empty grid cell.
func LoadMeshLibraryFromGLTF(gltfJSON []byte) (*MeshLibrary, error)LoadMeshLibraryFromGLTF parses a glTF 2.0 JSON (.gltf) or binary (.glb) document's nodes, meshes, and POSITION accessor min/max bounds to build a MeshLibrary without external dependencies. Each node referencing a mesh becomes a MeshTileDef whose MeshID is the glTF mesh index, MaterialID is the first primitive's material index (or 0 if omitted), LocalBounds is the union of all primitive POSITION accessor bounds, and ColliderBoxes defaults to LocalBounds when present.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read the document from a file names it with loaderr.WithFile.
func NewMeshLibrary() *MeshLibraryNewMeshLibrary returns an empty MeshLibrary ready to register tile definitions.
func (l *MeshLibrary) Add(def MeshTileDef) uint16Add registers def in the library and returns its assigned non-zero tile ID. If def.ID is 0, the next available ID starting from 1 is assigned. If def.ID already exists in the library, its definition is replaced. When all 65535 IDs are taken, Add registers nothing and returns 0 (#546).
func (l *MeshLibrary) ByName(name string) (MeshTileDef, bool)ByName looks up a tile definition by Name.
func (l *MeshLibrary) Get(id uint16) (MeshTileDef, bool)Get looks up a tile definition by ID.
func (l *MeshLibrary) Items() []MeshTileDefItems returns all tile definitions registered in the library sorted by ascending ID. Each returned entry owns a copy of its ColliderBoxes.
func (l *MeshLibrary) Len() intLen returns the number of tile definitions registered in the library.
func (l *MeshLibrary) Revision() uint64Revision returns a counter that changes whenever Add replaces or registers a definition, so caches derived from the library can invalidate.
type MeshTileDef struct {
ID uint16
Name string
MeshID uint32
MaterialID uint32
LocalBounds math3d.AABB
ColliderBoxes []math3d.AABB
}MeshTileDef describes a modular 3D tile stored in a MeshLibrary.
type QualityLevel uint8QualityLevel selects a built-in foliage density and draw-distance tier.
const (
QualityLow QualityLevel = iota
QualityMedium
QualityHigh
QualityUltra
)func QualityLevelFor(l quality.Level) QualityLevelQualityLevelFor returns the foliage tier for a game-wide quality level: QualityLow for quality.Low, QualityMedium for quality.Medium and QualityHigh for quality.High. QualityUltra stays an explicit choice above every preset. An invalid level maps to QualityMedium, as quality.DefaultPreset does.
type QualityProfile struct {
// DensityScale scales the fraction of scattered instances emitted, in [0, 1].
DensityScale float32
// MaxDistance caps the maximum visible distance in world units (meters).
// If <= 0, the layer's BaseMaxDistance is used.
MaxDistance float32
// FadeStartRatio is the fraction of effective MaxDistance in [0, 1] at which
// instances begin fading smoothly from 1.0 down to 0.0 at MaxDistance.
FadeStartRatio float32
}QualityProfile controls runtime foliage density scaling, maximum visibility distance, and smooth distance fade-out.
func DefaultQualityProfile(level QualityLevel) QualityProfileDefaultQualityProfile returns recommended foliage settings for level.
type TerrainDoc struct {
// Version is the schema version; must be 1.
Version int `yaml:"version" schema:"required"`
// Name is an optional human-readable name for the terrain.
Name string `yaml:"name,omitempty"`
// Size is the optional [cols, rows] heightmap grid dimensions (each >= 2). When set alongside heightmap, the decoded heightmap image must match these dimensions; when heightmap is omitted, a flat heightmap of this size is created.
Size *[2]int `yaml:"size,omitempty"`
// Heightmap is the asset path to the 16-bit (or 8-bit) grayscale PNG heightmap image.
Heightmap string `yaml:"heightmap,omitempty"`
// CellSize is the world-space XZ spacing between adjacent heightmap samples; omitted or 0 defaults to 1.
CellSize float32 `yaml:"cellSize,omitempty" schema:"exclusiveMinimum=0"`
// HeightScale scales normalized [0, 1] heightmap samples into world-space Y units.
HeightScale float32 `yaml:"heightScale,omitempty" schema:"minimum=0"`
// Origin is the world-space [x, y, z] origin of heightmap sample (0, 0); omitted defaults to [0, 0, 0].
Origin *[3]float32 `yaml:"origin,omitempty"`
// ChunkSize is the number of heightmap grid cells along each terrain LOD chunk edge; omitted or 0 defaults to 64.
ChunkSize int `yaml:"chunkSize,omitempty" schema:"minimum=1"`
// SplatMaps lists 1 or 2 RGBA weight-map asset paths: map 0 drives layers 0..3 (R,G,B,A) and map 1 drives layers 4..7 (R,G,B,A). Mutually exclusive with per-layer weightMap paths.
SplatMaps []string `yaml:"splatMaps,omitempty"`
// HeightBlendContrast enables height-based layer blending when > 0 in [0, 1]; higher values sharpen layer transitions using per-layer height maps, and 0 uses linear splat blending.
HeightBlendContrast float32 `yaml:"heightBlendContrast,omitempty" schema:"minimum=0,maximum=1"`
// Triplanar configures slope-driven triplanar texture projection on steep terrain faces.
Triplanar *TerrainTriplanarDoc `yaml:"triplanar,omitempty"`
// Layers lists 1 to 8 PBR terrain material layers in channel order (0..3 from splatMaps[0] RGBA and 4..7 from splatMaps[1] RGBA, or each driven by its own weightMap PNG).
Layers []TerrainLayerDoc `yaml:"layers" schema:"required,minItems=1"`
// Foliage lists optional procedural foliage scatter layers attached to this terrain, each with an optional grayscale density map PNG.
Foliage []FoliageLayerDoc `yaml:"foliage,omitempty"`
}TerrainDoc is the root of a versioned YAML terrain definition specifying heightmap dimensions, splat or per-layer weight-map asset paths, height-blending and triplanar settings, up to 8 PBR material layers, and optional procedural foliage scatter layers with density maps.
func ParseTerrain(data []byte) (*TerrainDoc, error)ParseTerrain decodes and validates a YAML terrain definition document. Unknown fields and trailing YAML documents are rejected. Returned errors are *loaderr.Error values carrying line, column, field path, and a fix hint.
func ParseTerrainWith(data []byte, file string) (*TerrainDoc, error)ParseTerrainWith is ParseTerrain with an optional source file name attached to errors.
func (d *TerrainDoc) BuildFoliageLayers(opts FoliageBuildOptions) ([]FoliageLayer, error)BuildFoliageLayers validates d and converts every entry in d.Foliage into a runtime FoliageLayer using opts. Returns nil, nil when d.Foliage is empty.
func (d *TerrainDoc) BuildHeightmap(imgs TerrainImages) (*Heightmap, error)BuildHeightmap validates d and constructs a *Heightmap configured with d's CellSize, HeightScale, Origin, optional attached *TerrainSplatMap (from imgs.SplatMaps or imgs.LayerWeights, with HeightBlendContrast and per-layer height maps), and optional attached foliage density maps.
func (d *TerrainDoc) BuildLOD(hm *Heightmap) *TerrainLODBuildLOD constructs a *TerrainLOD for hm using d's TerrainDoc.LODConfig.
func (d *TerrainDoc) EffectiveCellSize() float32EffectiveCellSize returns d.CellSize, defaulting to 1 when zero.
func (d *TerrainDoc) EffectiveChunkSize() intEffectiveChunkSize returns d.ChunkSize, defaulting to 64 when omitted or zero.
func (d *TerrainDoc) EffectiveOrigin() math3d.Vec3EffectiveOrigin returns d.Origin as a math3d.Vec3, defaulting to the zero vector when omitted.
func (d *TerrainDoc) HasLayerWeightMaps() boolHasLayerWeightMaps reports whether any layer in d specifies a per-layer WeightMap path.
func (d *TerrainDoc) LODConfig() TerrainLODConfigLODConfig returns a TerrainLODConfig populated from d's ChunkSize.
func (d *TerrainDoc) LayerInfos() []TerrainLayerInfoLayerInfos converts d.Layers into TerrainLayerInfo metadata (name, UV scale, and height bias) suitable for constructing a TerrainSplatMap.
func (d *TerrainDoc) LoadHeightmap(fsys fs.FS) (*Heightmap, error)LoadHeightmap decodes the heightmap, optional splat or per-layer weight maps, optional per-layer height maps, and optional foliage density maps referenced by d from fsys, then builds a runtime *Heightmap.
func (d *TerrainDoc) ScatterFoliage(hm *Heightmap, region math3d.AABB, opts FoliageBuildOptions) ([]*FoliageField, error)ScatterFoliage builds every foliage layer declared in d.Foliage and scatters it across hm within region (or the full heightmap bounds when region is empty/zero). When a layer's density map is already loaded on hm.FoliageDensity and opts.LoadDensityMap is nil, the attached density map is reused directly.
type TerrainEdgeLODs struct {
North int // neighbor toward -Z (smaller row)
South int // neighbor toward +Z (larger row)
West int // neighbor toward -X (smaller col)
East int // neighbor toward +X (larger col)
}TerrainEdgeLODs specifies the LOD level of each cardinal neighbor of a terrain chunk so BuildMeshLOD can stitch shared borders without cracks or T-junctions. A neighbor LOD less than or equal to the chunk's own LOD (including negative values for absent neighbors) leaves that edge unstitched.
type TerrainHeightLayer struct {
Width int
Height int
Heights []float32
}TerrainHeightLayer holds a CPU-readable normalized [0, 1] height texture for one terrain material layer so TerrainSplatMap.SampleUV and Heightmap.LayerAt can apply height-based blending matching the GPU terrain shader.
func LoadTerrainHeightLayer(img image.Image) *TerrainHeightLayerLoadTerrainHeightLayer converts a grayscale (or color, converted to 16-bit luminance) image into a normalized [0, 1] TerrainHeightLayer. Returns nil if img is nil or has empty bounds.
func (l *TerrainHeightLayer) SampleUV(u, v float32) float32SampleUV bilinearly samples the height layer at repeating texture coordinates (u, v), matching GPU linear-repeat texture sampling. Returns 0.5 when l is nil or empty.
type TerrainHit struct {
Point math3d.Vec3
Normal math3d.Vec3
Distance float32
Col, Row int
}TerrainHit describes the closest intersection between a ray and a Heightmap.
type TerrainImages struct {
// Heightmap is the grayscale heightmap image (required when TerrainDoc.Size is nil; at least 2x2 pixels).
Heightmap image.Image
// SplatMaps holds 0, 1, or 2 RGBA weight-map images matching TerrainDoc.SplatMaps.
SplatMaps []image.Image
// LayerWeights optionally maps a layer's Name to its decoded grayscale weight-map PNG when per-layer weightMap paths are used instead of SplatMaps.
LayerWeights map[string]image.Image
// LayerHeights optionally maps a layer's Name to its decoded grayscale height map for height-based blending.
LayerHeights map[string]image.Image
// FoliageDensityMaps optionally maps a foliage layer's Name to its decoded grayscale density map PNG.
FoliageDensityMaps map[string]image.Image
}TerrainImages holds decoded images supplied to TerrainDoc.BuildHeightmap when constructing a runtime *Heightmap without reading from an fs.FS.
type TerrainLOD struct {
// contains filtered or unexported fields
}TerrainLOD partitions a Heightmap into chunks, selects per-chunk LOD levels from camera distance with hysteresis and quality bias, culls chunk AABBs against a camera frustum, and caches crack-free stitched TerrainMesh geometry per chunk. It works in world space or with FloatingOrigin and ChunkStreamer.
func NewTerrainLOD(hm *Heightmap, cfg TerrainLODConfig) *TerrainLODNewTerrainLOD constructs a TerrainLOD manager for hm using cfg.
func (t *TerrainLOD) ChunkBounds(coord ChunkCoord) (math3d.AABB, bool)ChunkBounds returns the world-space AABB for the chunk at coord.
func (t *TerrainLOD) ChunkCells() intChunkCells returns the nominal cell count along each chunk edge.
func (t *TerrainLOD) ChunkCount() intChunkCount returns the total number of chunks partitioning the heightmap.
func (t *TerrainLOD) ChunkLOD(coord ChunkCoord) (int, bool)ChunkLOD returns the most recently selected LOD level for coord, or (-1, false) if coord is out of bounds or has not been evaluated while active.
func (t *TerrainLOD) ChunkWorldSize() float64ChunkWorldSize returns the world-space width of a full chunk (ChunkCells * Heightmap.CellSize), suitable for configuring ChunkStreamerConfig.ChunkSize.
func (t *TerrainLOD) EvictHiddenMeshes()EvictHiddenMeshes frees cached TerrainMesh buffers for chunks that were not visible in the most recent Update.
func (t *TerrainLOD) GridSize() (cols, rows int)GridSize returns the number of terrain chunks along X (cols) and Z (rows).
func (t *TerrainLOD) InvalidateAll()InvalidateAll recomputes every chunk AABB and forces all cached meshes to rebuild as they become visible.
func (t *TerrainLOD) InvalidateChunk(coord ChunkCoord)InvalidateChunk recomputes the AABB for coord and forces its mesh to rebuild on the next Update (for example after editing Heightmap.Heights in place).
func (t *TerrainLOD) IsChunkActive(coord ChunkCoord) boolIsChunkActive reports whether coord is a valid chunk coordinate in t and is currently active.
func (t *TerrainLOD) LODBias() float32LODBias returns the current LOD bias.
func (t *TerrainLOD) MaxLOD() intMaxLOD returns the coarsest LOD index managed by t.
func (t *TerrainLOD) SetChunkActive(coord ChunkCoord, active bool)SetChunkActive activates or deactivates the chunk at coord (typically called from ChunkStreamer's OnLoad and OnUnload callbacks when StreamManaged is true). Deactivating a chunk releases its cached mesh; neighboring seams automatically re-stitch on the next Update.
func (t *TerrainLOD) SetLODBias(bias float32)SetLODBias updates the LOD bias (threshold scale = 2^(-bias)) and resets per-chunk hysteresis memory so the next Update reflects the new bias immediately.
func (t *TerrainLOD) SetQualityLevel(level quality.Level)SetQualityLevel applies TerrainLODBiasFor(level) to t.
func (t *TerrainLOD) Stats() TerrainLODStatsStats returns summary statistics from the most recent Update or UpdateWithOrigin call.
func (t *TerrainLOD) Update(camPos math3d.Vec3, frustum *math3d.Frustum) []TerrainLODChunkUpdate selects per-chunk LOD levels for a world-space camera at camPos, culls chunk bounds against frustum (when non-nil), builds or reuses crack-free stitched meshes for visible chunks, and returns the visible chunk slice.
The returned slice aliases internal storage reused across calls; copy any fields needed past the next Update.
func (t *TerrainLOD) UpdateWithOrigin(camLocal math3d.Vec3, frustumLocal *math3d.Frustum, origin *FloatingOrigin) []TerrainLODChunkUpdateWithOrigin advances terrain LOD selection and frustum culling using a camera and frustum expressed in FloatingOrigin local space.
Camera-to-chunk distances are evaluated in float64 world space so LOD selection is completely invariant to FloatingOrigin rebasing. Each returned TerrainLODChunk carries Bounds and a translation Transform in local space, allowing cached chunk meshes to render cleanly across rebases without rebuilding vertex buffers.
type TerrainLODChunk struct {
Coord ChunkCoord
Col int
Row int
Cols int
Rows int
LOD int
Edges TerrainEdgeLODs
Bounds math3d.AABB
Transform math3d.Mat4
Mesh *TerrainMesh
Revision uint64
Changed bool
}TerrainLODChunk describes one visible terrain chunk returned by TerrainLOD.Update or TerrainLOD.UpdateWithOrigin.
type TerrainLODConfig struct {
// ChunkCells is the number of heightmap grid cells along each chunk edge.
// Defaults to 64 when <= 0.
ChunkCells int
// Distances lists the maximum camera-to-chunk-AABB distance for LOD 0, 1,
// ... in world units. Chunks beyond the last entry use the coarsest level.
// When empty, geometric distances starting at 1.0 * ChunkWorldSize (doubling
// per LOD level up to MaxLOD) are generated automatically.
Distances []float32
// Hysteresis is the relative deadband in (0, 0.5] around each LOD distance
// threshold to prevent popping when the camera oscillates near a boundary.
// Zero uses the default 0.10 (10%); negative values disable hysteresis.
Hysteresis float32
// LODBias shifts LOD distance thresholds by 2^(-LODBias). Positive values
// choose coarser LODs at shorter distances (fewer triangles); negative values
// keep finer detail farther away. Use TerrainLODBiasFor(level) to derive a
// bias from a game-wide quality preset.
LODBias float32
// MaxLOD optionally caps the coarsest LOD level (vertex stride 1<<MaxLOD).
// When <= 0, MaxLOD is derived from ChunkCells so stride reaches ChunkCells.
MaxLOD int
// WorldOrigin places the heightmap's (0, 0) sample in double-precision world
// space for FloatingOrigin and ChunkStreamer integration. When HasWorldOrigin
// is false and WorldOrigin is zero, Heightmap.Origin is used.
WorldOrigin WorldPos64
HasWorldOrigin bool
// StreamManaged, when true, starts with all chunks inactive so a
// ChunkStreamer activates and deactivates chunks via SetChunkActive.
// When false (default), every chunk covering the heightmap is active.
StreamManaged bool
}TerrainLODConfig configures a TerrainLOD chunk manager.
type TerrainLODStats struct {
TotalChunks int
ActiveChunks int
VisibleChunks int
CulledChunks int
RebuiltChunks int
TotalTriangles int
TotalVertices int
}TerrainLODStats summarizes the most recent TerrainLOD update.
type TerrainLayerDoc struct {
// Name is the unique gameplay and authoring identifier for this layer (such as "grass", "dirt", "rock", "snow").
Name string `yaml:"name" schema:"required,minLength=1"`
// Material is an optional asset path to a material resource file (such as materials/grass.material.yaml) supplying default base color, texture, roughness, and metallic values.
Material string `yaml:"material,omitempty"`
// WeightMap is an optional asset path to a per-layer grayscale weight-map PNG covering the terrain footprint; mutually exclusive with top-level splatMaps.
WeightMap string `yaml:"weightMap,omitempty"`
// Albedo is the asset path to the sRGB base-color texture.
Albedo string `yaml:"albedo,omitempty"`
// Normal is the asset path to the linear tangent-space normal map.
Normal string `yaml:"normal,omitempty"`
// MetallicRoughness is the asset path to the glTF metallic-roughness map (G = roughness, B = metallic).
MetallicRoughness string `yaml:"metallicRoughness,omitempty"`
// Height is the asset path to the optional grayscale height map used for height-based blending.
Height string `yaml:"height,omitempty"`
// Color is the linear RGB tint multiplier in [0, 1]^3; omitted defaults to [1, 1, 1].
Color *[3]float32 `yaml:"color,omitempty"`
// Roughness is the layer roughness factor in [0, 1]; omitted defaults to 1 when metallicRoughness is set or 0.85 otherwise.
Roughness *float32 `yaml:"roughness,omitempty" schema:"minimum=0,maximum=1"`
// Metallic is the layer metallic factor in [0, 1]; omitted defaults to 0.
Metallic float32 `yaml:"metallic,omitempty" schema:"minimum=0,maximum=1"`
// NormalScale scales the XY components of the tangent-space normal map; omitted defaults to 1.
NormalScale *float32 `yaml:"normalScale,omitempty"`
// UVScale is the per-layer UV tiling multiplier [u, v] across the terrain; omitted defaults to [1, 1].
UVScale *[2]float32 `yaml:"uvScale,omitempty"`
// HeightBias biases this layer's height map during height-based blending in [-1, 1].
HeightBias float32 `yaml:"heightBias,omitempty" schema:"minimum=-1,maximum=1"`
}TerrainLayerDoc describes one PBR terrain material layer in a TerrainDoc.
func (l TerrainLayerDoc) EffectiveColor() [3]float32EffectiveColor returns l.Color when set, or linear white [1, 1, 1] when omitted.
func (l TerrainLayerDoc) EffectiveNormalScale() float32EffectiveNormalScale returns l.NormalScale when set, or 1.0 when omitted.
func (l TerrainLayerDoc) EffectiveRoughness() float32EffectiveRoughness returns l.Roughness when set, 1.0 when MetallicRoughness is set, or DefaultTerrainLayerRoughness (0.85) otherwise.
func (l TerrainLayerDoc) EffectiveUVScale() math3d.Vec2EffectiveUVScale returns l.UVScale when set, or [1, 1] when omitted.
type TerrainLayerInfo struct {
// Name is the gameplay surface identifier (such as "grass", "dirt", "rock", "snow").
Name string
// UVScale scales terrain [0, 1] UVs when sampling HeightMap; zero components default to 1.
UVScale math3d.Vec2
// HeightBias biases this layer's height during height-based blending (typically in [-1, 1]).
HeightBias float32
// HeightMap optionally supplies a tiling height map for height-based blending; nil uses 0.5.
HeightMap *TerrainHeightLayer
}TerrainLayerInfo describes one material layer's gameplay identity and height-blending parameters inside a TerrainSplatMap.
type TerrainLayerSample struct {
// Dominant is the index in [0, Count) of the layer with the highest normalized weight.
// Ties break deterministically in favor of the lower layer index.
Dominant int
// Name is the configured name of the Dominant layer.
Name string
// Weights holds the normalized per-layer weights in [0, 1] summing to 1 across [0, Count).
// Entries at indices >= Count are zero.
Weights [MaxTerrainLayers]float32
// Count is the number of active layers in [0, MaxTerrainLayers].
Count int
}TerrainLayerSample is the zero-allocation result of sampling terrain material layers at a world position or terrain UV for footsteps, particles, and movement logic.
func (s TerrainLayerSample) Weight(index int) float32Weight returns the normalized weight of layer index, or 0 if index is out of range.
type TerrainMesh struct {
Positions []math3d.Vec3
Normals []math3d.Vec3
UVs []math3d.Vec2
Indices []uint32
}TerrainMesh holds indexed triangle-list geometry for a heightmap chunk ready for upload to a GPU vertex and index buffer. Triangles use counter-clockwise winding when viewed from +Y.
type TerrainSplatMap struct {
// Layers holds the 1..8 material layer definitions in splat-channel order.
Layers []TerrainLayerInfo
// HeightBlendContrast controls optional height-based weight sharpening in [0, 1].
// Zero disables height blending (pure linear splat weights).
HeightBlendContrast float32
// Origin is the world-space (X, Z) origin used by [TerrainSplatMap.LayerAt].
Origin math3d.Vec2
// Size is the world-space (X, Z) footprint used by [TerrainSplatMap.LayerAt].
// When zero or non-positive, [TerrainSplatMap.LayerAt] treats (x, z) directly as UVs.
Size math3d.Vec2
// contains filtered or unexported fields
}TerrainSplatMap stores 1 or 2 RGBA weight (splat) maps and up to 8 layer definitions for CPU-side gameplay queries via TerrainSplatMap.SampleUV, TerrainSplatMap.LayerAt, and Heightmap.LayerAt.
Splat map 0's R, G, B, A channels drive layers 0..3; splat map 1's R, G, B, A channels drive layers 4..7. Sampling uses bilinear texel-center interpolation with edge clamping, matching GPU linear clamp-to-edge sampling.
func LoadTerrainSplatMap(layers []TerrainLayerInfo, maps ...image.Image) (*TerrainSplatMap, error)LoadTerrainSplatMap constructs a TerrainSplatMap from 1..8 layer definitions and 1 or 2 RGBA splat-map images (splat0 for layers 0..3, optional splat1 for layers 4..7). Note that standard *image.NRGBA preserves all 4 channels verbatim including zero-alpha texels.
func LoadTerrainSplatMapFromWeights(layers []TerrainLayerInfo, weights []image.Image) (*TerrainSplatMap, error)LoadTerrainSplatMapFromWeights constructs a TerrainSplatMap from 1..8 layer definitions and per-layer grayscale weight-map images. Trailing omitted entries in weights default to zero weight; images with different dimensions are resampled to match the first non-nil weight image.
func NewTerrainSplatMapFromRGBA(width, height int, layers []TerrainLayerInfo, splat0, splat1 []byte) (*TerrainSplatMap, error)NewTerrainSplatMapFromRGBA constructs a TerrainSplatMap from tightly packed straight-alpha RGBA8 byte buffers (width × height × 4 bytes each). splat1 may be nil when len(layers) <= 4.
func (s *TerrainSplatMap) Height() intHeight returns the texel height of splat map 0, or 0 for a nil splat map.
func (s *TerrainSplatMap) LayerAt(x, z float32) TerrainLayerSampleLayerAt maps world coordinates (x, z) using s.Origin and s.Size, clamps to the terrain's [0, 1] UV extent, and returns the dominant layer and normalized weights. When attached to a Heightmap, prefer Heightmap.LayerAt, which derives UV bounds automatically from the heightmap's Origin, Cols, Rows, and CellSize.
func (s *TerrainSplatMap) LayerCount() intLayerCount returns the number of active layers in s (0 for nil).
func (s *TerrainSplatMap) LayerIndex(name string) intLayerIndex returns the index of the first layer named name, or -1 if not found.
func (s *TerrainSplatMap) LayerName(index int) stringLayerName returns the name of layer index, or "" if out of range.
func (s *TerrainSplatMap) LayerWeightImage(layer int) *image.GrayLayerWeightImage extracts layer's weight channel (0..7) as an 8-bit grayscale image, or nil if s is nil or layer is out of range.
func (s *TerrainSplatMap) SampleUV(u, v float32) TerrainLayerSampleSampleUV samples the splat map(s) at normalized terrain UV coordinates (u, v), clamping out-of-bounds UVs to [0, 1], applying optional height-based blending, and returning the dominant layer and normalized per-layer weights.
func (s *TerrainSplatMap) SetTexelWeight(layer, x, y int, weight float32)SetTexelWeight writes a clamped [0, 1] weight for layer at texel (x, y). Out-of-range coordinates or layers are ignored.
func (s *TerrainSplatMap) SplatImages() (splat0, splat1 *image.NRGBA)SplatImages returns copies of s's RGBA splat map(s) as *image.NRGBA images (splat1 is nil when s has at most 4 layers).
func (s *TerrainSplatMap) TexelWeight(layer, x, y int) float32TexelWeight returns the raw weight in [0, 1] stored for layer at texel (x, y), or 0 if out of range.
func (s *TerrainSplatMap) Width() intWidth returns the texel width of splat map 0, or 0 for a nil splat map.
type TerrainTriplanarDoc struct {
// Enabled activates triplanar projection on steep slopes whose upward normal falls below SlopeThreshold.
Enabled bool `yaml:"enabled,omitempty"`
// SlopeThreshold is the world normal Y threshold in [0, 1] below which triplanar projection begins blending in; omitted or 0 defaults to 0.7.
SlopeThreshold float32 `yaml:"slopeThreshold,omitempty" schema:"minimum=0,maximum=1"`
// SlopeBlend is the transition width in [0, 1] over which planar UVs cross-fade into triplanar projection; omitted or 0 defaults to 0.15.
SlopeBlend float32 `yaml:"slopeBlend,omitempty" schema:"minimum=0,maximum=1"`
// Sharpness controls triplanar axis blend sharpness (typically 1..16); omitted or 0 defaults to 4.
Sharpness float32 `yaml:"sharpness,omitempty" schema:"exclusiveMinimum=0"`
// Scale is the world-space triplanar repeat rate (repeats per world unit); omitted or 0 defaults to 0.25.
Scale float32 `yaml:"scale,omitempty" schema:"exclusiveMinimum=0"`
}TerrainTriplanarDoc configures slope-driven triplanar projection in a TerrainDoc.
func (t *TerrainTriplanarDoc) EffectiveScale() float32EffectiveScale returns t.Scale, defaulting to 0.25 when zero.
func (t *TerrainTriplanarDoc) EffectiveSharpness() float32EffectiveSharpness returns t.Sharpness, defaulting to 4.0 when zero.
func (t *TerrainTriplanarDoc) EffectiveSlopeBlend() float32EffectiveSlopeBlend returns t.SlopeBlend, defaulting to 0.15 when zero.
func (t *TerrainTriplanarDoc) EffectiveSlopeThreshold() float32EffectiveSlopeThreshold returns t.SlopeThreshold, defaulting to 0.7 when zero.
type TilemapStreamer struct {
// contains filtered or unexported fields
}TilemapStreamer bridges world3d.ChunkStreamer[*tilemap.Chunk] onto a sparse chunked tilemap.TileLayer, providing bounded streaming, background generation, hysteresis unloading, and deterministic YAML/JSON persistence of modified chunks without breaking game/tilemap's stability boundary.
func NewTilemapStreamer(cfg TilemapStreamerConfig) (*TilemapStreamer, error)NewTilemapStreamer constructs a TilemapStreamer backed by a world3d.ChunkStreamer[*tilemap.Chunk]. Call Close when finished to save any loaded modified chunks and stop worker goroutines.
func (s *TilemapStreamer) Close()Close stops background loader workers and unloads all remaining chunks, saving any modified chunks to Store.
func (s *TilemapStreamer) SaveModified() errorSaveModified persists every currently loaded modified chunk in deterministic order to Store.
func (s *TilemapStreamer) Streamer() *ChunkStreamer[*tilemap.Chunk]Streamer returns the underlying world3d.ChunkStreamer[*tilemap.Chunk].
func (s *TilemapStreamer) Update(worldX, worldY float64)Update advances chunk streaming for a 2D world position (worldX, worldY) in tilemap world points.
type TilemapStreamerConfig struct {
// Map is the Tilemap owning LayerIndex.
Map *tilemap.Tilemap
// LayerIndex selects the chunked TileLayer inside Map.Layers.
LayerIndex int
// LoadRadius is the Chebyshev chunk radius around the player chunk to load.
LoadRadius int
// UnloadRadius is the Chebyshev chunk radius beyond which loaded and in-flight chunks unload/cancel.
// Defaults to LoadRadius + 1 when smaller than LoadRadius.
UnloadRadius int
// MaxIntegrationsPerFrame caps how many completed chunks integrate into Map per Update call (<= 0 means unlimited).
MaxIntegrationsPerFrame int
// Workers sets the number of background ChunkStreamer loader goroutines (0 runs synchronously inside Update).
Workers int
// Format selects tilemap.ChunkFormatYAML (default) or tilemap.ChunkFormatJSON for Store persistence.
Format tilemap.ChunkFormat
// Store persists modified chunks on unload and restores them on reload before invoking Generator.
// When Workers > 0, Store must be safe for concurrent use (such as tilemap.MemoryChunkStore or tilemap.DirChunkStore).
Store tilemap.ChunkStore
// Generator populates a freshly allocated chunk when Store has no saved entry for coord.
// It must respect ctx cancellation when Workers > 0.
Generator func(ctx context.Context, coord tilemap.ChunkCoord, chunk *tilemap.Chunk) error
// OnLoad runs on the Update goroutine after a chunk is installed into Map.Layers[LayerIndex].
OnLoad func(coord tilemap.ChunkCoord, chunk *tilemap.Chunk)
// OnUnload runs on the Update/Close goroutine after a chunk is saved (if modified) and removed from Map.Layers[LayerIndex].
OnUnload func(coord tilemap.ChunkCoord, chunk *tilemap.Chunk)
// OnError runs on the Update goroutine when loading, generating, or saving a chunk fails.
OnError func(coord tilemap.ChunkCoord, err error)
}TilemapStreamerConfig configures a TilemapStreamer that drives a sparse chunked tilemap.TileLayer with a world3d.ChunkStreamer[*tilemap.Chunk].
type WorldPos64 struct {
X, Y, Z float64
}WorldPos64 is a double-precision 3D world-space position used for large worlds (tens to hundreds of kilometers) where float32 world coordinates would suffer noticeable precision jitter.
func (p WorldPos64) ChunkCoord(chunkSize float64) ChunkCoordChunkCoord returns the 2D XZ streaming chunk coordinate containing p for a world partitioned into square chunks of size chunkSize.
func (p WorldPos64) Dist(b WorldPos64) float64Dist returns the Euclidean distance between p and b.
func (p WorldPos64) DistSq(b WorldPos64) float64DistSq returns the squared Euclidean distance between p and b.