Documentation
¶
Overview ¶
Package gltf implements a pure-Go glTF 2.0 (.gltf) and binary GLB (.glb) asset loader using only the Go standard library and pkg/math3d.
Supported features:
- Auto-detection of JSON .gltf and binary .glb containers via Load and LoadFS
- Embedded base64 data URIs, GLB BIN chunks, and external fs.FS buffers/images
- Full typed accessor decoding (SCALAR, VEC2, VEC3, VEC4, MAT4, indices, joints, weights) with all component types, normalized integer unpacking, interleaved byteStride buffers, zero-initialized accessors, and sparse accessors
- Scene graph and node hierarchy with matrix/TRS transforms, cycle detection, and world matrix computation
- PBR metallic-roughness materials, textures, samplers, PNG/JPEG image decoding, KHR_materials_unlit, KHR_texture_transform, and KHR_materials_variants
- Mesh primitives with bounds, morph targets with CPU position/normal blending, skins with inverse bind matrices, and STEP/LINEAR/CUBICSPLINE keyframe animations
- Compressed geometry: KHR_draco_mesh_compression primitives (Draco bitstream 2.2, sequential and edgebreaker connectivity), EXT_meshopt_compression and KHR_meshopt_compression buffer views (attribute, triangle and index codecs with the octahedral, quaternion, exponential and color filters, never fetching fallback buffers), and KHR_mesh_quantization; every reader returns the decoded data
Index ¶
- Constants
- func EvaluateMorphNormals(prim Primitive, weights []float32, out []math3d.Vec3) []math3d.Vec3
- func EvaluateMorphPositions(prim Primitive, weights []float32, out []math3d.Vec3) []math3d.Vec3
- func EvaluateMorphTangents(prim Primitive, weights []float32, out []math3d.Vec4) []math3d.Vec4
- func ParseLODNodeName(name string) (baseName string, level int, ok bool)
- func PrimitiveLightmapUVs(prim Primitive) (uvs []math3d.Vec2, usedFallback bool)
- func ResolveWeights(doc *Document, nodeIndex int) []float32
- func ResolveWeightsInto(doc *Document, nodeIndex int, dst []float32) []float32
- func SampleMorphWeights(anim Animation, nodeIndex int, t float32, dst []float32) ([]float32, bool)
- type Accessor
- type AccessorSparse
- type AccessorSparseIndices
- type AccessorSparseValues
- type AccessorType
- type AlphaMode
- type Animation
- type AnimationChannel
- type Asset
- type Buffer
- type BufferResolver
- type BufferView
- type Camera
- type CameraType
- type ChannelSample
- type Clearcoat
- type ColliderKind
- type ComponentType
- type Document
- func (d *Document) ColliderNodes() ([]NodeCollider, error)
- func (d *Document) ComputeWorldMatrices() error
- func (d *Document) DecodeImage(index int) (image.Image, error)
- func (d *Document) DrawableNodes() []int
- func (d *Document) ImageBytes(index int) ([]byte, error)
- func (d *Document) LightmapTexCoords(prim Primitive, ref *LightmapRef) (uvs []math3d.Vec2, usedFallback bool, err error)
- func (d *Document) MaterialForPrimitive(prim Primitive, variantIndex int) int
- func (d *Document) MaterialForVariant(prim Primitive, variantName string) int
- func (d *Document) MaterialLightmap(materialIndex int) (*LightmapRef, error)
- func (d *Document) MeshMaterials(meshIndex, variantIndex int) ([]int, error)
- func (d *Document) PrimitiveTexCoords(prim Primitive, texCoord int) ([]math3d.Vec2, error)
- func (d *Document) ReadIndices(accessorIndex int) ([]uint32, error)
- func (d *Document) ReadJoints(accessorIndex int) ([][4]uint16, error)
- func (d *Document) ReadMat4(accessorIndex int) ([]math3d.Mat4, error)
- func (d *Document) ReadScalar(accessorIndex int) ([]float32, error)
- func (d *Document) ReadVec2(accessorIndex int) ([]math3d.Vec2, error)
- func (d *Document) ReadVec3(accessorIndex int) ([]math3d.Vec3, error)
- func (d *Document) ReadVec4(accessorIndex int) ([]math3d.Vec4, error)
- func (d *Document) ReadWeights(accessorIndex int) ([]math3d.Vec4, error)
- func (d *Document) ResolveVariantMaterials(variantIndex int) [][]int
- func (d *Document) SceneColliderNodes(sceneIdx int) ([]NodeCollider, error)
- func (d *Document) SceneDrawableNodes(sceneIdx int) []int
- func (d *Document) TransformTexCoords(prim Primitive, ref *TextureRef, out []math3d.Vec2) ([]math3d.Vec2, error)
- func (d *Document) VariantIndex(name string) int
- type FilterMode
- type Image
- type Interpolation
- type LightmapRef
- type Material
- type MaterialVariant
- type Mesh
- type MorphResult
- type MorphTarget
- type Node
- type NodeCollider
- type Primitive
- type PrimitiveMode
- type Sampler
- type Scene
- type Skin
- type TargetPath
- type Texture
- type TextureRef
- type TextureTransform
- type Transmission
- type WrapMode
Examples ¶
Constants ¶
const ( // ExtMOZLightmap is the Mozilla Hubs / Blender glTF material extension name for baked lightmaps. ExtMOZLightmap = "MOZ_lightmap" // ExtLightmap is the generic EXT_lightmap glTF material extension name for baked lightmaps. ExtLightmap = "EXT_lightmap" )
Variables ¶
This section is empty.
Functions ¶
func EvaluateMorphNormals ¶
EvaluateMorphNormals computes the morphed and re-normalized vertex normals for prim given morph target weights. If out has sufficient capacity it is reused without allocation.
func EvaluateMorphPositions ¶
EvaluateMorphPositions computes the morphed vertex positions for prim given morph target weights:
out[i] = prim.Positions[i] + sum_k(weights[k] * prim.Targets[k].Positions[i])
If out has sufficient capacity it is reused without allocation; otherwise a new slice is allocated and returned.
func EvaluateMorphTangents ¶
EvaluateMorphTangents computes the morphed vertex tangents for prim given morph target weights:
out[i].xyz = normalize(prim.Tangents[i].xyz + sum_k(weights[k] * prim.Targets[k].Tangents[i])) out[i].w = prim.Tangents[i].w
Per glTF 2.0, morph target TANGENT deltas displace only the XYZ components and leave the W handedness sign unchanged. If out has sufficient capacity it is reused without allocation; otherwise a new slice is allocated and returned.
func ParseLODNodeName ¶
ParseLODNodeName inspects a glTF node or mesh name for the case-insensitive _LOD<N> suffix convention (such as "Tree_LOD0", "Tree_LOD1", "Tree_lod2"), tolerating Blender's optional trailing ".001" duplicate numbering.
When name carries a recognized suffix with a non-empty base name and a non-negative integer level, ParseLODNodeName returns (baseName, level, true). Otherwise it returns ("", 0, false).
func PrimitiveLightmapUVs ¶
PrimitiveLightmapUVs returns the lightmap UV channel for prim: prim.TexCoords1 (TEXCOORD_1) when present, falling back to prim.TexCoords0 (TEXCOORD_0) when TEXCOORD_1 is absent. The second return value reports whether the fallback path was used.
func ResolveWeights ¶
ResolveWeights returns the effective morph target weights for doc.Nodes[nodeIndex] following glTF 2.0 precedence: non-empty node.Weights override mesh.Weights, and missing weights default to zeros matching the mesh's morph target count. Returns nil when doc is nil, nodeIndex is out of range, the node has no mesh, or the mesh has no morph targets.
func ResolveWeightsInto ¶
ResolveWeightsInto resolves the effective morph target weights for doc.Nodes[nodeIndex] into dst following glTF 2.0 precedence (node.Weights overrides mesh.Weights, else zeros matching the target count). If dst has sufficient capacity it is reused without allocation.
func SampleMorphWeights ¶
SampleMorphWeights evaluates the PathWeights channel targeting nodeIndex in anim at time t (in seconds) into dst and reports whether a matching channel was found and sampled.
It supports InterpolationStep, InterpolationLinear, and InterpolationCubicSpline (unpacking 3*N values per keyframe in glTF order: in-tangent, value, out-tangent), clamping outside the channel's keyframe time range. If dst has sufficient capacity it is reused without allocation.
Types ¶
type Accessor ¶
type Accessor struct {
Name string
BufferView int
ByteOffset int
ComponentType ComponentType
Normalized bool
Count int
Type AccessorType
Min []float32
Max []float32
Sparse *AccessorSparse
Extras json.RawMessage
// contains filtered or unexported fields
}
Accessor defines typed view metadata over a BufferView (or zero-initialized storage). BufferView is -1 when omitted (zero-initialized per glTF 2.0 spec).
type AccessorSparse ¶
type AccessorSparse struct {
Count int
Indices AccessorSparseIndices
Values AccessorSparseValues
}
AccessorSparse describes sparse overrides applied on top of a base accessor.
type AccessorSparseIndices ¶
type AccessorSparseIndices struct {
BufferView int
ByteOffset int
ComponentType ComponentType
}
AccessorSparseIndices describes the index buffer of a sparse accessor.
type AccessorSparseValues ¶
AccessorSparseValues describes the replacement values buffer of a sparse accessor.
type AccessorType ¶
type AccessorType string
AccessorType identifies the element structure of an accessor.
const ( AccessorScalar AccessorType = "SCALAR" AccessorVec2 AccessorType = "VEC2" AccessorVec3 AccessorType = "VEC3" AccessorVec4 AccessorType = "VEC4" AccessorMat2 AccessorType = "MAT2" AccessorMat3 AccessorType = "MAT3" AccessorMat4 AccessorType = "MAT4" )
func (AccessorType) Components ¶
func (t AccessorType) Components() int
Components returns the number of scalar components in an element of type t, or 0 if t is unknown.
type AlphaMode ¶
type AlphaMode string
AlphaMode controls how a material's alpha channel is interpreted.
type Animation ¶
type Animation struct {
Name string
Duration float32
Channels []AnimationChannel
Extras json.RawMessage
}
Animation represents a glTF 2.0 keyframe animation clip.
Example ¶
An Animation samples its channels at a time, and Apply writes the sampled values into the document's nodes.
package main
import (
"encoding/base64"
"encoding/binary"
"fmt"
"math"
"github.com/nsgo-dev/game/pkg/gltf"
)
// floats packs little-endian float32 values as a glTF buffer stores them.
func floats(vs ...float32) []byte {
b := make([]byte, 0, 4*len(vs))
for _, v := range vs {
b = binary.LittleEndian.AppendUint32(b, math.Float32bits(v))
}
return b
}
// sceneJSON is a small glTF document: a triangle mesh on a child node, and an animation that slides the parent node along +X over one second.
func sceneJSON() []byte {
var bin []byte
bin = append(bin, floats(0, 0, 0, 1, 0, 0, 0, 1, 0)...)
bin = append(bin, floats(0, 1)...)
bin = append(bin, floats(0, 0, 0, 4, 0, 0)...)
uri := "data:application/octet-stream;base64," + base64.StdEncoding.EncodeToString(bin)
return fmt.Appendf(nil, `{
"asset": {"version": "2.0"},
"scene": 0,
"scenes": [{"nodes": [0]}],
"nodes": [
{"name": "cart", "translation": [10, 0, 0], "children": [1]},
{"name": "sail", "translation": [0, 2, 0], "mesh": 0}
],
"meshes": [{"primitives": [{"attributes": {"POSITION": 0}}]}],
"buffers": [{"byteLength": %d, "uri": %q}],
"bufferViews": [
{"buffer": 0, "byteOffset": 0, "byteLength": 36},
{"buffer": 0, "byteOffset": 36, "byteLength": 8},
{"buffer": 0, "byteOffset": 44, "byteLength": 24}
],
"accessors": [
{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 0], "max": [1, 1, 0]},
{"bufferView": 1, "componentType": 5126, "count": 2, "type": "SCALAR", "min": [0], "max": [1]},
{"bufferView": 2, "componentType": 5126, "count": 2, "type": "VEC3"}
],
"animations": [{
"name": "roll",
"samplers": [{"input": 1, "output": 2}],
"channels": [{"sampler": 0, "target": {"node": 0, "path": "translation"}}]
}]
}`, len(bin), uri)
}
func main() {
doc, err := gltf.Load(sceneJSON(), nil)
if err != nil {
fmt.Println(err)
return
}
anim := &doc.Animations[0]
for _, s := range anim.Sample(0.25) {
fmt.Println(s.Node, s.Path, s.Translation)
}
anim.Apply(doc, 0.5)
fmt.Println(doc.Nodes[0].Translation)
}
Output: 0 translation {1 0 0} {2 0 0}
func (*Animation) Apply ¶
Apply evaluates the animation at time t and writes sampled translation, rotation, scale, and morph target weights directly onto matching nodes in doc. Call doc.ComputeWorldMatrices afterwards to propagate updated transforms.
func (*Animation) Sample ¶
func (a *Animation) Sample(t float32) []ChannelSample
Sample evaluates all channels of the animation at time t (in seconds) and returns one ChannelSample per channel with a valid TargetNode (>= 0).
type AnimationChannel ¶
type AnimationChannel struct {
TargetNode int
Path TargetPath
Interpolation Interpolation
Times []float32
Values []float32
Stride int
}
AnimationChannel holds a single decoded keyframe track targeting one node property. For InterpolationCubicSpline, Values stores 3*Stride floats per keyframe in glTF order: [inTangent, value, outTangent].
func (*AnimationChannel) Sample ¶
func (ch *AnimationChannel) Sample(t float32) ChannelSample
Sample evaluates this channel at time t (in seconds), clamping to the first and last keyframes outside the channel's time range.
type Asset ¶
type Asset struct {
Version string
MinVersion string
Generator string
Copyright string
Extras json.RawMessage
}
Asset holds metadata about the glTF asset.
type Buffer ¶
Buffer holds resolved binary buffer bytes. For a buffer that meshopt-compressed bufferViews decode into (an EXT_meshopt_compression or KHR_meshopt_compression fallback or placeholder buffer), Data holds the decompressed views and the buffer's own URI is never fetched.
type BufferResolver ¶
BufferResolver resolves relative external URIs (for .bin buffers and images) to their raw bytes.
type BufferView ¶
type BufferView struct {
Name string
Buffer int
ByteOffset int
ByteLength int
ByteStride int
Target int
Extras json.RawMessage
// Extensions keeps unsupported optional extension payloads by name.
Extensions map[string]json.RawMessage
}
BufferView defines a slice of a Buffer with an optional interleaved ByteStride.
type Camera ¶
type Camera struct {
Name string
Type CameraType
AspectRatio float32 // perspective only; 0 means unspecified
YFOV float32 // perspective vertical field of view in radians
XMag float32 // orthographic horizontal magnification
YMag float32 // orthographic vertical magnification
ZNear float32
ZFar float32 // perspective: 0 means infinite far plane
Extras json.RawMessage
}
Camera describes a glTF 2.0 perspective or orthographic camera.
type CameraType ¶
type CameraType string
CameraType identifies the projection model of a glTF camera.
const ( CameraPerspective CameraType = "perspective" CameraOrthographic CameraType = "orthographic" )
type ChannelSample ¶
type ChannelSample struct {
Node int
Path TargetPath
Translation math3d.Vec3
Rotation math3d.Quat
Scale math3d.Vec3
Weights []float32
}
ChannelSample holds the evaluated value of one animation channel at time t.
type Clearcoat ¶
type Clearcoat struct {
// Factor is clearcoatFactor in [0, 1] (default 0). Multiplied by Texture's R channel when present.
Factor float32
// Texture is clearcoatTexture (optional, linear; R channel modulates Factor).
Texture *TextureRef
// RoughnessFactor is clearcoatRoughnessFactor in [0, 1] (default 0). Multiplied by RoughnessTexture's G channel when present.
RoughnessFactor float32
// RoughnessTexture is clearcoatRoughnessTexture (optional, linear; G channel modulates RoughnessFactor).
RoughnessTexture *TextureRef
// NormalTexture is clearcoatNormalTexture (optional, tangent-space normal map; Scale defaults to 1).
NormalTexture *TextureRef
}
Clearcoat represents the Khronos KHR_materials_clearcoat material extension, describing a dielectric coating layer (IOR 1.5, F0 = 0.04) on top of the base PBR metallic-roughness material.
type ColliderKind ¶
type ColliderKind string
ColliderKind identifies the physics collision shape declared on a glTF node through naming conventions or extras.collider metadata.
const ( // ColliderNone indicates that a node carries no collider annotation. ColliderNone ColliderKind = "" // ColliderTriMesh builds a static triangle-mesh collider from the node's mesh. ColliderTriMesh ColliderKind = "trimesh" // ColliderBox builds a box collider from explicit extras dimensions or the // node mesh's local bounds. ColliderBox ColliderKind = "box" // ColliderSphere builds a sphere collider from explicit extras dimensions or // the node mesh's local bounds. ColliderSphere ColliderKind = "sphere" // ColliderCapsule builds a capsule collider from explicit extras dimensions // or the node mesh's local bounds. ColliderCapsule ColliderKind = "capsule" // ColliderConvex marks a convex hull collider (falling back to a triangle // mesh collider until native convex hulls are available). ColliderConvex ColliderKind = "convex" )
type ComponentType ¶
type ComponentType int
ComponentType identifies the binary storage type of an accessor component.
const ( ComponentByte ComponentType = 5120 // int8 ComponentUnsignedByte ComponentType = 5121 // uint8 ComponentShort ComponentType = 5122 // int16 ComponentUnsignedShort ComponentType = 5123 // uint16 ComponentUnsignedInt ComponentType = 5125 // uint32 ComponentFloat ComponentType = 5126 // float32 )
func (ComponentType) ByteSize ¶
func (c ComponentType) ByteSize() int
ByteSize returns the size in bytes of a single component, or 0 if unknown.
type Document ¶
type Document struct {
Asset Asset
ExtensionsUsed []string
ExtensionsRequired []string
Scene int // default scene index, or -1 if unspecified
Scenes []Scene
Nodes []Node
Cameras []Camera
Buffers []Buffer
BufferViews []BufferView
Accessors []Accessor
Samplers []Sampler
Images []Image
Textures []Texture
Materials []Material
Variants []MaterialVariant
Meshes []Mesh
Skins []Skin
Animations []Animation
Extras json.RawMessage
// contains filtered or unexported fields
}
Document is a parsed glTF 2.0 / GLB asset with resolved buffers, decoded meshes, materials, scene hierarchy, skins, and animations.
func Load ¶
func Load(data []byte, resolver BufferResolver) (*Document, error)
Load parses a glTF 2.0 JSON (.gltf) or binary GLB (.glb) document from data. External buffer/image URIs are resolved via resolver (which may be nil when all resources are embedded via GLB BIN chunks or base64 data URIs).
Its errors are *loaderr.Error values that give the field of the problem, the line in the JSON (in a GLB, the line in its JSON chunk) and how to fix it; a caller that read data from a file names it with loaderr.WithFile, as LoadFS does.
Example ¶
Load parses a .gltf or .glb document and decodes its meshes' vertex data.
package main
import (
"encoding/base64"
"encoding/binary"
"fmt"
"math"
"github.com/nsgo-dev/game/pkg/gltf"
)
// floats packs little-endian float32 values as a glTF buffer stores them.
func floats(vs ...float32) []byte {
b := make([]byte, 0, 4*len(vs))
for _, v := range vs {
b = binary.LittleEndian.AppendUint32(b, math.Float32bits(v))
}
return b
}
// sceneJSON is a small glTF document: a triangle mesh on a child node, and an animation that slides the parent node along +X over one second.
func sceneJSON() []byte {
var bin []byte
bin = append(bin, floats(0, 0, 0, 1, 0, 0, 0, 1, 0)...)
bin = append(bin, floats(0, 1)...)
bin = append(bin, floats(0, 0, 0, 4, 0, 0)...)
uri := "data:application/octet-stream;base64," + base64.StdEncoding.EncodeToString(bin)
return fmt.Appendf(nil, `{
"asset": {"version": "2.0"},
"scene": 0,
"scenes": [{"nodes": [0]}],
"nodes": [
{"name": "cart", "translation": [10, 0, 0], "children": [1]},
{"name": "sail", "translation": [0, 2, 0], "mesh": 0}
],
"meshes": [{"primitives": [{"attributes": {"POSITION": 0}}]}],
"buffers": [{"byteLength": %d, "uri": %q}],
"bufferViews": [
{"buffer": 0, "byteOffset": 0, "byteLength": 36},
{"buffer": 0, "byteOffset": 36, "byteLength": 8},
{"buffer": 0, "byteOffset": 44, "byteLength": 24}
],
"accessors": [
{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 0], "max": [1, 1, 0]},
{"bufferView": 1, "componentType": 5126, "count": 2, "type": "SCALAR", "min": [0], "max": [1]},
{"bufferView": 2, "componentType": 5126, "count": 2, "type": "VEC3"}
],
"animations": [{
"name": "roll",
"samplers": [{"input": 1, "output": 2}],
"channels": [{"sampler": 0, "target": {"node": 0, "path": "translation"}}]
}]
}`, len(bin), uri)
}
func main() {
doc, err := gltf.Load(sceneJSON(), nil)
if err != nil {
fmt.Println(err)
return
}
prim := doc.Meshes[0].Primitives[0]
fmt.Println(doc.Nodes[1].Name, len(prim.Positions), prim.Positions[1])
fmt.Println(prim.Bounds.Min, prim.Bounds.Max)
}
Output: sail 3 {1 0 0} {0 0 0} {1 1 0}
func LoadFS ¶
LoadFS loads a .gltf or .glb file at path from fsys, automatically resolving relative external .bin buffers and image URIs against path's directory in fsys. Its errors are *loaderr.Error values that name path.
func (*Document) ColliderNodes ¶
func (d *Document) ColliderNodes() ([]NodeCollider, error)
ColliderNodes returns all collider annotations found on nodes in the document's default scene (or all nodes when no scenes are defined), in deterministic scene traversal order.
func (*Document) ComputeWorldMatrices ¶
ComputeWorldMatrices validates the node hierarchy (rejecting out-of-range child indices, multiple parents, and cycles), updates LocalMatrix from TRS for non-matrix nodes, and computes exact parent-to-child WorldMatrix values for every node in the document.
Example ¶
ComputeWorldMatrices composes each node's transform with its parents', so a child placed relative to its parent gets its place in the scene.
package main
import (
"encoding/base64"
"encoding/binary"
"fmt"
"math"
"github.com/nsgo-dev/game/pkg/gltf"
)
// floats packs little-endian float32 values as a glTF buffer stores them.
func floats(vs ...float32) []byte {
b := make([]byte, 0, 4*len(vs))
for _, v := range vs {
b = binary.LittleEndian.AppendUint32(b, math.Float32bits(v))
}
return b
}
// sceneJSON is a small glTF document: a triangle mesh on a child node, and an animation that slides the parent node along +X over one second.
func sceneJSON() []byte {
var bin []byte
bin = append(bin, floats(0, 0, 0, 1, 0, 0, 0, 1, 0)...)
bin = append(bin, floats(0, 1)...)
bin = append(bin, floats(0, 0, 0, 4, 0, 0)...)
uri := "data:application/octet-stream;base64," + base64.StdEncoding.EncodeToString(bin)
return fmt.Appendf(nil, `{
"asset": {"version": "2.0"},
"scene": 0,
"scenes": [{"nodes": [0]}],
"nodes": [
{"name": "cart", "translation": [10, 0, 0], "children": [1]},
{"name": "sail", "translation": [0, 2, 0], "mesh": 0}
],
"meshes": [{"primitives": [{"attributes": {"POSITION": 0}}]}],
"buffers": [{"byteLength": %d, "uri": %q}],
"bufferViews": [
{"buffer": 0, "byteOffset": 0, "byteLength": 36},
{"buffer": 0, "byteOffset": 36, "byteLength": 8},
{"buffer": 0, "byteOffset": 44, "byteLength": 24}
],
"accessors": [
{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 0], "max": [1, 1, 0]},
{"bufferView": 1, "componentType": 5126, "count": 2, "type": "SCALAR", "min": [0], "max": [1]},
{"bufferView": 2, "componentType": 5126, "count": 2, "type": "VEC3"}
],
"animations": [{
"name": "roll",
"samplers": [{"input": 1, "output": 2}],
"channels": [{"sampler": 0, "target": {"node": 0, "path": "translation"}}]
}]
}`, len(bin), uri)
}
func main() {
doc, err := gltf.Load(sceneJSON(), nil)
if err != nil {
fmt.Println(err)
return
}
if err := doc.ComputeWorldMatrices(); err != nil {
fmt.Println(err)
return
}
m := doc.Nodes[1].WorldMatrix
fmt.Println(m[12], m[13], m[14])
}
Output: 10 2 0
func (*Document) DecodeImage ¶
DecodeImage decodes the PNG or JPEG image at index from its bufferView, data URI, or external URI (resolved via the loader's BufferResolver / fs.FS).
func (*Document) DrawableNodes ¶
DrawableNodes returns the deterministic slice of node indices in the document's default scene (or all nodes when no scenes are defined) that reference a valid mesh and should be drawn visually, excluding collider-only nodes such as *-colonly and extras.collider.draw == false.
func (*Document) ImageBytes ¶
ImageBytes returns the raw encoded bytes (e.g. PNG or JPEG) for image index.
func (*Document) LightmapTexCoords ¶
func (d *Document) LightmapTexCoords(prim Primitive, ref *LightmapRef) (uvs []math3d.Vec2, usedFallback bool, err error)
LightmapTexCoords resolves the baked lightmap UVs for prim using ref (or TEXCOORD_1 when ref is nil). When TEXCOORD_1 is requested but absent on prim, it falls back to prim.TexCoords0 and reports usedFallback = true. A primitive with neither TEXCOORD_1 nor TEXCOORD_0 is an error, since every vertex would sample the same lightmap texel.
func (*Document) MaterialForPrimitive ¶
MaterialForPrimitive returns the material index to use for prim under the specified KHR_materials_variants variantIndex. If variantIndex is negative, out of range, or unmapped on prim, it falls back to prim.Material.
func (*Document) MaterialForVariant ¶
MaterialForVariant returns the material index to use for prim under the named KHR_materials_variants variant. If name does not match any variant or is unmapped on prim, it falls back to prim.Material.
Example ¶
KHR_materials_variants maps named variants to per-primitive materials and falls back to Primitive.Material when a variant is unmapped.
package main
import (
"encoding/base64"
"encoding/binary"
"fmt"
"math"
"github.com/nsgo-dev/game/pkg/gltf"
)
// floats packs little-endian float32 values as a glTF buffer stores them.
func floats(vs ...float32) []byte {
b := make([]byte, 0, 4*len(vs))
for _, v := range vs {
b = binary.LittleEndian.AppendUint32(b, math.Float32bits(v))
}
return b
}
func main() {
posURI := "data:application/octet-stream;base64," + base64.StdEncoding.EncodeToString(floats(0, 0, 0, 1, 0, 0, 0, 1, 0))
raw := fmt.Sprintf(`{
"asset": {"version": "2.0"},
"extensionsUsed": ["KHR_materials_variants"],
"extensions": {"KHR_materials_variants": {"variants": [{"name": "Day"}, {"name": "Night"}]}},
"buffers": [{"byteLength": 36, "uri": %q}],
"bufferViews": [{"buffer": 0, "byteLength": 36}],
"accessors": [{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3"}],
"materials": [{"name": "Default"}, {"name": "NightMat"}],
"meshes": [{"primitives": [{
"attributes": {"POSITION": 0},
"material": 0,
"extensions": {"KHR_materials_variants": {"mappings": [{"material": 1, "variants": [1]}]}}
}]}]
}`, posURI)
doc, err := gltf.Load([]byte(raw), nil)
if err != nil {
fmt.Println(err)
return
}
prim := doc.Meshes[0].Primitives[0]
fmt.Println(doc.Materials[doc.MaterialForVariant(prim, "Day")].Name)
fmt.Println(doc.Materials[doc.MaterialForVariant(prim, "Night")].Name)
}
Output: Default NightMat
func (*Document) MaterialLightmap ¶
func (d *Document) MaterialLightmap(materialIndex int) (*LightmapRef, error)
MaterialLightmap extracts baked lightmap metadata from d.Materials[materialIndex], checking MOZ_lightmap, EXT_lightmap, and extras.lightmap in that order. It returns (nil, nil) when the material carries no lightmap metadata.
func (*Document) MeshMaterials ¶
MeshMaterials returns the resolved material index for each primitive of d.Meshes[meshIndex] under variantIndex, falling back to each primitive's default Material when variantIndex is negative, out of range, or unmapped.
func (*Document) PrimitiveTexCoords ¶
PrimitiveTexCoords returns the raw texture coordinates for UV set texCoord (TEXCOORD_<texCoord>) on prim. Sets 0 and 1 return prim.TexCoords0 and prim.TexCoords1 directly when loaded; higher sets (TEXCOORD_2, ...) are decoded on demand from prim.Attributes.
func (*Document) ReadIndices ¶
ReadIndices decodes a SCALAR index accessor (UNSIGNED_BYTE, UNSIGNED_SHORT, or UNSIGNED_INT) as []uint32.
func (*Document) ReadJoints ¶
ReadJoints decodes a VEC4 JOINTS_n accessor (UNSIGNED_BYTE or UNSIGNED_SHORT) as [][4]uint16.
func (*Document) ReadScalar ¶
ReadScalar decodes a SCALAR accessor as []float32, supporting all glTF component types, normalized unpacking, byteStride, and sparse accessors.
func (*Document) ReadWeights ¶
ReadWeights decodes a VEC4 WEIGHTS_n accessor (FLOAT, normalized UNSIGNED_BYTE, or normalized UNSIGNED_SHORT) as []math3d.Vec4.
func (*Document) ResolveVariantMaterials ¶
ResolveVariantMaterials returns resolved material indices [mesh][primitive] for every mesh in d under variantIndex without modifying Primitive.Material, so switching variants or reverting to defaults (variantIndex < 0) is repeatable.
func (*Document) SceneColliderNodes ¶
func (d *Document) SceneColliderNodes(sceneIdx int) ([]NodeCollider, error)
SceneColliderNodes returns all collider annotations found on nodes in d.Scenes[sceneIdx] (or all nodes when sceneIdx < 0), in deterministic scene traversal order.
func (*Document) SceneDrawableNodes ¶
SceneDrawableNodes returns the deterministic slice of node indices in d.Scenes[sceneIdx] (or all nodes when sceneIdx < 0) that reference a valid mesh and should be drawn visually, excluding collider-only nodes.
func (*Document) TransformTexCoords ¶
func (d *Document) TransformTexCoords(prim Primitive, ref *TextureRef, out []math3d.Vec2) ([]math3d.Vec2, error)
TransformTexCoords evaluates the final UV coordinates for ref on prim, selecting ref.EffectiveTexCoord() and applying ref.Transform when present. If out has sufficient capacity it is reused without allocation; otherwise a new slice is allocated and returned.
func (*Document) VariantIndex ¶
VariantIndex returns the index of the first KHR_materials_variants entry whose Name equals name, or -1 when no variant matches.
type FilterMode ¶
type FilterMode int
FilterMode defines glTF texture minification/magnification filtering modes.
const ( FilterNearest FilterMode = 9728 FilterLinear FilterMode = 9729 FilterNearestMipmapNearest FilterMode = 9984 FilterLinearMipmapNearest FilterMode = 9985 FilterNearestMipmapLinear FilterMode = 9986 FilterLinearMipmapLinear FilterMode = 9987 )
type Image ¶
Image represents an embedded or external texture image. BufferView is -1 when the image is referenced via URI.
type Interpolation ¶
type Interpolation string
Interpolation defines the keyframe interpolation mode for an animation channel.
const ( InterpolationLinear Interpolation = "LINEAR" InterpolationStep Interpolation = "STEP" InterpolationCubicSpline Interpolation = "CUBICSPLINE" )
type LightmapRef ¶
type LightmapRef struct {
// Texture points to the lightmap texture in Document.Textures and its UV channel (defaulting to 1 for TEXCOORD_1). A KHR_texture_transform on the lightmap is folded into UVScale and UVOffset, so Texture.Transform carries only its texCoord override (if any) and passing Texture to [Document.TransformTexCoords] never applies the scale and offset a second time.
Texture TextureRef
// Intensity scales the decoded lightmap irradiance (defaults to 1).
Intensity float32
// Encoding is an optional encoding hint such as "linear", "srgb", "rgbm", or "rgbd", normalized to lower case. Empty when unspecified.
Encoding string
// RGBMMaxRange is an optional peak HDR scale hint for RGBM lightmaps (0 when unspecified, letting the renderer apply its default range).
RGBMMaxRange float32
// UVScale scales lightmap UVs when mapping into a shared lightmap atlas (defaults to [1, 1]). UVScale and UVOffset are the authoritative atlas transform: pass them to render3d's LightmapMaterial.SetUVTransform. They come from, in increasing precedence, the lightmap's KHR_texture_transform (scale and offset; a non-zero rotation is refused), a scaleOffset [sx, sy, ox, oy] field, and separate uvScale and uvOffset fields.
UVScale [2]float32
// UVOffset offsets scaled lightmap UVs when mapping into a shared lightmap atlas (defaults to [0, 0]). See UVScale for precedence.
UVOffset [2]float32
}
LightmapRef describes a baked lightmap binding extracted from a glTF material's MOZ_lightmap extension, EXT_lightmap extension, or extras.lightmap metadata.
func DefaultLightmapRef ¶
func DefaultLightmapRef(textureIndex int) LightmapRef
DefaultLightmapRef returns a LightmapRef referencing textureIndex on TEXCOORD_1 with unit intensity and identity atlas UV transform.
type Material ¶
type Material struct {
Name string
BaseColorFactor math3d.Vec4
BaseColorTexture *TextureRef
MetallicFactor float32
RoughnessFactor float32
MetallicRoughnessTexture *TextureRef
NormalTexture *TextureRef
OcclusionTexture *TextureRef
EmissiveFactor math3d.Vec3
EmissiveTexture *TextureRef
AlphaMode AlphaMode
AlphaCutoff float32
DoubleSided bool
Unlit bool // KHR_materials_unlit
Clearcoat *Clearcoat // KHR_materials_clearcoat
Transmission *Transmission // KHR_materials_transmission
Extras json.RawMessage
// Extensions keeps unsupported optional extension payloads by name.
Extensions map[string]json.RawMessage
}
Material defines a glTF 2.0 PBR metallic-roughness material.
func (Material) EmissiveStrength ¶
EmissiveStrength returns the KHR_materials_emissive_strength multiplier for m, defaulting to 1.0 when the extension or its emissiveStrength property is omitted. A payload that is not an object, or an emissiveStrength that is not a finite number >= 0, returns an error.
type MaterialVariant ¶
type MaterialVariant struct {
Name string
Extras json.RawMessage
}
MaterialVariant represents an entry in KHR_materials_variants.
type Mesh ¶
type Mesh struct {
Name string
Primitives []Primitive
Weights []float32
Extras json.RawMessage
}
Mesh groups one or more geometry primitives and optional default morph weights.
type MorphResult ¶
type MorphResult struct {
Positions []math3d.Vec3
Normals []math3d.Vec3
Tangents []math3d.Vec4
Bounds math3d.AABB
}
MorphResult holds the evaluated vertex attributes and object-space bounding box for a morphed Primitive. Reuse one MorphResult across frames to evaluate morph targets with zero steady-state allocations.
func ApplyMorphWeights ¶
func ApplyMorphWeights(base Primitive, weights []float32, dst *MorphResult) *MorphResult
ApplyMorphWeights evaluates base's morph targets with weights into dst and returns dst (allocating one if dst is nil). It blends Positions, renormalizes blended Normals, blends and renormalizes Tangents.xyz while preserving Tangents.w handedness, and recomputes Bounds from the resulting Positions. Reusing dst across calls performs zero heap allocations once its slices are sized.
type MorphTarget ¶
MorphTarget holds vertex attribute displacement deltas for a single morph target.
type Node ¶
type Node struct {
Name string
Parent int
Children []int
Translation math3d.Vec3
Rotation math3d.Quat
Scale math3d.Vec3
LocalMatrix math3d.Mat4
WorldMatrix math3d.Mat4
// HasMatrix reports whether this node's transform is governed directly by
// LocalMatrix (authored via the glTF "matrix" property) rather than TRS.
// When false, ComputeWorldMatrices recomputes LocalMatrix from Translation,
// Rotation, and Scale.
HasMatrix bool
// MatrixNotTRS reports that the authored matrix has shear or another part a translation, rotation and scale cannot express. Translation then holds the matrix's translation, Rotation and Scale stay identity, and LocalMatrix is the only exact transform (#546).
MatrixNotTRS bool
Mesh int
Skin int
Camera int
Weights []float32
Extras json.RawMessage
Extensions map[string]json.RawMessage
}
Node represents a node in the glTF 2.0 scene graph. Index fields (Parent, Mesh, Skin, Camera) are -1 when unset.
func (Node) IsDrawable ¶
IsDrawable reports whether n should be rendered visually. It returns false when n has no mesh (Mesh < 0) or when n is marked as a collider-only / non-drawn node via a *-colonly name suffix or extras ("draw": false, "collider": {"draw": false | "only": true | "visible": false}).
func (*Node) SetTransform ¶
SetTransform updates the node's local TRS properties, clears HasMatrix, and refreshes LocalMatrix.
type NodeCollider ¶
type NodeCollider struct {
// NodeIndex is the node's index in Document.Nodes (-1 when parsed from a
// standalone Node outside a Document).
NodeIndex int
// NodeName is the original Node.Name.
NodeName string
// BaseName is Node.Name with any recognized collider suffix removed.
BaseName string
// MeshIndex is Node.Mesh (-1 if the node has no mesh).
MeshIndex int
// Kind is the resolved collider shape kind.
Kind ColliderKind
// Draw reports whether the node's mesh should still be rendered visually.
// It is false for *-colonly suffixes, extras.collider.draw == false,
// extras.collider.only == true, extras.collider.visible == false, or nodes
// without a mesh.
Draw bool
// IsTrigger marks a sensor/trigger volume rather than a solid obstacle.
IsTrigger bool
// Tag is the resolved physics tag (extras.collider.tag when provided,
// otherwise BaseName, falling back to NodeName).
Tag string
// WorldMatrix is the node's world transform matrix (identity when unset).
WorldMatrix math3d.Mat4
// Optional local-space shape overrides supplied via extras.collider.
HasCenter bool
Center math3d.Vec3
HasHalfExtents bool
HalfExtents math3d.Vec3
HasRadius bool
Radius float32
HasHeight bool
Height float32
// Optional physics material and layer filter overrides from extras.collider.
HasFriction bool
Friction float32
HasRestitution bool
Restitution float32
HasLayer bool
Layer uint32
HasMask bool
Mask uint32
}
NodeCollider describes the collider metadata resolved from a glTF node's name suffix and/or extras.collider object.
func ParseNodeCollider ¶
func ParseNodeCollider(node Node) (NodeCollider, bool, error)
ParseNodeCollider inspects a glTF node's name suffix and extras.collider metadata to determine whether it defines a physics collider and whether its mesh should be drawn visually.
Recognized Godot-style node name suffixes (case-insensitive, with optional trailing Blender ".001" numbering):
- -col / -colonly: triangle mesh collider (drawn / collider-only)
- -boxcol / -boxcolonly: box collider (drawn / collider-only)
- -spherecol / -spherecolonly: sphere collider (drawn / collider-only)
- -capsulecol / -capsulecolonly: capsule collider (drawn / collider-only)
- -convcol / -convcolonly: convex collider (drawn / collider-only)
Recognized node extras metadata:
- {"collider": "box"|"sphere"|"capsule"|"trimesh"|"convex"|"none"}
- {"collider": true|false}
- {"collider": {"shape"|"type": ..., "draw": bool, "only": bool, "trigger": bool, "tag": string, "center": [x,y,z], "halfExtents"|"size": [x,y,z], "radius": r, "height": h, "friction": f, "restitution": r, "layer": u32, "mask": u32}}
- optional top-level {"draw": false} paired with a shorthand collider.
When extras.collider is present it takes precedence over name-suffix defaults. It returns (info, true, nil) when the node defines a collider, (zero, false, nil) when the node is not a collider, or an error when extras.collider is malformed.
type Primitive ¶
type Primitive struct {
Mode PrimitiveMode
Material int
Positions []math3d.Vec3
Normals []math3d.Vec3
Tangents []math3d.Vec4
TexCoords0 []math3d.Vec2
TexCoords1 []math3d.Vec2
Colors0 []math3d.Vec4
Joints0 [][4]uint16
Weights0 []math3d.Vec4
Indices []uint32
Bounds math3d.AABB
Targets []MorphTarget
VariantMappings map[int]int
Attributes map[string]int
Extras json.RawMessage
}
Primitive holds decoded geometry attributes, indices, bounding volume, morph targets, and KHR_materials_variants mappings for a single draw primitive. Material is -1 when no default material is assigned.
type PrimitiveMode ¶
type PrimitiveMode int
PrimitiveMode specifies the topology of a mesh primitive.
const ( ModePoints PrimitiveMode = 0 ModeLines PrimitiveMode = 1 ModeLineLoop PrimitiveMode = 2 ModeLineStrip PrimitiveMode = 3 ModeTriangles PrimitiveMode = 4 ModeTriangleStrip PrimitiveMode = 5 ModeTriangleFan PrimitiveMode = 6 )
type Sampler ¶
type Sampler struct {
Name string
MagFilter FilterMode
MinFilter FilterMode
WrapS WrapMode
WrapT WrapMode
Extras json.RawMessage
}
Sampler describes filtering and wrapping properties for a texture.
type Scene ¶
type Scene struct {
Name string
Roots []int
Extras json.RawMessage
}
Scene represents a glTF 2.0 scene with its root node indices.
type Skin ¶
type Skin struct {
Name string
Joints []int
Skeleton int
InverseBindMatrices []math3d.Mat4
Extras json.RawMessage
}
Skin defines skeletal joints and their inverse bind matrices. Skeleton is -1 when unset.
type TargetPath ¶
type TargetPath string
TargetPath identifies which node property an animation channel drives.
const ( PathTranslation TargetPath = "translation" PathRotation TargetPath = "rotation" PathScale TargetPath = "scale" PathWeights TargetPath = "weights" )
type Texture ¶
type Texture struct {
Name string
Sampler int
Source int
Extras json.RawMessage
Extensions map[string]json.RawMessage
}
Texture binds an Image source with an optional Sampler. Sampler and Source are -1 when unset.
type TextureRef ¶
type TextureRef struct {
TextureIndex int
TexCoord int
Scale float32
Strength float32
Transform *TextureTransform
}
TextureRef references a Texture in Document.Textures along with UV channel, normal scale / occlusion strength, and optional KHR_texture_transform.
func (TextureRef) ApplyUV ¶
func (r TextureRef) ApplyUV(uv math3d.Vec2) math3d.Vec2
ApplyUV transforms uv with r.Transform if present, or returns uv unchanged.
func (TextureRef) EffectiveTexCoord ¶
func (r TextureRef) EffectiveTexCoord() int
EffectiveTexCoord returns Transform.TexCoord if KHR_texture_transform overrides the UV set, otherwise TexCoord.
type TextureTransform ¶
TextureTransform represents the Khronos KHR_texture_transform extension. Transforms are applied in exact spec order: T(Offset) * R(Rotation) * S(Scale) in glTF UV space (origin top-left, +U right, +V down, positive rotation counter-clockwise).
Example ¶
TextureTransform evaluates KHR_texture_transform in exact T * R * S order.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/gltf"
"github.com/nsgo-dev/game/pkg/math3d"
)
func main() {
tr := gltf.DefaultTextureTransform()
tr.Offset = [2]float32{0.5, 0.25}
tr.Scale = [2]float32{2, 2}
fmt.Println(tr.Apply(math3d.Vec2{X: 0.25, Y: 0.5}))
}
Output: {1 1.25}
func DefaultTextureTransform ¶
func DefaultTextureTransform() TextureTransform
DefaultTextureTransform returns the identity KHR_texture_transform value (offset [0, 0], rotation 0, scale [1, 1], no texCoord override).
func (TextureTransform) Apply ¶
func (t TextureTransform) Apply(uv math3d.Vec2) math3d.Vec2
Apply transforms a 2D texture coordinate using the exact KHR_texture_transform matrix order M = T * R * S.
func (TextureTransform) ApplyUV ¶
func (t TextureTransform) ApplyUV(u, v float32) (float32, float32)
ApplyUV transforms texture coordinates (u, v) using the exact KHR_texture_transform matrix order M = T * R * S:
su = u * Scale[0] sv = v * Scale[1] u' = cos(Rotation)*su + sin(Rotation)*sv + Offset[0] v' = -sin(Rotation)*su + cos(Rotation)*sv + Offset[1]
func (TextureTransform) IsIdentity ¶
func (t TextureTransform) IsIdentity() bool
IsIdentity reports whether t leaves UV coordinates unchanged (offset [0, 0], rotation 0, and scale [1, 1]).
func (TextureTransform) Matrix ¶
func (t TextureTransform) Matrix() math3d.Mat3
Matrix returns the column-major 3x3 homogeneous UV transform matrix T * R * S matching the Khronos KHR_texture_transform specification.
type Transmission ¶
type Transmission struct {
// Factor is transmissionFactor in [0, 1] (default 0). Multiplied by Texture's R channel when present.
Factor float32
// Texture is transmissionTexture (optional, linear; R channel modulates Factor).
Texture *TextureRef
}
Transmission represents the Khronos KHR_materials_transmission material extension, describing optical transmission through thin dielectric surfaces.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
draco
Package draco decodes Draco-compressed triangle meshes (bitstream version 2.2, the version KHR_draco_mesh_compression normatively references) in pure Go.
|
Package draco decodes Draco-compressed triangle meshes (bitstream version 2.2, the version KHR_draco_mesh_compression normatively references) in pure Go. |
|
meshopt
Package meshopt decodes the meshoptimizer bitstreams used by the EXT_meshopt_compression and KHR_meshopt_compression glTF extensions in pure Go: the attribute codec (versions 0 and 1), the triangle and index sequence codecs, and the octahedral, quaternion, exponential and color filters.
|
Package meshopt decodes the meshoptimizer bitstreams used by the EXT_meshopt_compression and KHR_meshopt_compression glTF extensions in pure Go: the attribute codec (versions 0 and 1), the triangle and index sequence codecs, and the octahedral, quaternion, exponential and color filters. |