merge ws/3d3

This commit is contained in:
4DBug committed 2026-10-31 15:39:55 -05:00
commit 47345b2c8f
96 files changed
+24729 -21

No files matched your search

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