# Scene (3D models) and Voxels Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D, B3D, LDraw, LightWave LWO, DirectX .x, IQM, PMX / PMD, VRML, X3D, the [game models](#game-models) MD2 / MD3 / MDL / MD5 / BSP / SMD, [Blender .blend](#blender-blend), [Roblox meshes](roblox.md) and the [Minecraft and Qubicle voxel files](voxel.md)) 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(Rosetta.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, IQM | see [FORMATS.md](../FORMATS.md) and the format's options | | | VRML, X3D | texture images into `opts.files` (else `url` = the texture's uri) | `name`, `flipV`; X3D `encoding = "x3dv"` (or a `.x3dv` destination) for the classic encoding | 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" })) ``` ## MikuMikuDance (PMX / PMD) `.pmx` (PMX 2.0 / 2.1) and `.pmd` files load as one skinned mesh with one primitive per material. MMD is left-handed, so z is negated and the winding reversed on load; `meta.up` is `"y"` (one unit is about 8 cm). Bones become nodes (a translation relative to the parent bone) under the model's root node and one `Skin`; every vertex carries `JOINTS_0` / `WEIGHTS_0` (BDEF1 / 2 / 4, SDEF and QDEF all as linear weights, normalized; the SDEF C / R0 / R1 vectors as `_SDEF_C` / `_SDEF_R0` / `_SDEF_R1` and the deform type as `_DEFORM` when a file uses them), the additional UVs as `_UVA1` .. `_UVA4` (vec4) and the edge scale as `_EDGE_SCALE`. Vertex morphs are morph targets (`mesh.extras.targetNames` holds their names); the other morphs (group, bone, UV, material, flip, impulse) are in `mesh.extras.pmx.morphs`. Materials take the diffuse colour as `baseColor`, the specular power as roughness and the no-cull flag as `doubleSided`; the MMD terms (specular, ambient, edge, sphere map and its mode, toon texture or shared toon index, memo) are in `material.extras.pmx`, bone flags / IK / inherit settings in `node.extras.pmx`, display frames, rigid bodies and joints in `meta.source`. Textures are referenced by their file names (`opts.files` / `opts.resolve` give the bytes). `morphs = false` skips the morph targets. ## VRML and X3D VRML97 (`.wrl`, gzipped `.wrz`) and X3D (XML `.x3d`, classic `.x3dv`, gzipped `.x3dz` / `.x3dvz`) share one reader: the scene graph becomes nodes (a `Transform` with a `center` or `scaleOrientation` adds an inner node), `DEF` / `USE` shares meshes and materials, `PROTO` / `ProtoInstance` are expanded, Box / Sphere / Cone / Cylinder are tessellated (`opts.segments`, default 32), polygons are fan-triangulated unless `triangulate = false`, texture coordinates are flipped to glTF's top-left origin, viewpoints become cameras, lights become lights, and ROUTEs from a `TimeSensor` through position / orientation interpolators to a `Transform` become animations. `Inline` files and textures come from `opts.files` / `opts.resolve`. Binary X3D (`.x3db`) is `UNSUPPORTED`. ```luau local wrl = [[#VRML V2.0 utf8 DEF Red Transform { translation 2 0 0 children Shape { appearance Appearance { material Material { diffuseColor 1 0 0 } } geometry Box { size 1 2 3 } } } DEF Cam Viewpoint { position 0 0 10 } ]] local scene = assert(F.load(wrl)) -- detected by the #VRML header assert(scene.meta.source.format == "vrml" and #scene.cameras == 1) assert(scene.nodes[1].name == "Red" and scene.materials[1].baseColor[1] == 1) local lo, hi = F.ops.mesh.bounds(scene) assert(lo[1] == 1.5 and hi[1] == 2.5) -- the Box, moved by its Transform ``` Both write too: VRML97 text, X3D XML, or the classic X3D encoding. Shared meshes are written once and `USE`d; textures with bytes go into `opts.files`: ```luau local x3d = [[ ]] local quad = assert(F.load(x3d, { triangulate = false })) assert(quad.meshes[1].primitives[1].mode == "polygons" and quad.meshes[1].primitives[1].faces.count == 1) local out = assert(F.save(quad, nil, { format = "wrl" })) -- VRML97 assert(buffer.readstring(out, 0, 15) == "#VRML V2.0 utf8") local classic = assert(F.save(quad, nil, { format = "x3dv" })) -- the classic X3D encoding assert(F.load(classic, { triangulate = false }).meshes[1].primitives[1].faces.count == 1) ``` ## 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 | | `blocks` | `{ palette, data, blockEntities?, entities? }?` | Minecraft grids: the exact block state of every cell ([voxel.md](voxel.md)) | | `colors` | `buffer?` | true-colour grids (Qubicle): r, g, b, a bytes per cell | ```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) ``` ## Game models Game model formats load as Scenes too, with what games need: skins (joints + inverse bind matrices, `JOINTS_0` / `WEIGHTS_0`) and animations, vertex-animated models as morph targets. Units are as the game stores them, z up (`meta.up = "z"`). | Format | What loads | Animations | |---|---|---| | MD2 (Quake II) | one primitive; skins as texture URIs | every frame a morph target (weight k = 1 shows frame k); one animation per frame-name group (`run1`..`run6` -> `run`) | | MD3 (Quake III) | a primitive per surface; shaders as URIs; tags as nodes | frames as morph targets, tag motion, one animation | | MDL (Quake 1, Half-Life 1) | Quake: skins decoded through the palette; Half-Life: bones, body parts, textures with their own palettes | Quake: morph targets per frame group; Half-Life: every sequence | | MD5 (Doom 3 `.md5mesh` / `.md5anim`) | skeleton, weighted meshes, shaders as URIs | the `.md5anim` files named in `anims` | | SMD (Valve, read + write) | skeleton, weight links, a primitive per material | the skeleton frames | | BSP (Quake 1 / 2 / 3, Half-Life) | each model a mesh, a primitive per texture (and Quake III lightmap); entities in `meta.entities` | - | | VBSP (Source 19 / 20 / 21) | each model a mesh, a primitive per material, displacements; static props as nodes; lights; entities; the pak lump | - | | VMF (Hammer, read + write) | a mesh per entity with solids, displacements; point entities as nodes; cameras; visgroups | - | | BSP (Quake 1 / 2 / 3, Half-Life; BSP2, 2PSB) | each model a mesh, a primitive per texture; lightmaps as `TEXCOORD_1`; entities in `meta.entities`; tree, hulls and PVS in `meta.bsp` | - | ```luau local tank = assert(F.model.load(md2Bytes)) local prim = tank.meshes[1].primitives[1] assert(#prim.targets == 5 and #tank.meshes[1].weights == 5) -- 5 frames assert(tank.animations[1].name == "stand" and tank.animations[2].name == "run") assert(tank.textures[1].uri == "models/tank/skin.pcx") assert(tank.meta.up == "z") ``` MD5 animations are separate files: name them in `anims` (they are found through `files` or `resolve`, which the api fills in for paths), or load a `.md5anim` alone as a skeleton with its animation: ```luau local imp = assert(F.model.load(md5meshBytes, { anims = { "idle.md5anim" }, files = { ["idle.md5anim"] = md5animBytes } })) assert(#imp.skins == 1 and imp.animations[1].name == "idle") assert(imp.meshes[1].primitives[1].attributes.JOINTS_0) local idle = assert(F.model.load(md5animBytes, { format = "md5" })) assert(#idle.animations == 1) ``` Quake's palette (`gfx/palette.lmp`, inside the game's PAK) is not redistributable, so Quake MDL skins and Quake 1 BSP textures need it passed in (`palette`, or through `files` / `resolve`); without it they decode as grey ramps (`meta.source.palette = false`). Half-Life models and maps carry their own palettes. ```luau local map = assert(F.model.load(bspBytes)) -- a Half-Life map assert(map.meta.source.variant == "halflife") assert(map.meta.entities[1].classname == "worldspawn") local world = map.meshes[1] -- "world"; brush entities are "*1", "*2", ... assert(world.name == "world" and map.meshes[2].name == "*1") local barney = assert(F.model.load(smdBytes)) local again = assert(F.save(barney, nil, { format = "smd" })) -- SMD writes back (bind pose, weights) assert(F.model.load(again).skins[1]) ``` ## Build engine maps Duke Nukem 3D / Shadow Warrior `.map` files (versions 7-9; the text Quake `.map` is a different format, told apart by content) load as one mesh: floors and ceilings triangulated with their slopes, walls with upper and lower parts at red walls (and masked walls), a primitive per surface kind and tile (`extras.build = { kind, tile }`); materials and textures are named `tile`. Sprites become nodes under the map with their tile in `extras.build.tile` (the raw sprite in `extras.build.sprite`), and the player start is the node `start`. Coordinates turn z up (Build's y and z point down), z is divided by 16 so all axes share Build's xy unit, and `scale` multiplies everything. `tiles` (tile number to Image, e.g. from an ART file) gives the texture sizes for the UVs and attaches the images. The raw sector, wall and sprite tables stay in `meta.build`, and saving writes them back: ```luau local map = assert(F.model.load(buildmapBytes, { scale = 1 / 512 })) local level = map.meta.build assert(level.version == 7 and #level.sectors == 3) assert(map.nodes[2].name == "start" and map.nodes[3].extras.build.tile == level.sprites[1].picnum) local again = assert(F.save(map, nil, { format = "buildmap" })) assert(buffer.tostring(again) == buffer.tostring(buildmapBytes)) local Build = F.format("buildmap") -- the floor height under a point, slopes included assert(Build.slopeZ(level, 0, true, 100, 100) == level.sectors[1].floorz) ``` ## Source engine models (MDL v44-49) `sourcemdl` reads Source studio models (Half-Life 2 to CS:GO-era v44-49; GoldSrc v10 stays `mdl`). The geometry is in sibling files found through `files` / `resolve` (or `vvd` / `vtx` / `phy` / `ani` buffers): `.vvd` vertices, `.dx90.vtx` (else `.dx80` / `.sw` / `.vtx`) strips, optional `.phy` collision and the `.ani` animation blocks; `` is the stem of `opts.name`, else of the name stored in the MDL. Without them the Scene has the skeleton and the animations only (`meta.source.warnings` says what was missing). - Bones become a skin (`poseToBone` as the inverse bind matrices); procedural bones (jiggle, aim-at, ...) are data in the joint nodes' `extras.procedural`. - Each body part model is a mesh (one primitive per studio mesh); `bodies` picks the model per body part for the nodes (default 1), the others are in `scene.meshes` and `meta.source.bodyParts`. `lod` picks the LOD of `prim.indices`; every LOD's indices are in `prim.extras.lods`. - Flexes are morph targets (stereo flexes split by side), named in `mesh.extras.targetNames`; attachments are nodes under their bones; hitboxes, sequences (activities, events, blends), pose parameters and flex rules are in `meta.source`. - Each animation (decoded from the run-length / Quaternion48 / 64 data, sections and `.ani` blocks; delta animations added to the rest pose) is named after the first sequence that plays it. - Materials: each texture name is looked up as `materials/.vmt`; `$basetexture` / `$bumpmap` become `.vtf` texture URIs (`F.model.loadTextures` with a `resolve` for the game's files decodes them), `$translucent` / `$alphatest` / `$nocull` / `$color` map to the material, and every parameter is kept in `material.extras.vmt`. ```luau local files = { ["model.vvd"] = sourceVvdBytes, ["model.dx90.vtx"] = sourceVtxBytes, ["model.phy"] = sourcePhyBytes, ["materials/models/test/skin_a.vmt"] = skinVmtText, } local model = assert(F.model.load(sourceMdlBytes, { name = "model.mdl", files = files })) local src = model.meta.source assert(src.format == "sourcemdl" and src.version == 49 and model.meta.up == "z") assert(#model.skins[1].joints == 6) local body = model.meshes[src.bodyParts[1].models[1].mesh] assert(#body.primitives == 2 and body.extras.targetNames[1] == "AU1L") assert(#body.primitives[1].extras.lods == 2) assert(model.animations[1].name == "idle" and src.sequences[1].activity == "ACT_IDLE") local skinA = model.materials[1] assert(model.textures[skinA.baseColorTexture.texture].uri == "materials/models/test/skin_a.vtf") assert(#src.physics.solids[1].hulls == 2) ``` ### Source maps (VBSP) Compiled Source maps (`.bsp` with the `VBSP` magic: HL2, TF2, Portal, L4D2, CS:GO) load as one mesh per brush model (`world`, `*1`, ...) with a primitive per material; brush entities place their model by `origin` / `angles`. Displacements are tessellated (their blend alpha is the `_BLEND` attribute), tool faces (nodraw, skip, hint, sky) are left out unless `tools = true`. Static props are nodes with `extras.model` (the `.mdl` path) and `extras.vbsp` (skin, solid, fade, ...); `light`, `light_spot` and `light_environment` become lights. Entities are `meta.entities` (KeyValues objects: a repeated output is an array), the pak lump `meta.pak` (an Archive), and a material's texture is `materials/.vtf`, embedded when the pak has it. LZMA-compressed lumps and the L4D2 lump header are read; lightmaps and visibility are not. ```luau local room = assert(F.model.load(vbspBytes, { name = "room.bsp" })) assert(room.meta.source.format == "vbsp" and room.meta.source.version == 21) local props = {} for _, n in room.nodes do if n.extras and n.extras.model then table.insert(props, n.extras.model) end end assert(props[1] == "models/props_junk/wood_crate001a.mdl") assert(room.meta.entities[1].classname == "worldspawn") assert(room.meta.pak:read("materials/custom/note.txt")) ``` ### Hammer maps (VMF) `.vmf` sources load like `.map` files: a mesh per entity with solids (Valve 220 texture axes through `codecs/model/Brush`), displacements tessellated as the compiler does (a brush with a displaced side keeps only its displaced sides), point entities as nodes (`extras.model` for props), Hammer cameras as cameras. `tools/*` materials are left out unless `tools = true`; texture sizes come from `textureSizes`, or `materials/.vtf` through `resolve` and `decodeImage`, else 512 x 512. `meta.entities` holds the keys (outputs under `connections`), `meta.visgroups`, `meta.groups` and `meta.solids` the editor data, and `meta.vmf` the parsed document, which `F.save` writes back exactly as Hammer lays it out. `F.format("vmf")` builds documents: `document`, `world`, `box`, `solid`, `entity`. ```luau local hammer = assert(F.model.load(vmfText, { format = "vmf" })) assert(hammer.meta.entities[1].classname == "worldspawn" and hammer.meta.visgroups[1].name == "Walls") assert(#hammer.cameras == 2) assert(F.saveString(hammer, { format = "vmf" }) == vmfText) -- unchanged documents write back byte for byte local Vmf = F.format("vmf") local doc = Vmf.document({ skyname = "sky_day01_01" }) table.insert(Vmf.world(doc), Vmf.box({ -128, -128, -16 }, { 128, 128, 0 }, "DEV/DEV_MEASUREGENERIC01B")) Vmf.entity(doc, { { "classname", "info_player_start" }, { "origin", "0 0 8" } }) local built = assert(F.model.load(assert(F.saveString(doc, { format = "vmf" })), { format = "vmf" })) assert(#built.meshes[1].primitives == 1 and built.meta.entities[2].classname == "info_player_start") ``` ## Doom maps (UDMF) Doom-engine maps load as Scenes (z up, map units): floors and ceilings triangulated from the sector outlines, walls with vanilla texture alignment, things as child nodes standing on their floor. Maps inside a WAD (binary lumps or a UDMF `TEXTMAP`) load through `F.format("wad").map(wad, name)` (see the archive page); a standalone UDMF text (`.udmf`, or a `TEXTMAP` lump saved alone) loads directly, with texture sizes from `textureSize` (else 64 x 128 walls and 64 x 64 flats) and the textures as URIs. `F.format("udmf").data` gives the tables: every UDMF block keeps its fields as written (`fields`, lower-case keys: namespace and `user_` keys too), flags are rebuilt in the binary layout (Doom bits for the Doom / Heretic / Strife namespaces, Hexen bits otherwise), and unknown blocks stay in `blocks`. ```luau local room = assert(F.model.load(udmfText)) assert(room.meta.source.format == "udmf" and room.meta.source.namespace == "ZDoom") assert(room.nodes[3].translation[3] == 40) -- a thing 8 units above the 32-unit pillar local Udmf = F.format("udmf") local data = assert(Udmf.data(F.Bytes.reader(buffer.fromstring(udmfText)))) assert(data.sectors[1].fields.user_gravity == 0.5) assert(data.linedefs[4].tag == 7 and data.blocks[1].type == "vavoombox") ``` ## Doom 3 / Quake 4 levels A compiled `.proc` file (dmap's render geometry: `mapProcFile003`, Quake 4's `PROC "4"`) loads as a Scene: each model (the areas `_area0`, `_area1`, ... and the inline models of entities) is a mesh with a primitive per surface (positions, normals, texture coordinates, Quake 4 vertex colours as `COLOR_0`) and a child node of the root; the materials are URIs. id Tech 4 triangles are clockwise-front, so they are turned counter-clockwise. The portals between areas, the BSP nodes and the shadow models load as data in `meta.proc`. The editor's `.map` (`Version 2` for Doom 3, `Version 3` for Quake 4; told apart from Quake's `.map` by that line) loads as a Scene too: `brushDef3` brushes (plane equations) become polygons through the same brush clipper as the Quake maps, with Doom 3's texture matrices, and `patchDef2` / `patchDef3` surfaces become triangle grids (patchDef3 at its stored subdivisions, patchDef2 at `patchLevel` segments per sub-patch). Each entity is a node with its keys in `extras.keys`; entities with geometry get a mesh (in world coordinates), point entities their `origin`, `rotation` or `angle`. `skip` leaves materials out (`"textures/common/caulk"`), `hull` drops faces hidden inside other brushes. ```luau local level = assert(F.model.load(procText)) assert(level.meshes[1].name == "_area0" and level.meta.up == "z") local proc = level.meta.proc assert(proc.areas == 2 and proc.portals[1].positive == 1 and #proc.portals[1].points == 12) assert(proc.nodes[1].negative == -1) -- < 0: area -1 - n; > 0: a node (1-based); 0: solid assert(level.materials[1].name == "textures/base_wall/lfwall1") local room = assert(F.model.load(d3mapText, { name = "room.map", skip = { "textures/common/caulk" } })) assert(room.meta.source.format == "d3map" and room.meta.source.variant == "doom3") assert(#room.meshes[1].primitives == 1) -- the floor material; caulk skipped local start = room.nodes[3] assert(start.extras.classname == "info_player_start" and start.translation[3] == 1) ``` ## Quake maps: editor `.map` and compiled BSP `model/map` reads and writes the editor maps of Quake, Half-Life (Valve 220), Quake II (with content / surface flags) and Quake III (`brushDef` brush primitives, `patchDef2` / `patchDef3` patches). Every entity is a node (child of the `map` root) with `extras.classname`, `extras.keys` (an ordered object) and `extras.brushes` (the brushes as written); entities with brushes get a mesh, a primitive per texture. Point entities stand at their `origin`. Brushes become polygons the way qbsp builds them (`codecs/model/Brush`; tested against ericw-tools); `hull = true` drops the faces inside or touching other brushes of the same entity, `merge = true` merges coplanar faces. Texture coordinates need texture sizes: they come from `textureSizes`, the worldspawn's WADs (`"wad"` key), Quake II `.wal` files or Quake III images (with `decodeImage`) through `files` / `resolve`; unknown textures count as 64 x 64 (`material.extras.map.sizeKnown = false`). ```luau local Map = F.format("map") local room = assert(F.model.load(roomMapText, { files = { ["gfx/tex.wad"] = texWadBytes }, hull = true })) assert(room.meta.source.variant == "quake" and room.meta.up == "z") local world = room.nodes[2] -- node 1 is the "map" root assert(world.extras.classname == "worldspawn" and world.mesh) local door = room.nodes[3] assert(door.name == "door1" and door.extras.keys.angle == "90") assert(room.materials[1].extras.map.sizeKnown) -- sizes from the WAD local start = room.nodes[4] -- a point entity at its origin assert(start.translation[1] == -128) start.translation = { 0, 0, 24 } -- edit and write back door.extras.keys.speed = "200" local text = buffer.tostring(assert(F.save(room, nil, { format = "map" }))) assert(string.find(text, '"origin" "0 0 24"', 1, true)) local valve = assert(F.save(room, nil, { format = "map", variant = "valve220" })) -- Quake standard -> Valve 220 axes assert(F.model.load(valve).meta.source.variant == "valve220") local parsed = assert(Map.parse(roomMapText)) -- the raw entities: keys, brushes, faces as written assert(#parsed.entities == 4 and parsed.entities[1].brushes[1].faces[1].texture) ``` Compiled `.bsp` maps carry what the engines need beyond the triangles. Quake 1 (BSP 29, BSP2, 2PSB), Half-Life and Quake II lightmaps (the first light style) are packed into one atlas texture named `"lightmap"`, mapped by `TEXCOORD_1` and named by each material's `extras.bsp.lightmap` (Quake III keeps its own 128 x 128 pages). Coloured Quake light comes from the map's `.lit` (`lit`, or `.lit` through `files` / `resolve` with `name`). The BSP tree, the collision hulls (Quake 1 clipnodes, Quake II / III brushes) and the visibility data are tables in `meta.bsp`, with point queries on the format module: ```luau local Bsp = F.format("bsp") local map = assert(F.model.load(roomBspBytes)) assert(map.meta.source.variant == "quake") local prim = map.meshes[1].primitives[1] assert(prim.attributes.TEXCOORD_1) -- lightmap coordinates local atlas = map.textures[map.materials[prim.material].extras.bsp.lightmap] assert(atlas.name == "lightmap" and atlas.image.width > 0) assert(Bsp.contents(map, -128, -128, 100) == -1) -- CONTENTS_EMPTY in the room assert(Bsp.contents(map, 0, 0, -8) == -2) -- CONTENTS_SOLID: the floor assert(Bsp.contents(map, -250, 0, 100, 1) == -2) -- hull 1 (player size) touches the wall local here = assert(Bsp.leafAt(map, -128, -128, 24)) local seen = assert(Bsp.pvs(map, here)) -- leaves potentially visible from here assert(table.find(seen, Bsp.leafAt(map, 0, 0, 220))) assert(#map.meta.bsp.planes > 0 and #map.meta.bsp.clipnodes > 0) ``` ## 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") ``` ## LightWave, DirectX and Inter-Quake models **LightWave objects** (`.lwo`: LWO2 and the older LWOB; Modo's `.lxo`) give one node per layer (its pivot as the translation, parents by layer index), one mesh per layer and one primitive per surface. LightWave is left-handed: z is negated and the winding reversed on load, so the scene is glTF's right-handed y up. UV maps become `TEXCOORD_n` (one set per map name), the colour map a surface names becomes `COLOR_0`, weight maps `_WEIGHT_n` and morph maps morph targets (names in `prim.extras.lwo.maps` / `mesh.extras.targetNames`). Surface values and texture blocks are in `material.extras.lwo`; image textures keep only the file name as `uri` (`F.model.loadTextures` reads them). Subdivision cages (`PTCH` / `SUBD`) stay polygons with `prim.extras.lwo.subdivision = true`. ```luau -- a one-triangle LWO2 file, built by hand (IFF chunks, big-endian) local function be(n, bytes) local s = "" for i = bytes - 1, 0, -1 do s ..= string.char(bit32.band(bit32.rshift(n, i * 8), 255)) end return s end local function f4(x) local b = buffer.create(4) buffer.writef32(b, 0, x) return be(buffer.readu32(b, 0), 4) end local function chunk(id, body) return id .. be(#body, 4) .. body end local body = "LWO2" .. chunk("TAGS", "Red\0") .. chunk("LAYR", be(0, 4) .. f4(0) .. f4(0) .. f4(0) .. "Body\0\0") .. chunk("PNTS", f4(0) .. f4(0) .. f4(0) .. f4(1) .. f4(0) .. f4(0) .. f4(0) .. f4(1) .. f4(0)) .. chunk("POLS", "FACE" .. be(3, 2) .. be(0, 2) .. be(1, 2) .. be(2, 2)) .. chunk("PTAG", "SURF" .. be(0, 4)) .. chunk("SURF", "Red\0\0\0" .. "COLR" .. be(14, 2) .. f4(1) .. f4(0) .. f4(0) .. be(0, 2)) local scene = assert(F.load("FORM" .. be(#body, 4) .. body)) assert(scene.nodes[1].name == "Body" and scene.meta.source.version == "LWO2") assert(scene.materials[1].name == "Red" and scene.materials[1].baseColor[1] == 1) assert(scene.meshes[1].primitives[1].indices.count == 3) ``` **DirectX `.x`** files (text, binary and MSZIP-compressed, 32- or 64-bit floats) give the frame hierarchy, one primitive per material, materials with their texture file names, skins (`SkinWeights`) and animation sets. Direct3D is left-handed too: z is negated and the winding reversed. Key times are in seconds (`AnimTicksPerSecond`, default 4800). ```luau local text = [[xof 0303txt 0032 Material Wood { 0.8; 0.6; 0.4; 1.0;; 20.0; 0.1; 0.1; 0.1;; 0.0; 0.0; 0.0;; TextureFilename { "wood.png"; } } Frame Root { FrameTransformMatrix { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,5,1;; } Mesh Tri { 3; 0;0;0;, 1;0;0;, 0;1;0;; 1; 3;0,1,2;; MeshMaterialList { 1; 1; 0;; { Wood } } } } ]] local scene = assert(F.load(text, { format = "x" })) local root = scene.nodes[1] assert(root.name == "Root" and root.translation[3] == -5) -- z negated assert(scene.materials[1].name == "Wood") assert(scene.textures[scene.materials[1].baseColorTexture.texture].uri == "wood.png") local glb = assert(F.save(scene, nil, { format = "glb" })) ``` **IQM** (Inter-Quake Model, version 2) reads and writes meshes, every vertex array, the skeleton (a node per joint and one skin), animations (dequantized frames as translation / rotation / scale channels, loop flags and frame ranges in `meta.source.animations`) and per-frame bounds. IQM is z-up (`meta.up = "z"`); nothing is rotated either way. The writer turns any Scene's triangles into IQM meshes, merges the skins into one skeleton and samples each animation at its key spacing when uniform (else `opts.framerate`, default 30 frames per second). ```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") local iqm = assert(F.save(scene, nil, { format = "iqm" })) local back = assert(F.load(iqm)) assert(back.meta.source.format == "iqm" and back.meshes[1].name == "tri") assert(back.meshes[1].primitives[1].indices.count == 3) ``` ## Blender (.blend) `.blend` files load read only, from every Blender version since 2.4x: plain, gzip (before 3.0) or zstd (3.0+) compressed, 32 or 64-bit pointers, either byte order, and the 5.0+ header. Each file is read through its own SDNA (the struct catalogue Blender writes into every file), so fields are found by name whatever version wrote them. The current scene loads: objects (transforms with euler orders, quaternions, axis angles, delta transforms, the parent inverse, bone parents), collections as nodes (`collections = false` flattens them), meshes, materials, images, cameras, lights, armatures, skins, shape keys and actions. Blender is z-up (`meta.up = "z"`). | Part | What loads | |---|---| | Meshes | every storage generation: MFace (before 2.63 and the 2.7x "legacy mesh format"), MPoly / MLoop (2.63 - 3.x), attribute layers (`position`, `.corner_vert`, ... 3.x - 4.x), AttributeStorage (5.x); a primitive per used material slot, `triangulate = false` keeps the faces (`"polygons"`) | | Mesh data | UV maps (`TEXCOORD_n`, v flipped to glTF's origin), colour attributes (byte and float, point and corner) as linear `COLOR_n`, corner normals from Blender's smooth fans (sharp edges / faces, auto smooth before 4.1) or the stored custom normals, weights (`JOINTS_0` / `WEIGHTS_0`: the 4 largest deform-bone groups, normalized) | | Materials | the Principled BSDF (base colour, metallic, roughness, alpha, emission and its strength, image textures on Base Color / Emission, Normal through a Normal Map node, Roughness / Metallic through Separate RGB), else the legacy `r, g, b` colour | | Images | packed images as encoded bytes (`texture.data`), external ones as `uri` (relative to the `.blend`, bytes through `files` / `resolve`) | | Cameras, lights | perspective (`yfov` from the lens, sensor fit and render aspect) / orthographic; point, sun, spot (watts to candela / lux as Blender's glTF exporter does); area lights are skipped (`meta.source.skippedLights`) | | Armatures | a joint node per bone (rest pose times the saved pose), one skin per deformed mesh | | Animation | the active action of each object, armature (pose bones) and shape key set, f-curves evaluated (constant, linear, bezier, easing; extrapolation) and sampled once per frame (`sampleStep`) into channels; time 0 is `meta.source.frameZero` at `meta.source.fps` | | Not loaded | modifiers (listed per object in `meta.source.modifiers`, never applied), curves, text, metaballs, grease pencil, volumes, NLA strips, drivers, constraints, linked libraries | ```luau local scene = assert(F.model.load(riggedBlendBytes)) local src = scene.meta.source assert(src.format == "blend" and src.version >= 500 and src.compression == "zstd") assert(scene.meta.up == "z" and #scene.skins == 1 and #scene.animations == 1) local tube = scene.meshes[1].primitives[1] assert(tube.attributes.JOINTS_0 and tube.attributes.WEIGHTS_0 and #tube.targets == 1) assert(scene.materials[1].name == "Skin" and scene.materials[1].roughness > 0.69) print(src.modifiers.Tube[1].type) -- Armature (not applied) ``` Anything else in the file is reachable through the container: `F.format("blend").open` parses the blocks and the SDNA, and every struct reads by field name (`get`, `num`, `str`, `vec`, `sub`, `deref`, `list` for ListBase, `array` and `pointers` behind pointers). ```luau local blend = F.format("blend") local file = assert(blend.open(F.Bytes.reader(riggedBlendBytes))) local Blend = blend.container for _, block in Blend.blocks(file, "OB") do local ob = assert(Blend.struct(file, block)) print(ob:idName(), ob:num("type"), ob:vec("loc")[3]) -- Rig 25 0 / Tube 1 0 end local arm = assert(Blend.struct(file, Blend.blocks(file, "AR")[1])) local bones = arm:list("bonebase") assert(bones[1]:str("name") == "lower" and bones[1]:list("childbase")[1]:str("name") == "upper") ``` ## 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 | | LightWave LWO (LWO2, LWOB, Modo LXOB) | yes | | layers, vertex maps, surfaces; see below | | DirectX .x (text, binary, MSZIP) | yes | | frames, materials, skins, animation | | IQM (Inter-Quake Model) | yes | yes | skeleton, skin, sampled animations, bounds | | Minecraft `.schem` / `.schematic` / `.litematic` | yes | yes | block grids, see [voxel.md](voxel.md) | | Minecraft region `.mca` | yes | | block grids of chosen chunks, see [voxel.md](voxel.md) | | Qubicle `.qb` | yes | yes | true-colour grids, see [voxel.md](voxel.md) | | PMX / PMD (MikuMikuDance) | yes | | bones + skin, vertex morphs, MMD materials and physics in extras | | VRML97 (WRL / WRZ) | yes | yes | primitives, PROTO, Inline, ROUTE animations, cameras, lights | | X3D (XML / classic) | yes | yes | the VRML reader plus the X3D triangle / quad / line sets; no binary `.x3db` | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | | MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | | Build engine MAP (v7-9) | yes | yes | sloped sectors, walls, sprites as nodes, raw tables in `meta.build`; see "Build engine maps" above | | Source MDL (v44-49) + VVD / VTX / PHY | yes | - | skeleton, body parts, LODs, flexes, animations, VMT materials: see above | | MD2, MD3, MDL, MD5, BSP, VBSP | yes | - | game models and maps: see "Game models" above | | VMF | yes | yes (round trip, builders) | Hammer maps: see "Hammer maps (VMF)" above | | MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above; BSP lightmaps, hulls, PVS: "Quake maps" | | Quake / Half-Life / Quake II / Quake III `.map` | yes | yes | entities as nodes, brushes CSG'd, patches: see "Quake maps" | | SMD | yes | yes | Valve studiomdl data | | Doom 3 / Quake 4 `.proc` | yes | | render geometry per area, portals and BSP nodes as data | | Doom 3 / Quake 4 `.map` (d3map) | yes | | brushDef3, patchDef2 / 3, entities as nodes | | UDMF (`.udmf`, `TEXTMAP`) | yes | | Doom maps as text: see "Doom maps (UDMF)" above | | Blender `.blend` | yes | | 2.4x - 5.x, compressed; meshes of every generation, materials, skins, shape keys, actions; see "Blender" above | | Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) | | Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.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.