GitHubCommencer

Cette page n’est pas encore traduite en français ; la version anglaise est affichée ci-dessous.

3D

world3d

game/world3d provides 3D world-building primitives built on math3d: heightmap terrain, multi-level 3D navigation meshes, modular 3D mesh GridMaps, procedural scattered foliage with frustum/distance culling, and floating-origin chunk streaming.

import "github.com/nsgo-dev/game/pkg/world3d"

Heightmap terrain (Heightmap)

Load a 16-bit (or 8-bit) grayscale PNG heightmap (LoadHeightmapGray, DecodeHeightmapPNG) or create one with NewHeightmap, then sample bilinear heights and normals, raycast against triangles, build chunked TerrainMesh geometry, and write back lossless 16-bit grayscale PNGs (ToGray16, EncodePNG, EncodeHeightmapPNG) without 8-bit slope banding:

hm := world3d.LoadHeightmapGray(grayImg, 2.0, 40.0)

y, ok := hm.HeightAt(player.X, player.Z)
normal := hm.NormalAt(player.X, player.Z)
hit, hitOK := hm.Raycast(ray, 500)

// Build a 32x32 cell mesh chunk for GPU upload:
chunkMesh := hm.BuildMesh(0, 0, 32, 32)
// Or bridge directly to a physics3d.HeightfieldCollider:
hfCollider := hm.Collider()
_, _, _, _, _, _ = y, ok, normal, hit, chunkMesh, hfCollider
_ = hitOK

Terrain level of detail (TerrainLOD)

Large terrains can contain tens of millions of triangles at full resolution. TerrainLOD partitions a Heightmap into chunks (default 64×64 cells), selects per-chunk power-of-two vertex strides (1, 2, 4, ...) from camera-to-AABB distance with hysteresis, applies bias from the game-wide quality preset (TerrainLODBiasFor), culls chunk AABBs against the camera frustum, and caches crack-free stitched TerrainMesh geometry per chunk:

terrain := world3d.NewTerrainLOD(hm, world3d.TerrainLODConfig{
	ChunkCells: 64,
	Hysteresis: 0.10, // 10% deadband around each LOD threshold
	LODBias:    world3d.TerrainLODBiasFor(sel.Level()),
})

// Each frame (or use UpdateWithOrigin with a *FloatingOrigin):
visibleChunks := terrain.Update(camPos, &frustum)
for _, ch := range visibleChunks {
	if ch.Changed {
		uploadChunkMesh(ch.Coord, ch.Mesh, ch.Revision)
	}
	drawTerrainChunk(ch.Coord, ch.Transform)
}
  • Crack-free seams: whenever a chunk borders a coarser neighbor along North, South, West, or East, BuildMeshLOD re-triangulates that border strip to connect directly to the neighbor's coarse edge vertices, avoiding both height cracks and T-junctions at every LOD pair (including partial heightmap border chunks).
  • Quality presets: call terrain.SetQualityLevel(level) (or terrain.SetLODBias(bias)) when the player's quality tier changes. TerrainLODBiasFor returns +1.0 for quality.Low, +0.5 for quality.Medium, and 0.0 for quality.High, scaling distance thresholds by 2^(-bias).
  • Floating origin & streaming: set WorldOrigin and call UpdateWithOrigin(camLocal, &frustumLocal, origin) so LOD distances stay invariant in float64 world space across rebases while returned Bounds and Transform track local space without rebuilding cached meshes. Set StreamManaged: true and hook SetChunkActive to ChunkStreamerConfig.OnLoad / OnUnload (with ChunkSize: terrain.ChunkWorldSize()) to stream chunks on demand.
  • Direct meshing: hm.BuildMeshLOD(col, row, cols, rows, lod, neighbors) and hm.ChunkBounds(col, row, cols, rows) are read-only and safe to call directly from background streaming workers.

Terrain material layers and splat maps (TerrainSplatMap, TerrainDoc)

Blend up to 8 PBR material layers across a heightmap using 1 or 2 RGBA weight (splat) maps (channels R, G, B, A of map 0 drive layers 0..3; map 1 drives layers 4..7), author the layers in a versioned YAML terrain definition (*.terrain.yaml), query the surface underfoot for gameplay via Heightmap.LayerAt(x, z), and render the terrain with render3d's TerrainMaterial / GPUTerrainMaterial:

doc, err := world3d.ParseTerrain(yamlBytes) // strict version 1 YAML (EncodeTerrain writes canonical form)
if err != nil {
	return err
}

splat, err := world3d.LoadTerrainSplatMap(doc.LayerInfos(), splatImg0) // pass splatImg0, splatImg1 for 5..8 layers
if err != nil {
	return err
}
splat.HeightBlendContrast = doc.HeightBlendContrast
hm.Splat = splat

// Zero-allocation gameplay query for footsteps, particles, and traction:
sample, inBounds := hm.LayerAt(player.X, player.Z)
playFootstep(sample.Name, sample.Dominant, sample.Weight(sample.Dominant))
_ = inBounds
  • Bilinear sampling & clamping: TerrainSplatMap.SampleUV and Heightmap.LayerAt use texel-center bilinear filtering with edge clamping, matching GPU linear clamp-to-edge splat sampling. Outside the heightmap footprint, Heightmap.LayerAt returns ok = false alongside the clamped edge sample.
  • Height-based blending: attach per-layer grayscale height maps (LoadTerrainHeightLayer) and set HeightBlendContrast in (0, 1] to sharpen layer transitions (such as rock protruding through dirt) using the same algebraic BlendTerrainWeights formula as render3d's terrain shader.
  • Text definition: ParseTerrain / EncodeTerrain read and write version 1 YAML (https://game.nsgo.dev/schemas/terrain.v1.json) declaring size ([cols, rows]), heightmap (16-bit grayscale PNG), cellSize, heightScale, origin, chunkSize (default 64 cells per LOD chunk), either packed RGBA splatMaps or per-layer grayscale weightMap PNGs (PackLayerWeightMaps, LoadTerrainSplatMapFromWeights), heightBlendContrast, triplanar, 1–8 layers (each with optional material resource path, weightMap, uvScale, PBR maps/factors, and heightBias), and optional embedded foliage scatter layers with grayscale densityMap PNGs (DensityMap.EncodePNG, Heightmap.FoliageDensityAt, TerrainDoc.ScatterFoliage). Unknown fields, duplicate layer names, mixing splatMaps with per-layer weightMap paths, size mismatches, and mismatched splat-map counts are refused with *loaderr.Error. Call doc.BuildHeightmap(imgs) / doc.BuildLOD(hm) (or world3d.LoadTerrainFS(fsys, path)) to build the runtime *Heightmap, attached *TerrainSplatMap, attached foliage density maps, and *TerrainLOD directly from YAML. game check validates every *.terrain.yaml file and its referenced heightmap, splat/weight maps, material resources, layer textures, and foliage meshes and density maps.

Multi-level 3D NavMesh

Build a 3D NavMesh from convex walkable polygons (ramps, bridges, and stacked floors). BuildNavMesh filters polygons steeper than maxSlopeRad, links shared edges in 3D, and runs portal A* with 3D string-pulling in FindPath:

nav := world3d.BuildNavMesh(walkablePolys, math3d.DegToRad(45))
if path, ok := nav.FindPath(startPos, goalPos); ok {
	follow3DWaypoints(path)
}

Use nav.FindPolygon(p) to locate the closest walkable polygon vertically within VerticalTolerance (supporting stacked floors and overpasses), Contains(p) and NearestPolygon(p) for membership and closest-surface queries, FindCorridor(start, goal) to query polygon corridors, AddOffMeshLink(NavOffMeshLink{...}) / OffMeshLinks() / ClearOffMeshLinks() for jumps, ladders, and teleports, and SetEdgeFlags(fromPoly, toPoly, flags) for special portal edges.

Connect vertically separated ledges, disconnected islands, ladders, or teleporters across a 3D NavMesh with AddOffMeshLink:

nav.AddOffMeshLink(world3d.NavOffMeshLink{
	Start:         math3d.Vec3{X: 9, Y: 4, Z: 5},
	End:           math3d.Vec3{X: 13, Y: 0, Z: 5},
	Radius:        0.5, // snaps off-edge endpoints within Radius while respecting stacked levels
	Bidirectional: false,
	Cost:          0, // <= 0 uses 3D Euclidean distance
	Area:          world3d.NavAreaJump,
	Flags:         uint32(world3d.NavFlagJump),
	ID:            7,
	UserData:      "drop",
})

res := nav.FindPathWithOptions(startPos, goalPos, ai.PathOptions{})
if res.Found {
	for i := 0; i+1 < len(res.Path); i++ {
		if link, ok := res.LinkAt(i); ok {
			// Segment Path[link.StartIndex] -> Path[link.EndIndex] traverses a 3D off-mesh link.
			_ = link.UserData
		}
	}
}
  • Path segment metadata: NavPathResult.Links records every traversed 3D off-mesh link (StartIndex, EndIndex == StartIndex + 1, FromPoly, ToPoly, Start, End, Radius, Area, Flags, LinkID, UserData), with HasLinks() and LinkAt(segmentIndex). NavAgent delivers the same Radius, Area, and UserData in NavLinkEvent and triggers link entry within Radius.
  • Shortcut-aware 3D search & filtering: A* filters off-mesh links by NavFilter (Area and Flags), scales traversal cost by filter.AreaCost(link.Area), and uses a shortcut-aware admissible 3D heuristic so cheap teleporters are chosen only when strictly cheaper than walking.
  • YAML storage and scene placement: place "nav_link" components on scene objects (sceneformat.RegisterNavLink, sceneformat.ExtractNavLinks3D, sceneformat.ExtractBuiltNavLinks3D); navbake3d.Geometry.AddSceneFile bakes them into meshes[].links in *.navmesh.yaml, and navbake3d.Mesh.NavMesh restores them automatically.

Polygon areas, runtime flags, and query filters

Tag 3D polygons at build time with BuildNavMeshWithAreas using NavPolygonInput{Vertices, Area, Flags}. world3d.NavArea, world3d.NavFlags, and world3d.NavFilter alias the types in ai, so the same filter and area/flag constants work seamlessly across 2D and 3D navigation meshes:

nav := world3d.BuildNavMeshWithAreas([]world3d.NavPolygonInput{
	{Vertices: grassQuad, Area: world3d.NavAreaGrass},
	{Vertices: roadQuad, Area: world3d.NavAreaRoad},
	{Vertices: waterQuad, Area: world3d.NavAreaWater, Flags: world3d.NavFlagSwim},
	{Vertices: gateQuad, Area: world3d.NavAreaDoor, Flags: world3d.NavFlagWalk | world3d.NavFlagDoor},
}, math3d.DegToRad(45))

filter := world3d.DefaultNavFilter()
filter.SetAreaCost(world3d.NavAreaRoad, 0.5)
filter.ExcludeFlags |= world3d.NavFlagSwim

path, ok := nav.FindPathWithFilter(startPos, goalPos, filter)

// Toggle a gate or drawbridge polygon at runtime without rebuilding:
nav.AddPolygonFlags(gatePolyIndex, world3d.NavFlagDisabled)
detour, ok := nav.FindPathWithFilter(startPos, goalPos, filter)
nav.ClearPolygonFlags(gatePolyIndex, world3d.NavFlagDisabled)
_, _, _ = path, detour, ok
  • Default compatibility: BuildNavMesh assigns NavAreaDefault and NavFlagWalk to every walkable NavPoly, and FindPath delegates to FindPathWithFilter with DefaultNavFilter().
  • Admissible 3D weighted portal A*: traversal inside each polygon is weighted by filter.AreaCost(poly.Area) with an admissible 3D heuristic scaled by the minimum allowed area cost across the mesh, followed by exact 3D funnel smoothing across ramps and stacked levels.
  • Runtime mutation & filtered queries: inspect or update polygons in O(1) via PolygonCount, PolygonArea, SetPolygonArea, PolygonFlags, SetPolygonFlags, AddPolygonFlags, and ClearPolygonFlags, and run filtered lookups with FindPolygonWithFilter, ContainsWithFilter, NearestPolygonWithFilter, NearestPointWithFilter, RaycastWithFilter, MoveAlongSurfaceWithFilter, RandomPointWithFilter, and RandomPointAroundWithFilter.

Spatial queries, surface movement, and zero-allocation path reuse

world3d.NavMesh builds a flat 3D AABB BVH spatial index at construction time so FindPolygon, NearestPolygon, NearestPoint, and pathfinding endpoint lookups scale logarithmically on large multi-level worlds without scanning every polygon:

rng := random.New(42)

// Snap a 3D click or spawn position within 3D half-extents (cleanly separating stacked floors):
snapped, poly, ok := nav.NearestPoint(spawnPos, math3d.Vec3{X: 3, Y: 1.5, Z: 3})

// Cast a surface ray across ramps and bridges (stops at bridge edges instead of dropping levels):
hit, obstructed := nav.Raycast(agentPos, targetPos)

// Slide an agent along the 3D mesh surface while tracking ramp elevation and staying off ledges:
moved, onMesh := nav.MoveAlongSurface(agentPos, desiredPos)

// Pick deterministic 3D surface-area-weighted random points (anywhere or reachable within 3D radius):
patrolPt, _, _ := nav.RandomPoint(rng)
wanderPt, _, _ := nav.RandomPointAround(agentPos, 12, rng)

// Reuse buffers via NavMeshQuery for zero-allocation path and corridor queries:
query := world3d.NewNavMeshQuery(nav)
pathBuf, ok = query.FindPathInto(pathBuf, snapped, wanderPt)
corridorBuf, _ = query.FindCorridorInto(corridorBuf, snapped, wanderPt)
_, _, _, _, _, _, _ = poly, hit, obstructed, moved, onMesh, patrolPt, ok
  • 3D extent-bounded snapping: NearestPoint(p, extent) and NearestPointWithFilter(p, extent, filter) restrict matches to [p - extent, p + extent] in full 3D (clipping sloped polygons to the extent box when needed), keeping stacked floors and overpasses cleanly separated by extent.Y.
  • 3D surface raycast and sliding: Raycast / RaycastWithFilter traverse only shared 3D polygon edges, returning NavRaycastHit{Point, Normal, Poly, T, Hit} with exact HeightAt elevation and a 3D surface-tangent inward normal; MoveAlongSurface / MoveAlongSurfaceWithFilter slide along boundary edges across ramps and bridges without dropping between stacked levels (NavMoveResult{Point, Poly, Visited, HitBoundary}).
  • Deterministic 3D surface-area random points: RandomPoint / RandomPointWithFilter weight polygons by true 3D surface area (not just XZ projection); RandomPointAround / RandomPointAroundWithFilter sample only reachable polygons within 3D Euclidean radius of the snapped center (never jumping to unconnected floors overhead). Results are bit-identical across runs and architectures for the same *random.Stream seed.
  • Zero-allocation path reuse & concurrent queries: nav.FindPathInto, nav.FindPathWithFilterInto, nav.FindPathWithFilterAndOptionsInto, and nav.FindCorridorInto reuse generation-stamped scratch buffers with 0 heap allocations after warm-up; allocate one NewNavMeshQuery(nav) per worker goroutine for concurrent read-only queries over a shared NavMesh.

For unreachable targets or frame-budgeted multi-agent queries, pass ai.PathOptions{MaxExpansions, AllowPartial} to nav.FindPathWithOptions(startPos, goalPos, opts) (returning a NavPathResult with Partial, Exhausted, and Expansions), or create a deterministic multi-frame *world3d.NavMeshSearch via nav.StartSearch(startPos, goalPos, opts):

search := nav.StartSearch(startPos, goalPos, ai.PathOptions{
	MaxExpansions: 128,
	AllowPartial:  true,
})
// Step directly, or schedule alongside 2D searches in an ai.PathQueue:
queue.Submit(search, 0, func(_ ai.PathRequestID, _ ai.SearchStatus) {
	res := search.Result()
	if res.Found {
		follow3DWaypoints(res.Path) // res.Partial is true if goal was unreachable or budgeted out
	}
})

Stepping NavMeshSearch across any positive per-step budget returns the exact same 3D surface path as FindPathWithOptions, and partial paths end at the closest reachable 3D point on the explored polygons.

To bake the polygons from the level's geometry instead of writing them by hand, use navbake3d: it rasterizes glTF models, terrain, GridMaps and physics colliders for each agent type and Mesh.NavMesh returns the NavMesh.

3D navigation agents (NavAgent, NavAgentGroup)

world3d.NavAgent follows and locally repairs 3D polygon corridors over a world3d.NavMesh, steering smoothly on XZ toward the next funnel corner while tracking exact 3D surface elevation (NavPoly.HeightAt) across sloped ramps and multi-level bridges, slowing inside ArrivalRadius to stop within StoppingDistance, and exposing explicit state (NavAgentIdle, NavAgentMoving, NavAgentArrived, NavAgentUnreachable):

group := world3d.NewNavAgentGroup(world3d.NavAgentGroupConfig{
	MaxReplansPerStep: 4,
	ReplanInterval:    100 * time.Millisecond,
})
agent := group.Add(nav, startPos, world3d.NavAgentConfig{
	MaxSpeed:         6,
	MaxAcceleration:  30,
	Radius:           0.4,
	ArrivalRadius:    1.5,
	StoppingDistance: 0.35,
	OnLink: func(a *world3d.NavAgent, ev world3d.NavLinkEvent, dt time.Duration) bool {
		// Drive custom jump/ladder traversal and return true when done.
		return true
	},
})
agent.SetTarget(goalPos)

// Inside game.Loop.Update:
agent.SetTarget(movingTargetPos)
group.Step(dt)
  • Local corridor repair & vertical separation: NavAgent checks connected shared-edge neighbors first so agents on upper bridges never snap down to floors underneath, and repairs pushed start positions (SetPosition) or shifted targets locally within MaxRepairDepth (default 2) without a full A* replan.
  • Throttled & staggered replanning: NavAgentGroup.Step(dt) strictly bounds full A* replans to MaxReplansPerStep per fixed step in deterministic round-robin order (optionally staggered by StaggerStride), and automatically detects mesh changes (including runtime area/flag updates and off-mesh links) via NavMesh.Revision().
  • Deterministic fixed-step replay: replaying the same inputs produces bit-identical 3D positions every step.

Tiled 3D NavMesh, dynamic obstacles, and chunk streaming (TiledNavMesh, NavTileStreamer)

For open worlds, doors, placed buildings, and destructible cover, world3d.TiledNavMesh partitions 3D walkable polygons into fixed-size XZ tiles aligned 1:1 with ChunkCoord, linking polygons in full 3D across tile borders (preserving ramps and stacked levels), rebuilding only touched tiles when dynamic obstacles change, and invalidating paths that crossed modified or unloaded tiles:

tm := world3d.NewTiledNavMesh(world3d.TiledNavMeshConfig{TileSize: 64})

// Follow world3d chunk streaming: bake tiles on background workers and load/unload with chunks:
streamer, err := world3d.NewNavTileStreamer(world3d.NavTileStreamerConfig{
	Mesh:         tm,
	LoadRadius:   2,
	UnloadRadius: 3,
	Workers:      2,
	Bake: func(ctx context.Context, coord world3d.ChunkCoord, bounds math3d.AABB) (*world3d.NavTile, error) {
		return bakeChunkNavTile(ctx, coord, bounds) // e.g. world3d.BakeNavTile or navbake3d.BakeTile
	},
})
if err != nil {
	return err
}
defer streamer.Close()

streamer.Update(world3d.WorldPos64{X: float64(player.X), Z: float64(player.Z)})

// Drop a 3D box, cylinder, or extruded polygon obstacle (rebuilds ONLY touched tiles):
obsID, _ := tm.AddObstacle(world3d.NavBoxObstacle(minPos, maxPos))
detour, _ := tm.FindPath(startPos, goalPos) // detours around box; vertical Y bounds keep bridges above unaffected
tm.RemoveObstacle(obsID)                    // restores original geometry and path
_, _ = detour, obsID
  • Independent tile lifecycle: bake standalone tiles off-thread with world3d.BakeNavTile (or voxel-bake directly from navbake3d.Geometry via navbake3d.BakeTile), then call AddTile, ReplaceTile, SetTile, RemoveTile, or RebuildTile; BuildTiledNavMesh / BuildTiledNavMeshWithAreas and navbake3d.Mesh.TiledNavMesh(tileSize) build a tiled mesh from existing polygons or baked meshes.
  • 3D dynamic obstacles: NavBoxObstacle, NavOrientedBoxObstacle, NavCylinderObstacle, and NavPolygonObstacle check vertical Y overlap so obstacles on a ground floor never carve bridges overhead. Both NavObstacleCarve (exact planar subtraction) and NavObstacleMark (splitting and setting NavFlagDisabled or custom Area/Flags) are supported; group multi-obstacle edits inside tm.Batch(func() { ... }).
  • Two-level 3D spatial index & path invalidation: FindPolygon, NearestPoint, NearestPolygon, and Raycast use O(1) XZ tile lookup + per-tile 3D flat BVHs (plus a coarse 3D tile BVH for unbounded nearest lookups). Track path validity with tm.IsPathValid(res) (TiledNavPathResult.Tiles), register per-tile invalidation callbacks with tm.WatchPath(res.TileCoords(), fn), or observe all tile changes via tm.AddTileListener.

Modular 3D GridMap

Place reusable 3D mesh tiles on an integer GridCoord{X, Y, Z} lattice with 24 axis-aligned cube orientations (GridOrientationMat4, RotateGridOrientation, FindGridOrientation), fast collision box extraction, chunk-culled raycasting (chunks are sorted along the ray and the occupied cells of each are tested), cell enumeration (EachCell), sorted library inspection (MeshLibrary.Items), and frustum-culled instanced batches. LoadMeshLibraryFromGLTF reads both .gltf JSON and binary .glb mesh libraries:

lib, err := world3d.LoadMeshLibraryFromGLTF(gltfBytes) // or world3d.NewMeshLibrary()
if err != nil {
	return err
}
grid := world3d.NewGridMap(math3d.Vec3{X: 2, Y: 2, Z: 2}, lib)
floorDef, _ := lib.ByName("stone_floor")
grid.FillBox(world3d.GridCoord{X: 0, Y: 0, Z: 0}, world3d.GridCoord{X: 15, Y: 0, Z: 15}, floorDef.ID, 0)

batches = grid.BuildInstances(&frustum, batches[:0])
colliders := grid.CollisionBoxesIn(playerAABB)
hit, ok := grid.Raycast(ray, 100)
_, _, _, _ = batches, colliders, hit, ok

To populate a physics3d.World from a GridMap's ColliderBoxes, call grid.AddCollidersToWorld(world, opts) (or grid.BuildStaticBodies(opts) / grid.MergedColliderBoxes()). Adjacent aligned cell boxes are greedily merged along X, then Z, then Y via physics3d.MergeBoxes, cutting static body counts and removing internal cell seams while producing identical collision outcomes (set GridColliderOptions{DisableMerge: true} to emit one body per cell box).

Grid maps can also be authored and saved as version 1 YAML (*.gridmap.yaml, schema https://game.nsgo.dev/schemas/gridmap.v1.json) with origin, cellSize, meshLibrary, non-overlapping filled box runs (boxes), and individual cells (cells), all written in canonical (y, z, x) order:

grid, doc, err := world3d.LoadGridMapFS(projectFS, "levels/dungeon.gridmap.yaml")
if err != nil {
	return err
}
exported, err := grid.ToDoc(doc.Name, doc.MeshLibrary)
if err != nil {
	return err
}
yamlBytes, err := world3d.EncodeGridMap(exported) // deterministic, refuses unknown fields on ParseGridMap
_, _ = exported, yamlBytes

game check validates every *.gridmap.yaml file (and every scene object gridMap reference), checks that its meshLibrary exists and loads (.gltf or .glb), and verifies that every boxes[*].tile and cells[*].tile name exists in that library. Scene objects can attach a .gridmap.yaml file via gridMap for automatic instancing in scenemodel and interactive painting in the 3D editor.

Procedural foliage culling (FoliageField)

Deterministically scatter grass, rocks, or trees across a Heightmap constrained by slope, height, and an optional DensityMap, then collect frustum- and distance-culled instances scaled by a QualityProfile:

field := world3d.Scatter(hm, world3d.FoliageLayer{
	Name:            "grass",
	MeshID:          grassMeshID,
	MaterialID:      grassMatID,
	Density:         1.5,
	MinScale:        0.8,
	MaxScale:        1.3,
	AlignToNormal:   0.6,
	MaxSlopeDeg:     35,
	BaseMaxDistance: 80,
	Seed:            42,
}, hm.Bounds())

quality := world3d.DefaultQualityProfile(world3d.QualityHigh)
visible = field.CollectVisible(camPos, frustum, quality, visible[:0])

Foliage layers can also be authored in version 1 YAML (*.foliage.yaml, schema https://game.nsgo.dev/schemas/foliage.v1.json) specifying each layer's mesh, optional material and densityMap, either density (instances/m²) or spacing (average distance in meters, where density = 1 / spacing²), scale range (minScale, maxScale), alignToNormal, slope limits (minSlopeDeg, maxSlopeDeg), height limits (minHeight, maxHeight), baseMaxDistance, boundingRadius, and seed:

foliageDoc, err := world3d.LoadFoliageFS(projectFS, "terrain/meadow.foliage.yaml")
if err != nil {
	return err
}
fields, err := foliageDoc.ScatterAll(hm, hm.Bounds(), world3d.FoliageBuildOptions{
	ResolveMesh:     resolveMeshID,
	ResolveMaterial: resolveMaterialID,
	FS:              projectFS,
})

ParseFoliage refuses unknown fields and contradictory settings (such as setting both density and spacing), EncodeFoliage writes deterministic canonical YAML, and game check validates every *.foliage.yaml file and its referenced terrain, meshes, materials, and density map images.

world3d.QualityLevelFor(level) maps a game-wide quality level to the foliage tier of the same name, so DefaultQualityProfile(QualityLevelFor(sel.Level())) follows the player's preset. QualityUltra stays an explicit choice above every preset.

Each returned FoliageInstance provides its world Transform and a smooth distance Fade factor in [0, 1]. Set FoliageLayer.BoundingRadius to the radius of a sphere around the mesh pivot that encloses the mesh at scale 1: culling and the draw distance then use each instance's scaled sphere and measure from its nearest point, so large trees stay visible while any part of them is in range. Without it, culling assumes a unit-radius mesh and distances are measured from the pivot.

Heightmap.Raycast walks only the cells under the ray and never scans the whole height grid.

Floating-origin chunk streaming

Prevent float32 jitter far from the world origin with FloatingOrigin (WorldPos64 in float64) and load/unload surrounding world chunks asynchronously with ChunkStreamer[T]:

origin := world3d.NewFloatingOrigin(512) // rebase when player exceeds 512m from local origin
streamer := world3d.NewChunkStreamer(world3d.ChunkStreamerConfig[*ChunkData]{
	ChunkSize:               64,
	LoadRadius:              3,
	UnloadRadius:            5,
	MaxIntegrationsPerFrame: 2,
	Workers:                 2,
	Loader:                  loadChunkAsync,
	OnLoad:                  attachChunk,
	OnUnload:                releaseChunk,
})
defer streamer.Close()

// Each frame:
if rebased, shift := origin.Update(playerLocalPos); rebased {
	rebaseSceneObjects(shift) // shift Mat4 transforms with world3d.RebaseMat4(m, shift)
	playerLocalPos = playerLocalPos.Add(shift) // the player moves with everything else
}
streamer.Update(origin.LocalToWorld(playerLocalPos))
Modifier cette page