834 lines
47 KiB
Markdown
834 lines
47 KiB
Markdown
# 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,
|
|
[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):
|
|
|
|
<!-- 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`.
|
|
|
|
### 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_<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, 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:
|
|
|
|
<!-- 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" }))
|
|
```
|
|
|
|
## 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 = [[<X3D profile="Interchange" version="3.3"><Scene>
|
|
<Shape><IndexedFaceSet coordIndex="0 1 2 3 -1"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0"/></IndexedFaceSet></Shape>
|
|
</Scene></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` | - |
|
|
|
|
```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<n>`. 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): `<name>.vvd`
|
|
vertices, `<name>.dx90.vtx` (else `.dx80` / `.sw` / `.vtx`) strips, optional `<name>.phy` collision and the `.ani`
|
|
animation blocks; `<name>` 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/<cdmaterials dir><name>.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)
|
|
```
|
|
|
|
## 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)
|
|
```
|
|
|
|
## 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 |
|
|
| SMD | yes | yes | Valve studiomdl data |
|
|
| 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.
|