# Scene (3D models) and Voxels Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D, B3D, LDraw) 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): ```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`. ### Compressed glTF (Draco) Primitives compressed with `KHR_draco_mesh_compression` decode on load (through `codecs/model/Draco`, a port of Google's Draco decoder: Edgebreaker and sequential connectivity, every prediction scheme, quantized attributes, bit-exact with libdraco). The attributes come out as their accessors declare them, and the indices as `u32`. Saving writes the geometry back uncompressed, without the extension. `EXT_meshopt_compression` is not supported. ```luau local scene = assert(F.load(dracoGlbBytes)) -- Box.glb through draco_transcoder local prim = scene.meshes[1].primitives[1] assert(prim.indices.count == 36 and prim.attributes.POSITION.type == "f32") local plain = assert(F.save(scene, nil, { format = "glb" })) assert(not string.find(buffer.tostring(plain), "KHR_draco", 1, true)) ``` Raw `.drc` files (and Draco data inside other formats) go through the codec itself: `require(Formats.codecs.model.Draco).decode(bytes)` returns `{ kind, numPoints, numFaces, indices, attributes }` with each attribute's values per point (`name`, `uniqueId`, `components`, `type`, `normalized`, `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_` | | `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 `.bin` and the images into `opts.files` (default: embedded `data:` URIs) | `binary`, `external`, `name` | | OBJ | `.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, 3DS, MS3D | 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: ```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) ``` ## Blitz3D (B3D) `.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS; each `MESH` becomes one mesh whose primitives (one per `TRIS` chunk) share the vertex accessors; brushes become materials (colour, alpha, shininess, the first texture as `baseColorTexture` with its position / scale / rotation as `transform`, the full brush in `extras.b3d`); `BONE` weights become a skin (the 4 strongest weights per vertex) and `KEYS` + `ANIM` one animation sampled at `frame / fps`. Texture files come through `files` / `resolve` like any other model's (by the stored path, then by its base name: B3D files often store absolute Windows paths). Blitz3D is **left-handed**: the reader mirrors z (and turns the triangle winding and rotations to match), so the scene is glTF's right-handed Y-up with the model looking as it did in Blitz3D. `meta.source.handedness = "left"` records the origin, `meta.source.fps` / `frames` the `ANIM` chunk. ## LDraw LDraw files (`.ldr` models, `.dat` parts, `.mpd` multi-part files) load read-only. Every reference to a **part** becomes a node with the reference's matrix, and each part is baked once per colour into a mesh those nodes share; **sub-models** (`.ldr` / `.mpd` files, MPD sections that are not parts) become nodes with children. Colour 16 takes the colour of the reference above it, 24 its edge colour; codes come from the LDConfig.ldr table built in (one material per colour, `extras.ldraw.code` / `name`), `0x2RRGGBB` is a direct colour. BFC (`CERTIFY`, `CW` / `CCW`, `INVERTNEXT`, `NOCLIP`) turns every face counter-clockwise; faces of uncertified parts get double-sided materials. Edge lines (type 2) are `"lines"` primitives (`lines = false` drops them); optional lines only on request (`optionalLines = true`). ```luau local mpd = [[ 0 FILE house.ldr 1 4 0 0 0 1 0 0 0 1 0 0 0 1 wall.dat 1 4 50 0 0 1 0 0 0 1 0 0 0 1 wall.dat 1 1 0 -30 0 1 0 0 0 1 0 0 0 1 roof.dat 0 FILE wall.dat 0 !LDRAW_ORG Unofficial_Part 0 BFC CERTIFY CCW 4 16 -10 0 -10 10 0 -10 10 0 10 -10 0 10 2 24 -10 0 -10 10 0 -10 0 FILE roof.dat 0 BFC CERTIFY CCW 3 16 0 -10 0 10 0 0 -10 0 0 ]] local scene = assert(F.model.load(mpd, { format = "ldraw" })) print(#scene.meshes) -- 2: wall.dat in red (both walls share it), roof.dat in blue local root = scene.nodes[scene.roots[1]] -- "LDraw": turns LDraw's -Y up into Y up local a, b = scene.nodes[root.children[1]], scene.nodes[root.children[2]] assert(a.mesh == b.mesh and b.matrix[13] == 50) local red = scene.materials[scene.meshes[a.mesh].primitives[1].material] print(red.name, red.extras.ldraw.code) -- Red 4 assert(scene.meta.up == "y" and scene.meta.unit == 0.0004) -- 1 LDU = 0.4 mm ``` Parts and primitives that are not in the file come through `files` or `resolve`, asked for by their LDraw library path: the name as written (backslashes turned into slashes), then in lower case, under `""`, `parts/`, `p/`, `parts/s/` and `models/`. Point `resolve` at an LDraw library folder to load real models; missing files are skipped and listed in `meta.source.missing`: ```luau local library = { ["p/box.dat"] = "0 BFC CERTIFY CCW\n4 16 -1 -1 -1 1 -1 -1 1 -1 1 -1 -1 1\n4 16 -1 1 -1 -1 1 1 1 1 1 1 1 -1\n", ["parts/plate.dat"] = "0 !LDRAW_ORG Part\n1 16 0 4 0 20 0 0 0 4 0 0 0 10 box.dat\n", } local model = "0 two plates\n1 14 0 0 0 1 0 0 0 1 0 0 0 1 plate.dat\n1 0x2FF8000 0 -8 0 1 0 0 0 1 0 0 0 1 plate.dat\n" .. "1 4 0 -16 0 1 0 0 0 1 0 0 0 1 3001.dat\n" local scene = assert(F.model.load(model, { format = "ldraw", files = library })) assert(#scene.meshes == 2 and scene.meta.source.missing[1] == "3001.dat") local same = assert(F.model.load(model, { format = "ldraw", resolve = function(path) return library[path] -- or: read ldrawFolder .. "/" .. path end })) local flat = assert(F.model.load(model, { format = "ldraw", files = library, flatten = true })) assert(#flat.meshes == 1) -- one mesh, one primitive per colour ``` `upright = false` leaves out the root node (LDraw's axes as stored, `meta.source.up = "-y"`); `ldconfig` takes the text of another LDConfig.ldr, and `color` the colour of code 16 at the top (default 16, "Main_Colour"). ## 3D Studio (3DS) `.3ds` files load with their keyframer: the node hierarchy, pivots, instances of one object, the first key of each track as the node's TRS and, when tracks have several keys, one animation (frames / `opts.fps`, default 30). Normals come from the smoothing groups (`normals = false` keeps the file's shared vertices); the groups stay in `prim.extras["3ds"].smoothing` and are written back. Materials are Phong (the raw values in `extras["3ds"]`), texture maps become textures with a `uri` only (`F.model.loadTextures` reads them). Cameras get `yfov` from the lens at a 4:3 aspect and look at their target; omni lights are `point`, spotlights `spot`. The writer puts one object per mesh (split past 65535 vertices), its first instance's world matrix as the mesh matrix, and the scene's first animation into the keyframer. ```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 scene = S.fromPrimitive({ attributes = { POSITION = pos }, mode = "triangles", material = 1 }, "tri") scene.materials[1] = S.material("red") scene.materials[1].baseColor = { 1, 0, 0, 1 } scene.nodes[1].translation = { 0, 0, 2 } local bytes = assert(F.save(scene, nil, { format = "3ds" })) local back = assert(F.load(bytes)) -- detected by its 0x4D4D main chunk assert(back.meta.source.format == "3ds" and back.meta.up == "z") local prim = back.meshes[1].primitives[1] assert(prim.attributes.NORMAL and prim.extras["3ds"].smoothing[1] == 1) assert(back.materials[prim.material].baseColor[1] == 1) assert(back.nodes[1].translation[3] == 2) -- the keyframer keeps the node transform ``` ## MilkShape 3D (MS3D) Each group loads as a node with one mesh (per-corner normals and uvs, so vertices are split per corner); joints become nodes with a skin (`JOINTS_0` / `WEIGHTS_0`, up to four bones from the 1.8 vertex extras) and their keys one animation. Comments, joint colours and the other MilkShape fields stay in `extras.ms3d` / `meta.source`. The writer puts every placed primitive in a group, the first skin's joints plus every node the first animation moves (meshes under them are bound rigidly) into the skeleton, and the weights in percent. ```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 scene = S.fromPrimitive({ attributes = { POSITION = pos }, mode = "triangles" }, "tri") -- spin the node a quarter turn about z in one second local times = S.accessor(nil, "f32", 1, 2) buffer.writef32(times.data, 4, 1) local turns = S.accessor(nil, "f32", 4, 2) for i, v in { 0, 0, 0, 1, 0, 0, math.sqrt(0.5), math.sqrt(0.5) } do buffer.writef32(turns.data, (i - 1) * 4, v) end scene.animations[1] = { channels = { { node = 1, path = "rotation", input = times, output = turns, interpolation = "LINEAR" } } } local back = assert(F.load(assert(F.save(scene, nil, { format = "ms3d" })))) assert(back.meta.source.format == "ms3d" and #back.skins == 1) -- the animated node became a joint local prim = back.meshes[1].primitives[1] assert(prim.attributes.JOINTS_0 and prim.attributes.NORMAL) assert(back.animations[1].channels[1].path == "rotation") ``` ## Formats | Format | Read | Write | Notes | |---|---|---|---| | glTF 2.0 / GLB | yes | yes | everything above, `KHR_*` material extensions, `KHR_mesh_quantization`, Draco (read); no 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 | | B3D (Blitz3D) | yes | | brushes, textures, skins, keyframe animation; left-handed source mirrored to glTF's frame | | LDraw (LDR / DAT / MPD) | yes | | parts as shared meshes per colour, sub-models as nodes, BFC, LDConfig colours, `files` / `resolve` for the library | | 3DS | yes | yes | keyframer hierarchy and animation, Phong materials, texture names, cameras, lights; Z up | | MS3D (MilkShape 3D) | yes | yes | groups, materials, joints -> skin + animation, comments | | 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.