Documentation
¶
Overview ¶
Package scenemodel is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package scenemodel gives the objects of a scene file their 3D look: the built-in primitive an object names in mesh, or the glTF 2.0 model it names in model, optionally narrowed to one node (modelNode) or one mesh (modelMesh), with the material file it names in material replacing the model's materials (sceneformat.ObjectDoc). So a 3D level can be written as a scene file, as a 2D one is, instead of being assembled in Go.
Build builds a scene into a scene3d node tree, as sceneformat.BuildNodes3D does, loads each model through a ModelResolver, as sceneformat.Build loads materials through a MaterialResolver, and attaches each object's geometry and materials to its node as a Drawable, with the node's LocalBounds set from the geometry. BuildObject and BuildPrefab build individual objects or prefab subtrees at run time while sharing an Assets' model, scene and texture caches. Assets is a ModelResolver, sceneformat.SceneResolver, MaterialResolver and ImageResolver over a project's files. Built.AppendDrawItems lists the parts as render3d.DrawItem values for render3d.Queue, and Renderer uploads them to a gpu.Device, draws them lit by a render3d.LightRig and textured with their base color, and adds or removes drawables at run time through Add and Remove while sharing and reference-counting GPU meshes, textures and materials.
assets := scenemodel.NewAssets(os.DirFS(projectRoot))
built, err := scenemodel.Build(doc, scene.Root(), assets)
...
r, err := scenemodel.NewRenderer(cx, dev, built, scenemodel.RendererOptions{})
...
// Each frame:
r.Prepare(cam, lights)
pass := frame.BeginRenderPass(gpu.RenderPassDesc{})
r.Draw(pass)
pass.End()
game check reports a model file that is missing or does not load, and a modelNode or modelMesh the model does not have, with the scene file and line; game mv, game index and the editor's MoveFile rewrite the scenes that name a model when it moves (package refs).
Index ¶
- Constants
- Variables
- func BakeCSG(doc *sceneformat.SceneDoc, objectID string, models ModelResolver) ([]byte, int, error)
- func BakeLightProbeGrid(b *Built, grid *LightProbeGrid, opts ProbeBakeOptions) (*render3d.LightProbeGrid, error)
- func BakeReflectionProbe(b *Built, probe *ReflectionProbe, opts ProbeBakeOptions) (*render3d.HDRCubemap, error)
- func ClearCSGCache()
- func DefaultLODScreenRatio(level, count int) float32
- func DrawItemID(di, pi int) uint64
- func DrawPipeline(m Material) uint32
- func FindMesh(doc *gltf.Document, name string) int
- func FindNode(doc *gltf.Document, name string) int
- func PrimitiveMesh(name string) (render3d.Mesh, error)
- type Assets
- func (a *Assets) Bytes(path string) ([]byte, error)
- func (a *Assets) GridMap(path string) (*world3d.GridMapDoc, error)
- func (a *Assets) HDR(path string) (*render3d.HDRImage, error)
- func (a *Assets) Image(path string) (image.Image, error)
- func (a *Assets) ImportSettings(modelPath string) (*importsettings.File, error)
- func (a *Assets) KTX2(path string) ([]byte, error)
- func (a *Assets) LUT(path string) (*image.NRGBA, error)
- func (a *Assets) Library() *resource.Library
- func (a *Assets) LightProbeGrid(path string) (*render3d.LightProbeGrid, error)
- func (a *Assets) LightmapSidecar(path string) (*render3d.LightmapSidecarDoc, error)
- func (a *Assets) Material(path string) (*resource.Material, error)
- func (a *Assets) Model(path string) (*gltf.Document, error)
- func (a *Assets) Scene(path string) (*sceneformat.SceneDoc, error)
- func (a *Assets) Terrain(path string) (*world3d.Heightmap, error)
- func (a *Assets) TerrainAsset(path string) (*TerrainAsset, error)
- type BuildOptions
- type Built
- func Build(doc *sceneformat.SceneDoc, parent *scene3d.Node, models ModelResolver) (*Built, error)
- func BuildObject(o *sceneformat.ObjectDoc, parent *scene3d.Node, models ModelResolver) (*Built, error)
- func BuildPrefab(path string, parent *scene3d.Node, models ModelResolver) (*Built, error)
- func BuildWith(doc *sceneformat.SceneDoc, parent *scene3d.Node, models ModelResolver, ...) (*Built, error)
- func (b *Built) ActiveCamera(aspect float32) (*scene3d.Camera, bool)
- func (b *Built) ActiveCameraObject() (*Camera, bool)
- func (b *Built) ActiveFogVolumes(dst []render3d.FogVolume) []render3d.FogVolume
- func (b *Built) AddCSGCollidersToWorld(w *physics3d.World) []*physics3d.TriMeshCollider
- func (b *Built) AppendDrawItems(dst []render3d.DrawItem) []render3d.DrawItem
- func (b *Built) AppendOccluders(dst []render3d.Occluder) []render3d.Occluder
- func (b *Built) AttachMeshColliders()
- func (b *Built) DynamicLightRig() render3d.LightRig
- func (b *Built) HasBakedLightProbeGrid() bool
- func (b *Built) HasBakedProbes() bool
- func (b *Built) HasLightmaps() bool
- func (b *Built) HasSceneLighting() bool
- func (b *Built) LightRig() render3d.LightRig
- func (b *Built) LightRigNear(cameraPos math3d.Vec3) render3d.LightRig
- func (b *Built) Part(id uint64) (*Drawable, *Part, bool)
- func (b *Built) RasterizeOccluders(buf *render3d.OcclusionBuffer, viewProj math3d.Mat4) int
- func (b *Built) SampleLightProbes(worldPos math3d.Vec3) (render3d.IrradianceSH, bool)
- func (b *Built) SceneLights() (rig render3d.LightRig, local []render3d.ClusterLight)
- func (b *Built) ShadowLights() (dir *render3d.DirectionalLight, point *render3d.PointLight, ...)
- func (b *Built) WorldBounds() (math3d.AABB, bool)
- type BytesResolver
- type Camera
- type Drawable
- type Environment
- type FogVolume
- type FoliagePart
- type GridMapResolver
- type HDRResolver
- type Handle
- type ImageResolver
- type ImportSettingsResolver
- type KTX2Data
- type KTX2Resolver
- type LUTResolver
- type Light
- type LightProbeGrid
- type LightProbeGridResolver
- type LightmapSidecarResolver
- type LightmapTexture
- type Material
- type ModelResolver
- type Occluder
- type Part
- type PartLOD
- type PartLightmap
- type ProbeBakeOptions
- type ReflectionProbe
- type Renderer
- func (r *Renderer) Add(b *Built) (Handle, error)
- func (r *Renderer) CaptureFrame(desc gpu.RenderPassDesc, width, height int, opts render3d.FrameCaptureOptions) (*render3d.CapturedFrame, error)
- func (r *Renderer) ClearColor(fallback core.Color) core.Color
- func (r *Renderer) Close() error
- func (r *Renderer) ClusteredLights() *render3d.ClusteredLightSystem
- func (r *Renderer) DispatchVisibility(onEnter, onExit func(objectID string))
- func (r *Renderer) Draw(pass *gpu.RenderPass)
- func (r *Renderer) DrawFogVolumes(pass *gpu.RenderPass, sceneDepth *gpu.Texture) error
- func (r *Renderer) DrawOpaque(pass *gpu.RenderPass)
- func (r *Renderer) DrawSky(pass *gpu.RenderPass)
- func (r *Renderer) DrawTransparent(pass *gpu.RenderPass)
- func (r *Renderer) DrawableCount() int
- func (r *Renderer) EnteredObjects() []string
- func (r *Renderer) ExitedObjects() []string
- func (r *Renderer) FrameCapture() *render3d.FrameCapture
- func (r *Renderer) GPUTimer() *render3d.GPUTimer
- func (r *Renderer) HasFogVolumes() bool
- func (r *Renderer) HasSky() bool
- func (r *Renderer) LayerMask() uint32
- func (r *Renderer) PipelineCacheStats() gpu.PipelineCacheStats
- func (r *Renderer) Plan() render3d.RenderPlan
- func (r *Renderer) Prepare(cam *scene3d.Camera, lights render3d.LightRig) (render3d.RenderStats, error)
- func (r *Renderer) PrepareScene(cam *scene3d.Camera) (render3d.RenderStats, error)
- func (r *Renderer) RecordFogVolumes(target render3d.ShadowPassTarget, colorTex, sceneDepth *gpu.Texture) error
- func (r *Renderer) RecordScene(target render3d.ShadowPassTarget, desc gpu.RenderPassDesc)
- func (r *Renderer) RecordShadows(target render3d.ShadowPassTarget)
- func (r *Renderer) Remove(h Handle)
- func (r *Renderer) ResetVisibility()
- func (r *Renderer) SampleCount() int
- func (r *Renderer) SetFrameCapture(fc *render3d.FrameCapture)
- func (r *Renderer) SetGPUTimer(t *render3d.GPUTimer)
- func (r *Renderer) SetLayerMask(mask uint32)
- func (r *Renderer) SetShading(s Shading) error
- func (r *Renderer) SetViewport(width, height float32)
- func (r *Renderer) Shading() Shading
- func (r *Renderer) ShadowInfo() ShadowInfo
- func (r *Renderer) VisibilityTracker() *render3d.VisibilityTracker
- func (r *Renderer) Visible(objectID string) bool
- type RendererOptions
- type Shading
- type ShadowInfo
- type ShadowMapInfo
- type Terrain
- type TerrainAsset
- type TerrainFoliage
- type TerrainResolver
- type Texture
Examples ¶
Constants ¶
const ( // DefaultShadowResolution is the default width and height in texels of the directional and spot shadow maps (RendererOptions.ShadowResolution). DefaultShadowResolution uint32 = 512 // DefaultPointShadowResolution is the default width and height in texels of each point shadow cube face (RendererOptions.PointShadowResolution). DefaultPointShadowResolution uint32 = 256 )
Shadow map sizes Renderer uses when RendererOptions leaves them zero.
const AttachmentKey = "scenemodel.drawable"
AttachmentKey is the scene3d.Node attachment under which Build stores the *Drawable of each node that draws geometry, so code that holds a node, such as an editor's picking, can find what it draws with scene3d.AttachmentAs.
const BaseColorGroup = render3d.PBRDrawGroup + 1
BaseColorGroup is the bind group of the base color texture and sampler in ShaderWGSL, after render3d's camera (render3d.CameraGroup), scene lights and environment (render3d.LightGroup) and per-draw uniform (render3d.PBRDrawGroup).
const TerrainAttachmentKey = "scenemodel.terrain"
TerrainAttachmentKey is the scene3d.Node attachment under which Build stores the *Terrain of each node that draws terrain geometry, so code holding a node (such as an editor's picking or live terrain brush sync) can retrieve it with scene3d.AttachmentAs.
Variables ¶
var ShaderWGSL = buildShaderPreludeWGSL(false) + litFragmentBodyWGSL + litFragmentTailWGSL
ShaderWGSL is the clustered-lighting shader module Renderer draws with in ShadingLit on devices with storage buffers: render3d metallic-roughness PBR lighting with directional/point/spot lights, clustered local lights, optional directional/point/spot shadows, per-object reflection probes and light probe SH irradiance (falling back to scene sky IBL), distance and height fog, exposure, tone mapping, and a base color texture.
Functions ¶
func BakeCSG ¶
func BakeCSG(doc *sceneformat.SceneDoc, objectID string, models ModelResolver) ([]byte, int, error)
BakeCSG evaluates the CSG object objectID in doc and encodes the resulting multi-material mesh (and optional TriMeshCollider extras) to deterministic binary glTF 2.0 (.glb). Returns the GLB bytes and total triangle count.
func BakeLightProbeGrid ¶
func BakeLightProbeGrid(b *Built, grid *LightProbeGrid, opts ProbeBakeOptions) (*render3d.LightProbeGrid, error)
BakeLightProbeGrid renders b's 3D scene from every lattice point of grid into a small linear HDR cubemap using render3d on an offscreen software GPU renderer and integrates each probe's cosine-convolved L2 spherical harmonic irradiance coefficients.
func BakeReflectionProbe ¶
func BakeReflectionProbe(b *Built, probe *ReflectionProbe, opts ProbeBakeOptions) (*render3d.HDRCubemap, error)
BakeReflectionProbe renders b's 3D scene from probe's world position into all six faces of a linear HDR cubemap using render3d on an offscreen software GPU renderer, disabling existing baked probe contributions so rebaking captures direct lighting, shadows, sky, and emissives.
func DefaultLODScreenRatio ¶
DefaultLODScreenRatio returns the default MinScreenRatio threshold for level (0-indexed from finest to coarsest) in an LOD chain of count levels. The coarsest level (level >= count-1) always returns 0 (unbounded fallback).
func DrawItemID ¶
DrawItemID returns the render3d.DrawItem ID AppendDrawItems gives part pi of drawable di.
func DrawPipeline ¶
DrawPipeline returns the render3d.DrawItem PipelineID of a part drawn with m: 0 for a single-sided opaque or cutout surface, 1 for a double-sided one, 2 for a single-sided blended surface and 3 for a double-sided one. Renderer draws each with its own pipeline.
func FindMesh ¶
FindMesh returns the index of the first mesh of doc named name, or -1 when none is, as sceneformat.ObjectDoc.ModelMesh looks it up.
func FindNode ¶
FindNode returns the index of the first node of doc named name, or -1 when none is, as sceneformat.ObjectDoc.ModelNode looks it up.
func PrimitiveMesh ¶
PrimitiveMesh returns the geometry of the built-in primitive name, one of sceneformat.MeshPrimitives, in the object's space: indexed triangles wound counter-clockwise from outside, with unit normals and UVs from 0 to 1. Every call returns new slices.
The shapes are sized so that an object's scale reads as meters: a box 1 on each side, a sphere 1 across, a plane 1 by 1 in the XZ plane facing +Y, a cylinder 1 across and 1 tall, and a capsule 1 across and 2 tall, each centered on the origin with its round axis along Y.
Types ¶
type Assets ¶
type Assets struct {
// contains filtered or unexported fields
}
Assets loads models, scenes and prefabs, grid maps, terrains, material files, images, KTX2 textures, model import sidecars, Radiance HDR panoramas/cubemaps, color LUTs, baked light probe grids, baked lightmap sidecars and binary buffers from a project's files, such as os.DirFS(projectRoot) or an embed.FS, and keeps each one it loaded (along with decoded glTF and material textures), so it serves Build, BuildObject and BuildPrefab as a ModelResolver, a sceneformat.SceneResolver, a GridMapResolver, a TerrainResolver, a sceneformat.TerrainResolver, a sceneformat.MaterialResolver, an ImageResolver, a KTX2Resolver, an ImportSettingsResolver, an HDRResolver, a LUTResolver, a LightProbeGridResolver, a LightmapSidecarResolver and a BytesResolver. Models load with gltf.LoadFS, so a .gltf file's separate buffers and images are read from beside it; scenes and prefabs parse with sceneformat.ParseWith; grid maps parse with world3d.ParseGridMapWith; terrains load with world3d.LoadTerrainFS and render3d.TerrainMaterialFromDoc; material files load through a resource.Library, which shares one value per path; images decode as PNG or JPEG while KTX2 textures are validated and kept encoded for render3d.LoadKTX2; sidecars load through importsettings.Parse; HDR skies and reflection probes decode with render3d.DecodeHDR; .cube and strip LUTs decode via render3d.LoadCubeLUT or image.Decode; light probe grids load with render3d.LoadLightProbeGridFS; lightmap sidecars load with render3d.LoadLightmapSidecarFS.
Its methods are safe to call from any goroutine.
func (*Assets) Bytes ¶
Bytes reads the raw bytes of the file at path on first use and returns the same slice after that.
func (*Assets) GridMap ¶
func (a *Assets) GridMap(path string) (*world3d.GridMapDoc, error)
GridMap loads and parses the YAML grid map at path (*.gridmap.yaml or *.gridmap.yml) on first use and returns the same document after that.
func (*Assets) HDR ¶
HDR decodes the Radiance .hdr panorama at path on first use and returns the same image after that.
func (*Assets) Image ¶
Image decodes the PNG or JPEG image at path on first use and returns the same image after that. KTX2 files return an error directing callers to Assets.KTX2.
func (*Assets) ImportSettings ¶
func (a *Assets) ImportSettings(modelPath string) (*importsettings.File, error)
ImportSettings reads and parses the *.import.yaml sidecar beside modelPath on first use and caches the result, returning (nil, nil) when no sidecar file exists.
func (*Assets) KTX2 ¶
KTX2 reads and validates the KTX2 texture header and sampling metadata at path on first use and returns the same bytes after that, for render3d.LoadKTX2.
func (*Assets) LUT ¶
LUT loads the color lookup table at path (.cube text file or 2D horizontal strip image) on first use, validates its dimensions, and returns the cached N*N × N RGBA8 strip image.
func (*Assets) Library ¶
Library returns the resource.Library that Material loads from, so a game can reload edited material files into it (resource.Library.Reload).
func (*Assets) LightProbeGrid ¶
func (a *Assets) LightProbeGrid(path string) (*render3d.LightProbeGrid, error)
LightProbeGrid parses the baked light probe grid YAML file at path on first use and returns the same grid after that.
func (*Assets) LightmapSidecar ¶
func (a *Assets) LightmapSidecar(path string) (*render3d.LightmapSidecarDoc, error)
LightmapSidecar parses the baked lightmap sidecar YAML file at path on first use and returns the same document after that.
func (*Assets) Material ¶
Material loads the material file at path through the Assets' resource.Library. It lets Assets serve as a sceneformat.MaterialResolver.
func (*Assets) Model ¶
Model loads the glTF model at path, a .gltf or .glb file, on first use and returns the same document after that.
func (*Assets) Scene ¶
func (a *Assets) Scene(path string) (*sceneformat.SceneDoc, error)
Scene reads and parses the scene or prefab YAML file at path on first use and returns the same document after that. It lets Assets serve as a sceneformat.SceneResolver for BuildPrefab and sceneformat.Resolve.
func (*Assets) Terrain ¶
Terrain returns the decoded *world3d.Heightmap for the terrain at path, sharing the same instance loaded by TerrainAsset so sceneformat.BuildPhysics heightfield colliders use the exact same heightmap as rendered terrain objects. It implements sceneformat.TerrainResolver.
func (*Assets) TerrainAsset ¶
func (a *Assets) TerrainAsset(path string) (*TerrainAsset, error)
TerrainAsset loads and validates the YAML terrain at path (*.terrain.yaml or *.terrain.yml) via world3d.LoadTerrainFS and render3d.TerrainMaterialFromDoc on first use and returns the same TerrainAsset after that.
type BuildOptions ¶
type BuildOptions struct {
// ScenePath is the slash-separated project path of the scene file (such as "scenes/level.scene.yaml").
// When SceneDoc.Lightmaps and LightmapSidecar are empty, BuildWith looks for a companion sidecar at
// render3d.LightmapSidecarPath(ScenePath) and loads it if it exists.
ScenePath string
// LightmapSidecar explicitly names the *.lightmaps.yaml sidecar path to load, overriding
// SceneDoc.Lightmaps and ScenePath auto-discovery.
LightmapSidecar string
// PickColliders makes BuildWith call Built.AttachMeshColliders, so scene3d's raycasts and picks hit the triangles each drawing node draws. Off by default: without it, a built node has no collider and picking falls back to its LocalBounds box, which hits the empty corners of round or concave geometry and reports axis-aligned normals and TriangleIndex -1.
PickColliders bool
}
BuildOptions configures BuildWith.
type Built ¶
type Built struct {
// Nodes3D holds the layer and object nodes, as sceneformat.BuildNodes3D builds them.
sceneformat.Nodes3D
// Drawables are the nodes that draw geometry, depth first in document order: an object's node, then the nodes made for its model's nodes or grid map instances, then its child objects.
Drawables []*Drawable
// GridMaps maps each object ID that named ObjectDoc.GridMap to its constructed runtime *world3d.GridMap, for collision queries, raycasting, or custom instancing.
GridMaps map[string]*world3d.GridMap
// Terrains maps each object ID that named ObjectDoc.Terrain to its built *Terrain (heightmap, TerrainLOD, TerrainMaterial and foliage).
Terrains map[string]*Terrain
// TerrainList holds the built *Terrain objects in depth-first document order.
TerrainList []*Terrain
// CSGColliders maps each CSG object ID that set collision: true to its world-space static *physics3d.TriMeshCollider.
CSGColliders map[string]*physics3d.TriMeshCollider
// Occluders are the occluders built from scene objects that set ObjectDoc.Occluder, in document order.
Occluders []Occluder
// LODHysteresis is the largest non-zero lodHysteresis declared by any model import sidecar in the built scene, or 0 when none sets one.
LODHysteresis float32
// Lights are the scene's 3D light objects in depth-first document order, linked to their scene3d nodes.
Lights []*Light
// Cameras are the scene's 3D camera objects in depth-first document order, linked to their scene3d nodes.
Cameras []*Camera
// ReflectionProbes are the scene's 3D reflection probe objects in depth-first document order, linked to their scene3d nodes and any loaded baked cubemaps.
ReflectionProbes []*ReflectionProbe
// LightProbeGrids are the scene's 3D light probe grid objects in depth-first document order, linked to their scene3d nodes and any loaded baked SH irradiance grids.
LightProbeGrids []*LightProbeGrid
// LightmapSidecar holds the parsed *.lightmaps.yaml sidecar loaded for the scene, or nil when none was loaded.
LightmapSidecar *render3d.LightmapSidecarDoc
// FogVolumes are the scene's local analytic 3D fog volume objects in depth-first document order, linked to their scene3d nodes.
FogVolumes []*FogVolume
// Environment holds the resolved sky, ambient/IBL lighting, fog, tone mapping and exposure from SceneDoc.Environment.
Environment Environment
// Meshes and Materials count the distinct MeshID and MaterialID values the parts use.
Meshes, Materials int
}
Built is a scene's 3D node tree with the geometry, lights, cameras and environment each scene declares, from Build.
func Build ¶
func Build(doc *sceneformat.SceneDoc, parent *scene3d.Node, models ModelResolver) (*Built, error)
Build builds doc's layers and objects into a 3D node tree under parent, as sceneformat.BuildNodes3D does, and gives every object that names a look its geometry and material:
- ObjectDoc.Mesh, a built-in primitive (PrimitiveMesh), drawn on the object's node with the object's material, or with a white, non-metallic, fully rough surface when it names none;
- ObjectDoc.Model, a glTF model loaded through models: with ModelMesh, that mesh drawn on the object's node; with ModelNode, that node's mesh drawn on the object's node and each of its descendants as a child node with its own transform; and with neither, a child node for each root node of the model's default scene (or of its first scene, or every parentless node when it has none) and their descendants. The model's materials are used unless the object names a material file, which replaces them all.
- ObjectDoc.GridMap, a 3D grid map loaded through a GridMapResolver and its glTF mesh library through models, instanced with world3d.GridMap.BuildInstances as child nodes of the object's node sharing the tile meshes and materials, with the built *world3d.GridMap recorded in Built.GridMaps.
A node Build makes for a glTF node is named after it, and is added after the object's child objects. Every node that draws gets its geometry's bounds as its LocalBounds and its *Drawable as the attachment AttachmentKey. Build attaches no collider, so scene3d picking hits a drawing node's LocalBounds box; BuildWith with BuildOptions.PickColliders, or Built.AttachMeshColliders, makes picks hit its triangles. A model draws in its bind pose with its meshes' default morph weights applied; skins, cameras, lights, animations and vertex colors are not used, nor are points and lines. A primitive without normals draws flat-shaded, and the base color texture's UV set and KHR_texture_transform are applied to the UVs.
models may be nil when no object names a model or grid map. It must implement sceneformat.MaterialResolver when an object names a material file, ImageResolver when such a file names a texture, and GridMapResolver when an object names a grid map; Assets does all four. A material file is read when Build runs: build again to see it edited.
Build returns an error and leaves parent unchanged when doc is invalid or still instances or inherits other scene files (pass it through sceneformat.Resolve first), when parent is nil, or when a model, node, mesh, grid map, material or image cannot be loaded or found.
Example ¶
A scene file places built-in primitives; Build gives each object's node its geometry and bounds, ready for a Renderer or render3d.Queue.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/scene3d"
"github.com/nsgo-dev/game/pkg/sceneformat"
"github.com/nsgo-dev/game/pkg/scenemodel"
)
func main() {
doc, err := sceneformat.Parse([]byte(`version: 2
layers:
- name: level
objects:
- id: floor
scaleX: 10
scaleZ: 10
mesh: plane
- id: pillar
x: 2
y: 1.5
scaleY: 3
mesh: cylinder
`))
if err != nil {
panic(err)
}
sc := scene3d.NewScene()
built, err := scenemodel.Build(doc, sc.Root(), nil) // no models, so no ModelResolver
if err != nil {
panic(err)
}
for _, d := range built.Drawables {
b := d.Node.WorldBounds()
fmt.Printf("%s: %d triangles, bounds %v to %v\n", d.Object, len(d.Parts[0].Mesh.Indices)/3, b.Min, b.Max)
}
fmt.Println(len(built.AppendDrawItems(nil)), "draw items")
}
Output: floor: 2 triangles, bounds {-5 0 -5} to {5 0 5} pillar: 128 triangles, bounds {1.5 0 -0.5} to {2.5 3 0.5} 2 draw items
func BuildObject ¶
func BuildObject(o *sceneformat.ObjectDoc, parent *scene3d.Node, models ModelResolver) (*Built, error)
BuildObject builds one scene object o (and any child objects in o.Children) into a 3D node subtree attached directly under parent, sharing the model, material and texture caches of models (such as an *Assets).
Like Build, it resolves primitives (ObjectDoc.Mesh), glTF models (ObjectDoc.Model, ModelNode, ModelMesh), grid maps (ObjectDoc.GridMap), material overrides (ObjectDoc.Material), LODs, occluders, lights, cameras and probes. When o (or a descendant) instances another scene file via ObjectDoc.Scene, models must implement sceneformat.SceneResolver (as Assets does) and BuildObject resolves it automatically.
Unlike Build, BuildObject attaches o's node directly as a child of parent without a wrapper layer node; Built.Objects maps o.ID and each descendant object ID to its node. On any error, BuildObject leaves parent unchanged.
func BuildPrefab ¶
BuildPrefab loads the prefab scene file at path through models (which must implement sceneformat.SceneResolver, as Assets does), resolves any nested scene instances or inheritance, and builds its 3D node subtree under parent while sharing models' caches (models, materials, textures, scenes).
Pass the returned *Built to Renderer.Add to draw the spawned prefab instance on the next frame (reusing already-uploaded GPU meshes and textures) and pass the returned Handle to Renderer.Remove when freeing it. On any error, BuildPrefab leaves parent unchanged.
func BuildWith ¶
func BuildWith(doc *sceneformat.SceneDoc, parent *scene3d.Node, models ModelResolver, opts BuildOptions) (*Built, error)
BuildWith is Build with additional options such as a scene path or explicit lightmap sidecar path for loading baked *.lightmaps.yaml lightmaps, or triangle-exact pick colliders.
func (*Built) ActiveCamera ¶
ActiveCamera builds a *scene3d.Camera from the scene's active 3D camera object (ActiveCameraObject) for the given aspect ratio (width / height).
func (*Built) ActiveCameraObject ¶
ActiveCameraObject returns the scene's active visible, enabled 3D camera object: the one marked Current, or the first visible, enabled 3D camera in document order when none is marked.
func (*Built) ActiveFogVolumes ¶
ActiveFogVolumes evaluates every visible, enabled local fog volume in b at its current world transform and appends the valid render3d.FogVolume values onto dst[:0] without allocating when dst has capacity.
func (*Built) AddCSGCollidersToWorld ¶
func (b *Built) AddCSGCollidersToWorld(w *physics3d.World) []*physics3d.TriMeshCollider
AddCSGCollidersToWorld registers every CSG TriMeshCollider built in b with w in deterministic object-ID order and returns the added colliders.
func (*Built) AppendDrawItems ¶
AppendDrawItems appends a render3d.DrawItem for every part of every drawable whose node is visible and enabled, in Drawables order, and returns the extended slice for render3d.Queue.Build. An item's ID holds the drawable's index in Drawables in its high 32 bits and the part's index in its low 32 bits (DrawItemID); its PipelineID is DrawPipeline of the part's material; its Transform is the node's world matrix and WorldBounds the part's bounds under it.
func (*Built) AppendOccluders ¶
AppendOccluders appends a render3d.Occluder for every visible, enabled occluder in b.Occluders at its node's current world transform and returns the extended slice.
func (*Built) AttachMeshColliders ¶
func (b *Built) AttachMeshColliders()
AttachMeshColliders gives the node of every drawable in b a *scene3d.MeshCollider holding the triangles of its parts in the node's space, so scene3d's Raycast, RaycastFirst, Pick and PickAll hit the drawn triangles instead of the node's LocalBounds. It replaces any collider those nodes had. Drawables with one part share one triangle slice per MeshID; a drawable with several parts gets a slice of its own. The triangles are copied from the parts' meshes, so the call costs memory in proportion to the scene's distinct geometry; BuildOptions.PickColliders calls it from BuildWith.
func (*Built) DynamicLightRig ¶
DynamicLightRig evaluates every visible, enabled light node in b excluding lights marked bake: "static", with Ambient set to zero. Renderer binds this rig for baked lightmapped static parts so static-baked lights are not evaluated a second time at runtime while dynamic lights still illuminate those parts.
func (*Built) HasBakedLightProbeGrid ¶
HasBakedLightProbeGrid reports whether b has at least one visible, enabled light probe grid with baked SH data.
func (*Built) HasBakedProbes ¶
HasBakedProbes reports whether b contains at least one reflection probe with a baked cubemap or light probe grid with baked irradiance data.
func (*Built) HasLightmaps ¶
HasLightmaps reports whether any part in b carries a baked lightmap (from a sidecar or glTF extension).
func (*Built) HasSceneLighting ¶
HasSceneLighting reports whether the built scene declares any 3D lights, an environment section, baked reflection/light probes, or baked lightmaps.
func (*Built) LightRig ¶
LightRig evaluates every visible, enabled light node in b at its current world transform and returns a render3d.LightRig combining b.Environment.Ambient with the scene's directional, point and spot lights. Within each category, shadow-casting lights come first so slot 0 matches render3d's shadow sampling slots. When point or spot lights exceed render3d.MaxPointLights or render3d.MaxSpotLights, slot 0 keeps the first shadow caster and the remaining slots pick the lights nearest the active 3D camera (or the world origin when the scene has no active 3D camera); use Built.LightRigNear to pass a specific camera position, or Built.SceneLights for clustered forward lighting.
func (*Built) LightRigNear ¶
LightRigNear is Built.LightRig using cameraPos to choose the nearest point and spot lights whenever a category exceeds render3d.MaxPointLights (16) or render3d.MaxSpotLights (8). When a category fits within its cap, lights keep document order with shadow casters first.
func (*Built) Part ¶
Part returns the drawable and part a render3d.DrawItem ID from AppendDrawItems names, and false when it names none.
func (*Built) RasterizeOccluders ¶
RasterizeOccluders clears buf, rasterizes every visible, enabled occluder in b for viewProj, builds the Hi-Z pyramid when at least one occluder was rasterized, and returns the number of occluders rasterized.
func (*Built) SampleLightProbes ¶
SampleLightProbes evaluates the scene's visible, enabled, baked light probe grids at worldPos and returns the trilinearly interpolated L2 spherical harmonic irradiance scaled by the chosen grid's intensity. When multiple baked grids contain worldPos, the smallest-volume grid wins (ties break in document order); when worldPos is outside every grid, the nearest grid is sampled (clamped to its boundary). Returns (zero, false) when no visible baked light probe grid exists.
func (*Built) SceneLights ¶
func (b *Built) SceneLights() (rig render3d.LightRig, local []render3d.ClusterLight)
SceneLights evaluates every visible, enabled light node in b at its current world transform and splits them for clustered forward lighting (render3d.ClusteredLightSystem): rig keeps b.Environment.Ambient, up to render3d.MaxDirectionalLights directional lights (shadow casters first), and at most one shadow-casting point light and one shadow-casting spot light in slot 0 (matching ShadowLights); local holds every other visible point and spot light as a render3d.ClusterLight without truncating at 16 or 8.
func (*Built) ShadowLights ¶
func (b *Built) ShadowLights() (dir *render3d.DirectionalLight, point *render3d.PointLight, spot *render3d.SpotLight)
ShadowLights returns the first visible shadow-casting directional, point and spot lights in b, matching slot 0 of each LightRig slice.
type BytesResolver ¶
BytesResolver reads raw binary asset bytes at path, a slash-separated path from the project root, such as a generated UV2 .bin buffer referenced by a lightmap sidecar.
type Camera ¶
type Camera struct {
// Node is the scene3d node placing and orienting the camera.
Node *scene3d.Node
// Object is the ID of the scene object the camera belongs to.
Object string
// Doc is a copy of the source camera definition.
Doc sceneformat.Camera3DDoc
}
Camera is a 3D camera built from a scene object (sceneformat.ObjectDoc.Camera), attached to its scene3d.Node so moving or rotating the node updates the camera's viewpoint.
type Drawable ¶
type Drawable struct {
// Node is the scene3d node the parts are drawn at; its LocalBounds hold the parts' bounds.
Node *scene3d.Node
// Object is the ID of the scene object the drawable belongs to.
Object string
// Parts are what the node draws, in the order the model lists them.
Parts []Part
// Shadow controls how the drawable participates in shadow and main passes (#1370).
Shadow render3d.ShadowMode
// VisibilityRange configures distance culling and optional screen-door dither fading (#1370).
VisibilityRange render3d.VisibilityRange
// ExtraCullMargin expands the world-space AABB for frustum and occlusion culling (#1370).
ExtraCullMargin float32
// SkipOcclusion exempts the drawable from CPU software occlusion culling (#1370).
SkipOcclusion bool
}
Drawable is a node that draws geometry: an object's node, or a node Build made for a node of the object's model.
type Environment ¶
type Environment struct {
// Present reports whether the scene declared an environment section.
Present bool
// Doc is a copy of SceneDoc.Environment when Present is true.
Doc sceneformat.EnvironmentDoc
// Ambient is the linear ambient fill light.
Ambient render3d.AmbientLight
// SkyKind is the resolved sky kind, or empty when Doc.Sky is nil.
SkyKind sceneformat.SkyKind
// SkyColor is the linear RGB color of a SkyColor sky.
SkyColor math3d.Vec3
// SkyClearColor is the display-space tone-mapped clear color for SkyColor.
SkyClearColor core.Color
// SkyCubemap is the linear HDR cubemap for SkyGradient or SkyHDR skies, or nil.
SkyCubemap *render3d.HDRCubemap
// IBLIrradiance is the L2 spherical-harmonic diffuse irradiance when IBLIntensity > 0.
IBLIrradiance render3d.IrradianceSH
// IBLPrefilter is the GGX prefiltered specular cubemap when IBLIntensity > 0.
IBLPrefilter *render3d.HDRCubemap
// IBLIntensity is the effective IBL multiplier (>= 0).
IBLIntensity float32
// Fog is the resolved render3d.Fog configuration.
Fog render3d.Fog
// HasFog reports whether distance or height fog is active.
HasFog bool
// ToneMap holds the tone mapping operator, exposure, and resolved color adjustments (upload LUTImage to populate ToneMap.Adjust.LUT).
ToneMap render3d.ToneMapOptions
// ColorAdjust holds the resolved post-tone-map brightness, contrast, saturation and LUT strength.
ColorAdjust render3d.ColorAdjust
// LUTPath is the project-relative LUT path from Doc.Adjustments.LUT, or empty.
LUTPath string
// LUTImage is the decoded N*N × N RGBA8 2D strip LUT image loaded from LUTPath, ready for render3d.UploadLUTImage.
LUTImage *image.NRGBA
// AutoExposure holds the resolved render3d.AutoExposure configuration from Doc.AutoExposure.
AutoExposure render3d.AutoExposure
// HasAutoExposure reports whether auto exposure is enabled for this environment.
HasAutoExposure bool
// SSR holds the resolved render3d.SSRConfig from Doc.SSR.
SSR render3d.SSRConfig
// HasSSR reports whether screen-space reflections are enabled for this environment.
HasSSR bool
// Antialiasing is the anti-aliasing mode Doc.Antialiasing asks for, render3d.AANone when it is empty or "none". Renderer does not apply it by itself, because the caller owns the render target: for an MSAA mode, create the target with Antialiasing.SampleCount() (render3d.NewMSAATarget) and pass the same count as RendererOptions.SampleCount; for render3d.AAFXAA, draw into a single-sampled texture and run render3d.FXAAPass over it.
Antialiasing render3d.AAMode
}
Environment is the resolved 3D environment built from sceneformat.SceneDoc.Environment, ready to drive render3d's sky, ambient fill, image-based lighting, fog, tone mapping and exposure.
func (Environment) ForQuality ¶
func (e Environment) ForQuality(preset quality.Preset) Environment
ForQuality returns a copy of e adjusted for preset: when preset disables SSR or auto exposure (such as quality.DefaultPreset(quality.Low)), HasSSR and HasAutoExposure / AutoExposure.Enabled are turned off while color adjustments and tone mapping stay intact.
type FogVolume ¶
type FogVolume struct {
// Node is the scene3d node placing, orienting and sizing the fog volume.
Node *scene3d.Node
// Object is the ID of the scene object the fog volume belongs to.
Object string
// Doc is a copy of the source fog volume definition.
Doc sceneformat.FogVolumeDoc
// contains filtered or unexported fields
}
FogVolume is a local analytic 3D fog volume built from a scene object (sceneformat.ObjectDoc.FogVolume), attached to its scene3d.Node so moving, rotating or scaling the node updates the volume's world transform.
type FoliagePart ¶
type FoliagePart struct {
Part
// LocalMatrix transforms vertices from the glTF node's local space into the foliage instance's local space.
LocalMatrix math3d.Mat4
}
FoliagePart is one mesh/material part of a TerrainFoliage layer with its model-local transform baked relative to the foliage instance origin.
type GridMapResolver ¶
type GridMapResolver interface {
GridMap(path string) (*world3d.GridMapDoc, error)
}
GridMapResolver loads the 3D grid map files objects name in sceneformat.ObjectDoc.GridMap. path is the slash-separated path from the project root that the scene file writes, such as "levels/dungeon.gridmap.yaml".
type HDRResolver ¶
HDRResolver loads the Radiance .hdr image at path, a slash-separated path from the project root, for an HDR sky (sceneformat.SkyDoc.HDR) or a baked reflection probe cubemap (sceneformat.ReflectionProbeDoc.Cubemap).
type Handle ¶
type Handle struct {
// contains filtered or unexported fields
}
Handle identifies a set of drawables added to a Renderer with Renderer.Add. Pass it to Renderer.Remove to release its per-part GPU buffers and decrement the reference counts on any shared meshes, textures and materials it uses. The zero Handle is invalid: Ready returns false, Err returns nil and Remove is a no-op.
func (Handle) Err ¶
Err returns the asynchronous upload error if an Uploader-backed upload for h failed, or nil while uploading, once ready, or for an invalid handle.
type ImageResolver ¶
ImageResolver loads the image at path, a slash-separated path from the project root, for the texture of a material file (resource.Material.Texture).
type ImportSettingsResolver ¶
type ImportSettingsResolver interface {
ImportSettings(modelPath string) (*importsettings.File, error)
}
ImportSettingsResolver loads the *.import.yaml sidecar of the model at modelPath, a slash-separated path from the project root such as "models/tree.glb". It returns (nil, nil) when the model has no sidecar file.
type KTX2Data ¶
type KTX2Data struct {
// Bytes are the encoded KTX2 file bytes passed to render3d.LoadKTX2.
Bytes []byte
}
KTX2Data holds the encoded bytes of a KTX2 container shared across materials that sample it.
type KTX2Resolver ¶
KTX2Resolver loads the raw KTX2 container bytes at path, a slash-separated path from the project root, for a compressed texture named by a material file (such as "textures/stone.ktx2").
type LUTResolver ¶
LUTResolver loads a color lookup table (.cube text file or 2D horizontal strip image) at path, a slash-separated path from the project root, for sceneformat.ColorAdjustDoc.LUT, returning a validated N*N × N RGBA8 strip image ready for render3d.UploadLUTImage.
type Light ¶
type Light struct {
// Node is the scene3d node placing and aiming the light.
Node *scene3d.Node
// Object is the ID of the scene object the light belongs to.
Object string
// Doc is a copy of the source light definition.
Doc sceneformat.LightDoc
}
Light is a 3D light built from a scene object (sceneformat.ObjectDoc.Light), attached to its scene3d.Node so moving or rotating the node updates the light's world position and direction (-Z in local space).
type LightProbeGrid ¶
type LightProbeGrid struct {
// Node is the scene3d node placing the light probe grid.
Node *scene3d.Node
// Object is the ID of the scene object the light probe grid belongs to.
Object string
// Doc is a copy of the source light probe grid definition.
Doc sceneformat.LightProbeGridDoc
// Grid is the loaded baked *render3d.LightProbeGrid when Doc.Data is set, or nil when unbaked.
Grid *render3d.LightProbeGrid
}
LightProbeGrid is a 3D light probe grid built from a scene object (sceneformat.ObjectDoc.LightProbeGrid), linked to its scene3d.Node and holding any baked L2 spherical harmonic irradiance grid loaded from Doc.Data.
func (*LightProbeGrid) WorldBounds ¶
func (g *LightProbeGrid) WorldBounds() math3d.AABB
WorldBounds returns the world-space axis-aligned volume covering g's light probes.
type LightProbeGridResolver ¶
type LightProbeGridResolver interface {
LightProbeGrid(path string) (*render3d.LightProbeGrid, error)
}
LightProbeGridResolver loads the baked light probe grid YAML file at path, a slash-separated path from the project root, for a scene object's light probe grid (sceneformat.LightProbeGridDoc.Data).
type LightmapSidecarResolver ¶
type LightmapSidecarResolver interface {
LightmapSidecar(path string) (*render3d.LightmapSidecarDoc, error)
}
LightmapSidecarResolver loads a baked scene lightmap sidecar YAML file at path (*.lightmaps.yaml), a slash-separated path from the project root.
type LightmapTexture ¶
type LightmapTexture struct {
// Name identifies the texture source for debug labels.
Name string
// Image holds the decoded 8-bit image when the lightmap is not a Radiance .hdr file.
Image image.Image
// HDR holds the decoded linear floating-point Radiance image when the lightmap is a .hdr file.
HDR *render3d.HDRImage
// Encoding specifies how texels decode to linear irradiance.
Encoding render3d.LightmapEncoding
// RGBMMaxRange sets the peak multiplier for render3d.LightmapRGBM (0 uses DefaultRGBMMaxRange).
RGBMMaxRange float32
// Sampler configures filtering and wrapping (defaults to linear clamp-to-edge).
Sampler render3d.SamplerOptions
}
LightmapTexture is a decoded baked lightmap image (an 8-bit PNG image for RGBM/RGBD/sRGB/linear or a linear Radiance *render3d.HDRImage for .hdr atlases) shared by every Part that samples it.
type Material ¶
type Material struct {
// BaseColor is the linear RGBA base color, multiplied by BaseColorTexture's texels.
BaseColor math3d.Vec4
// Metallic and Roughness are the metalness and perceptual roughness, from 0 to 1.
Metallic, Roughness float32
// Emissive is the linear RGB light the surface gives off, its glTF emissive strength included.
Emissive math3d.Vec3
// BaseColorTexture is the sRGB base color image, or nil for none.
BaseColorTexture *Texture
// MetallicRoughnessTexture is the glTF metallic-roughness image, roughness in green and metalness in blue, multiplied by Roughness and Metallic, or nil for none. Renderer does not sample it yet.
MetallicRoughnessTexture *Texture
// NormalTexture is the tangent-space normal map, or nil for none. Renderer does not sample it yet.
NormalTexture *Texture
// OcclusionTexture is the ambient occlusion image, occlusion in red, or nil for none. Renderer does not sample it yet.
OcclusionTexture *Texture
// EmissiveTexture is the sRGB emissive image, multiplied by Emissive, or nil for none. Renderer does not sample it yet.
EmissiveTexture *Texture
// NormalScale scales the normal map's X and Y, as glTF's normalTexture.scale; it is 0 when NormalTexture is nil.
NormalScale float32
// OcclusionStrength blends the occlusion map in from 0 (none) to 1 (full), as glTF's occlusionTexture.strength; it is 0 when OcclusionTexture is nil.
OcclusionStrength float32
// AlphaMode says how the base color's alpha is used: ignored, a cutout at AlphaCutoff, or blended over what is behind.
AlphaMode render3d.AlphaMode
// AlphaCutoff is the alpha below which a render3d.AlphaMask surface is discarded.
AlphaCutoff float32
// DoubleSided draws the back faces too, lit from the side the viewer sees.
DoubleSided bool
}
Material is the surface a Part draws with, in glTF 2.0's metallic-roughness terms.
func MaterialFromFile ¶
MaterialFromFile converts a material file into a Material without its texture: the base color and emissive CSS colors converted from sRGB to linear light, the base color's alpha times the opacity, render3d.AlphaBlend when that alpha is below 1, the metalness, roughness and double-sidedness as written. Its 2D blend mode does not apply in 3D, and a 3D surface is always lit, so Unlit is not used either.
type ModelResolver ¶
ModelResolver loads the glTF models objects name in sceneformat.ObjectDoc.Model, as sceneformat.MaterialResolver loads their material files. path is the slash-separated path from the project root that the scene file writes, such as "models/crate.glb". A resolver that returns the same document for the same path lets every object that names it share its decoded textures.
The ModelResolver given to Build, BuildObject or BuildPrefab may also implement sceneformat.MaterialResolver, to resolve the material files objects name in ObjectDoc.Material, ImageResolver, to load the PNG or JPEG textures those material files name, KTX2Resolver, to load the KTX2 textures those material files name, GridMapResolver, to load the 3D grid maps objects name in ObjectDoc.GridMap, TerrainResolver, to load the 3D terrains objects name in ObjectDoc.Terrain, ImportSettingsResolver, to read a model's *.import.yaml sidecar for LOD definitions, HDRResolver, to load Radiance .hdr sky panoramas named in EnvironmentDoc.Sky.HDR, LUTResolver, to load color LUTs named in EnvironmentDoc.Adjustments.LUT, LightProbeGridResolver, to load baked light probe grids, LightmapSidecarResolver, to load baked *.lightmaps.yaml sidecars, BytesResolver, to read raw UV2 buffer files, and sceneformat.SceneResolver, to load prefab or instanced scene files. Assets implements all of them, as well as sceneformat.TerrainResolver so heightfield colliders share the same decoded heightmap.
type Occluder ¶
type Occluder struct {
// Node is the scene3d node the occluder follows.
Node *scene3d.Node
// Object is the ID of the scene object that declared the occluder.
Object string
// Mode is sceneformat.OccluderModel or sceneformat.OccluderBox.
Mode sceneformat.OccluderMode
// LocalBounds is the occluder's bounding box in Node's local space.
LocalBounds math3d.AABB
// DoubleSided reports whether both front and back faces occlude.
DoubleSided bool
// contains filtered or unexported fields
}
Occluder is one occluder attached to a Built 3D scene (Built.Occluders), produced for any scene object that sets sceneformat.ObjectDoc.Occluder.
func (Occluder) RenderOccluder ¶
RenderOccluder returns a render3d.Occluder positioned at o.Node's current world matrix without copying vertex or index slices.
type Part ¶
type Part struct {
// Mesh is the triangle geometry in the space of the node that draws it.
Mesh render3d.Mesh
// MeshID identifies Mesh among the meshes of one Built, from 0 up: parts that draw the same glTF primitive or primitive shape share it, as render3d.DrawItem.MeshID expects.
MeshID uint32
// Material is the surface Mesh draws with.
Material Material
// MaterialID identifies Material among the materials of one Built, from 0 up, shared by the parts that use the same glTF material or material file.
MaterialID uint32
// Lightmap optionally binds this part to a baked lightmap from the scene's .lightmaps.yaml sidecar or a glTF MOZ_lightmap/EXT_lightmap/extras.lightmap material extension.
Lightmap *PartLightmap
// LODs are the detail levels for this part, ordered from finest (index 0, matching Mesh and MeshID) to coarsest. Empty when the part has only one detail level.
LODs []PartLOD
// contains filtered or unexported fields
}
Part is one piece of geometry a node draws with one material.
type PartLOD ¶
type PartLOD struct {
// Mesh is the triangle geometry in the space of the node that draws it.
Mesh render3d.Mesh
// MeshID identifies Mesh among the meshes of one Built, matching render3d.LODLevel.MeshID.
MeshID uint32
// MinScreenRatio is the minimum viewport-height fraction in [0, 1] at which this level is drawn (render3d.LODLevel.MinScreenRatio).
MinScreenRatio float32
// MaxDistance is the optional maximum camera distance in world units at which this level is drawn (render3d.LODLevel.MaxDistance).
MaxDistance float32
// Triangles and Vertices are the geometry counts of Mesh.
Triangles uint32
Vertices uint32
// contains filtered or unexported fields
}
PartLOD is one level of detail of a Part, ordered from finest (index 0) to coarsest.
type PartLightmap ¶
type PartLightmap struct {
// Texture is the primary baked irradiance lightmap texture.
Texture *LightmapTexture
// DirectionalTexture is an optional companion L1 SH directional lightmap texture.
DirectionalTexture *LightmapTexture
// UVTransform maps UV2 (TEXCOORD_1) into the lightmap atlas sub-rectangle.
UVTransform render3d.UVTransform
// Encoding specifies how Texture texels decode to linear irradiance.
Encoding render3d.LightmapEncoding
// Intensity scales decoded irradiance when shading.
Intensity float32
// RGBMMaxRange sets the peak multiplier for render3d.LightmapRGBM (0 uses DefaultRGBMMaxRange).
RGBMMaxRange float32
// FromSidecar reports whether this lightmap came from the scene's .lightmaps.yaml sidecar.
FromSidecar bool
}
PartLightmap binds a Part to its baked lightmap texture, atlas UV transform, encoding, and intensity.
type ProbeBakeOptions ¶
type ProbeBakeOptions struct {
// Size overrides the cubemap face resolution in texels; non-positive uses the probe's
// Resolution for reflection probes (default 64) or 16 for light probe grids.
Size int
// Near and Far set the 90-degree cubemap face clip planes; non-positive Near defaults to 0.05,
// and Far <= Near defaults to Near + 200.
Near float32
Far float32
// FallbackLights supplies the direct light rig used when the built scene has no 3D lights
// and no environment section. When nil, Built.LightRig() is always used.
FallbackLights *render3d.LightRig
// FallbackClearColor sets the background clear color when the scene has no solid or cubemap sky.
FallbackClearColor core.Color
}
ProbeBakeOptions configures BakeReflectionProbe and BakeLightProbeGrid.
type ReflectionProbe ¶
type ReflectionProbe struct {
// Node is the scene3d node placing the reflection probe.
Node *scene3d.Node
// Object is the ID of the scene object the reflection probe belongs to.
Object string
// Doc is a copy of the source reflection probe definition.
Doc sceneformat.ReflectionProbeDoc
// Cubemap is the loaded base-mip linear HDR cubemap when Doc.Cubemap is set, or nil when unbaked.
Cubemap *render3d.HDRCubemap
// Prefiltered is the GGX roughness-prefiltered HDR cubemap built from Cubemap, or nil when unbaked.
Prefiltered *render3d.HDRCubemap
}
ReflectionProbe is a 3D reflection probe built from a scene object (sceneformat.ObjectDoc.ReflectionProbe), linked to its scene3d.Node and holding any baked cubemap and GGX prefiltered specular mip chain loaded from Doc.Cubemap.
func (*ReflectionProbe) RuntimeProbe ¶
func (p *ReflectionProbe) RuntimeProbe(gpuCube *render3d.GPUCubemap) *render3d.ReflectionProbe
RuntimeProbe builds a *render3d.ReflectionProbe reflecting p's current node transform, visibility, and baked state, optionally attaching gpuCube for GPU shading.
func (*ReflectionProbe) WorldBounds ¶
func (p *ReflectionProbe) WorldBounds() (pos, boxMin, boxMax math3d.Vec3)
WorldBounds returns the probe's capture origin and world-space axis-aligned influence box [boxMin, boxMax].
type Renderer ¶
type Renderer struct {
// contains filtered or unexported fields
}
Renderer draws a Built scene's drawables, lights, shadows, reflection probes, light probe grids and environment on a gpu.Device, culled and ordered by a render3d.Queue (frustum culling, software occlusion culling when Built has occluders, LOD selection with hysteresis, opaque surfaces front to back by pipeline, material and mesh, blended ones back to front). Each frame, call PrepareScene (or Prepare with custom lights), call RecordShadows before the main render pass when any light casts shadows, and call DrawSky and Draw inside the render pass. Its GPU resources belong to the scope given to NewRenderer, or are released by Close. Use it from the engine goroutine, like the device.
func NewRenderer ¶
func NewRenderer(cx *core.Scope, dev *gpu.Device, b *Built, opts RendererOptions) (*Renderer, error)
NewRenderer uploads every mesh, texture, material, sky cubemap, IBL prefilter and shadow map of b to dev, scoped to cx, and creates the buffers and pipelines that draw them, through the pipeline cache attached to dev, or one render3d.AttachPipelineCache attaches when dev has none. b's nodes may move, hide and show at any time, and additional objects or prefabs may be added and removed at run time with Renderer.Add and Renderer.Remove.
func (*Renderer) Add ¶
Add registers b's drawables (and any occluders) with r so they appear on the next frame. Meshes, textures and materials already resident in r (keyed by the same primitive, model path, material and texture keys Build uses) are shared and reference-counted instead of re-uploaded.
When RendererOptions.Uploader is configured, meshes and textures not already resident are queued on the uploader so large prefabs do not stall the frame; Add returns before those parts appear and Handle.Ready reports when they do. When all resources are already resident or no Uploader is configured, the returned Handle is ready immediately.
On any error, Add rolls back every buffer, texture and reference it acquired and leaves r unchanged.
func (*Renderer) CaptureFrame ¶
func (r *Renderer) CaptureFrame(desc gpu.RenderPassDesc, width, height int, opts render3d.FrameCaptureOptions) (*render3d.CapturedFrame, error)
CaptureFrame renders the already-prepared scene pass by pass into desc, submitting after each pass so every pass target thumbnail (shadows, sky, opaque, transparent) reflects the exact output immediately after that pass ran, while honoring opts.MaxDraws ("draw up to here" scrubbing).
func (*Renderer) ClearColor ¶
ClearColor returns the scene environment's tone-mapped solid sky color when SkyKind is SkyColor, or fallback otherwise.
func (*Renderer) Close ¶
Close releases every GPU resource of r now instead of when its scope is disposed. It is safe to call on nil and more than once; after it, Prepare returns an error and Draw records nothing.
func (*Renderer) ClusteredLights ¶
func (r *Renderer) ClusteredLights() *render3d.ClusteredLightSystem
ClusteredLights returns the underlying render3d.ClusteredLightSystem owned by r, for inspecting whether the clustered or fallback path is active and reading per-frame cluster stats.
func (*Renderer) DispatchVisibility ¶
DispatchVisibility invokes onEnter for each object in Renderer.EnteredObjects and onExit for each object in Renderer.ExitedObjects. It snapshots the transition lists and guards against re-entrant calls so callbacks may safely mutate scene nodes or trigger visibility resets (#1370).
func (*Renderer) Draw ¶
func (r *Renderer) Draw(pass *gpu.RenderPass)
Draw records the parts Prepare planned into pass: the opaque and cutout ones (including terrain chunks and opaque foliage) first, then the blended ones back to front. pass must have a color attachment of RendererOptions.ColorFormat and a depth attachment of its DepthFormat. It records nothing once the renderer is closed.
func (*Renderer) DrawFogVolumes ¶
DrawFogVolumes records all prepared local fog volumes into pass, which must target the renderer's ColorFormat with no depth attachment so sceneDepth (nil for unoccluded volumes) can be sampled safely.
func (*Renderer) DrawOpaque ¶
func (r *Renderer) DrawOpaque(pass *gpu.RenderPass)
DrawOpaque records the opaque and cutout parts Prepare planned into pass, along with any visible terrain chunks and opaque/cutout foliage.
func (*Renderer) DrawSky ¶
func (r *Renderer) DrawSky(pass *gpu.RenderPass)
DrawSky draws the scene's gradient or HDR skybox cubemap into pass using the scene's exposure and tone mapping operator. Call it before Draw inside the render pass; it does nothing when the scene has no cubemap sky.
func (*Renderer) DrawTransparent ¶
func (r *Renderer) DrawTransparent(pass *gpu.RenderPass)
DrawTransparent records the alpha-blended parts Prepare planned into pass, back to front, along with any alpha-blended foliage.
func (*Renderer) DrawableCount ¶
DrawableCount returns the number of live ready drawables currently registered in r (from the initial Built and all ready, unremoved Handles added via Add).
func (*Renderer) EnteredObjects ¶
EnteredObjects returns the scene object IDs that became visible on the most recent Prepare call, in deterministic document order. The returned slice is owned by the renderer and reused across frames (#1370).
func (*Renderer) ExitedObjects ¶
ExitedObjects returns the scene object IDs that were visible on the previous Prepare call and are no longer visible on the most recent call, in deterministic document order. The returned slice is owned by the renderer and reused across frames (#1370).
func (*Renderer) FrameCapture ¶
func (r *Renderer) FrameCapture() *render3d.FrameCapture
FrameCapture returns the render3d.FrameCapture attached via SetFrameCapture, or nil.
func (*Renderer) GPUTimer ¶
GPUTimer returns the render3d.GPUTimer attached via SetGPUTimer, or nil.
func (*Renderer) HasFogVolumes ¶
HasFogVolumes reports whether the built scene has at least one visible prepared local fog volume.
func (*Renderer) HasSky ¶
HasSky reports whether the built scene has a gradient or HDR skybox cubemap that DrawSky draws.
func (*Renderer) LayerMask ¶
LayerMask returns the render layer bitmask configured via Renderer.SetLayerMask.
func (*Renderer) PipelineCacheStats ¶
func (r *Renderer) PipelineCacheStats() gpu.PipelineCacheStats
PipelineCacheStats reports the hits, misses and compilations of the pipeline cache the renderer compiles through, which every other user of the device shares.
func (*Renderer) Plan ¶
func (r *Renderer) Plan() render3d.RenderPlan
Plan returns the render3d.RenderPlan from the most recent Prepare call, allowing callers to inspect selected LOD indices and culling statistics.
func (*Renderer) Prepare ¶
func (r *Renderer) Prepare(cam *scene3d.Camera, lights render3d.LightRig) (render3d.RenderStats, error)
Prepare writes cam and lights to their buffers and each visible part's world transform to its draw buffer, and plans the frame with the renderer's render3d.Queue: frustum culling and draw order. Call it once a frame before the render pass that Draw records into. It returns the plan's statistics, and an error when lights fails render3d's validation or the renderer is closed.
func (*Renderer) PrepareScene ¶
PrepareScene prepares the frame using the built scene's own 3D lights (Built.SceneLights, lighting unshadowed point and spot lights through render3d.ClusteredLightSystem), shadow-casting lights (Built.ShadowLights) and environment (sky, IBL, fog, tone mapping, exposure). Call RecordShadows before the main render pass when any light casts shadows, then DrawSky and Draw inside the pass.
func (*Renderer) RecordFogVolumes ¶
func (r *Renderer) RecordFogVolumes(target render3d.ShadowPassTarget, colorTex, sceneDepth *gpu.Texture) error
RecordFogVolumes opens a color-only LoadLoad pass targeting colorTex (or the swapchain when nil) and draws all prepared local fog volumes clipped against sceneDepth.
func (*Renderer) RecordScene ¶
func (r *Renderer) RecordScene(target render3d.ShadowPassTarget, desc gpu.RenderPassDesc)
RecordScene records the complete prepared scene into target (a *gpu.Frame or *gpu.Encoder): shadow passes followed by sky, opaque, and transparent draws targeting desc.
When SetGPUTimer or an armed SetFrameCapture is set, RecordScene splits sky, opaque, and transparent into separate passes labeled "sky", "opaque", and "transparent" (preserving color and depth across passes with gpu.LoadLoad after the first pass), in addition to shadow passes from RecordShadows. Otherwise sky, opaque, and transparent share a single render pass using desc as given.
func (*Renderer) RecordShadows ¶
func (r *Renderer) RecordShadows(target render3d.ShadowPassTarget)
RecordShadows records the depth shadow passes for any active shadow-casting lights prepared by PrepareScene into target (a *gpu.Frame or *gpu.Encoder). Call it before BeginRenderPass for the main scene pass. It does nothing when no shadows are active or in ShadingUnlit. When SetGPUTimer is set, shadow passes are timed under the "shadows" label.
func (*Renderer) Remove ¶
Remove removes the drawables (and any occluders) added under h, immediately releasing their per-part GPU uniform buffers and bind groups and decrementing reference counts on shared meshes, textures, samplers and material bind groups (freeing any whose last user was removed, and canceling in-flight uploads that no other handle waits on).
Remove is safe and idempotent on a zero, already-removed, foreign or closed-renderer Handle.
func (*Renderer) ResetVisibility ¶
func (r *Renderer) ResetVisibility()
ResetVisibility clears tracked on-screen visibility history and distance hysteresis state without releasing backing storage (#1370).
func (*Renderer) SampleCount ¶
SampleCount returns the MSAA sample count the renderer's pipelines were created with (1 or 4), RendererOptions.SampleCount after render3d.ClampSampleCount, or 0 for a nil renderer. Every pass given to DrawSky, Draw, DrawOpaque and DrawTransparent, and the desc given to RecordScene, must have attachments with this sample count.
func (*Renderer) SetFrameCapture ¶
func (r *Renderer) SetFrameCapture(fc *render3d.FrameCapture)
SetFrameCapture attaches an optional render3d.FrameCapture so RecordScene, RecordShadows, DrawSky, DrawOpaque, DrawTransparent, and Draw record every pass and draw call (and respect MaxDraws "draw up to here" scrubbing) when fc is armed. Passing nil detaches frame capture.
func (*Renderer) SetGPUTimer ¶
SetGPUTimer attaches an optional render3d.GPUTimer so Prepare/PrepareScene populate RenderStats.GPUMs and RenderStats.Passes from completed frames, RecordShadows labels shadow passes as "shadows", and RecordScene labels the "shadows", "sky", "opaque", and "transparent" passes automatically. Passing nil detaches the timer without closing it.
func (*Renderer) SetLayerMask ¶
SetLayerMask sets the bitmask of render layers the renderer's internal queue accepts in the main color pass (0 defaults to scene3d.LayerAll) (#1370).
func (*Renderer) SetShading ¶
SetShading makes Draw shade the parts with s from the next frame on. The first change to ShadingUnlit creates its pipelines, under the scope given to NewRenderer, and returns an error when they cannot be created, leaving the shading as it was; so does an unknown Shading or a closed renderer.
func (*Renderer) SetViewport ¶
SetViewport sets the render target size in pixels used to map fragment coordinates to clustered light tiles. Call it before PrepareScene when rendering into a target whose dimensions differ from dev.SurfaceSize(); non-positive or non-finite values reset to using dev.SurfaceSize().
func (*Renderer) ShadowInfo ¶
func (r *Renderer) ShadowInfo() ShadowInfo
ShadowInfo returns the shadow maps used by the most recent prepared frame. It returns a zero value for a nil renderer. Before the first successful Prepare call every Active, Extent and TexelSize field is zero, while Resolution already reports each map's configured size.
func (*Renderer) VisibilityTracker ¶
func (r *Renderer) VisibilityTracker() *render3d.VisibilityTracker
VisibilityTracker returns the underlying render3d.VisibilityTracker used to diff per-object on-screen visibility across frames (#1370).
func (*Renderer) Visible ¶
Visible reports whether any part of the scene object named objectID survived frustum, layer, visibility-range, and occlusion culling on the most recent Renderer.Prepare or Renderer.PrepareScene call (#1370).
type RendererOptions ¶
type RendererOptions struct {
// Label prefixes the debug labels of the GPU resources; empty is "scenemodel".
Label string
// ColorFormat is the color attachment's format; gpu.FormatUndefined is the device's surface format.
ColorFormat gpu.TextureFormat
// DepthFormat is the depth attachment's format, which every pass the renderer draws in must have; gpu.FormatUndefined is gpu.FormatDepth24Plus.
DepthFormat gpu.TextureFormat
// SampleCount is the MSAA sample count of the color and depth attachments every pass the renderer draws in has, such as a render3d.MSAATarget's SampleCount or the sample count given to gpu.NewSoftwareRendererWithConfig. 0 and 1 mean single-sampled; 2 and above go through render3d.ClampSampleCount, which gives 4 on a device with Features.MSAA4x and 1 otherwise, as render3d.NewMSAATarget does. Renderer.SampleCount reports the resolved count. NSGo skips a draw whose pipeline's sample count differs from the pass's, so a pass with another sample count draws nothing. Built.Environment.Antialiasing.SampleCount() is the count the scene's environment asks for. A Built with local fog volumes needs a single-sampled renderer, because the fog volume pass samples the scene depth.
SampleCount int
// Retained keeps CPU copies of the buffers and textures so NSGo recreates them after a device loss (gpu.BufferDesc.Retained).
Retained bool
// DisableOcclusion disables CPU software occlusion culling even when Built holds occluders.
DisableOcclusion bool
// OcclusionWidth and OcclusionHeight configure the software render3d.OcclusionBuffer resolution; non-positive values use render3d's defaults (128x72).
OcclusionWidth, OcclusionHeight int
// LODHysteresis overrides the relative deadband [0, 0.5] used by render3d.Queue for LOD selection; 0 uses Built.LODHysteresis.
LODHysteresis float32
// LinearOutput compiles linear HDR shaders (no tone mapping or sRGB encode) for rendering into a floating-point target such as FormatRGBA16Float when baking reflection or light probes.
LinearOutput bool
// DisableProbes excludes baked local reflection probes and light probe grids from shading (still keeping direct lights, shadows, sky and emissives), used when baking or rebaking probes.
DisableProbes bool
// ClusterConfig configures the internal render3d.ClusteredLightSystem used for unshadowed point and spot lights; the zero value uses render3d.DefaultClusterConfig() (and falls back automatically to the uniform-buffer fallback path if the device's MaxStorageBufferBindingSize cannot fit the default storage buffers).
ClusterConfig render3d.ClusterConfig
// ShadowResolution is the width and height in texels of the directional and spot shadow maps; 0 uses DefaultShadowResolution. Non-zero values must be a power of two in [render3d.MinShadowResolution, render3d.MaxShadowResolution].
ShadowResolution uint32
// PointShadowResolution is the width and height in texels of each of a point shadow map's six cube faces; 0 uses DefaultPointShadowResolution. Non-zero values must be a power of two in [render3d.MinShadowResolution, render3d.MaxShadowResolution].
PointShadowResolution uint32
// PrecompileUnlit creates the unlit pipeline set during renderer construction so the first SetShading(ShadingUnlit) does not compile on a frame.
PrecompileUnlit bool
// Uploader optionally streams GPU meshes and textures for dynamically added objects (Renderer.Add) across frames within its per-frame byte budget so spawning a large prefab does not stall the frame. When nil, Renderer.Add uploads synchronously and Handle.Ready is immediately true. NewRenderer always uploads the initial Built synchronously. The caller owns Uploader and drives it via Uploader.Step each frame.
Uploader *render3d.Uploader
// FogVolumeShadowSamples sets how many points along each local fog volume ray sample the directional shadow map for light shafts (0 disables shadow sampling; capped at render3d.MaxFogVolumeShadowSamples).
FogVolumeShadowSamples int
}
RendererOptions configures NewRenderer.
type Shading ¶
type Shading uint8
Shading says how Renderer shades the parts it draws (Renderer.SetShading).
const ( // ShadingLit lights every part with the render3d.LightRig given to Prepare (or built.LightRig via PrepareScene), plus the scene's environment. It is a Renderer's shading until SetShading changes it. ShadingLit Shading = iota // ShadingUnlit draws every part at its textured base color plus its emissive color and ignores the lights, as an editor's unlit view shows a scene. ShadingUnlit )
type ShadowInfo ¶
type ShadowInfo struct {
Directional ShadowMapInfo
Spot ShadowMapInfo
Point ShadowMapInfo
}
ShadowInfo reports which scene shadow maps were written for the most recent prepared frame. It is a snapshot and remains unchanged until the next Prepare call.
type ShadowMapInfo ¶
ShadowMapInfo reports one shadow map's state after the most recent Renderer.Prepare or Renderer.PrepareScene call. Resolution is the map width and height in texels. Extent and TexelSize are populated for an active directional map and are zero for spot and point maps.
type Terrain ¶
type Terrain struct {
// Node is the scene3d node the terrain is attached to; its LocalBounds hold the heightmap bounds.
Node *scene3d.Node
// Object is the ID of the scene object that declared ObjectDoc.Terrain.
Object string
// Path is the project-relative *.terrain.yaml path from ObjectDoc.Terrain.
Path string
// Doc is the parsed terrain definition.
Doc *world3d.TerrainDoc
// Heightmap is the runtime heightmap shared with LOD, foliage, and heightfield colliders.
Heightmap *world3d.Heightmap
// LOD partitions Heightmap into crack-free stitched, distance-selected chunks.
LOD *world3d.TerrainLOD
// Material is the validated splat-blended PBR terrain material.
Material render3d.TerrainMaterial
// Foliage holds the scattered foliage layers declared in Doc.Foliage.
Foliage []*TerrainFoliage
// contains filtered or unexported fields
}
Terrain is a built 3D terrain object in a Built scene: its scene3d node, parsed TerrainDoc, runtime Heightmap, chunked TerrainLOD, validated TerrainMaterial, and any scattered foliage layers.
func (*Terrain) InvalidateAll ¶
func (t *Terrain) InvalidateAll()
InvalidateAll recomputes every terrain chunk's bounds and marks all cached chunk meshes for rebuild on the next Renderer.Prepare / PrepareScene call, refreshing Node.LocalBounds from Heightmap.
func (*Terrain) InvalidateWorldRect ¶
InvalidateWorldRect recomputes bounds and marks cached chunk meshes for rebuild for every chunk whose grid footprint (including a 1-cell border for shared vertex normals) overlaps the heightmap-local XZ rectangle [minX, maxX] x [minZ, maxZ].
func (*Terrain) MarkMaterialDirty ¶
func (t *Terrain) MarkMaterialDirty()
MarkMaterialDirty marks t.Material's scalar uniform parameters (height blend contrast, triplanar settings, layer factors/UV scales) for GPU upload on the next Renderer.Prepare / PrepareScene call.
func (*Terrain) RebuildFoliage ¶
RebuildFoliage re-scatters every foliage layer on t from t.Heightmap (for example after editing heights or foliage density maps in place).
func (*Terrain) SetSplatMaps ¶
SetSplatMaps replaces t.Material's RGBA splat map images in place and marks them for GPU upload on the next Renderer.Prepare / PrepareScene call without recreating the renderer or rebuilding the scene.
type TerrainAsset ¶
type TerrainAsset struct {
Doc *world3d.TerrainDoc
Heightmap *world3d.Heightmap
Material render3d.TerrainMaterial
}
TerrainAsset holds a loaded *.terrain.yaml definition, its decoded heightmap (including any splat and foliage density maps), and its validated render3d.TerrainMaterial.
type TerrainFoliage ¶
type TerrainFoliage struct {
// Name is the foliage layer's name from TerrainDoc.Foliage.
Name string
// Doc is the source foliage layer declaration.
Doc world3d.FoliageLayerDoc
// Field holds the deterministically scattered instances across the terrain heightmap.
Field *world3d.FoliageField
// Parts are the mesh and material parts drawn for every visible instance.
Parts []FoliagePart
// Quality overrides the foliage culling quality profile; the zero value uses world3d.DefaultQualityProfile(world3d.QualityHigh).
Quality world3d.QualityProfile
// contains filtered or unexported fields
}
TerrainFoliage holds one scattered foliage layer on a Terrain, pairing its world3d.FoliageField with the mesh parts instanced by Renderer.
type TerrainResolver ¶
type TerrainResolver interface {
TerrainAsset(path string) (*TerrainAsset, error)
}
TerrainResolver loads the 3D terrain files objects name in sceneformat.ObjectDoc.Terrain. path is the slash-separated path from the project root that the scene file writes, such as "worlds/island.terrain.yaml".
type Texture ¶
type Texture struct {
// Name says where the image came from, such as "models/crate.glb image 0" or "textures/stone.png", for debug labels.
Name string
// Image is the decoded PNG or JPEG image: sRGB color for a base color or emissive texture, linear data for a metallic-roughness, normal or occlusion texture. Nil when KTX2 is set.
Image image.Image
// KTX2 holds the encoded KTX2 container when the texture comes from a .ktx2 material texture or a glTF KHR_texture_basisu image, for render3d.LoadKTX2 at upload. Nil for PNG and JPEG textures.
KTX2 *KTX2Data
// Sampler is how the image is filtered and wrapped: the glTF texture's sampler, or the material file's sampler (with a KTX2 file's game.filter applied when present).
Sampler render3d.SamplerOptions
// Mipmaps reports whether the texture carries or needs a mip chain.
Mipmaps bool
// contains filtered or unexported fields
}
Texture is an image or KTX2 container a Material samples. Build returns one *Texture per image and sampler, which every material that uses them shares, so a renderer uploads each once.