Files
rosetta/docs/guide/scene.md
T

413 lines
21 KiB
Markdown

# Scene (3D models) and Voxels
Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX) loads as one `Scene`, a structure
shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials,
textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel
files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`.
```luau
local scene = assert(F.model.load(texturedGltfText))
print(#scene.nodes, #scene.meshes, scene.meta.up) -- 2 1 y
local prim = scene.meshes[1].primitives[1]
local pos = prim.attributes.POSITION -- f32, 3 components, 24 vertices
assert(pos.type == "f32" and pos.components == 3 and pos.count == 24)
assert(prim.indices.count == 36 and prim.mode == "triangles")
local merged = F.ops.mesh.merge(scene) -- one world-space triangle primitive
local lo, hi = F.ops.mesh.bounds(merged)
print(lo[1], hi[1]) -- -0.5 0.5
local glb = assert(F.save(scene, nil, { format = "glb" }))
local obj = assert(F.convert(texturedGltfText, "obj"))
```
## The type
**Indices are 1-based everywhere** (`node.mesh`, `node.children`, `prim.material`, `material.baseColorTexture.texture`,
`skin.joints`, `channel.node`, `scene.roots`). Only the *contents* of index accessors are 0-based vertex numbers, as
in glTF.
### Scene
| Field | Type | Meaning |
|---|---|---|
| `kind` | `"scene"` | |
| `nodes` | `{ Node }` | every node, in file order |
| `roots` | `{ number }` | the top-level node indices (the scene shown) |
| `meshes` | `{ Mesh }` | `{ name?, primitives = { Primitive }, weights? }` |
| `materials` | `{ Material }` | |
| `textures` | `{ Texture }` | |
| `cameras`, `lights`, `skins`, `animations` | arrays | see below |
| `voxels` | `{ Voxels }?` | voxel grids (VOX), shown by `node.voxels` |
| `meta.up` | `"y"` \| `"z"` | the source's up axis: `"y"` for glTF / OBJ, `"z"` for STL / VOX / CAD. Never rotated on load |
| `meta.unit` | `number?` | metres per scene unit when the file says (glTF: 1) |
| `meta.source` | table | `{ format = "gltf", binary = false, generator = ..., ... }` |
### Node
| Field | Type | Meaning |
|---|---|---|
| `name` | `string?` | |
| `children` | `{ number }` | child node indices |
| `mesh`, `camera`, `light`, `skin`, `voxels` | `number?` | indices into the scene arrays |
| `translation` | `{ x, y, z }?` | TRS form ... |
| `rotation` | `{ x, y, z, w }?` | ... unit quaternion |
| `scale` | `{ x, y, z }?` | |
| `matrix` | `{ number }?` (16) | ... or a **column-major** 4x4 matrix (`m[13], m[14], m[15]` = translation). Never both |
| `weights` | `{ number }?` | morph target weights |
`F.Types.Scene.nodeMatrix(node)` gives the local matrix of either form (T * R * S), `F.Types.Scene.mul(a, b)` multiplies
two column-major matrices, and `F.Types.Scene.flatten(scene)` walks the tree from the roots and returns
`{ { primitive, matrix (world), node, mesh } }` for every primitive.
```luau
local scene = assert(F.load(texturedGltfText))
local root = scene.nodes[scene.roots[1]]
assert(#root.matrix == 16) -- this file uses a matrix (a -90 degree turn about x)
for _, placed in F.Types.Scene.flatten(scene) do
local m = placed.matrix -- world matrix, column-major
print(placed.node, placed.mesh, m[13], m[14], m[15])
end
```
### Primitive and Accessor
| Primitive field | Type | Meaning |
|---|---|---|
| `attributes` | `{ [name]: Accessor }` | `POSITION`, `NORMAL`, `TANGENT` (vec4, w = handedness), `TEXCOORD_n`, `COLOR_n`, `JOINTS_n`, `WEIGHTS_n`; custom ones start with `_` (PLY extra properties: `_quality`) |
| `indices` | `Accessor?` | 0-based vertex numbers (`u8` / `u16` / `u32`); nil = vertices in order |
| `mode` | string | `"triangles"`, `"lines"`, `"points"`, `"triangle_strip"`, `"triangle_fan"`, `"line_strip"`, `"line_loop"`, `"polygons"` |
| `faces` | `Accessor?` | `"polygons"` only: one `u32` vertex count per face; `indices` holds the faces one after another |
| `material` | `number?` | index into `scene.materials` |
| `targets` | `{ { [name]: Accessor } }?` | morph targets: `POSITION` / `NORMAL` / `TANGENT` deltas |
| Accessor field | Type | Meaning |
|---|---|---|
| `data` | `buffer` | **tightly packed** little-endian elements: element `i`, component `c` sits at `(i * components + c) * size`. No stride, no padding; sparse accessors are already applied |
| `type` | string | `f32`, `f64`, `u8`, `u16`, `u32`, `i8`, `i16`, `i32`, or the normalized integers `unorm8`, `unorm16`, `snorm8`, `snorm16` (glTF `normalized: true`: `unorm8` 255 = 1.0, `snorm16` -32767 = -1.0) |
| `components` | number | 1 (scalar), 2, 3, 4 (vec4), or 4 / 9 / 16 with `matrix = true` (MAT2 / MAT3 / MAT4, column-major) |
| `count` | number | elements |
Read any accessor without caring about its type with `F.Types.Scene.reader`, which converts normalized types to floats:
```luau
local scene = assert(F.load(texturedGltfText))
local prim = scene.meshes[1].primitives[1]
local get = assert(F.Types.Scene.reader(prim.attributes.POSITION))
print(get(0, 0), get(0, 1), get(0, 2)) -- x, y, z of vertex 0 (0-based)
-- the same by hand: f32, 3 components, 4 bytes each
local x = buffer.readf32(prim.attributes.POSITION.data, (0 * 3 + 0) * 4)
assert(x == get(0, 0))
local idx = prim.indices -- u16 here
local first = buffer.readu16(idx.data, 0) -- the first triangle's first vertex (0-based)
assert(first >= 0 and first < prim.attributes.POSITION.count)
```
Build accessors with `F.Types.Scene.accessor(data?, type, components, count)` (`data = nil` allocates zeros); the
byte size of one component is `F.Types.COMPONENT_SIZE[type]`.
### Material, Texture, Sampler
| Material field | Type | Meaning |
|---|---|---|
| `baseColor` | `{ r, g, b, a }` | **linear** 0..1 |
| `baseColorTexture`, `metallicRoughnessTexture`, `normalTexture`, `occlusionTexture`, `emissiveTexture` | `TextureRef?` | `{ texture (index), texCoord? (TEXCOORD_n, default 0), scale?, strength?, transform? (KHR_texture_transform: offset, scale, rotation) }` |
| `metallic`, `roughness` | number | 0..1 |
| `emissive` | `{ r, g, b }` | linear |
| `alphaMode`, `alphaCutoff` | `"opaque"` \| `"mask"` \| `"blend"`, number | |
| `doubleSided` | boolean | |
| `extensions` | table? | glTF `KHR_materials_*` by name, their fields as in glTF (texture infos as TextureRefs) |
| `extras` | table? | format extras. OBJ: `extras.obj.values` holds the MTL statements (`Kd`, `Ks`, `Ns`, ...), `extras.obj.maps` the texture maps; the PBR fields are derived from them |
| Texture field | Type | Meaning |
|---|---|---|
| `data` | `buffer?` | the **encoded** image bytes (PNG, JPEG, WebP, KTX2, ...) |
| `mime` | `string?` | `"image/png"`, ... |
| `uri` | `string?` | the file name relative to the model, when the bytes were not embedded or not found |
| `image` | `Image?` | the decoded image, set by `F.model.loadTextures` (or you) |
| `sampler` | `Sampler?` | `{ wrapS, wrapT = "repeat" \| "clamp" \| "mirror", filter = "linear" \| "nearest", minFilter }` |
**Model formats never decode images.** Textures stay encoded until you ask:
```luau
local scene = assert(F.load(texturedGltfText))
local tex = scene.textures[1]
assert(tex.mime == "image/png" and tex.image == nil)
local _, errs = F.model.loadTextures(scene) -- decodes every texture.data (or texture.uri via opts.resolve)
assert(next(errs) == nil)
local img = tex.image -- an rgba8 Image, 256 x 256
assert(img.width == 256 and img.format == "rgba8")
local mat = scene.materials[1]
assert(scene.textures[mat.baseColorTexture.texture] == tex)
```
`loadTextures(scene, opts?)` returns `scene, errors` (`errors[i]` = the Err of texture `i`); textures whose image format
is missing keep `image = nil`. Saving a scene whose texture has only an `image` encodes it as PNG first.
### Cameras, lights, skins, animations
| Type | Fields |
|---|---|
| Camera | `type = "perspective"` (`yfov` radians, `aspect?`, `znear`, `zfar?`) or `"orthographic"` (`xmag`, `ymag`, `znear`, `zfar`) |
| Light | `type = "directional" \| "point" \| "spot"`, `color { r, g, b }`, `intensity`, `range?`, `innerCone?` / `outerCone?` (radians) |
| Skin | `joints { node index }`, `inverseBindMatrices` (Accessor, `f32`, 16 components, `matrix = true`), `skeleton?` |
| Animation | `name?`, `channels { { node, path = "translation" \| "rotation" \| "scale" \| "weights", input, output, interpolation = "LINEAR" \| "STEP" \| "CUBICSPLINE" } }` |
A channel's `input` accessor holds the key times in **seconds** (`f32` scalars), `output` the values (vec3 for
translation / scale, vec4 quaternions for rotation; CUBICSPLINE stores in-tangent, value, out-tangent per key).
Skinned vertices carry `JOINTS_0` (indices into `skin.joints`, 0-based) and `WEIGHTS_0`.
```luau
local scene = assert(F.load(riggedGlbBytes))
local skin = scene.skins[1]
assert(skin.inverseBindMatrices.components == 16 and skin.inverseBindMatrices.count == #skin.joints)
local ch = scene.animations[1].channels[1]
local times = assert(F.Types.Scene.reader(ch.input))
local lastKey = times(ch.input.count - 1, 0) -- seconds
print(scene.nodes[ch.node].name, ch.path, ch.interpolation, lastKey)
local prim = scene.meshes[1].primitives[1]
assert(prim.attributes.JOINTS_0 and prim.attributes.WEIGHTS_0)
```
## Loading
```luau
local a = assert(F.load(boxGlbBytes)) -- detected by content: GLB
local b = assert(F.model.load(objText, { format = "obj" })) -- text formats: pass format (or a name) when sniffing is unsure
local c = F.load(objText, { name = "cube.obj" }) -- the name's extension is the fallback
assert(a.kind == "scene" and b.kind == "scene" and c.kind == "scene")
```
Model options (each format's own; unknown ones are ignored):
| Option | Formats | Meaning |
|---|---|---|
| `resolve(uri) -> buffer \| string \| nil` | glTF, OBJ, DAE, ... | reads the other files a model names (`.bin`, `.mtl`, textures) |
| `files = { [name] = buffer \| string }` | glTF, OBJ, ... | the other files, by name, instead of `resolve` |
| `mtl` | OBJ | the material library text, when not found otherwise |
| `triangulate` | OBJ, PLY, OFF | `false` keeps n-gons as `mode = "polygons"` (default: fan-triangulated) |
| `flipV` | OBJ | `false` keeps OBJ's bottom-left UV origin (default flips to glTF's top-left) |
| `maxBytes`, `maxVertices`, `maxFaces` | various | size limits (`Err.LIMIT`) |
### Files next to the model
A `.gltf` may reference a `.bin` and image files; an `.obj` names its `.mtl`. Loading **from a path** on a host with a
file system (LuaJIT, LÖVE) reads them from the model's folder automatically (relative names only: no absolute paths, no
`..`, no URLs):
<!-- doc:files -->
```luau
local scene = assert(F.load("assets/BoxTextured.gltf")) -- reads BoxTextured0.bin and CesiumLogoFlat.png too
assert(scene.textures[1].data ~= nil and scene.textures[1].uri == "CesiumLogoFlat.png")
local cube = assert(F.load("assets/cube.obj")) -- and cube.mtl
assert(cube.materials[1].name == "red")
```
From bytes (Roblox, the luau CLI, downloaded data) hand the files over yourself, as a table or a function:
```luau
local files = { ["BoxTextured0.bin"] = boxBinBytes, ["CesiumLogoFlat.png"] = logoPngBytes }
local a = assert(F.load(boxGltfText, { files = files }))
local b = assert(F.load(boxGltfText, { resolve = function(uri) return files[uri] end }))
assert(a.textures[1].data and b.textures[1].data)
local missing, err = F.load(boxGltfText) -- the .bin is required
assert(missing == nil and err.code == F.Err.IO)
local cube = assert(F.load(objText, { format = "obj", files = { ["cube.mtl"] = mtlText } }))
assert(cube.materials[1].baseColor[1] == 0.8) -- from Kd 0.8 0.1 0.1
```
A missing **image** is not an error: the texture keeps its `uri` and no `data`.
## Editing: `F.ops.mesh`
Every function accepts any accessor type and writes `f32` attributes and `u32` indices. Bad arguments return
`nil, err`.
| Function | Does |
|---|---|
| `merge(scene, opts?)` | bakes every primitive (node transforms applied) into one triangle primitive; `byMaterial = true` returns one per material. Lines and points are skipped; skins / morphs stay in rest pose |
| `bounds(primitive \| scene)` | `min { x, y, z }, max { x, y, z }` (a scene: world space) |
| `transform(prim, matrix)` | in place: positions, normals, tangents (and morph deltas); a mirroring matrix flips the winding |
| `triangulate(prim, opts?)` | a new triangle primitive from strips, fans and polygons (`method = "earclip"` default, or `"fan"`) |
| `computeNormals(prim, opts?)` | area-weighted `NORMAL`; `flat = true` splits corners for faceted shading |
| `computeTangents(prim, opts?)` | `TANGENT` (vec4, w = +-1) from `TEXCOORD_<opts.texCoord or 0>` |
| `weld(prim, opts?)` | merges identical vertices; `epsilon` merges near positions; `positionsOnly = true` merges by position alone |
| `unweld(prim)` | one vertex per index (no indices) |
| `f32(accessor)` | the accessor converted to `f32` |
| `scale(scene, factor)` | in place: geometry, translations, animations, cameras, lights; `meta.unit` is divided by factor |
| `setUnit(scene, metresPerUnit)` | rescales so one unit is that many metres (from `meta.unit`, default 1) |
| `setUp(scene, "y" \| "z")` | adds a root node that rotates the old roots to the new up axis (nothing baked) |
| `voxelsToPrimitive(voxels, opts?)`, `meshVoxels(scene, opts?)` | greedy meshing of voxel grids (below) |
```luau
local M = F.ops.mesh
local scene = assert(F.load(texturedGltfText))
local prim = assert(M.merge(scene)) -- 24 vertices, 36 indices, world space
local solid = assert(M.weld(prim, { positionsOnly = true }))
assert(solid.attributes.POSITION.count == 8) -- the cube's corners
local faceted = assert(M.computeNormals(M.unweld(prim), { flat = true }))
assert(faceted.attributes.NORMAL.count == 36)
-- scale by 2 and move 10 units along x (column-major: translation in elements 13..15)
M.transform(prim, { 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 10, 0, 0, 1 })
local lo, hi = M.bounds(prim)
assert(lo[1] == 9 and hi[1] == 11)
local quads = assert(F.load(objText, { format = "obj", triangulate = false }))
local poly = quads.meshes[1].primitives[1]
assert(poly.mode == "polygons" and poly.faces.count == 6)
assert(M.triangulate(poly).indices.count == 36)
assert(M.setUnit(scene, 0.01)) -- centimetres: positions x 100
assert(scene.meta.unit == 0.01)
assert(M.setUp(scene, "z") and scene.meta.up == "z")
```
Build a mesh from scratch with the constructors:
```luau
local S = F.Types.Scene
local pos = S.accessor(nil, "f32", 3, 3)
for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do
buffer.writef32(pos.data, (i - 1) * 4, v)
end
local prim = { attributes = { POSITION = pos }, mode = "triangles", material = 1 }
local scene = S.fromPrimitive(prim, "triangle") -- one node, one mesh
scene.materials[1] = S.material("red")
scene.materials[1].baseColor = { 1, 0, 0, 1 }
F.ops.mesh.computeNormals(prim)
local stl = assert(F.save(scene, nil, { format = "stl" }))
assert(buffer.len(stl) == 84 + 50) -- binary STL: header + one facet
```
## Saving and converting
`F.save(scene, dest?, opts?)` picks the writer from `opts.format`, else the destination's extension, else
`scene.meta.source.format`. `glb` and `gltf` are the same format: `format = "glb"` (or a `.glb` destination) writes
the binary container.
| Writer | Other files | Options |
|---|---|---|
| glTF | `external = true` writes `<name>.bin` and the images into `opts.files` (default: embedded `data:` URIs) | `binary`, `external`, `name` |
| OBJ | `<name>.mtl` and texture files into `opts.files` | `name`, `mtlName`, `normals`, `texcoords`, `colors`, `flipV` |
| STL | | `ascii = true` (default binary), `normals = "attribute"` |
| PLY, OFF, FBX, DAE, 3MF, USDA, VOX | see [FORMATS.md](../FORMATS.md) and the format's options | |
Mesh-only writers (STL, PLY, OFF, OBJ) bake the node transforms into the vertices. Extra files go into the
`opts.files` table you pass, named after `opts.name`:
```luau
local scene = assert(F.load(texturedGltfText))
local files = {}
local gltf = assert(F.save(scene, nil, { format = "gltf", external = true, name = "box.gltf", files = files }))
assert(files["box.bin"] ~= nil) -- plus the texture, under its original name or box_1.png
local mtlFiles = {}
local obj = assert(F.save(scene, nil, { format = "obj", name = "box.obj", files = mtlFiles }))
assert(type(mtlFiles["box.mtl"]) == "string")
assert(string.find(buffer.tostring(obj), "mtllib box.mtl", 1, true))
```
Saving to a path writes those files next to the destination:
<!-- doc:files -->
```luau
local scene = assert(F.load("assets/BoxTextured.gltf"))
assert(F.save(scene, "out/box.glb")) -- one file, everything embedded
assert(F.save(scene, "out/box.gltf", { external = true })) -- box.gltf + box.bin + CesiumLogoFlat.png
assert(F.save(scene, "out/box.obj")) -- box.obj + box.mtl + the texture
assert(F.convert("assets/Box.glb", "stl", { out = "out/box.stl" }))
```
## Voxels
MagicaVoxel `.vox` files load as a Scene with `meta.up = "z"`, units of one voxel, and grids in `scene.voxels`; each
node that shows a model has `node.voxels` (an index into `scene.voxels`) and no mesh until you mesh it.
| Voxels field | Type | Meaning |
|---|---|---|
| `kind` | `"voxels"` | |
| `size` | `{ sx, sy, sz }` | cells per axis (z up) |
| `data` | `buffer` | one byte per cell, `0` = empty, `1..255` = palette index; cell `(x, y, z)` (0-based) at byte `x + sx * (y + sy * z)` |
| `palette` | `{ { r, g, b, a } }` | 255 entries, 0..255 **sRGB**, `palette[i]` for index `i`, shared by a file's models |
| `materials` | `{ [index]: { type, ... } }?` | MATL: `"diffuse"`, `"metal"`, `"glass"`, `"emit"`, ... with their properties |
```luau
local V = F.Types.Voxels
local scene = assert(F.load(voxBytes))
local grid = scene.voxels[1]
local sx, sy, sz = grid.size[1], grid.size[2], grid.size[3]
local filled = 0
for z = 0, sz - 1 do
for y = 0, sy - 1 do
for x = 0, sx - 1 do
if V.get(grid, x, y, z) ~= 0 then
filled += 1
end
end
end
end
print(sx, sy, sz, filled) -- 20 21 20 398
V.set(grid, 0, 0, 0, 1) -- paint a cell with palette entry 1
local r, g, b, a = table.unpack(grid.palette[1])
assert(a == 255)
-- greedy meshing: merged faces, per-vertex colours from the palette
assert(F.ops.mesh.meshVoxels(scene)) -- every node with voxels now has a mesh
local prim = scene.meshes[scene.nodes[1].mesh].primitives[1]
assert(prim.attributes.COLOR_0.type == "f32") -- linear RGBA (glTF's COLOR_0 meaning)
local glb = assert(F.save(scene, nil, { format = "glb" }))
```
`voxelsToPrimitive(voxels, opts)` meshes one grid. Options (both functions): `pivot = "center"` (default, MagicaVoxel's
placement: cell `x` spans `x - floor(sx / 2)` ..) or `"corner"` (0 .. sx), `scale` (units per voxel, default 1),
`colors = "linear"` (default, `f32`) or `"srgb"` (`unorm8`, the palette bytes), `indexAttribute = true` (adds
`_PALETTE_INDEX`, `u8`). Call `meshVoxels` once per scene, after editing the grids: each call adds meshes.
```luau
local V = F.Types.Voxels
local grid = V.new(4, 4, 2) -- empty; the default palette is a grey ramp
for x = 0, 3 do
for y = 0, 3 do
V.set(grid, x, y, 0, 200) -- a 4 x 4 floor
end
end
V.set(grid, 1, 1, 1, 10)
local prim = assert(F.ops.mesh.voxelsToPrimitive(grid, { pivot = "corner", colors = "srgb" }))
local lo, hi = F.ops.mesh.bounds(prim)
assert(hi[1] == 4 and hi[3] == 2)
local vox = assert(F.save(grid, nil, { format = "vox" })) -- a grid alone saves as a one-model .vox
assert(F.load(vox).voxels[1].size[1] == 4)
```
## Formats
| Format | Read | Write | Notes |
|---|---|---|---|
| glTF 2.0 / GLB | yes | yes | everything above, `KHR_*` material extensions, `KHR_mesh_quantization`; no Draco / meshopt |
| OBJ + MTL | yes | yes | polygons, vertex colours, Phong + PBR MTL |
| STL | yes | yes | ASCII / binary, colour conventions; a triangle soup |
| PLY | yes | yes | ASCII / binary, point clouds, custom `_` attributes |
| OFF | yes | yes | |
| FBX | yes | yes | binary + ASCII 7.x, skins, animation |
| Collada (DAE / ZAE) | yes | yes | |
| 3MF | yes | yes | |
| USDA (+ USDZ read) | yes | yes | |
| VOX | yes | yes | voxel grids, scene graph, materials |
| STEP | via the CAD plug-in | | see [cad.md](cad.md) |
Capabilities per format: [FORMATS.md](../FORMATS.md).
## Gotchas
- 1-based object indices, 0-based vertex indices and voxel coordinates.
- Matrices are column-major flat arrays of 16; quaternions are `{ x, y, z, w }`.
- Colours: `baseColor`, `emissive` and `f32` `COLOR_0` are linear; the voxel palette and `unorm8` colours from
`colors = "srgb"` are sRGB bytes.
- No format rotates the data to a common up axis: check `meta.up` (VOX, STL and CAD are z-up) and use
`F.ops.mesh.setUp` or your own matrix.
- OBJ UVs are flipped on load (`v = 1 - v`) to glTF's top-left origin, and flipped back on save.
- `F.ops.mesh.transform` and `computeNormals` / `computeTangents` change the primitive in place (and return it);
`merge`, `weld`, `unweld` and `triangulate` return new primitives.
- `merge` ignores skins and morph targets (the rest pose); bake animation yourself if you need a posed mesh.
- A text model (OBJ, ASCII STL / PLY) passed as a string is sniffed by content; pass `format` or `name` when the text
is ambiguous.