diff --git a/docs/FORMATS.md b/docs/FORMATS.md index c5bd460..30d1a59 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -34,12 +34,14 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | +| model | 3ds | .3ds | yes | yes | materials: true, textures: true, animation: true, cameras: true, lights: true, instancing: true | `tests/model/3ds.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | b3d | .b3d | yes | - | materials: true, textures: true, skins: true, animation: true, colors: true | `tests/model/b3d.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, draco: true | `tests/model/gltf.luau` | | model | ldraw | .ldr .mpd .dat | yes | - | materials: true, lines: true, instancing: true | `tests/model/ldraw.luau` | +| model | ms3d | .ms3d | yes | yes | materials: true, skins: true, animation: true | `tests/model/ms3d.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 9538560..f4f00de 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -1,8 +1,8 @@ # Scene (3D models) and Voxels -Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, B3D, LDraw) loads as one `Scene`, a structure -shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, -textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel +Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D, B3D, LDraw) loads as one +`Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), +PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. ```luau @@ -309,7 +309,7 @@ the binary container. | 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 | see [FORMATS.md](../FORMATS.md) and the format's options | | +| PLY, OFF, FBX, DAE, 3MF, USDA, VOX, 3DS, MS3D | see [FORMATS.md](../FORMATS.md) and the format's options | | Mesh-only writers (STL, PLY, OFF, OBJ) bake the node transforms into the vertices. Extra files go into the `opts.files` table you pass, named after `opts.name`: @@ -469,6 +469,66 @@ assert(#flat.meshes == 1) -- one mesh, one primitiv `upright = false` leaves out the root node (LDraw's axes as stored, `meta.source.up = "-y"`); `ldconfig` takes the text of another LDConfig.ldr, and `color` the colour of code 16 at the top (default 16, "Main_Colour"). +## 3D Studio (3DS) + +`.3ds` files load with their keyframer: the node hierarchy, pivots, instances of one object, the first key of each +track as the node's TRS and, when tracks have several keys, one animation (frames / `opts.fps`, default 30). +Normals come from the smoothing groups (`normals = false` keeps the file's shared vertices); the groups stay in +`prim.extras["3ds"].smoothing` and are written back. Materials are Phong (the raw values in `extras["3ds"]`), texture +maps become textures with a `uri` only (`F.model.loadTextures` reads them). Cameras get `yfov` from the lens at a +4:3 aspect and look at their target; omni lights are `point`, spotlights `spot`. The writer puts one object per mesh +(split past 65535 vertices), its first instance's world matrix as the mesh matrix, and the scene's first animation +into the keyframer. + +```luau +local S = F.Types.Scene +local pos = S.accessor(nil, "f32", 3, 3) +for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do + buffer.writef32(pos.data, (i - 1) * 4, v) +end +local scene = S.fromPrimitive({ attributes = { POSITION = pos }, mode = "triangles", material = 1 }, "tri") +scene.materials[1] = S.material("red") +scene.materials[1].baseColor = { 1, 0, 0, 1 } +scene.nodes[1].translation = { 0, 0, 2 } +local bytes = assert(F.save(scene, nil, { format = "3ds" })) +local back = assert(F.load(bytes)) -- detected by its 0x4D4D main chunk +assert(back.meta.source.format == "3ds" and back.meta.up == "z") +local prim = back.meshes[1].primitives[1] +assert(prim.attributes.NORMAL and prim.extras["3ds"].smoothing[1] == 1) +assert(back.materials[prim.material].baseColor[1] == 1) +assert(back.nodes[1].translation[3] == 2) -- the keyframer keeps the node transform +``` + +## MilkShape 3D (MS3D) + +Each group loads as a node with one mesh (per-corner normals and uvs, so vertices are split per corner); joints become +nodes with a skin (`JOINTS_0` / `WEIGHTS_0`, up to four bones from the 1.8 vertex extras) and their keys one +animation. Comments, joint colours and the other MilkShape fields stay in `extras.ms3d` / `meta.source`. The writer +puts every placed primitive in a group, the first skin's joints plus every node the first animation moves (meshes +under them are bound rigidly) into the skeleton, and the weights in percent. + +```luau +local S = F.Types.Scene +local pos = S.accessor(nil, "f32", 3, 3) +for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do + buffer.writef32(pos.data, (i - 1) * 4, v) +end +local scene = S.fromPrimitive({ attributes = { POSITION = pos }, mode = "triangles" }, "tri") +-- spin the node a quarter turn about z in one second +local times = S.accessor(nil, "f32", 1, 2) +buffer.writef32(times.data, 4, 1) +local turns = S.accessor(nil, "f32", 4, 2) +for i, v in { 0, 0, 0, 1, 0, 0, math.sqrt(0.5), math.sqrt(0.5) } do + buffer.writef32(turns.data, (i - 1) * 4, v) +end +scene.animations[1] = { channels = { { node = 1, path = "rotation", input = times, output = turns, interpolation = "LINEAR" } } } +local back = assert(F.load(assert(F.save(scene, nil, { format = "ms3d" })))) +assert(back.meta.source.format == "ms3d" and #back.skins == 1) -- the animated node became a joint +local prim = back.meshes[1].primitives[1] +assert(prim.attributes.JOINTS_0 and prim.attributes.NORMAL) +assert(back.animations[1].channels[1].path == "rotation") +``` + ## Formats | Format | Read | Write | Notes | @@ -485,6 +545,8 @@ text of another LDConfig.ldr, and `color` the colour of code 16 at the top (defa | VOX | yes | yes | voxel grids, scene graph, materials | | B3D (Blitz3D) | yes | | brushes, textures, skins, keyframe animation; left-handed source mirrored to glTF's frame | | LDraw (LDR / DAT / MPD) | yes | | parts as shared meshes per colour, sub-models as nodes, BFC, LDConfig colours, `files` / `resolve` for the library | +| 3DS | yes | yes | keyframer hierarchy and animation, Phong materials, texture names, cameras, lights; Z up | +| MS3D (MilkShape 3D) | yes | yes | groups, materials, joints -> skin + animation, comments | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6deafef..8e5c997 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -362,6 +362,18 @@ local list: { Entry } = { return require("@formats/video/y4m") end, }, + { + name = "3ds", + category = "model", + path = "model/3ds", + extensions = { "3ds" }, + mime = { "application/x-3ds", "image/x-3ds" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, + load = function() + return require("@formats/model/3ds") + end, + }, { name = "3mf", category = "model", @@ -434,6 +446,18 @@ local list: { Entry } = { return require("@formats/model/ldraw") end, }, + { + name = "ms3d", + category = "model", + path = "model/ms3d", + extensions = { "ms3d" }, + mime = { "application/x-ms3d" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true }, + load = function() + return require("@formats/model/ms3d") + end, + }, { name = "obj", category = "model", diff --git a/src/Formats/model/3ds/Build.luau b/src/Formats/model/3ds/Build.luau new file mode 100644 index 0000000..a652cf2 --- /dev/null +++ b/src/Formats/model/3ds/Build.luau @@ -0,0 +1,663 @@ +--!strict +-- model/3ds/Build: model/3ds/Read's chunk tables -> Types.Scene. The 3DS model: mesh vertices are stored in world +-- space and the mesh matrix (0x4160) is the object's world transform; the keyframer places node(t) = parent(t) * +-- T(pos) * R(rot) * S(scale) and draws a mesh at node(t) * T(-pivot) * inverse(mesh matrix) (a mirroring mesh matrix +-- also flips x, as 3ds Max writes it and assimp reads it). Rotation keys are axis / angle deltas from the previous key +-- (the angle measured clockwise). Cameras and spotlights look at their target node's position, with the camera's +-- roll about the view axis. Smoothing groups give the normals (corners of faces that share a group and a position +-- are averaged; group 0 is flat). Times are frame / fps. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Read = require("@formats/model/3ds/Read") + +local Build = {} + +local S = Types.Scene +local readf32, readu16, readu32, writef32, writeu32 = buffer.readf32, buffer.readu16, buffer.readu32, buffer.writef32, buffer.writeu32 +local band = bit32.band +local sqrt, abs = math.sqrt, math.abs + +export type Options = { normals: boolean?, flipV: boolean?, fps: number? } + +-- ------------------------------------------------------------------------------------------------ math +-- the mesh matrix (X, Y, Z axes, origin) as a column-major 4x4 +local function meshMatrix(m: { number }?): { number } + if not m then + return Mat4.identity() + end + return { m[1], m[2], m[3], 0, m[4], m[5], m[6], 0, m[7], m[8], m[9], 0, m[10], m[11], m[12], 1 } +end +Build.meshMatrix = meshMatrix + +local function det3(m: { number }): number + return m[1] * (m[6] * m[11] - m[7] * m[10]) - m[5] * (m[2] * m[11] - m[3] * m[10]) + m[9] * (m[2] * m[7] - m[3] * m[6]) +end +Build.det3 = det3 + +-- q(a) * q(b) +local function qmul(a: { number }, b: { number }): { number } + local ax, ay, az, aw = a[1], a[2], a[3], a[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + return { + aw * bx + ax * bw + ay * bz - az * by, + aw * by - ax * bz + ay * bw + az * bx, + aw * bz + ax * by - ay * bx + az * bw, + aw * bw - ax * bx - ay * by - az * bz, + } +end +Build.qmul = qmul + +-- a rotation key (angle in radians, axis) -> its quaternion (3DS angles turn clockwise) +local function keyQuat(angle: number, x: number, y: number, z: number): { number } + if x == 0 and y == 0 and z == 0 then + return { 0, 0, 0, 1 } + end + return Mat4.axisAngle(x, y, z, -math.deg(angle)) +end + +local function normalize(x: number, y: number, z: number): (number, number, number, number) + local l = sqrt(x * x + y * y + z * z) + if l < 1e-30 then + return 0, 0, 0, 0 + end + return x / l, y / l, z / l, l +end + +-- lookAt(pos, target, rollDegrees) -> the rotation whose -Z looks from pos to target, +Y up (world up +Z) +function Build.lookAt(p: { number }, t: { number }, roll: number): { number } + local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3]) + if l == 0 then + fx, fy, fz = 0, 1, 0 + end + local ux, uy, uz = 0, 0, 1 + if abs(fz) > 0.999999 then + ux, uy, uz = 0, 1, 0 + end + -- right = forward x up, up = right x forward + local rx, ry, rz = normalize(fy * uz - fz * uy, fz * ux - fx * uz, fx * uy - fy * ux) + ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx + local a = math.rad(roll) + local c, s = math.cos(a), math.sin(a) + local Rx, Ry, Rz = c * rx + s * ux, c * ry + s * uy, c * rz + s * uz + local Ux, Uy, Uz = c * ux - s * rx, c * uy - s * ry, c * uz - s * rz + return Mat4.quat({ Rx, Ry, Rz, 0, Ux, Uy, Uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 }) +end + +-- ------------------------------------------------------------------------------------------------ accessors +local function floats(values: { number }, comps: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, #values // comps) + for i = 1, (#values // comps) * comps do + writef32(a.data, (i - 1) * 4, values[i]) + end + return a +end + +-- ------------------------------------------------------------------------------------------------ materials +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff" } + +local function materials(raw: Read.Raw, scene: Types.Scene): { [string]: number } + local byName: { [string]: number } = {} + local texByFile: { [string]: number } = {} + local function texture(m: Read.Map): Types.TextureRef? + local file = m.file + if not file or file == "" then + return nil + end + local ti = texByFile[file] + if not ti then + local ext = string.lower(string.match(file, "%.(%w+)$") or "") + local tiling = m.tiling or 0 + local wrap: any = if band(tiling, 0x10) ~= 0 then "clamp" elseif band(tiling, 0x2) ~= 0 then "mirror" else "repeat" + local tex: Types.Texture = { name = file, uri = file, mime = MIME[ext] :: string?, sampler = { wrapS = wrap, wrapT = wrap } } + table.insert(scene.textures, tex) + ti = #scene.textures + texByFile[file] = ti + end + local ref: Types.TextureRef = { texture = ti } + local us, vs, uo, vo, ang = m.uscale or 1, m.vscale or 1, m.uoffset or 0, m.voffset or 0, m.angle or 0 + if us ~= 1 or vs ~= 1 or uo ~= 0 or vo ~= 0 or ang ~= 0 then + ref.transform = { scale = { us, vs }, offset = { uo, vo }, rotation = math.rad(ang) } + end + return ref + end + for i, m in raw.materials do + local mat = S.material(m.name) + local d = m.diffuse or { 0.5, 0.5, 0.5 } + local transparency = math.clamp(m.transparency or 0, 0, 1) + mat.baseColor = { d[1], d[2], d[3], 1 - transparency } + mat.metallic = 0 + mat.roughness = math.clamp(1 - (m.shininess or 0), 0, 1) + local si = m.selfIllum or 0 + if si > 0 then + mat.emissive = { d[1] * si, d[2] * si, d[3] * si } + end + mat.alphaMode = if transparency > 0 then "blend" else "opaque" + mat.doubleSided = m.twoSided + local maps: { [string]: any } = {} + for kind, mp in m.maps do + local ref = texture(mp) + maps[kind] = { file = mp.file, strength = mp.strength, tiling = mp.tiling, uscale = mp.uscale, vscale = mp.vscale, uoffset = mp.uoffset, voffset = mp.voffset, angle = mp.angle, texture = ref and ref.texture } + if kind == "diffuse" then + mat.baseColorTexture = ref + elseif kind == "selfIllum" and ref then + mat.emissiveTexture = ref + if si <= 0 then + mat.emissive = { 1, 1, 1 } + end + end + end + mat.extras = { + ["3ds"] = { + ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, shininess = m.shininess, + shinStrength = m.shinStrength, transparency = m.transparency, selfIllum = m.selfIllum, + shading = m.shading, wire = m.wire, twoSided = m.twoSided, maps = maps, + }, + } + table.insert(scene.materials, mat) + local key = string.lower(m.name) + if byName[key] == nil then + byName[key] = i + end + end + return byName +end + +-- ------------------------------------------------------------------------------------------------ meshes +-- mesh(obj, xf, matByName, opts) -> a Types.Mesh of the object's faces (one primitive per material), vertices moved +-- by xf (world -> the node's local space) +local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [string]: number }, opts: Options): Types.Mesh + local nv, nf = m.nv, m.nf + local pos, faces = m.positions, m.faces + -- local positions + local lp = table.create(nv * 3, 0) + for v = 0, nv - 1 do + local x, y, z = Mat4.point(xf, readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)) + lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] = x, y, z + end + -- faces with valid corners, their materials + local fa, fb, fc = table.create(nf, 0), table.create(nf, 0), table.create(nf, 0) + local valid = table.create(nf, false) + for f = 0, nf - 1 do + local a, b, c = readu16(faces :: buffer, f * 8), readu16(faces :: buffer, f * 8 + 2), readu16(faces :: buffer, f * 8 + 4) + fa[f + 1], fb[f + 1], fc[f + 1] = a, b, c + valid[f + 1] = a < nv and b < nv and c < nv + end + local fmat = table.create(nf, 0) + for _, fm in m.faceMats do + local mi = matByName[string.lower(fm.name)] or 0 + for _, f in fm.faces do + if f < nf then + fmat[f + 1] = mi + end + end + end + local smooth = m.smoothing + local doNormals = opts.normals ~= false + -- face normals (area weighted) and the faces around each distinct position + local fn = table.create(nf * 3, 0) + local around: { [number]: { number } } = {} + local group = table.create(nv, 0) + if doNormals then + local keyToGroup: { [string]: number } = {} + for v = 0, nv - 1 do + local k = buffer.readstring(pos, v * 12, 12) + local g = keyToGroup[k] + if not g then + g = v + keyToGroup[k] = g + end + group[v + 1] = g + end + for f = 1, nf do + if valid[f] then + local a, b, c = fa[f] * 3, fb[f] * 3, fc[f] * 3 + local e1x, e1y, e1z = lp[b + 1] - lp[a + 1], lp[b + 2] - lp[a + 2], lp[b + 3] - lp[a + 3] + local e2x, e2y, e2z = lp[c + 1] - lp[a + 1], lp[c + 2] - lp[a + 2], lp[c + 3] - lp[a + 3] + fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { fa[f], fb[f], fc[f] } do + local g = group[v + 1] + local list = around[g] + if not list then + list = {} + around[g] = list + end + if list[#list] ~= f then + table.insert(list, f) + end + end + end + end + end + local function sgOf(f: number): number + return if smooth then readu32(smooth, (f - 1) * 4) else 1 + end + local function cornerNormal(f: number, v: number, sg: number): (number, number, number) + local x, y, z = fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] + if sg ~= 0 then + local sx, sy, sz = 0, 0, 0 + for _, g in around[group[v + 1]] do + if band(sgOf(g), sg) ~= 0 then + sx, sy, sz = sx + fn[g * 3 - 2], sy + fn[g * 3 - 1], sz + fn[g * 3] + end + end + local nx, ny, nz, l = normalize(sx, sy, sz) + if l > 0 then + return nx, ny, nz + end + end + local nx, ny, nz = normalize(x, y, z) + return nx, ny, nz + end + -- primitives in the order their material first appears + local order: { number } = {} + local byMat: { [number]: { number } } = {} + for f = 1, nf do + if valid[f] then + local mi = fmat[f] + if not byMat[mi] then + byMat[mi] = {} + table.insert(order, mi) + end + table.insert(byMat[mi], f) + end + end + local uvs, nuv = m.uvs, m.nuv + local flipV = opts.flipV ~= false + local out: Types.Mesh = { name = name, primitives = {} } + for _, mi in order do + local list = byMat[mi] + local remap: { [number]: number } = {} + local P: { number }, N: { number }, U: { number } = {}, {}, {} + local idx = table.create(#list * 3, 0) + local sgs = table.create(#list, 0) + local count = 0 + for i, f in list do + local sg = sgOf(f) + sgs[i] = sg + for k, v in { fa[f], fb[f], fc[f] } do + local key = if not doNormals then v elseif sg ~= 0 then v * 4294967296 + sg else -(f * 65536 + v + 1) + local o: number = remap[key] or -1 + if o < 0 then + o = count + count += 1 + remap[key] = o + P[o * 3 + 1], P[o * 3 + 2], P[o * 3 + 3] = lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] + if doNormals then + N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = cornerNormal(f, v, sg) + end + if uvs then + local u: number, w: number = 0, 0 + if v < nuv then + u = readf32(uvs, v * 8) + w = readf32(uvs, v * 8 + 4) + end + U[o * 2 + 1] = u + U[o * 2 + 2] = if flipV then 1 - w else w + end + end + idx[(i - 1) * 3 + k] = o + end + end + local ind = S.accessor(nil, "u32", 1, #idx) + for i, v in idx do + writeu32(ind.data, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { POSITION = floats(P, 3) }, + indices = ind, + mode = "triangles", + material = if mi > 0 then mi else nil, + extras = { ["3ds"] = { smoothing = sgs } }, + } + if doNormals then + prim.attributes.NORMAL = floats(N, 3) + end + if uvs then + prim.attributes.TEXCOORD_0 = floats(U, 2) + end + table.insert(out.primitives, prim) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ tracks +-- the value of a track at a frame (linear between keys, clamped at the ends) +local function evalTrack(t: Read.Track?, frame: number, default: { number }): { number } + if not t or #t.frames == 0 then + return default + end + local fr, vals, n = t.frames, t.values, t.size + local function at(k: number): { number } + local r = table.create(n, 0) + for c = 1, n do + r[c] = vals[(k - 1) * n + c] + end + return r + end + if frame <= fr[1] then + return at(1) + end + for k = 1, #fr - 1 do + local f0, f1 = fr[k], fr[k + 1] + if frame <= f1 then + local u = if f1 > f0 then (frame - f0) / (f1 - f0) else 1 + local a, b = at(k), at(k + 1) + for c = 1, n do + a[c] += (b[c] - a[c]) * u + end + return a + end + end + return at(#fr) +end + +local function first(t: Read.Track?, default: { number }): { number } + return evalTrack(t, -math.huge, default) +end + +local function scaleKey(v: { number }): { number } + return { if v[1] == 0 then 1 else v[1], if v[2] == 0 then 1 else v[2], if v[3] == 0 then 1 else v[3] } +end + +-- absolute rotations from a rotation track: times (frames), quaternions; deltas over ~180 degrees get extra keys +local function rotations(t: Read.Track): ({ number }, { { number } }) + local frames, quats = {}, {} + local acc: { number }? = nil + for k = 1, #t.frames do + local o = (k - 1) * 4 + local angle, x, y, z = t.values[o + 1], t.values[o + 2], t.values[o + 3], t.values[o + 4] + if acc == nil then + acc = keyQuat(angle, x, y, z) + else + local prev = acc :: { number } + local steps = math.clamp(math.ceil(abs(angle) / (math.pi * 0.9)), 1, 64) + local f0 = frames[#frames] + for s = 1, steps - 1 do + table.insert(frames, f0 + (t.frames[k] - f0) * s / steps) + table.insert(quats, qmul(prev, keyQuat(angle * s / steps, x, y, z))) + end + acc = qmul(prev, keyQuat(angle, x, y, z)) + end + local q = acc :: { number } + local n = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if n > 0 then + q = { q[1] / n, q[2] / n, q[3] / n, q[4] / n } + end + acc = q + table.insert(frames, t.frames[k]) + table.insert(quats, q) + end + return frames, quats +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene + local o: Options = opts or {} + local fps = o.fps or 30 + local scene = S.new() + local matByName = materials(raw, scene) + -- objects by name + local objByName: { [string]: Read.Object } = {} + for _, obj in raw.objects do + if objByName[obj.name] == nil then + objByName[obj.name] = obj + end + local low = string.lower(obj.name) + if objByName[low] == nil then + objByName[low] = obj + end + end + local function findObj(name: string): Read.Object? + return objByName[name] or objByName[string.lower(name)] + end + local meshCache: { [any]: number } = {} + local function meshOf(obj: Read.Object, pivot: { number }?, placed: boolean): number? + local m = obj.mesh + if not m or m.nf == 0 or not m.faces then + return nil + end + local pv = pivot or { 0, 0, 0 } + local key = obj.name .. (if placed then string.format("|%.9g|%.9g|%.9g", pv[1], pv[2], pv[3]) else "|free") + if meshCache[key] then + return meshCache[key] + end + local M = meshMatrix(m.matrix) + local inv = Mat4.inverse(M) or Mat4.identity() + local xf = inv + if placed then + if det3(M) < 0 then + xf = Mat4.mul(Mat4.scaling(-1, 1, 1), xf) + end + xf = Mat4.mul(Mat4.translation(-pv[1], -pv[2], -pv[3]), xf) + end + local me = mesh(obj.name, m, xf, matByName, o) + if #me.primitives == 0 then + return nil + end + table.insert(scene.meshes, me) + meshCache[key] = #scene.meshes + return #scene.meshes + end + local camIndex: { [Read.Object]: number } = {} + local function cameraOf(obj: Read.Object): number + if camIndex[obj] then + return camIndex[obj] + end + local c = obj.camera :: Read.Camera + local hfov = if c.lens > 1e-3 then 2400 / c.lens else 45 + hfov = math.clamp(hfov, 0.01, 179) + local aspect = 4 / 3 + local yfov = 2 * math.atan(math.tan(math.rad(hfov) / 2) / aspect) + local near = if c.near and c.near > 0 then c.near else 0.1 + local far = if c.far and c.far > near then c.far else nil + local cam: Types.Camera = { name = obj.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } + table.insert(scene.cameras, cam) + camIndex[obj] = #scene.cameras + return #scene.cameras + end + local lightIndex: { [Read.Object]: number } = {} + local function lightOf(obj: Read.Object): number + if lightIndex[obj] then + return lightIndex[obj] + end + local l = obj.light :: Read.Light + local L: Types.Light = { name = obj.name, type = "point", color = { l.color[1], l.color[2], l.color[3] }, intensity = l.multiplier } + if l.spot then + L.type = "spot" + local hot = math.clamp(l.spot.hotspot, 0, 179.9) + local fall = math.clamp(math.max(l.spot.falloff, hot), 0, 179.9) + L.innerCone, L.outerCone = math.rad(hot) / 2, math.rad(fall) / 2 + end + if l.attenuate and l.outer and l.outer > 0 then + L.range = l.outer + end + table.insert(scene.lights, L) + lightIndex[obj] = #scene.lights + return #scene.lights + end + + local kf = raw.keyframer + local kfNodes = if kf then kf.nodes else {} + -- targets of cameras / spotlights by name + local targets: { [string]: Read.Node } = {} + for _, n in kfNodes do + if n.kind == "target" or n.kind == "lightTarget" then + targets[n.name] = targets[n.name] or n + end + end + local placedObj: { [Read.Object]: boolean } = {} + local sceneOf: { [number]: number } = {} -- kf id -> scene node + local channels: { Types.Channel } = {} + local function channel(node: number, path: any, times: { number }, values: { number }, comps: number) + for i = 1, #times do + times[i] /= fps + end + local ch: Types.Channel = { node = node, path = path, input = floats(times, 1), output = floats(values, comps), interpolation = "LINEAR" } + table.insert(channels, ch) + end + local function addNode(n: Types.Node, parent: number?): number + table.insert(scene.nodes, n) + local i = #scene.nodes + if parent then + table.insert(scene.nodes[parent].children, i) + else + table.insert(scene.roots, i) + end + return i + end + + for k, kn in kfNodes do + local kind = kn.kind + if kind == "target" or kind == "lightTarget" or kind == "ambient" then + continue + end + local id = kn.id or (k - 1) + local parent = if kn.parent >= 0 then sceneOf[kn.parent] else nil + local obj = findObj(kn.name) + local tr = kn.tracks + local name = if kn.instance and kn.instance ~= "" then kn.instance else kn.name + local node: Types.Node = { name = name, children = {} } + local x3ds: { [string]: any } = { kind = kind, object = kn.name, id = id, pivot = kn.pivot } + node.extras = { ["3ds"] = x3ds } + local animated = false + if kind == "object" then + if obj and obj.mesh then + node.mesh = meshOf(obj, kn.pivot, true) + placedObj[obj] = true + x3ds.hidden = obj.hidden or nil + end + node.translation = first(tr.pos, { 0, 0, 0 }) + node.rotation = if tr.rot and #tr.rot.frames > 0 then (select(2, rotations(tr.rot)) :: any)[1] else { 0, 0, 0, 1 } + node.scale = scaleKey(first(tr.scl, { 1, 1, 1 })) + local ni = addNode(node, parent) + sceneOf[id] = ni + if tr.pos and #tr.pos.frames > 1 then + channel(ni, "translation", table.clone(tr.pos.frames), table.clone(tr.pos.values), 3) + end + if tr.rot and #tr.rot.frames > 1 then + local frames, quats = rotations(tr.rot) + local vals = {} + for _, q in quats do + table.move(q, 1, 4, #vals + 1, vals) + end + channel(ni, "rotation", frames, vals, 4) + end + if tr.scl and #tr.scl.frames > 1 then + local vals = {} + for i = 1, #tr.scl.frames do + local v = scaleKey({ tr.scl.values[i * 3 - 2], tr.scl.values[i * 3 - 1], tr.scl.values[i * 3] }) + table.move(v, 1, 3, #vals + 1, vals) + end + channel(ni, "scale", table.clone(tr.scl.frames), vals, 3) + end + else + -- cameras and lights: position, target, roll + local isCam = kind == "camera" + local cam = if obj and isCam then obj.camera else nil + local lit = if obj and not isCam then obj.light else nil + local tgt = targets[kn.name] + local basePos = if cam then cam.pos elseif lit then lit.pos else { 0, 0, 0 } + local baseTgt = if cam then cam.target elseif lit and lit.spot then lit.spot.target else nil + local aims = isCam or kind == "spot" or baseTgt ~= nil + local function pose(frame: number): ({ number }, { number }?) + local p = evalTrack(tr.pos, frame, basePos) + if not aims then + return p, nil + end + local t = evalTrack(tgt and tgt.tracks.pos, frame, baseTgt or { p[1], p[2] + 1, p[3] }) + local roll = evalTrack(tr.roll, frame, { if cam then cam.roll else 0 })[1] + return p, Build.lookAt(p, t, roll) + end + local p0, r0 = pose(-math.huge) + node.translation, node.rotation = p0, r0 + if cam then + node.camera = cameraOf(obj :: Read.Object) + placedObj[obj :: Read.Object] = true + x3ds.lens, x3ds.roll = cam.lens, cam.roll + elseif lit then + node.light = lightOf(obj :: Read.Object) + placedObj[obj :: Read.Object] = true + x3ds.off = lit.off or nil + end + local ni = addNode(node, parent) + sceneOf[id] = ni + -- every key time of the position, roll and target tracks + local set: { [number]: boolean } = {} + local times: { number } = {} + for _, t in { tr.pos, tr.roll, if aims and tgt then tgt.tracks.pos else nil } do + if t and #t.frames > 1 then + animated = true + end + for _, f in (if t then t.frames else {}) :: { number } do + if not set[f] then + set[f] = true + table.insert(times, f) + end + end + end + if animated then + table.sort(times) + local tv, rv = {}, {} + for _, f in times do + local p, r = pose(f) + table.move(p, 1, 3, #tv + 1, tv) + if r then + table.move(r, 1, 4, #rv + 1, rv) + end + end + channel(ni, "translation", table.clone(times), tv, 3) + if aims then + channel(ni, "rotation", times, rv, 4) + end + end + end + end + -- objects the keyframer does not place (or files without one): at their own matrix / position + for _, obj in raw.objects do + if placedObj[obj] then + continue + end + local node: Types.Node = { name = obj.name, children = {}, extras = { ["3ds"] = { object = obj.name, hidden = obj.hidden or nil } } } + if obj.mesh then + local mi = meshOf(obj, nil, false) + if not mi then + continue + end + node.mesh = mi + if obj.mesh.matrix then + node.matrix = meshMatrix(obj.mesh.matrix) + end + elseif obj.camera then + local c = obj.camera + node.camera = cameraOf(obj) + node.translation, node.rotation = c.pos, Build.lookAt(c.pos, c.target, c.roll) + elseif obj.light then + local l = obj.light + node.light = lightOf(obj) + node.translation = l.pos + if l.spot then + node.rotation = Build.lookAt(l.pos, l.spot.target, 0) + end + else + continue + end + addNode(node, nil) + end + if #channels > 0 then + table.insert(scene.animations, { name = kf and kf.name or "3ds", channels = channels }) + end + scene.meta.up = "z" + scene.meta.source = { + format = "3ds", + version = raw.version, + meshVersion = raw.meshVersion, + masterScale = raw.masterScale, + ambient = raw.ambient, + keyframer = kf ~= nil, + frames = if kf and kf.first then { kf.first, kf.last } else nil, + fps = fps, + } + return scene +end + +return Build diff --git a/src/Formats/model/3ds/Read.luau b/src/Formats/model/3ds/Read.luau new file mode 100644 index 0000000..648b4c5 --- /dev/null +++ b/src/Formats/model/3ds/Read.luau @@ -0,0 +1,506 @@ +--!strict +-- model/3ds/Read: the 3DS chunk tree (a u16 id and a u32 size that counts the 6-byte header, little endian) read +-- into plain tables: materials, named objects (triangle meshes, cameras, lights) and the keyframer (nodes with their +-- tracks). Chunk ids and layouts from the 3D Studio file format as documented by Autodesk's 3DS File Toolkit notes +-- and read by assimp's 3DS importer (BSD-3, used as the reference) and lib3ds (read for the layout only, no code). +-- Unknown chunks are skipped. A chunk running past the end of the data is an error; one running past its parent is +-- clipped to the parent. Never throws on bad data: returns nil, message, offset. +local Read = {} + +local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32 +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ chunk ids +local C = { + MAIN = 0x4D4D, VERSION = 0x0002, EDITOR = 0x3D3D, MESH_VERSION = 0x3D3E, MASTER_SCALE = 0x0100, + RGBF = 0x0010, RGBB = 0x0011, LIN_RGBB = 0x0012, LIN_RGBF = 0x0013, PERCENTW = 0x0030, PERCENTF = 0x0031, + AMBIENT_LIGHT = 0x2100, OBJECT = 0x4000, TRIMESH = 0x4100, VERTICES = 0x4110, FACES = 0x4120, FACE_MAT = 0x4130, + UVS = 0x4140, SMOOTH = 0x4150, MATRIX = 0x4160, LIGHT = 0x4600, SPOT = 0x4610, LIGHT_OFF = 0x4620, + ATTENUATE = 0x4625, INNER_RANGE = 0x4659, OUTER_RANGE = 0x465A, MULTIPLIER = 0x465B, CAMERA = 0x4700, + CAM_RANGES = 0x4720, OBJ_HIDDEN = 0x4010, + MATERIAL = 0xAFFF, MAT_NAME = 0xA000, MAT_AMBIENT = 0xA010, MAT_DIFFUSE = 0xA020, MAT_SPECULAR = 0xA030, + MAT_SHININESS = 0xA040, MAT_SHIN_STRENGTH = 0xA041, MAT_TRANSPARENCY = 0xA050, MAT_SELF_ILPCT = 0xA084, + MAT_TWO_SIDE = 0xA081, MAT_WIRE = 0xA085, MAT_SHADING = 0xA100, MAP_FILE = 0xA300, MAP_TILING = 0xA351, + MAP_USCALE = 0xA354, MAP_VSCALE = 0xA356, MAP_UOFFSET = 0xA358, MAP_VOFFSET = 0xA35A, MAP_ANGLE = 0xA35C, + KEYFRAMER = 0xB000, KF_HDR = 0xB00A, KF_FRAMES = 0xB008, NODE_HDR = 0xB010, NODE_INSTANCE = 0xB011, + NODE_PIVOT = 0xB013, NODE_ID = 0xB030, TRACK_POS = 0xB020, TRACK_ROT = 0xB021, TRACK_SCALE = 0xB022, + TRACK_FOV = 0xB023, TRACK_ROLL = 0xB024, TRACK_COLOR = 0xB025, TRACK_HOTSPOT = 0xB027, TRACK_FALLOFF = 0xB028, +} +Read.C = C + +-- material map chunks -> their name in Raw materials +Read.MAPS = { + [0xA200] = "diffuse", [0xA33A] = "diffuse2", [0xA210] = "opacity", [0xA230] = "bump", [0xA204] = "specular", + [0xA33C] = "shininess", [0xA33D] = "selfIllum", [0xA220] = "reflection", +} +-- keyframer node chunks -> kind +local NODE_KINDS = { + [0xB001] = "ambient", [0xB002] = "object", [0xB003] = "camera", [0xB004] = "target", [0xB005] = "light", + [0xB006] = "lightTarget", [0xB007] = "spot", +} +-- track chunks -> (field, values per key) +local TRACKS: { [number]: { any } } = { + [0xB020] = { "pos", 3 }, [0xB021] = { "rot", 4 }, [0xB022] = { "scl", 3 }, [0xB023] = { "fov", 1 }, + [0xB024] = { "roll", 1 }, [0xB025] = { "color", 3 }, [0xB027] = { "hotspot", 1 }, [0xB028] = { "falloff", 1 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Map = { file: string?, strength: number?, tiling: number?, uscale: number?, vscale: number?, uoffset: number?, voffset: number?, angle: number? } +export type Material = { + name: string, + ambient: { number }?, diffuse: { number }?, specular: { number }?, + shininess: number?, shinStrength: number?, transparency: number?, selfIllum: number?, -- fractions 0..1 + twoSided: boolean, wire: boolean, shading: number?, + maps: { [string]: Map }, +} +export type Mesh = { + nv: number, positions: buffer, -- nv * 3 f32 (world space) + nuv: number, uvs: buffer?, -- nuv * 2 f32 + nf: number, faces: buffer?, -- nf * 4 u16 (a, b, c, flags) + faceMats: { { name: string, faces: { number } } }, -- 0-based face numbers + smoothing: buffer?, -- nf u32 + matrix: { number }?, -- 12 floats: the X, Y, Z axes and the origin (world space) +} +export type Camera = { pos: { number }, target: { number }, roll: number, lens: number, near: number?, far: number? } +export type Light = { + pos: { number }, color: { number }, multiplier: number, off: boolean, attenuate: boolean, + inner: number?, outer: number?, spot: { target: { number }, hotspot: number, falloff: number }?, +} +export type Object = { name: string, hidden: boolean, mesh: Mesh?, camera: Camera?, light: Light? } +export type Track = { frames: { number }, values: { number }, size: number, flags: number } +export type Node = { + kind: string, id: number?, name: string, parent: number, flags: number, instance: string?, pivot: { number }?, + tracks: { [string]: Track }, +} +export type Raw = { + version: number?, meshVersion: number?, masterScale: number?, ambient: { number }?, + materials: { Material }, objects: { Object }, + keyframer: { name: string?, length: number?, first: number?, last: number?, nodes: { Node } }?, + vertices: number, +} + +-- ------------------------------------------------------------------------------------------------ helpers +type Ctx = { b: buffer, limit: number, maxVertices: number, raw: Raw } + +-- each(ctx, p, stop, fn): calls fn(id, body, chunkEnd) for the chunks of [p, stop); returns fn's error or a size error +local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, number) -> (string?, number?)): (string?, number?) + local b = ctx.b + while p + 6 <= stop do + local id, size = readu16(b, p), readu32(b, p + 2) + if size < 6 then + return nil, nil -- padding or garbage after the last chunk + end + local e = p + size + if e > ctx.limit then + return string.format("chunk 0x%04x runs past the end of the data", id), p + end + local err, at = fn(id, p + 6, math.min(e, stop)) + if err then + return err, at + end + p = e + end + return nil, nil +end + +-- cstring(b, p, stop) -> the NUL-terminated string at p, the offset after it | nil +local function cstring(b: buffer, p: number, stop: number): (string?, number) + for q = p, stop - 1 do + if readu8(b, q) == 0 then + return buffer.readstring(b, p, q - p), q + 1 + end + end + return nil, stop +end + +local function vec3(b: buffer, p: number): { number } + return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } +end + +-- a colour chunk list: the first float or byte colour (gamma-corrected "linear" variants only when nothing else) +local function color(ctx: Ctx, p: number, stop: number): { number }? + local b = ctx.b + local main: { number }?, lin: { number }? = nil, nil + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if (id == C.RGBF or id == C.LIN_RGBF) and e - q >= 12 then + local c = vec3(b, q) + if id == C.RGBF then + main = main or c + else + lin = lin or c + end + elseif (id == C.RGBB or id == C.LIN_RGBB) and e - q >= 3 then + local c = { readu8(b, q) / 255, readu8(b, q + 1) / 255, readu8(b, q + 2) / 255 } + if id == C.RGBB then + main = main or c + else + lin = lin or c + end + end + return nil, nil + end) + return main or lin +end + +-- a percentage chunk list -> a fraction 0..1 +local function percent(ctx: Ctx, p: number, stop: number): number? + local b = ctx.b + local v: number? = nil + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if v == nil and id == C.PERCENTW and e - q >= 2 then + v = readu16(b, q) / 100 + elseif v == nil and id == C.PERCENTF and e - q >= 4 then + v = readf32(b, q) / 100 + end + return nil, nil + end) + return v +end + +-- ------------------------------------------------------------------------------------------------ materials +local function map(ctx: Ctx, p: number, stop: number): Map + local b = ctx.b + local m: Map = {} + m.strength = percent(ctx, p, stop) + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + local n = e - q + if id == C.MAP_FILE then + m.file = cstring(b, q, e) + elseif id == C.MAP_TILING and n >= 2 then + m.tiling = readu16(b, q) + elseif n >= 4 then + local v = readf32(b, q) + if id == C.MAP_USCALE then + m.uscale = v + elseif id == C.MAP_VSCALE then + m.vscale = v + elseif id == C.MAP_UOFFSET then + m.uoffset = v + elseif id == C.MAP_VOFFSET then + m.voffset = v + elseif id == C.MAP_ANGLE then + m.angle = v + end + end + return nil, nil + end) + return m +end + +local function material(ctx: Ctx, p: number, stop: number) + local b = ctx.b + local m: Material = { name = "", twoSided = false, wire = false, maps = {} } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.MAT_NAME then + m.name = cstring(b, q, e) or "" + elseif id == C.MAT_AMBIENT then + m.ambient = color(ctx, q, e) + elseif id == C.MAT_DIFFUSE then + m.diffuse = color(ctx, q, e) + elseif id == C.MAT_SPECULAR then + m.specular = color(ctx, q, e) + elseif id == C.MAT_SHININESS then + m.shininess = percent(ctx, q, e) + elseif id == C.MAT_SHIN_STRENGTH then + m.shinStrength = percent(ctx, q, e) + elseif id == C.MAT_TRANSPARENCY then + m.transparency = percent(ctx, q, e) + elseif id == C.MAT_SELF_ILPCT then + m.selfIllum = percent(ctx, q, e) + elseif id == C.MAT_TWO_SIDE then + m.twoSided = true + elseif id == C.MAT_WIRE then + m.wire = true + elseif id == C.MAT_SHADING and e - q >= 2 then + m.shading = readu16(b, q) + elseif Read.MAPS[id] then + m.maps[Read.MAPS[id]] = map(ctx, q, e) + end + return nil, nil + end) + table.insert(ctx.raw.materials, m) +end + +-- ------------------------------------------------------------------------------------------------ objects +local function faceList(ctx: Ctx, mesh: Mesh, p: number, stop: number): (string?, number?) + local b = ctx.b + if stop - p < 2 then + return "truncated face list", p + end + local nf = readu16(b, p) + if p + 2 + nf * 8 > stop then + return "face list runs past its chunk", p + end + local faces = buffer.create(nf * 8) + buffer.copy(faces, 0, b, p + 2, nf * 8) + mesh.nf, mesh.faces = nf, faces + return each(ctx, p + 2 + nf * 8, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.FACE_MAT then + local name, r = cstring(b, q, e) + if not name or r + 2 > e then + return "bad face material list", q + end + local n = readu16(b, r) + if r + 2 + n * 2 > e then + return "face material list runs past its chunk", q + end + local list: { number } = {} + for i = 0, n - 1 do + list[i + 1] = readu16(b, r + 2 + i * 2) + end + table.insert(mesh.faceMats, { name = name, faces = list }) + elseif id == C.SMOOTH then + local n = math.min(nf, (e - q) // 4) + local s = buffer.create(nf * 4) + buffer.copy(s, 0, b, q, n * 4) + mesh.smoothing = s + end + return nil, nil + end) +end + +local function trimesh(ctx: Ctx, p: number, stop: number): (Mesh?, string?, number?) + local b = ctx.b + local mesh: Mesh = { nv = 0, positions = buffer.create(0), nuv = 0, nf = 0, faceMats = {} } + local err, at = each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.VERTICES or id == C.UVS then + if e - q < 2 then + return "truncated vertex list", q + end + local n = readu16(b, q) + local size = if id == C.VERTICES then 12 else 8 + if q + 2 + n * size > e then + return "vertex list runs past its chunk", q + end + local data = buffer.create(n * size) + buffer.copy(data, 0, b, q + 2, n * size) + if id == C.VERTICES then + ctx.raw.vertices += n + if ctx.raw.vertices > ctx.maxVertices then + return "limit: more than " .. ctx.maxVertices .. " vertices", q + end + mesh.nv, mesh.positions = n, data + else + mesh.nuv, mesh.uvs = n, data + end + elseif id == C.FACES then + return faceList(ctx, mesh, q, e) + elseif id == C.MATRIX and e - q >= 48 then + local m: { number } = {} + for i = 0, 11 do + m[i + 1] = readf32(b, q + i * 4) + end + mesh.matrix = m + end + return nil, nil + end) + if err then + return nil, err, at + end + return mesh, nil, nil +end + +local function camera(ctx: Ctx, p: number, stop: number): Camera? + local b = ctx.b + if stop - p < 32 then + return nil + end + local cam: Camera = { pos = vec3(b, p), target = vec3(b, p + 12), roll = readf32(b, p + 24), lens = readf32(b, p + 28) } + each(ctx, p + 32, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.CAM_RANGES and e - q >= 8 then + cam.near, cam.far = readf32(b, q), readf32(b, q + 4) + end + return nil, nil + end) + return cam +end + +local function light(ctx: Ctx, p: number, stop: number): Light? + local b = ctx.b + if stop - p < 12 then + return nil + end + local l: Light = { pos = vec3(b, p), color = { 1, 1, 1 }, multiplier = 1, off = false, attenuate = false } + l.color = color(ctx, p + 12, stop) or l.color + each(ctx, p + 12, stop, function(id: number, q: number, e: number): (string?, number?) + local n = e - q + if id == C.SPOT and n >= 20 then + l.spot = { target = vec3(b, q), hotspot = readf32(b, q + 12), falloff = readf32(b, q + 16) } + elseif id == C.LIGHT_OFF then + l.off = true + elseif id == C.ATTENUATE then + l.attenuate = true + elseif id == C.MULTIPLIER and n >= 4 then + l.multiplier = readf32(b, q) + elseif id == C.INNER_RANGE and n >= 4 then + l.inner = readf32(b, q) + elseif id == C.OUTER_RANGE and n >= 4 then + l.outer = readf32(b, q) + end + return nil, nil + end) + return l +end + +local function object(ctx: Ctx, p: number, stop: number): (string?, number?) + local b = ctx.b + local name, q = cstring(b, p, stop) + if not name then + return "object without a name", p + end + local obj: Object = { name = name, hidden = false } + local err, at = each(ctx, q, stop, function(id: number, r: number, e: number): (string?, number?) + if id == C.TRIMESH then + local mesh, merr, mat = trimesh(ctx, r, e) + if not mesh then + return merr, mat + end + obj.mesh = mesh + elseif id == C.CAMERA then + obj.camera = camera(ctx, r, e) + elseif id == C.LIGHT then + obj.light = light(ctx, r, e) + elseif id == C.OBJ_HIDDEN then + obj.hidden = true + end + return nil, nil + end) + if err then + return err, at + end + table.insert(ctx.raw.objects, obj) + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ keyframer +-- a track: u16 flags, 8 unused bytes, u32 keys; each key: u32 frame, u16 spline flags (+ one f32 per set bit of +-- tension / continuity / bias / ease to / ease from), then the values +local function track(b: buffer, p: number, stop: number, size: number): Track? + if stop - p < 14 then + return nil + end + local flags, n = readu16(b, p), readu32(b, p + 10) + local t: Track = { frames = {}, values = {}, size = size, flags = flags } + p += 14 + for _ = 1, n do + if p + 6 > stop then + break + end + local frame, spline = readu32(b, p), readu16(b, p + 4) + p += 6 + for bit = 0, 4 do + if band(spline, bit32.lshift(1, bit)) ~= 0 then + p += 4 + end + end + if p + size * 4 > stop then + break + end + table.insert(t.frames, frame) + for k = 0, size - 1 do + table.insert(t.values, readf32(b, p + k * 4)) + end + p += size * 4 + end + return t +end + +local function node(ctx: Ctx, kind: string, p: number, stop: number, list: { Node }) + local b = ctx.b + local n: Node = { kind = kind, name = "", parent = -1, flags = 0, tracks = {} } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.NODE_ID and e - q >= 2 then + n.id = readu16(b, q) + elseif id == C.NODE_HDR then + local name, r = cstring(b, q, e) + n.name = name or "" + if r + 6 <= e then + n.flags = readu16(b, r) + n.parent = readi16(b, r + 4) + end + elseif id == C.NODE_INSTANCE then + n.instance = cstring(b, q, e) + elseif id == C.NODE_PIVOT and e - q >= 12 then + n.pivot = vec3(b, q) + elseif TRACKS[id] then + local spec = TRACKS[id] + n.tracks[spec[1]] = track(b, q, e, spec[2]) + end + return nil, nil + end) + table.insert(list, n) +end + +local function keyframer(ctx: Ctx, p: number, stop: number) + local b = ctx.b + local kf = { nodes = {} :: { Node }, name = nil :: string?, length = nil :: number?, first = nil :: number?, last = nil :: number? } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.KF_HDR and e - q >= 2 then + local name, r = cstring(b, q + 2, e) + kf.name = name + if r + 4 <= e then + kf.length = readu32(b, r) + end + elseif id == C.KF_FRAMES and e - q >= 8 then + kf.first, kf.last = readu32(b, q), readu32(b, q + 4) + elseif NODE_KINDS[id] then + node(ctx, NODE_KINDS[id], q, e, kf.nodes) + end + return nil, nil + end) + ctx.raw.keyframer = kf +end + +-- ------------------------------------------------------------------------------------------------ parse +local function editor(ctx: Ctx, p: number, stop: number): (string?, number?) + local b = ctx.b + return each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.MATERIAL then + material(ctx, q, e) + elseif id == C.OBJECT then + return object(ctx, q, e) + elseif id == C.MESH_VERSION and e - q >= 4 then + ctx.raw.meshVersion = readu32(b, q) + elseif id == C.MASTER_SCALE and e - q >= 4 then + ctx.raw.masterScale = readf32(b, q) + elseif id == C.AMBIENT_LIGHT then + ctx.raw.ambient = color(ctx, q, e) + elseif id == C.KEYFRAMER then + keyframer(ctx, q, e) -- some writers nest it here + end + return nil, nil + end) +end + +-- parse(b, base, limit, opts) -> Raw | nil, message, offset +function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, string?, number?) + if limit - base < 6 or readu16(b, base) ~= C.MAIN then + return nil, "not a 3DS file (no 0x4D4D main chunk)", base + end + local raw: Raw = { materials = {}, objects = {}, vertices = 0 } + local ctx: Ctx = { b = b, limit = limit, maxVertices = opts and opts.maxVertices or 2 ^ 24, raw = raw } + local size = readu32(b, base + 2) + if size < 6 then + return nil, "bad main chunk size", base + end + -- a main chunk declared longer than the data: truncated + if base + size > limit then + return nil, "truncated: the main chunk runs past the end of the data", base + end + local err, at = each(ctx, base + 6, base + size, function(id: number, q: number, e: number): (string?, number?) + if id == C.VERSION and e - q >= 4 then + raw.version = readu32(b, q) + elseif id == C.EDITOR then + return editor(ctx, q, e) + elseif id == C.KEYFRAMER then + keyframer(ctx, q, e) + end + return nil, nil + end) + if err then + return nil, err, at + end + return raw, nil, nil +end + +return Read diff --git a/src/Formats/model/3ds/Write.luau b/src/Formats/model/3ds/Write.luau new file mode 100644 index 0000000..8718a7b --- /dev/null +++ b/src/Formats/model/3ds/Write.luau @@ -0,0 +1,857 @@ +--!strict +-- model/3ds/Write: Types.Scene -> 3DS. One named object per mesh (split at 65535 vertices / faces), vertices in world +-- space at the first node that shows the mesh, its world matrix as the mesh matrix, uvs (v flipped back to 3DS's +-- bottom-left origin), smoothing groups (extras["3ds"].smoothing from model/3ds, else 0 for flat-shaded faces and 1 +-- for the others), per-face materials; Phong materials (extras["3ds"] when present, else from the PBR fields) with +-- texture maps (file names: texture.uri, or a name for texture.data put into opts.files); cameras (lens from yfov and +-- aspect, target along -Z) and lights (omni / spot; directional lights become spots); the keyframer: every node in +-- tree order (object nodes, $$$DUMMY nodes for empty ones, camera / light nodes with their targets), pivot 0, one key +-- per track or the keys of the first animation (frames = round(time * fps)), rotation keys as axis / angle deltas. +-- Mirroring nodes are written the way 3ds Max does (positive keyframer transform, mirror in the mesh matrix). +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") +local Read = require("@formats/model/3ds/Read") +local Build = require("@formats/model/3ds/Build") + +local Write = {} + +local C = Read.C +local S = Types.Scene +local writeu32 = buffer.writeu32 +local sqrt, abs = math.sqrt, math.abs + +export type Options = { flipV: boolean?, fps: number?, name: string?, files: { [string]: any }?, smoothing: boolean? } + +-- ------------------------------------------------------------------------------------------------ chunks +type W = Bytes.Writer +local function open(w: W, id: number): number + local at = w.pos + w:u16le(id) + w:u32le(0) + return at +end +local function close(w: W, at: number) + writeu32(w.buf, at + 2, w.pos - at) +end +local function leaf(w: W, id: number, fn: () -> ()) + local at = open(w, id) + fn() + close(w, at) +end +local function name(s: string?, fallback: string): string + local n = string.gsub(s or "", "%z", "") + if n == "" then + n = fallback + end + return string.sub(n, 1, 63) +end + +local function colorChunk(w: W, id: number, c: { number }) + leaf(w, id, function() + leaf(w, C.RGBF, function() + for k = 1, 3 do + w:f32le(c[k] or 0) + end + end) + leaf(w, C.RGBB, function() + for k = 1, 3 do + w:u8(math.clamp(math.floor((c[k] or 0) * 255 + 0.5), 0, 255)) + end + end) + end) +end +local function percentChunk(w: W, id: number, v: number) + leaf(w, id, function() + leaf(w, C.PERCENTW, function() + w:u16le(math.clamp(math.floor(v * 100 + 0.5), 0, 100)) + end) + leaf(w, C.PERCENTF, function() + w:f32le(v * 100) + end) + end) +end + +-- ------------------------------------------------------------------------------------------------ math +local function world(scene: Types.Scene): ({ [number]: { number } }, { [number]: number }, { number }) + local W: { [number]: { number } } = {} + local parent: { [number]: number } = {} + local order: { number } = {} + local function visit(i: number, p: number?, pm: { number }, depth: number) + local n = scene.nodes[i] + if type(n) ~= "table" or W[i] or depth > 256 then + return + end + W[i] = S.mul(pm, S.nodeMatrix(n)) + parent[i] = p or 0 + table.insert(order, i) + for _, c in n.children or {} do + visit(c, i, W[i], depth + 1) + end + end + for _, r in scene.roots do + visit(r, nil, S.IDENTITY, 0) + end + return W, parent, order +end + +local function col(m: { number }, c: number): (number, number, number) + return m[c * 4 + 1], m[c * 4 + 2], m[c * 4 + 3] +end +local function unit(x: number, y: number, z: number): (number, number, number) + local l = sqrt(x * x + y * y + z * z) + if l < 1e-30 then + return 0, 0, 0 + end + return x / l, y / l, z / l +end + +-- a quaternion -> the 3DS (clockwise angle, axis) +local function axisAngle(q: { number }): (number, number, number, number) + local x, y, z, w = q[1], q[2], q[3], q[4] + local n = sqrt(x * x + y * y + z * z + w * w) + if n < 1e-30 then + return 0, 0, 0, 0 + end + x, y, z, w = x / n, y / n, z / n, w / n + local s = sqrt(x * x + y * y + z * z) + if s < 1e-12 then + return 0, 0, 0, 0 + end + local angle = 2 * math.atan2(s, w) + return -angle, x / s, y / s, z / s +end + +local function conj(q: { number }): { number } + return { -q[1], -q[2], -q[3], q[4] } +end + +-- a channel's value at a time (linear; rotations normalized lerp along the short way) +local function sample(ch: Types.Channel, t: number): { number } + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local n = ch.input.count + local comps = if ch.path == "rotation" then 4 else 3 + local cubic = ch.interpolation == "CUBICSPLINE" + local function v(k: number): { number } + local e = if cubic then k * 3 + 1 else k + local r = table.create(comps, 0) + for c = 1, comps do + r[c] = OUT(e, c - 1) + end + return r + end + if n == 0 then + return if comps == 4 then { 0, 0, 0, 1 } else { 0, 0, 0 } + end + if t <= IN(0, 0) then + return v(0) + end + for k = 0, n - 2 do + local t0, t1 = IN(k, 0), IN(k + 1, 0) + if t <= t1 then + if ch.interpolation == "STEP" or t1 <= t0 then + return if t >= t1 then v(k + 1) else v(k) + end + local u = (t - t0) / (t1 - t0) + local a, b = v(k), v(k + 1) + if comps == 4 and a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] < 0 then + b = { -b[1], -b[2], -b[3], -b[4] } + end + for c = 1, comps do + a[c] += (b[c] - a[c]) * u + end + return a + end + end + return v(n - 1) +end + +-- ------------------------------------------------------------------------------------------------ materials +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/gif"] = "gif", ["image/x-tga"] = "tga", ["image/webp"] = "webp" } + +local function textureFiles(scene: Types.Scene, opts: Options): { [number]: string } + local files = opts.files + local base = string.match(opts.name or "", "([^/\\]-)%.[^.]*$") or "texture" + local out: { [number]: string } = {} + for i, tex in scene.textures do + local file = tex.uri + if not file or file == "" or string.sub(file, 1, 5) == "data:" then + file = string.format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png") + if tex.data and type(files) == "table" then + files[file] = tex.data + end + end + out[i] = file + end + return out +end + +local MAP_IDS: { [string]: number } = {} +for id, kind in Read.MAPS do + MAP_IDS[kind] = id +end +local MAP_ORDER = { "diffuse", "diffuse2", "opacity", "bump", "specular", "shininess", "selfIllum", "reflection" } + +local function writeMaterial(w: W, m: Types.Material, mname: string, files: { [number]: string }) + local x = (m.extras and m.extras["3ds"] or {}) :: { [string]: any } + local bc = m.baseColor or { 1, 1, 1, 1 } + local diffuse = { bc[1], bc[2], bc[3] } + local shininess = math.clamp(1 - (m.roughness or 1), 0, 1) + local transparency = math.clamp(1 - (bc[4] or 1), 0, 1) + local e = m.emissive or { 0, 0, 0 } + local selfIllum = math.clamp(math.max(e[1], e[2], e[3]), 0, 1) + local at = open(w, C.MATERIAL) + leaf(w, C.MAT_NAME, function() + w:cstring(mname) + end) + colorChunk(w, C.MAT_AMBIENT, x.ambient or diffuse) + colorChunk(w, C.MAT_DIFFUSE, diffuse) + colorChunk(w, C.MAT_SPECULAR, x.specular or { 0.5, 0.5, 0.5 }) + percentChunk(w, C.MAT_SHININESS, shininess) + percentChunk(w, C.MAT_SHIN_STRENGTH, x.shinStrength or 0.5) + percentChunk(w, C.MAT_TRANSPARENCY, transparency) + percentChunk(w, C.MAT_SELF_ILPCT, x.selfIllum or selfIllum) + leaf(w, C.MAT_SHADING, function() + w:u16le(x.shading or 3) + end) + if m.doubleSided then + leaf(w, C.MAT_TWO_SIDE, function() end) + end + if x.wire then + leaf(w, C.MAT_WIRE, function() end) + end + -- maps: the PBR texture refs first, then the other kinds model/3ds read + local maps: { [string]: any } = {} + local function fromRef(ref: Types.TextureRef?, saved: any): any + if not ref or not files[ref.texture] then + return nil + end + local s = saved or {} + local tf = ref.transform + return { + file = files[ref.texture], strength = s.strength or 1, tiling = s.tiling, + uscale = if tf and tf.scale then tf.scale[1] else s.uscale, vscale = if tf and tf.scale then tf.scale[2] else s.vscale, + uoffset = if tf and tf.offset then tf.offset[1] else s.uoffset, voffset = if tf and tf.offset then tf.offset[2] else s.voffset, + angle = if tf and tf.rotation then math.deg(tf.rotation) else s.angle, + } + end + local saved = (x.maps or {}) :: { [string]: any } + maps.diffuse = fromRef(m.baseColorTexture, saved.diffuse) + maps.selfIllum = fromRef(m.emissiveTexture, saved.selfIllum) + for kind, s in saved do + if maps[kind] == nil and kind ~= "diffuse" and kind ~= "selfIllum" and type(s) == "table" then + maps[kind] = fromRef(if s.texture then { texture = s.texture } else nil, s) + end + end + for _, kind in MAP_ORDER do + local mp = maps[kind] + if mp then + local mat = open(w, MAP_IDS[kind]) + leaf(w, C.PERCENTW, function() + w:u16le(math.clamp(math.floor((mp.strength or 1) * 100 + 0.5), 0, 100)) + end) + leaf(w, C.MAP_FILE, function() + w:cstring(name(mp.file, "texture")) + end) + if mp.tiling then + leaf(w, C.MAP_TILING, function() + w:u16le(mp.tiling) + end) + end + for _, f in { { C.MAP_USCALE, mp.uscale }, { C.MAP_VSCALE, mp.vscale }, { C.MAP_UOFFSET, mp.uoffset }, { C.MAP_VOFFSET, mp.voffset }, { C.MAP_ANGLE, mp.angle } } do + local v = f[2] + if type(v) == "number" then + leaf(w, f[1], function() + w:f32le(v) + end) + end + end + close(w, mat) + end + end + close(w, at) +end + +-- ------------------------------------------------------------------------------------------------ meshes +type Part = { name: string, positions: { number }, uvs: { number }?, faces: { number }, smooth: { number }, mats: { [number]: { number } } } + +-- the mesh as 3DS parts (local space), or nil, message +local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, string?) + local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { mesh } }, function(n: string): boolean + return n == "TEXCOORD_0" or n == "NORMAL" + end, { triangulate = true }) + if not merged then + return nil, err + end + local P = merged.attrs.POSITION.values + local N = merged.attrs.NORMAL and merged.attrs.NORMAL.values + local T = merged.attrs.TEXCOORD_0 + local tv, tc = if T then T.values else nil, if T then T.components else 0 + local flipV = opts.flipV ~= false + local corners = merged.corners + -- per face: material, smoothing group + local nf = #corners // 3 + local fmat, fsg = table.create(nf, 0), table.create(nf, 1) + for _, part in merged.parts do + local prim: any = part.prim + local saved = prim.extras and prim.extras["3ds"] and prim.extras["3ds"].smoothing + local savedOk = type(saved) == "table" and #saved == part.faceCount and (prim.mode or "triangles") == "triangles" + for f = part.firstFace + 1, part.firstFace + part.faceCount do + fmat[f] = if type(prim.material) == "number" then prim.material else 0 + if savedOk then + fsg[f] = saved[f - part.firstFace] + elseif N then + -- flat when every corner normal is the face normal + local a, b, c = corners[f * 3 - 2], corners[f * 3 - 1], corners[f * 3] + local e1 = { P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3] } + local e2 = { P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3] } + local nx, ny, nz = unit(e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]) + local flat = true + for _, v in { a, b, c } do + local vx, vy, vz = unit(N[v * 3 + 1], N[v * 3 + 2], N[v * 3 + 3]) + if vx * nx + vy * ny + vz * nz < 0.9998 then + flat = false + end + end + fsg[f] = if flat then 0 else 1 + end + end + end + local out: { Part } = {} + local cur: Part? = nil + local remap: { [number]: number } = {} + local count = 0 + for f = 1, nf do + local fresh = 0 + for k = 1, 3 do + if not remap[corners[f * 3 - 3 + k]] then + fresh += 1 + end + end + if cur == nil or count + fresh > 65535 or #cur.smooth >= 65535 then + cur = { name = if #out == 0 then base else string.sub(base, 1, 56) .. "." .. #out, positions = {}, uvs = if tv then {} else nil, faces = {}, smooth = {}, mats = {} } + table.insert(out, cur :: Part) + remap, count = {}, 0 + end + local p = cur :: Part + for k = 1, 3 do + local v = corners[f * 3 - 3 + k] + local o = remap[v] + if not o then + o = count + count += 1 + remap[v] = o + table.move(P, v * 3 + 1, v * 3 + 3, #p.positions + 1, p.positions) + if tv and p.uvs then + local u, vv = tv[v * tc + 1] or 0, tv[v * tc + 2] or 0 + table.insert(p.uvs, u) + table.insert(p.uvs, if flipV then 1 - vv else vv) + end + end + table.insert(p.faces, o) + end + table.insert(p.smooth, fsg[f]) + local mi = fmat[f] + if mi > 0 then + p.mats[mi] = p.mats[mi] or {} + table.insert(p.mats[mi], #p.smooth - 1) + end + end + return out, nil +end + +local function writeMesh(w: W, part: Part, M: { number }, matNames: { [number]: string }) + local at = open(w, C.OBJECT) + w:cstring(part.name) + local tm = open(w, C.TRIMESH) + local nv = #part.positions // 3 + leaf(w, C.VERTICES, function() + w:u16le(nv) + local p = part.positions + for v = 0, nv - 1 do + local x, y, z = Mat4.point(M, p[v * 3 + 1], p[v * 3 + 2], p[v * 3 + 3]) + w:f32le(x) + w:f32le(y) + w:f32le(z) + end + end) + if part.uvs then + local uvs = part.uvs + leaf(w, C.UVS, function() + w:u16le(nv) + for i = 1, nv * 2 do + w:f32le(uvs[i] or 0) + end + end) + end + leaf(w, C.MATRIX, function() + for _, c in { 0, 1, 2, 3 } do + local x, y, z = col(M, c) + w:f32le(x) + w:f32le(y) + w:f32le(z) + end + end) + local fl = open(w, C.FACES) + local nf = #part.smooth + w:u16le(nf) + for f = 0, nf - 1 do + w:u16le(part.faces[f * 3 + 1]) + w:u16le(part.faces[f * 3 + 2]) + w:u16le(part.faces[f * 3 + 3]) + w:u16le(7) -- edges AB, BC, CA visible + end + local mats: { number } = {} + for mi in part.mats do + table.insert(mats, mi) + end + table.sort(mats) + for _, mi in mats do + local list = part.mats[mi] + leaf(w, C.FACE_MAT, function() + w:cstring(matNames[mi]) + w:u16le(#list) + for _, f in list do + w:u16le(f) + end + end) + end + leaf(w, C.SMOOTH, function() + for _, s in part.smooth do + w:u32le(s) + end + end) + close(w, fl) + close(w, tm) + close(w, at) +end + +-- ------------------------------------------------------------------------------------------------ cameras / lights +-- the eye, target and roll of a node's world matrix (looking down -Z, Y up) +local function aim(m: { number }, dist: number): ({ number }, { number }, number) + local p = { m[13], m[14], m[15] } + local fx, fy, fz = unit(-m[9], -m[10], -m[11]) + if fx == 0 and fy == 0 and fz == 0 then + fx, fy, fz = 0, 0, -1 + end + local t = { p[1] + fx * dist, p[2] + fy * dist, p[3] + fz * dist } + -- the roll: the angle from the unrolled up vector (Build.lookAt) to the node's Y axis + local q0 = Build.lookAt(p, t, 0) + local m0 = Mat4.fromQuat(q0) + local ux, uy, uz = unit(m[5], m[6], m[7]) + local cu = ux * m0[5] + uy * m0[6] + uz * m0[7] + local cr = ux * m0[1] + uy * m0[2] + uz * m0[3] + return p, t, math.deg(math.atan2(-cr, cu)) +end + +local function writeCamera(w: W, cname: string, cam: Types.Camera, m: { number }, dist: number) + local p, t, roll = aim(m, dist) + local aspect = cam.aspect or 4 / 3 + local yfov = if cam.type == "perspective" and cam.yfov then cam.yfov else math.rad(45) + local hfov = math.deg(2 * math.atan(math.tan(yfov / 2) * aspect)) + local at = open(w, C.OBJECT) + w:cstring(cname) + local c = open(w, C.CAMERA) + for _, v in { p[1], p[2], p[3], t[1], t[2], t[3], roll, 2400 / math.max(hfov, 1e-3) } do + w:f32le(v) + end + leaf(w, C.CAM_RANGES, function() + w:f32le(cam.znear or 0) + w:f32le(cam.zfar or 1000) + end) + close(w, c) + close(w, at) +end + +local function writeLight(w: W, lname: string, l: Types.Light, m: { number }, dist: number) + local p, t = aim(m, dist) + local at = open(w, C.OBJECT) + w:cstring(lname) + local c = open(w, C.LIGHT) + for k = 13, 15 do + w:f32le(m[k]) + end + leaf(w, C.RGBF, function() + for k = 1, 3 do + w:f32le(l.color and l.color[k] or 1) + end + end) + if l.type ~= "point" then + local inner = if l.type == "spot" then (l.innerCone or 0) else math.rad(45) + local outer = if l.type == "spot" then (l.outerCone or math.pi / 4) else math.rad(45) + leaf(w, C.SPOT, function() + for k = 1, 3 do + w:f32le(t[k]) + end + w:f32le(math.deg(inner * 2)) + w:f32le(math.deg(math.max(outer, inner) * 2)) + end) + end + if l.range and l.range > 0 then + leaf(w, C.ATTENUATE, function() end) + leaf(w, C.OUTER_RANGE, function() + w:f32le(l.range :: number) + end) + end + leaf(w, C.MULTIPLIER, function() + w:f32le(l.intensity or 1) + end) + close(w, c) + close(w, at) + return p +end + +-- ------------------------------------------------------------------------------------------------ keyframer +local function writeTrack(w: W, id: number, frames: { number }, values: { number }, size: number) + leaf(w, id, function() + w:u16le(0) + w:u32le(0) + w:u32le(0) + w:u32le(#frames) + for k, f in frames do + w:u32le(f) + w:u16le(0) + for c = 1, size do + w:f32le(values[(k - 1) * size + c]) + end + end + end) +end + +type KfNode = { + chunk: number, name: string, instance: string?, parent: number, -- parent: kf index or -1 + frames: { [string]: { number } }, values: { [string]: { number } }, +} + +-- frames (rounded, strictly increasing) and the indices of the channel keys they keep +local function frameKeys(ch: Types.Channel, fps: number): ({ number }, { number }) + local IN = S.reader(ch.input) :: any + local frames, keep = {}, {} + for k = 0, ch.input.count - 1 do + local f = math.max(0, math.floor(IN(k, 0) * fps + 0.5)) + if #frames == 0 or f > frames[#frames] then + table.insert(frames, f) + table.insert(keep, k) + end + end + return frames, keep +end + +local function channelValues(ch: Types.Channel, keep: { number }, comps: number): { { number } } + local OUT = S.reader(ch.output) :: any + local cubic = ch.interpolation == "CUBICSPLINE" + local out = {} + for _, k in keep do + local e = if cubic then k * 3 + 1 else k + local v = table.create(comps, 0) + for c = 1, comps do + v[c] = OUT(e, c - 1) + end + table.insert(out, v) + end + return out +end + +local function rotTrack(quats: { { number } }): { number } + local vals = {} + local prev: { number }? = nil + for _, q in quats do + local d = q + if prev then + d = Build.qmul(conj(prev), q) + if d[4] < 0 then + d = { -d[1], -d[2], -d[3], -d[4] } + end + end + local a, x, y, z = axisAngle(d) + table.insert(vals, a) + table.insert(vals, x) + table.insert(vals, y) + table.insert(vals, z) + prev = q + end + return vals +end + +-- ------------------------------------------------------------------------------------------------ encode +function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local fps = o.fps or 30 + local W, parentOf, order = world(scene) + local w = Bytes.writer(65536) + local main = open(w, C.MAIN) + leaf(w, C.VERSION, function() + w:u32le(3) + end) + local ed = open(w, C.EDITOR) + leaf(w, C.MESH_VERSION, function() + w:u32le(3) + end) + -- materials (unique names) + local files = textureFiles(scene, o) + local matNames: { [number]: string } = {} + local used: { [string]: boolean } = {} + local function unique(base: string): string + local n, k = base, 1 + while used[string.lower(n)] do + k += 1 + n = string.sub(base, 1, 56) .. "_" .. k + end + used[string.lower(n)] = true + return n + end + for i, m in scene.materials do + matNames[i] = unique(name(m.name, "Material" .. i)) + writeMaterial(w, m, matNames[i], files) + end + leaf(w, C.MASTER_SCALE, function() + w:f32le(1) + end) + -- meshes: at the first node showing them; their kf world (mirrors moved out of the keyframer) + used = {} + local firstNode: { [number]: number } = {} + for _, i in order do + local mi = scene.nodes[i].mesh + if mi and scene.meshes[mi] and not firstNode[mi] then + firstNode[mi] = i + end + end + local meshParts: { [number]: { Part } } = {} + local meshM: { [number]: { number } } = {} + for mi, mesh in scene.meshes do + local ni = firstNode[mi] + if ni == nil and #scene.nodes > 0 then + continue + end + local list, err = parts(mesh, unique(name(mesh.name, "Mesh" .. mi)), o) + if not list then + return nil, err + end + local M = if ni then W[ni] else S.IDENTITY + if not Mat4.inverse(M) then + M = S.IDENTITY + end + meshParts[mi], meshM[mi] = list, M + for _, part in list do + used[string.lower(part.name)] = true + writeMesh(w, part, M, matNames) + end + end + -- the keyframer world of each node: W, or W * flip-x where the node's mesh matrix mirrors + local KW: { [number]: { number } } = {} + for _, i in order do + local n = scene.nodes[i] + local m = W[i] + if n.mesh and meshM[n.mesh] and Build.det3(meshM[n.mesh]) < 0 then + m = S.mul(m, Mat4.scaling(-1, 1, 1)) + end + KW[i] = m + end + local kfs: { KfNode } = {} + local kfOf: { [number]: number } = {} + local anim = scene.animations[1] + local byNode: { [number]: { [string]: Types.Channel } } = {} + if anim then + for _, ch in anim.channels do + if ch.path ~= "weights" then + byNode[ch.node] = byNode[ch.node] or {} + byNode[ch.node][ch.path] = ch + end + end + end + local lastFrame = 0 + local function single(v: { number }): { number } + return table.clone(v) + end + for _, i in order do + local n = scene.nodes[i] + local p = parentOf[i] + local pk = if p ~= 0 then kfOf[p] else nil + local camOrLight = (n.camera and scene.cameras[n.camera]) or (n.light and scene.lights[n.light]) + local dist = 100 + local function placeCamLight(kind: number, objName: string, tgtChunk: number?) + local pos, tgt, roll = aim(W[i], dist) + local kn: KfNode = { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } } + table.insert(kfs, kn) + local idx = #kfs + -- animated root cameras / lights: position, target and roll at the key times + local chs: any = if p == 0 then byNode[i] else nil + local targetFrames, targetVals = { 0 }, tgt + if chs and (chs.translation or chs.rotation) then + local fr: { [number]: boolean } = {} + local frames: { number } = {} + local list: { Types.Channel } = {} + table.insert(list, chs.translation) + table.insert(list, chs.rotation) + for _, ch in list do + for _, f in (frameKeys(ch, fps)) do + if not fr[f] then + fr[f] = true + table.insert(frames, f) + end + end + end + table.sort(frames) + local pv, tv, rv = {}, {}, {} + for _, f in frames do + local t = f / fps + local ct, cr = chs.translation, chs.rotation + local tr = if ct then sample(ct, t) else { W[i][13], W[i][14], W[i][15] } + local rq = if cr then sample(cr, t) else (n.rotation or { 0, 0, 0, 1 }) + local sc = n.scale or { 1, 1, 1 } + local ps, ts, rs = aim(Mat4.compose(tr, rq, sc), dist) + table.move(ps, 1, 3, #pv + 1, pv) + table.move(ts, 1, 3, #tv + 1, tv) + table.insert(rv, rs) + lastFrame = math.max(lastFrame, f) + end + kn.frames.pos, kn.values.pos = frames, pv + kn.frames.roll, kn.values.roll = frames, rv + targetFrames, targetVals = frames, tv + end + if tgtChunk then + table.insert(kfs, { chunk = tgtChunk, name = objName, parent = -1, frames = { pos = targetFrames }, values = { pos = targetVals } }) + end + if kind ~= 0xB003 then + kn.frames.roll, kn.values.roll = nil :: any, nil :: any + end + return idx + end + local function camLight(onlyThis: boolean): number? + if not camOrLight then + return nil + end + local idx: number? = nil + if n.camera and scene.cameras[n.camera] then + local cname = unique(name(scene.cameras[n.camera].name or n.name, "Camera" .. n.camera)) + writeCamera(w, cname, scene.cameras[n.camera], W[i], dist) + idx = placeCamLight(0xB003, cname, 0xB004) + end + if n.light and scene.lights[n.light] then + local l = scene.lights[n.light] + local lname = unique(name(l.name or n.name, "Light" .. n.light)) + writeLight(w, lname, l, W[i], dist) + local k = placeCamLight(if l.type == "point" then 0xB005 else 0xB007, lname, if l.type == "point" then nil else 0xB006) + idx = idx or k + end + if onlyThis and idx then + kfOf[i] = idx + -- the node's frame in the keyframer: the camera / light pose + local kn = kfs[idx] + local pos = kn.values.pos + local m: { number } = W[i] + if kn.chunk == 0xB005 then + KW[i] = Mat4.translation(pos[1], pos[2], pos[3]) + else + local _, tgt, roll = aim(m, dist) + KW[i] = Mat4.compose(pos, Build.lookAt({ pos[1], pos[2], pos[3] }, tgt, if kn.chunk == 0xB003 then roll else 0), nil) + end + end + return idx + end + if n.mesh == nil and camOrLight then + camLight(true) + continue + end + -- an object node (or a dummy) with the node's transform relative to its keyframer parent + local pkw = if p ~= 0 and kfOf[p] then KW[p] else S.IDENTITY + local inv = Mat4.inverse(pkw) or Mat4.identity() + local L = S.mul(inv, KW[i]) + local t, r, s = Mat4.decompose(L) + local plist = if n.mesh then meshParts[n.mesh] else nil + local objName = if plist then plist[1].name else "$$$DUMMY" + local instance = if plist and n.name and n.name ~= objName then name(n.name, objName) elseif not plist then name(n.name, "Dummy" .. i) else nil + local kn: KfNode = { chunk = 0xB002, name = objName, instance = instance, parent = if pk then pk - 1 else -1, frames = { pos = { 0 }, rot = { 0 }, scl = { 0 } }, values = { pos = single(t), rot = rotTrack({ r }), scl = single(s) } } + -- animation keys, when the keyframer transform is the node's own (no mirror fix-up up the tree) + local chs = byNode[i] + if chs then + local own = S.nodeMatrix(n) + local same = true + for k = 1, 16 do + if abs(own[k] - L[k]) > 1e-5 * math.max(1, abs(own[k])) then + same = false + end + end + if same then + for path, field in { translation = "pos", rotation = "rot", scale = "scl" } :: { [string]: string } do + local ch = chs[path] + if ch then + local frames, keep = frameKeys(ch, fps) + local vals = channelValues(ch, keep, if path == "rotation" then 4 else 3) + lastFrame = math.max(lastFrame, frames[#frames] or 0) + kn.frames[field] = frames + if path == "rotation" then + kn.values[field] = rotTrack(vals) + else + local flat = {} + for _, v in vals do + table.move(v, 1, 3, #flat + 1, flat) + end + kn.values[field] = flat + end + end + end + end + end + table.insert(kfs, kn) + kfOf[i] = #kfs + for k = 2, if plist then #plist else 0 do + local extra = table.clone(kn) + extra.name, extra.instance = (plist :: { Part })[k].name, nil + table.insert(kfs, extra) + end + camLight(false) + end + close(w, ed) + -- the keyframer + local kf = open(w, C.KEYFRAMER) + leaf(w, C.KF_HDR, function() + w:u16le(5) + w:cstring("MAXSCENE") + w:u32le(math.max(lastFrame, 100)) + end) + leaf(w, C.KF_FRAMES, function() + w:u32le(0) + w:u32le(math.max(lastFrame, 100)) + end) + for id, kn in kfs do + local nc = open(w, kn.chunk) + leaf(w, C.NODE_ID, function() + w:u16le(id - 1) + end) + leaf(w, C.NODE_HDR, function() + w:cstring(kn.name) + w:u16le(0x4000) + w:u16le(0) + w:u16le(if kn.parent >= 0 then kn.parent else 0xFFFF) + end) + if kn.instance then + leaf(w, C.NODE_INSTANCE, function() + w:cstring(kn.instance :: string) + end) + end + if kn.chunk == 0xB002 then + leaf(w, C.NODE_PIVOT, function() + w:f32le(0) + w:f32le(0) + w:f32le(0) + end) + end + for _, tr in { { "pos", C.TRACK_POS, 3 }, { "rot", C.TRACK_ROT, 4 }, { "scl", C.TRACK_SCALE, 3 }, { "roll", C.TRACK_ROLL, 1 } } do + local field = tr[1] :: string + local frames = kn.frames[field] + if frames then + writeTrack(w, tr[2] :: number, frames, kn.values[field], tr[3] :: number) + end + end + close(w, nc) + end + close(w, kf) + close(w, main) + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Write diff --git a/src/Formats/model/3ds/init.luau b/src/Formats/model/3ds/init.luau new file mode 100644 index 0000000..2e7b581 --- /dev/null +++ b/src/Formats/model/3ds/init.luau @@ -0,0 +1,100 @@ +--!strict +-- model/3ds: Autodesk 3D Studio (.3ds, the chunked binary of 3D Studio R4 / 3ds Max's exporter). New code, from the +-- chunk layout as documented by the 3DS File Toolkit notes and read by assimp's 3DS importer (BSD-3: the reference +-- for transforms and conventions; no code ported) and lib3ds (layouts only). +-- Reads: triangle meshes (vertices, faces, uvs (TEXCOORD_0, flipped to glTF's top-left origin), the mesh matrix, +-- per-face materials -> one primitive per material, smoothing groups -> NORMAL: corners of faces sharing a group and +-- a position are averaged, group 0 is flat; extras["3ds"].smoothing keeps the groups per triangle), materials +-- (ambient / diffuse / specular colours, shininess, shininess strength, transparency, self-illumination, two-sided, +-- shading, wire; texture maps -> Textures with `uri` (never loaded: F.model.loadTextures resolves them), diffuse as +-- baseColorTexture, self-illumination as emissiveTexture, the others in extras["3ds"].maps; uv scale / offset / +-- angle as a texture transform), cameras (lens -> yfov at a 4:3 aspect, near / far ranges; -Z looking at the +-- target, rolled), lights (omni -> point, spot -> spot with hotspot / falloff cones, colour, multiplier, outer range), +-- the keyframer (node hierarchy by node id, $$$DUMMY nodes with their instance names, instances of one object, +-- pivots, the first key of every track as the node's TRS, tracks with several keys -> one animation: position / +-- scale keys linear, rotation keys accumulated from their axis / angle deltas, cameras / spotlights sampled from +-- their position, target and roll tracks; TCB spline parameters are ignored, times are frame / opts.fps). Objects +-- without a keyframer node stand at their mesh matrix. meta.up = "z"; meta.source has version, masterScale (not +-- applied), the keyframer frame range. +-- Writes: see model/3ds/Write (meshes, materials, texture names, cameras, lights, the keyframer and the first +-- animation). Not supported: 3DS project / material library files (.prj, .mli), morph / hide tracks, procedural +-- and shadow parameters, background / atmosphere settings, mesh limits beyond 65535 vertices per object (split on +-- write), vertex colours / normals (3DS has neither; normals come from smoothing groups). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/3ds/Read") +local Build = require("@formats/model/3ds/Build") +local Write = require("@formats/model/3ds/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local ThreeDs = { + name = "3ds", + category = "model", + extensions = { "3ds" }, + mime = { "application/x-3ds", "image/x-3ds" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + normals: boolean?, -- compute NORMAL from the smoothing groups (default true; false keeps the file's vertices) + flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) + fps: number?, -- keyframer frames per second (default 30, 3ds Max's default) + maxVertices: number?, -- refuse more vertices in total (default 2^24) +} +export type EncodeOptions = { + flipV: boolean?, -- default true (the inverse of decode) + fps: number?, -- seconds -> keyframer frames (default 30) + name: string?, -- the destination's file name (names textures that have no uri) + files: { [string]: any }?, -- receives the bytes of textures that have data but no uri +} + +-- ------------------------------------------------------------------------------------------------ sniff +function ThreeDs.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h < 8 or string.byte(h, 1) ~= 0x4D or string.byte(h, 2) ~= 0x4D then + return 0 + end + local b1, b2, b3, b4, c1, c2 = string.byte(h, 3, 8) + local size = b1 + b2 * 256 + b3 * 65536 + b4 * 16777216 + local child = c1 + c2 * 256 + if size < 16 or not (child == 0x0002 or child == 0x3D3D or child == 0xB000) then + return 0 + end + return if size == r.limit - r.pos then 0.95 else 0.7 +end + +-- ------------------------------------------------------------------------------------------------ decode +function ThreeDs.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local raw, msg, at = Read.parse(r.buf, r.base, r.limit, opts) + if not raw then + return nil, Err.from(msg, at) + end + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene = pcall(Build.scene, raw, opts :: any) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function ThreeDs.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, err = pcall(Write.encode, scene, opts :: any) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + return nil, Err.new(Err.ARG, tostring(err)) + end + return out, nil +end + +return ThreeDs diff --git a/src/Formats/model/ms3d/Read.luau b/src/Formats/model/ms3d/Read.luau new file mode 100644 index 0000000..2470edd --- /dev/null +++ b/src/Formats/model/ms3d/Read.luau @@ -0,0 +1,464 @@ +--!strict +-- model/ms3d/Read: MilkShape 3D 1.8 (.ms3d, version 3 / 4) -> Types.Scene. The layout from MilkShape's ms3dspec.h +-- (chUmbaLum soft): vertices (position, a bone), triangles (three vertex indices, per-corner normals and uvs, a +-- smoothing group, a group), groups (named triangle lists with a material), materials (Phong colours, shininess +-- 0..128, transparency, texture and alpha map file names), the animation header (fps, current time, frames) and +-- joints (name, parent name, local Euler XYZ rotation in radians and position, rotation / position keys in seconds +-- relative to that rest pose); then the optional sub-versioned blocks: comments (groups, materials, joints, model), +-- vertex extras (three more bones and weights in percent: subversion 1-3, with one or two extra u32s from 2 / 3), +-- joint extras (colours) and model extras (joint size, transparency mode, alpha reference). +-- Mapping: one node + mesh + primitive per group; joints -> nodes in their hierarchy, a skin (inverse bind matrices +-- of the rest pose; JOINTS_0 / WEIGHTS_0 when a vertex has a bone) and one animation (rest * key rotations, rest + +-- key positions). Never throws on bad data: returns nil, message, offset. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") + +local Read = {} + +local S = Types.Scene +local readu8, readi8, readu16, readi32, readf32, readstring = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi32, buffer.readf32, buffer.readstring +local writef32, writeu8, writeu16, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu16, buffer.writeu32 + +Read.MAGIC = "MS3D000000" + +export type Options = { maxVertices: number? } + +-- ------------------------------------------------------------------------------------------------ helpers +local function fixed(b: buffer, p: number, n: number): string + local s = readstring(b, p, n) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +local function floats(values: { number }, comps: number): Types.Accessor + local n = #values // comps + local a = S.accessor(nil, "f32", comps, n) + for i = 1, n * comps do + writef32(a.data, (i - 1) * 4, values[i]) + end + return a +end + +local function color(b: buffer, p: number): { number } + return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8), readf32(b, p + 12) } +end + +-- the texture file name as a relative uri (MilkShape writes ".\name.jpg") +local function uri(s: string): string + local u = string.gsub(s, "\\", "/") + u = string.gsub(u, "^%./", "") + return u +end + +-- the rotation of Euler XYZ radians (R = Rz * Ry * Rx) as a quaternion +local function euler(x: number, y: number, z: number): { number } + return Mat4.quat(Mat4.euler(math.deg(x), math.deg(y), math.deg(z))) +end + +-- ------------------------------------------------------------------------------------------------ parse +type Vertex = { pos: { number }, bones: { number }, weights: { number } } +type Joint = { + name: string, parent: string, flags: number, rot: { number }, pos: { number }, + rotKeys: { { number } }, posKeys: { { number } }, comment: string?, color: { number }?, +} + +-- scene(b, base, limit, opts) -> Scene | nil, message, offset +function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Types.Scene?, string?, number?) + local p = base + local function need(n: number): boolean + return p + n <= limit + end + if not need(14) or readstring(b, p, 10) ~= Read.MAGIC then + return nil, "not a MilkShape 3D file", base + end + local version = readi32(b, p + 10) + if version ~= 3 and version ~= 4 then + return nil, "unsupported: version " .. version, p + 10 + end + p += 14 + local maxV = opts and opts.maxVertices or 2 ^ 20 + -- vertices + if not need(2) then + return nil, "truncated vertex count", p + end + local nv = readu16(b, p) + p += 2 + if not need(nv * 15) then + return nil, "truncated vertices", p + end + local verts: { Vertex } = {} + for i = 1, nv do + local q = p + (i - 1) * 15 + verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } } + end + p += nv * 15 + -- triangles + if not need(2) then + return nil, "truncated triangle count", p + end + local nt = readu16(b, p) + p += 2 + if not need(nt * 70) then + return nil, "truncated triangles", p + end + if nt * 3 > maxV then + return nil, "limit: more than " .. maxV .. " triangle corners", p + end + local triAt = p + p += nt * 70 + -- groups + if not need(2) then + return nil, "truncated group count", p + end + local ng = readu16(b, p) + p += 2 + local groups = {} + for _ = 1, ng do + if not need(35) then + return nil, "truncated group", p + end + local g = { flags = readu8(b, p), name = fixed(b, p + 1, 32), tris = {} :: { number }, material = -1, comment = nil :: string? } + local n = readu16(b, p + 33) + p += 35 + if not need(n * 2 + 1) then + return nil, "truncated group triangles", p + end + for k = 0, n - 1 do + local ti = readu16(b, p + k * 2) + if ti >= nt then + return nil, "group triangle " .. ti .. " out of range", p + k * 2 + end + table.insert(g.tris, ti) + end + p += n * 2 + g.material = readi8(b, p) + p += 1 + table.insert(groups, g) + end + -- materials + if not need(2) then + return nil, "truncated material count", p + end + local nm = readu16(b, p) + p += 2 + if not need(nm * 361) then + return nil, "truncated materials", p + end + local mats = {} + for i = 0, nm - 1 do + local q = p + i * 361 + table.insert(mats, { + name = fixed(b, q, 32), ambient = color(b, q + 32), diffuse = color(b, q + 48), specular = color(b, q + 64), + emissive = color(b, q + 80), shininess = readf32(b, q + 96), transparency = readf32(b, q + 100), + mode = readi8(b, q + 104), texture = fixed(b, q + 105, 128), alphamap = fixed(b, q + 233, 128), comment = nil :: string?, + }) + end + p += nm * 361 + -- animation header and joints (version 3 files may end here) + local fps, current, frames = 24, 0, 0 + local joints: { Joint } = {} + if need(12) then + fps, current, frames = readf32(b, p), readf32(b, p + 4), readi32(b, p + 8) + p += 12 + if not need(2) then + return nil, "truncated joint count", p + end + local nj = readu16(b, p) + p += 2 + for _ = 1, nj do + if not need(93) then + return nil, "truncated joint", p + end + local j: Joint = { + flags = readu8(b, p), name = fixed(b, p + 1, 32), parent = fixed(b, p + 33, 32), + rot = { readf32(b, p + 65), readf32(b, p + 69), readf32(b, p + 73) }, + pos = { readf32(b, p + 77), readf32(b, p + 81), readf32(b, p + 85) }, + rotKeys = {}, posKeys = {}, + } + local nr, np = readu16(b, p + 89), readu16(b, p + 91) + p += 93 + if not need((nr + np) * 16) then + return nil, "truncated joint keys", p + end + for k = 0, nr + np - 1 do + local q = p + k * 16 + local key = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12) } + table.insert(if k < nr then j.rotKeys else j.posKeys, key) + end + p += (nr + np) * 16 + table.insert(joints, j) + end + end + -- sub-versioned blocks + local source: { [string]: any } = { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames } + local function comments(list: { any }): string? + if not need(4) then + return "truncated comments" + end + local n = readi32(b, p) + p += 4 + for _ = 1, math.max(n, 0) do + if not need(8) then + return "truncated comment" + end + local index, len = readi32(b, p), readi32(b, p + 4) + p += 8 + if len < 0 or not need(len) then + return "comment runs past the end" + end + if list[index + 1] then + list[index + 1].comment = readstring(b, p, len) + end + p += len + end + return nil + end + if need(4) then + local sub = readi32(b, p) + p += 4 + source.commentVersion = sub + if sub == 1 then + for _, list in { groups, mats, joints } :: { { any } } do + local e = comments(list) + if e then + return nil, e, p + end + end + if not need(4) then + return nil, "truncated model comment", p + end + local has = readi32(b, p) + p += 4 + if has ~= 0 then + if not need(4) then + return nil, "truncated model comment", p + end + local len = readi32(b, p) + p += 4 + if len < 0 or not need(len) then + return nil, "model comment runs past the end", p + end + source.comment = readstring(b, p, len) + p += len + end + end + end + if need(4) then + local sub = readi32(b, p) + p += 4 + source.vertexVersion = sub + local size = if sub == 1 then 6 elseif sub == 2 then 10 elseif sub == 3 then 14 else 0 + if size > 0 and need(nv * size) then + for i = 1, nv do + local q = p + (i - 1) * size + local v = verts[i] + local w0, w1, w2 = readu8(b, q + 3), readu8(b, q + 4), readu8(b, q + 5) + if w0 + w1 + w2 > 0 then + local scale = if w0 > 100 or w1 > 100 or w2 > 100 or w0 + w1 + w2 > 100 then 255 else 100 + v.bones = { v.bones[1], readi8(b, q), readi8(b, q + 1), readi8(b, q + 2) } + v.weights = { w0 / scale, w1 / scale, w2 / scale, math.max(0, 1 - (w0 + w1 + w2) / scale) } + end + end + p += nv * size + end + end + if need(4) then + local sub = readi32(b, p) + p += 4 + if (sub == 1 or sub == 2) and need(#joints * 12) then + for _, j in joints do + j.color = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } + p += 12 + end + end + end + if need(16) and readi32(b, p) >= 1 then + source.jointSize, source.transparencyMode, source.alphaRef = readf32(b, p + 4), readi32(b, p + 8), readf32(b, p + 12) + end + return Read.build(b, triAt, verts, groups, mats, joints, source), nil, nil +end + +-- ------------------------------------------------------------------------------------------------ build +function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }, mats: { any }, joints: { Joint }, source: { [string]: any }): Types.Scene + local scene = S.new() + scene.meta.up = "y" + scene.meta.source = source :: any + -- materials, textures + for _, m in mats do + local mat = S.material(m.name) + local d = m.diffuse + mat.baseColor = { d[1], d[2], d[3], math.clamp(m.transparency, 0, 1) } + mat.metallic = 0 + mat.roughness = math.clamp(math.sqrt(2 / (math.clamp(m.shininess, 0, 128) + 2)), 0, 1) + mat.emissive = { m.emissive[1], m.emissive[2], m.emissive[3] } + mat.alphaMode = if m.transparency < 1 then "blend" else "opaque" + if m.texture ~= "" then + local tex: Types.Texture = { name = m.texture, uri = uri(m.texture) } + table.insert(scene.textures, tex) + mat.baseColorTexture = { texture = #scene.textures } + end + mat.extras = { + ms3d = { + ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, emissive = m.emissive, shininess = m.shininess, + transparency = m.transparency, mode = m.mode, texture = m.texture, alphamap = m.alphamap, comment = m.comment, + }, + } + table.insert(scene.materials, mat) + end + -- joints: nodes, rest pose, skin + local nj = #joints + local jointNode: { [number]: number } = {} + local byName: { [string]: number } = {} + local abs: { { number } } = {} + for i, j in joints do + local node: Types.Node = { name = j.name, children = {}, translation = j.pos, rotation = euler(j.rot[1], j.rot[2], j.rot[3]) } + node.extras = { ms3d = { flags = j.flags, comment = j.comment, color = j.color } } + table.insert(scene.nodes, node) + jointNode[i] = #scene.nodes + if byName[j.name] == nil then + byName[j.name] = i + end + end + for i, j in joints do + local pi = byName[j.parent] + -- parents must come first (MilkShape writes them in that order); others become roots + local local_ = S.nodeMatrix(scene.nodes[jointNode[i]]) + if pi and pi < i then + table.insert(scene.nodes[jointNode[pi]].children, jointNode[i]) + abs[i] = S.mul(abs[pi], local_) + else + table.insert(scene.roots, jointNode[i]) + abs[i] = local_ + end + end + local skinned = false + for _, v in verts do + for k = 1, 4 do + if v.bones[k] >= nj then + v.bones[k] = -1 + end + end + skinned = skinned or (nj > 0 and v.bones[1] >= 0) + end + if nj > 0 then + local ibm = S.accessor(nil, "f32", 16, nj) + ibm.matrix = true + for i = 1, nj do + local inv = Mat4.inverse(abs[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm.data, ((i - 1) * 16 + k - 1) * 4, inv[k]) + end + end + local list = table.create(nj, 0) + for i = 1, nj do + list[i] = jointNode[i] + end + scene.skins[1] = { joints = list, inverseBindMatrices = ibm } + end + -- groups: one node + mesh each; vertices unwelded per (vertex, normal, uv) corner + local nv = #verts + for gi, g in groups do + local remap: { [string]: number } = {} + local P, N, U, J, W = {}, {}, {}, {}, {} + local idx: { number } = {} + local sgs: { number } = {} + local count = 0 + for _, ti in g.tris do + local q = triAt + ti * 70 + -- a triangle with an out-of-range vertex is dropped + if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then + continue + end + table.insert(sgs, readu8(b, q + 68)) + for k = 0, 2 do + local vi = readu16(b, q + 2 + k * 2) + local key = vi .. readstring(b, q + 8 + k * 12, 12) .. readstring(b, q + 44 + k * 4, 4) .. readstring(b, q + 56 + k * 4, 4) + local o = remap[key] + if o == nil then + o = count + count += 1 + remap[key] = o + local v = verts[vi + 1] + table.move(v.pos, 1, 3, o * 3 + 1, P) + N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12) + U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4) + -- influences: the valid bones, weights normalized + local sum = 0 + for c = 1, 4 do + if v.bones[c] >= 0 then + sum += v.weights[c] + end + end + for c = 1, 4 do + local ok = v.bones[c] >= 0 and sum > 0 + J[o * 4 + c] = if ok then v.bones[c] else 0 + W[o * 4 + c] = if ok then v.weights[c] / sum else 0 + end + end + table.insert(idx, o :: number) + end + end + local prim: Types.Primitive = { + attributes = { POSITION = floats(P, 3), NORMAL = floats(N, 3), TEXCOORD_0 = floats(U, 2) }, + mode = "triangles", + material = if g.material >= 0 and g.material < #mats then g.material + 1 else nil, + extras = { ms3d = { smoothing = sgs } }, + } + local ind = S.accessor(nil, "u32", 1, #idx) + for i, v in idx do + writeu32(ind.data, (i - 1) * 4, v) + end + prim.indices = ind + local node: Types.Node = { name = g.name, children = {}, extras = { ms3d = { flags = g.flags, comment = g.comment } } } + if skinned then + local ja = S.accessor(nil, if nj > 255 then "u16" else "u8", 4, count) + for i = 1, count * 4 do + if nj > 255 then + writeu16(ja.data, (i - 1) * 2, J[i]) + else + writeu8(ja.data, i - 1, J[i]) + end + end + prim.attributes.JOINTS_0 = ja + prim.attributes.WEIGHTS_0 = floats(W, 4) + node.skin = 1 + end + local mesh: Types.Mesh = { name = g.name :: string, primitives = { prim } } + scene.meshes[gi] = mesh + node.mesh = gi + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + -- the animation: rest * key rotations, rest + key positions + local channels: { Types.Channel } = {} + for i, j in joints do + if #j.rotKeys > 0 then + local times, vals = {}, {} + local rest = scene.nodes[jointNode[i]].rotation :: { number } + for _, k in j.rotKeys do + table.insert(times, k[1]) + local q = Mat4.quat(Mat4.mul(Mat4.fromQuat(rest), Mat4.fromQuat(euler(k[2], k[3], k[4])))) + table.move(q, 1, 4, #vals + 1, vals) + end + local ch: Types.Channel = { node = jointNode[i], path = "rotation", input = floats(times, 1), output = floats(vals, 4), interpolation = "LINEAR" } + table.insert(channels, ch) + end + if #j.posKeys > 0 then + local times, vals = {}, {} + for _, k in j.posKeys do + table.insert(times, k[1]) + table.insert(vals, j.pos[1] + k[2]) + table.insert(vals, j.pos[2] + k[3]) + table.insert(vals, j.pos[3] + k[4]) + end + local ch: Types.Channel = { node = jointNode[i], path = "translation", input = floats(times, 1), output = floats(vals, 3), interpolation = "LINEAR" } + table.insert(channels, ch) + end + end + if #channels > 0 then + table.insert(scene.animations, { name = "ms3d", channels = channels }) + end + return scene +end + +return Read diff --git a/src/Formats/model/ms3d/Write.luau b/src/Formats/model/ms3d/Write.luau new file mode 100644 index 0000000..3cef5bd --- /dev/null +++ b/src/Formats/model/ms3d/Write.luau @@ -0,0 +1,486 @@ +--!strict +-- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped, +-- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first +-- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2); +-- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each +-- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's +-- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials: +-- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and +-- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment), +-- joint colours and model extras are written in their sub-versioned blocks. +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") + +local Write = {} + +local S = Types.Scene +local sqrt = math.sqrt + +export type Options = { fps: number?, name: string?, files: { [string]: any }? } + +local function fixedString(w: Bytes.Writer, s: string, n: number) + local v = string.sub(string.gsub(s, "%z", ""), 1, n - 1) + w:string(v) + for _ = #v + 1, n do + w:u8(0) + end +end + +local function msg(s: any): string + return if type(s) == "string" then s else "" +end + +-- ------------------------------------------------------------------------------------------------ tree +type Tree = { world: { [number]: { number } }, parent: { [number]: number }, order: { number } } +local function tree(scene: Types.Scene): Tree + local t: Tree = { world = {}, parent = {}, order = {} } + local function visit(i: number, p: number, pm: { number }, depth: number) + local n = scene.nodes[i] + if type(n) ~= "table" or t.world[i] or depth > 256 then + return + end + t.world[i] = S.mul(pm, S.nodeMatrix(n)) + t.parent[i] = p + table.insert(t.order, i) + for _, c in n.children or {} do + visit(c, i, t.world[i], depth + 1) + end + end + for _, r in scene.roots do + visit(r, 0, S.IDENTITY, 0) + end + return t +end + +-- ------------------------------------------------------------------------------------------------ joints +type Joint = { node: number, name: string, parent: string, pos: { number }, rot: { number }, quat: { number }, rotKeys: { { number } }, posKeys: { { number } } } + +-- the rigid part (rotation and translation) of a matrix +local function rigid(m: { number }): { number } + local t, r = Mat4.decompose(m) + return Mat4.compose(t, r, nil) +end + +-- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order; +-- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices +local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: number }, { [number]: number }, { number }) + local skin = scene.skins[1] + local anim = scene.animations[1] + local out: { Joint } = {} + local bySkin: { [number]: number } = {} + local byNode: { [number]: number } = {} + local skinIndex: { [number]: number } = {} + local isJoint: { [number]: boolean } = {} + for k, ni in (if skin then skin.joints else {}) :: { number } do + skinIndex[ni] = k - 1 + isJoint[ni] = true + end + local chans: { [number]: { Types.Channel } } = {} + for _, ch in (if anim then anim.channels else {}) :: { Types.Channel } do + if (ch.path == "rotation" or ch.path == "translation") and tr.world[ch.node] then + isJoint[ch.node] = true + chans[ch.node] = chans[ch.node] or {} + table.insert(chans[ch.node], ch) + end + end + -- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix + local B = S.IDENTITY + local IBM: any = if skin and skin.inverseBindMatrices then S.reader(skin.inverseBindMatrices) else nil + if skin and IBM and tr.world[skin.joints[1]] then + local m = table.create(16, 0) + for c = 1, 16 do + m[c] = (IBM :: any)(0, c - 1) + end + B = S.mul(tr.world[skin.joints[1]], m) + end + local names: { [string]: boolean } = {} + for _, ni in tr.order do + if not isJoint[ni] or #out >= 127 then + continue + end + local p = tr.parent[ni] + while p ~= 0 and byNode[p] == nil do + p = tr.parent[p] + end + -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the + -- joint and its joint parent (C) carry over to the keys + local invP = if p ~= 0 then Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() else Mat4.identity() + local gp = tr.parent[ni] + local C = S.mul(invP, if gp ~= 0 then tr.world[gp] else S.IDENTITY) + local t, r = Mat4.decompose(S.mul(invP, rigid(tr.world[ni]))) + local e = Mat4.eulerXYZ(r) + local base = string.sub(msg(scene.nodes[ni].name), 1, 27) + local name = if base ~= "" then base else "joint" .. #out + local n = 1 + while names[name] do + n += 1 + name = base .. "_" .. n + end + names[name] = true + local j: Joint = { + node = ni, name = name, parent = if p ~= 0 then out[byNode[p] + 1].name else "", pos = t, + rot = { math.rad(e[1]), math.rad(e[2]), math.rad(e[3]) }, quat = r, rotKeys = {}, posKeys = {}, + } + table.insert(out, j) + byNode[ni] = #out - 1 + if skinIndex[ni] then + bySkin[skinIndex[ni]] = #out - 1 + end + -- keys relative to the rest pose: rotation rest^-1 * C * R(t), position C * T(t) - rest + local _, rc = Mat4.decompose(C) + local inv = Mat4.transpose3(Mat4.fromQuat(r)) + for _, ch in chans[ni] or {} do + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local cubic = ch.interpolation == "CUBICSPLINE" + for k = 0, ch.input.count - 1 do + local v = if cubic then k * 3 + 1 else k + local time = IN(k, 0) + if ch.path == "rotation" then + local q = { OUT(v, 0), OUT(v, 1), OUT(v, 2), OUT(v, 3) } + local l = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + q = if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else { 0, 0, 0, 1 } + local d = Mat4.eulerXYZ(Mat4.quat(S.mul(inv, S.mul(Mat4.fromQuat(rc), Mat4.fromQuat(q))))) + table.insert(j.rotKeys, { time, math.rad(d[1]), math.rad(d[2]), math.rad(d[3]) }) + else + local x, y, z = Mat4.point(C, OUT(v, 0), OUT(v, 1), OUT(v, 2)) + table.insert(j.posKeys, { time, x - t[1], y - t[2], z - t[3] }) + end + end + end + end + return out, bySkin, byNode, B +end + +-- ------------------------------------------------------------------------------------------------ geometry +type Vertex = { x: number, y: number, z: number, bones: { number }, weights: { number } } +type Tri = { v: { number }, n: { number }, uv: { number }, sg: number, group: number } +type Group = { name: string, tris: { number }, material: number, flags: number, comment: string? } + +-- every placed primitive as a group: vertices, triangles; or nil, message +local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number }, byNode: { [number]: number }, B: { number }): ({ Vertex }, { Tri }, { Group }, string?) + local verts: { Vertex }, tris: { Tri }, groups: { Group } = {}, {}, {} + for _, pl in S.flatten(scene) do + local prim: any = pl.primitive + local node = scene.nodes[pl.node] + local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } }, function(): boolean + return false + end, { triangulate = true }) + if not merged then + return verts, tris, groups, err + end + local corners = merged.corners + if #corners == 0 then + continue + end + local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil + -- a rigid mesh follows its nearest joint + local rigid = -1 + if not skinned then + local p = pl.node + while p and p ~= 0 do + if byNode[p] then + rigid = byNode[p] + break + end + p = tr.parent[p] + end + end + local M = if skinned then B else pl.matrix + local NM = Mat4.normalMatrix(M) + local mirror = M[1] * (M[6] * M[11] - M[7] * M[10]) - M[5] * (M[2] * M[11] - M[3] * M[10]) + M[9] * (M[2] * M[7] - M[3] * M[6]) < 0 + local A = prim.attributes + local POS = S.reader(A.POSITION) :: any + local zero = function(_: number, _: number): number + return 0 + end + type Get = (number, number) -> number + local hasN, hasUV = A.NORMAL ~= nil, A.TEXCOORD_0 ~= nil + local NOR: Get = (if hasN then S.reader(A.NORMAL) else nil) or zero + local UV: Get = (if hasUV then S.reader(A.TEXCOORD_0) else nil) or zero + local JO: Get = (if skinned then S.reader(A.JOINTS_0) else nil) or zero + local WE: Get = (if skinned then S.reader(A.WEIGHTS_0) else nil) or zero + local base = #verts + local nv = A.POSITION.count + if base + nv > 65535 then + return verts, tris, groups, "more than 65535 vertices" + end + for v = 0, nv - 1 do + local x, y, z = Mat4.point(M, POS(v, 0), POS(v, 1), POS(v, 2)) + local bones, weights = { rigid, -1, -1, -1 }, { 1, 0, 0, 0 } + if skinned then + local inf = {} + for c = 0, 3 do + local w = WE(v, c) + local j = bySkin[JO(v, c)] + if w > 0 and j then + table.insert(inf, { j, w }) + end + end + table.sort(inf, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for _, e in inf do + sum += e[2] + end + for c = 1, 4 do + local e = inf[c] + bones[c] = if e then e[1] else -1 + weights[c] = if e and sum > 0 then e[2] / sum else 0 + end + end + table.insert(verts, { x = x, y = y, z = z, bones = bones, weights = weights }) + end + local gi = #groups + if gi >= 255 then + return verts, tris, groups, "more than 255 groups" + end + local name = msg(node.name) + if name == "" then + name = msg(scene.meshes[pl.mesh] and scene.meshes[pl.mesh].name) + end + local x = node.extras and node.extras.ms3d + local g: Group = { + name = if name ~= "" then name else "group" .. gi, tris = {}, flags = if x and type(x.flags) == "number" then x.flags else 0, + material = if type(prim.material) == "number" and prim.material <= 127 then prim.material - 1 else -1, + comment = x and x.comment, + } + local saved = prim.extras and prim.extras.ms3d and prim.extras.ms3d.smoothing + if type(saved) ~= "table" or #saved ~= #corners // 3 then + saved = nil + end + for f = 0, #corners // 3 - 1 do + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + if mirror then + b, c = c, b + end + local t: Tri = { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = if saved then saved[f + 1] else 1, group = gi } + -- the face normal for primitives without normals + local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1] + local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z + local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z + local fx, fy, fz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { a, b, c } do + local nx, ny, nz = fx, fy, fz + if hasN then + local ox, oy, oz = NOR(v, 0), NOR(v, 1), NOR(v, 2) + nx = NM[1] * ox + NM[5] * oy + NM[9] * oz + ny = NM[2] * ox + NM[6] * oy + NM[10] * oz + nz = NM[3] * ox + NM[7] * oy + NM[11] * oz + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + table.move({ nx, ny, nz }, 1, 3, #t.n + 1, t.n) + table.insert(t.uv, UV(v, 0)) + table.insert(t.uv, UV(v, 1)) + end + table.insert(tris, t) + table.insert(g.tris, #tris - 1) + end + if #tris > 65535 then + return verts, tris, groups, "more than 65535 triangles" + end + table.insert(groups, g) + end + return verts, tris, groups, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local tr = tree(scene) + local js, bySkin, byNode, B = joints(scene, tr) + local verts, tris, groups, gerr = geometry(scene, tr, bySkin, byNode, B) + if gerr then + return nil, gerr + end + if #scene.materials > 127 then + return nil, "more than 127 materials" + end + local src: any = scene.meta.source + local fromMs3d = src ~= nil and src.format == "ms3d" + local w = Bytes.writer(65536) + w:string("MS3D000000") + w:u32le(4) + w:u16le(#verts) + for _, v in verts do + w:u8(0) + w:f32le(v.x) + w:f32le(v.y) + w:f32le(v.z) + w:i8(v.bones[1] % 256) + w:u8(1) + end + w:u16le(#tris) + for _, t in tris do + w:u16le(0) + for k = 1, 3 do + w:u16le(t.v[k]) + end + for k = 1, 9 do + w:f32le(t.n[k]) + end + for k = 1, 3 do + w:f32le(t.uv[k * 2 - 1]) + end + for k = 1, 3 do + w:f32le(t.uv[k * 2]) + end + w:u8(math.clamp(t.sg, 0, 255)) + w:u8(t.group) + end + w:u16le(#groups) + for _, g in groups do + w:u8(g.flags % 256) + fixedString(w, g.name, 32) + w:u16le(#g.tris) + for _, ti in g.tris do + w:u16le(ti) + end + w:i8(g.material % 256) + end + -- materials + w:u16le(#scene.materials) + local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture" + for i, m in scene.materials do + local x = (m.extras and m.extras.ms3d or {}) :: { [string]: any } + local bc = m.baseColor or { 1, 1, 1, 1 } + fixedString(w, msg(m.name) ~= "" and msg(m.name) or ("material" .. i), 32) + local e = m.emissive or { 0, 0, 0 } + for _, c in { x.ambient or { 0.2, 0.2, 0.2, 1 }, { bc[1], bc[2], bc[3], bc[4] or 1 }, x.specular or { 0, 0, 0, 1 }, { e[1], e[2], e[3], 1 } } do + for k = 1, 4 do + w:f32le(c[k] or 1) + end + end + local r = math.max(m.roughness or 1, 0.1) + w:f32le(x.shininess or math.clamp(2 / (r * r) - 2, 0, 128)) + w:f32le(bc[4] or 1) + w:i8((tonumber(x.mode) or 0) % 256) + local file = "" + local ref: any = m.baseColorTexture + local tex: any = ref and scene.textures[ref.texture] + if tex then + file = tex.uri or "" + if file == "" or string.sub(file, 1, 5) == "data:" then + file = base .. "_" .. ref.texture .. ".png" + if o.files and tex.data then + o.files[file] = tex.data + end + end + end + fixedString(w, file, 128) + fixedString(w, msg(x.alphamap), 128) + end + -- the animation header and joints + local fps = o.fps or (if fromMs3d and type(src.fps) == "number" and src.fps > 0 then src.fps else 24) + local last = 0 + for _, j in js do + for _, k in j.rotKeys do + last = math.max(last, k[1]) + end + for _, k in j.posKeys do + last = math.max(last, k[1]) + end + end + w:f32le(fps) + w:f32le(0) + w:u32le(math.max(1, math.ceil(last * fps))) + w:u16le(#js) + for _, j in js do + local x = scene.nodes[j.node].extras + local jx = x and x.ms3d + w:u8(if jx and type(jx.flags) == "number" then jx.flags % 256 else 0) + fixedString(w, j.name, 32) + fixedString(w, j.parent, 32) + for k = 1, 3 do + w:f32le(j.rot[k]) + end + for k = 1, 3 do + w:f32le(j.pos[k]) + end + w:u16le(#j.rotKeys) + w:u16le(#j.posKeys) + for _, list in { j.rotKeys, j.posKeys } do + for _, k in list do + for c = 1, 4 do + w:f32le(k[c]) + end + end + end + end + -- comments + w:u32le(1) + local function comments(list: { any }, get: (any) -> string?) + local found = {} + for i, item in list do + local c = get(item) + if type(c) == "string" and c ~= "" then + table.insert(found, { i - 1, c }) + end + end + w:u32le(#found) + for _, f in found do + w:u32le(f[1]) + w:u32le(#f[2]) + w:string(f[2]) + end + end + comments(groups, function(g: any): string? + return g.comment + end) + comments(scene.materials, function(m: any): string? + return m.extras and m.extras.ms3d and m.extras.ms3d.comment + end) + comments(js, function(j: any): string? + local x: any = scene.nodes[j.node].extras + return x and x.ms3d and x.ms3d.comment + end) + local mc = if fromMs3d then msg(src.comment) else "" + w:u32le(if mc ~= "" then 1 else 0) + if mc ~= "" then + w:u32le(#mc) + w:string(mc) + end + -- vertex extras: three more bones, the weights in percent (the last one implied), an extra u32 + w:u32le(2) + for _, v in verts do + local p = table.create(3, 0) + local left = 100 + for c = 1, 3 do + p[c] = math.clamp(math.floor(v.weights[c] * 100 + 0.5), 0, left) + left -= p[c] + end + if v.bones[2] < 0 and v.bones[1] >= 0 then + p = { 100, 0, 0 } + end + for c = 2, 4 do + w:i8(v.bones[c] % 256) + end + for c = 1, 3 do + w:u8(p[c]) + end + w:u32le(0) + end + -- joint colours, model extras + w:u32le(1) + for _, j in js do + local x: any = scene.nodes[j.node].extras + local c = x and x.ms3d and x.ms3d.color or { 1, 1, 1 } + for k = 1, 3 do + w:f32le(c[k] or 1) + end + end + w:u32le(1) + w:f32le(if fromMs3d and type(src.jointSize) == "number" then src.jointSize else 1) + w:u32le(if fromMs3d and type(src.transparencyMode) == "number" then src.transparencyMode else 0) + w:f32le(if fromMs3d and type(src.alphaRef) == "number" then src.alphaRef else 0.5) + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Write diff --git a/src/Formats/model/ms3d/init.luau b/src/Formats/model/ms3d/init.luau new file mode 100644 index 0000000..e9db7b7 --- /dev/null +++ b/src/Formats/model/ms3d/init.luau @@ -0,0 +1,82 @@ +--!strict +-- model/ms3d: MilkShape 3D (.ms3d, versions 3 and 4, with the comment / vertex / joint / model extra blocks of +-- MilkShape 1.8). New code from MilkShape's ms3dspec.h; assimp's MS3D importer (BSD-3) is the reference it is tested +-- against (no code ported). +-- Reads (model/ms3d/Read): groups -> one node, mesh and primitive each (POSITION, the per-corner NORMAL and +-- TEXCOORD_0: MilkShape's uv origin is already glTF's top left; vertices unwelded per corner; smoothing groups in +-- extras.ms3d.smoothing), materials (diffuse -> baseColor with transparency as alpha, shininess -> roughness, emissive; +-- ambient / specular / mode / alpha map in extras.ms3d; the texture file -> a Texture with `uri`, not loaded: use +-- F.model.loadTextures), joints -> nodes (hierarchy by parent name, Euler XYZ rest rotations), one skin (inverse +-- bind matrices of the rest pose, JOINTS_0 / WEIGHTS_0 from the vertex bone and the extra bones / weights), keyframes +-- -> one animation (rotation and translation channels, times in seconds), comments and joint colours in extras.ms3d, +-- the model comment / fps / frames / joint size in meta.source. meta.up = "y". +-- Writes (model/ms3d/Write): version 4 with subversion 1 comments, subversion 2 vertex extras (four bones per vertex), +-- joint colours and model extras. Limits of the format (Err.ARG): 65535 vertices / triangles, 255 groups, 127 +-- materials, 127 joints. Not supported: scale keys (MilkShape has none), more than one skin (the first one is written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/ms3d/Read") +local Write = require("@formats/model/ms3d/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Ms3d = { + name = "ms3d", + category = "model", + extensions = { "ms3d" }, + mime = { "application/x-ms3d" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxVertices: number?, -- refuse more triangle corners (default 2^20) +} +export type EncodeOptions = { + fps: number?, -- the animation's frames per second (default: the source's, else 24) + name: string?, -- the destination's file name (names textures that have no uri) + files: { [string]: any }?, -- receives the bytes of textures that have data but no uri +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ms3d.sniff(r: Bytes.Reader): number + local h = r:peek(14) + if string.sub(h, 1, 10) ~= Read.MAGIC then + return 0 + end + local v = string.byte(h, 11) + return if v == 3 or v == 4 then 1 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ms3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, at) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ms3d.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local ok, out, err = pcall(Write.encode, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + return nil, Err.new(Err.ARG, tostring(err)) + end + return out, nil +end + +return Ms3d diff --git a/tests/model/3ds.luau b/tests/model/3ds.luau new file mode 100644 index 0000000..52aeb63 --- /dev/null +++ b/tests/model/3ds.luau @@ -0,0 +1,602 @@ +-- model/3ds tests: assimp's 3DS test models (meshes, materials, textures, keyframer hierarchies, pivots, camera / +-- target / rotation animation, cameras, lights) and assimp's 3DS exporter output, against assimp (meshes, faces, +-- corners, materials, animations, cameras, lights, world bounds); the keyframer placing every mesh where its mesh +-- matrix says; round trips through our writer (world triangles, materials, textures, cameras, lights, sampled +-- animation) for the reference files and for glTF sample models; assimp reading our files like the originals +-- (3ds_xcheck); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/3ds.py. +local T = require("@tests/T") +local F = require("@formats") +local ThreeDs = require("@formats/model/3ds") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/3ds_cases") +local Picks = require("@tests/gen/3ds_gltf") +local Xcheck = require("@tests/gen/3ds_xcheck") + +local t = T.suite("3ds") +local S = Types.Scene + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return ThreeDs.decode(Bytes.reader(b), opts) +end + +t:eq(ThreeDs.name, "3ds", "name") +t:eq(ThreeDs.category, "model", "category") +t:check(ThreeDs.caps.decode and ThreeDs.caps.encode, "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +-- placed primitives, triangles, corners +local function counts(scene: any): (number, number, number) + local prims, faces, corners = 0, 0, 0 + local seen = {} + for _, pl in S.flatten(scene) do + if not seen[pl.primitive] then + seen[pl.primitive] = true + prims += 1 + faces += pl.primitive.indices.count // 3 + corners += pl.primitive.indices.count + end + end + return prims, faces, corners +end + +local function noMaterial(scene: any): boolean + for _, m in scene.meshes do + for _, p in m.primitives do + if p.material == nil then + return true + end + end + end + return false +end + +-- assimp's default material: an existing grey untextured material named "*default*" is reused +local function defaultReused(scene: any): boolean + for _, m in scene.materials do + local c = m.baseColor + if string.find(string.lower(m.name or ""), "default", 1, true) and c[1] == c[2] and c[1] == c[3] and not m.baseColorTexture then + local x = m.extras["3ds"].maps + if next(x) == nil then + return true + end + end + end + return false +end + +-- world bounds: as they are, or under assimp's Z-up -> Y-up root rotation (x, z, -y) +local function boundsMatch(lo: { number }, hi: { number }, want: any, eps: number): boolean + local function eq(a: { number }, b: { number }): boolean + for k = 1, 3 do + if not near(a[k], want.min[k], eps) or not near(b[k], want.max[k], eps) then + return false + end + end + return true + end + return eq(lo, hi) or eq({ lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] }) +end + +local function bstr(lo: any, hi: any): string + if not lo then + return "-" + end + return string.format("(%.4g %.4g %.4g) (%.4g %.4g %.4g)", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]) +end + +-- ------------------------------------------------------------------------------------------------ reference files +-- assimp ignores the camera / light frame of their children (CameraRollAnimWithChildObject: a box linked to the +-- camera); our bounds follow the mesh matrices there (checked below) +local ASSIMP_BOUNDS_DIFFER = { ["assimp/models/CameraRollAnimWithChildObject.3ds"] = true } +local function boundsDiffer(i: number): boolean + return ASSIMP_BOUNDS_DIFFER[Cases[i].name] == true +end +local scenes = {} +local checked = 0 +for i, c in Cases do + local scene, err = decode(c.data) + local a = c.assimp + if a.failed then + t:note("%s: assimp rejects it; we read it: %s", c.name, tostring(scene ~= nil)) + else + t:check(scene, c.name .. ": decode: " .. tostring(err)) + scenes[i] = scene + if scene then + local prims, faces, corners = counts(scene) + t:eq(prims, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, a.faces, c.name .. ": faces (assimp)") + t:eq(corners, a.vertices, c.name .. ": corners (assimp)") + t:eq(#scene.cameras, a.cameras, c.name .. ": cameras (assimp)") + t:eq(#scene.lights, a.lights, c.name .. ": lights (assimp)") + t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)") + local extra = if noMaterial(scene) and not defaultReused(scene) then 1 else 0 + t:eq(#scene.materials + extra, a.materials, c.name .. ": materials (assimp, + its default)") + if a.min and not ASSIMP_BOUNDS_DIFFER[c.name] then + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + t:check(lo and boundsMatch(lo, hi, a, 1e-3), c.name .. ": world bounds (assimp) " .. bstr(lo, hi) .. " want " .. bstr(a.min, a.max)) + end + checked += 1 + end + end +end +t:note("%d files against assimp", checked) + +-- the keyframer places every mesh where its mesh matrix put the stored (world space) vertices +do + local n = 0 + for i, c in Cases do + local scene = scenes[i] + if scene and scene.meta.source.keyframer and #scene.animations == 0 and string.sub(c.name, 1, 7) == "assimp/" then + local raw = decode(c.data, { normals = false }) + local flat = decode(c.data, { normals = false }) + -- the file's vertices: the meshes placed at identity (Read only; via the writer-free path: raw bounds) + local lo, hi = MeshOps.bounds(MeshOps.merge(raw)) + local _ = flat + local Read = require("@formats/model/3ds/Read") + local parsed = Read.parse(buffer.fromstring(c.data), 0, #c.data) + local plo, phi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local placed: { [string]: boolean } = {} + for _, kn in parsed.keyframer.nodes do + if kn.kind == "object" then + placed[kn.name] = true + end + end + for _, o in parsed.objects do + if o.mesh and o.mesh.nf > 0 and placed[o.name] then + for v = 0, o.mesh.nv - 1 do + for k = 1, 3 do + local x = buffer.readf32(o.mesh.positions, (v * 3 + k - 1) * 4) + plo[k], phi[k] = math.min(plo[k], x), math.max(phi[k], x) + end + end + end + end + if lo and plo[1] <= phi[1] then + local ok = true + for k = 1, 3 do + ok = ok and near(lo[k], plo[k], 2e-3) and near(hi[k], phi[k], 2e-3) + end + t:check(ok, c.name .. ": keyframer world bounds = the stored vertices " .. bstr(lo, hi) .. " / " .. bstr(plo, phi)) + n += 1 + end + end + end + t:note("%d keyframer scenes match their stored vertices", n) +end + +-- ------------------------------------------------------------------------------------------------ round trips +local function triArea(prim: any): number + local P = S.reader(prim.attributes.POSITION) :: any + local I = S.reader(prim.indices) :: any + local area = 0 + for tri = 0, prim.indices.count // 3 - 1 do + local a, b, c = I(tri * 3, 0), I(tri * 3 + 1, 0), I(tri * 3 + 2, 0) + local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) } + local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(x * x + y * y + z * z) / 2 + end + return area +end + +-- the world matrices of the nodes with a camera / light, in tree order +local function worldOf(s: any, field: string): { { number } } + local out = {} + local function visit(i: number, parent: { number }) + local n = s.nodes[i] + local w = S.mul(parent, S.nodeMatrix(n)) + if n[field] then + table.insert(out, { w = w, item = n[field] }) + end + for _, c in n.children do + visit(c, w) + end + end + for _, r in s.roots do + visit(r, S.IDENTITY) + end + return out +end + +-- channel value at a time (LINEAR / STEP; quaternions lerped the short way) +local function evalCh(ch: any, time: number, comps: number): { number } + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local n = ch.input.count + local cubic = ch.interpolation == "CUBICSPLINE" + local function v(k: number): { number } + local e = if cubic then k * 3 + 1 else k + local r = {} + for q = 0, comps - 1 do + r[q + 1] = OUT(e, q) + end + return r + end + if time <= IN(0, 0) then + return v(0) + end + for k = 0, n - 2 do + local t0, t1 = IN(k, 0), IN(k + 1, 0) + if time <= t1 then + if ch.interpolation == "STEP" or t1 <= t0 then + return if time >= t1 then v(k + 1) else v(k) + end + local u = (time - t0) / (t1 - t0) + local a0, a1 = v(k), v(k + 1) + if comps == 4 and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then + a1 = { -a1[1], -a1[2], -a1[3], -a1[4] } + end + local r = {} + for q = 1, comps do + r[q] = a0[q] + (a1[q] - a0[q]) * u + end + return r + end + end + return v(n - 1) +end + +-- the world matrix of every named node at a time (animations[1] applied) +local function posed(s: any, time: number): { [string]: { number } } + local byNode: { [number]: { [string]: any } } = {} + local anim = s.animations[1] + if anim then + for _, ch in anim.channels do + byNode[ch.node] = byNode[ch.node] or {} + byNode[ch.node][ch.path] = ch + end + end + local out = {} + local count: { [string]: number } = {} + local function visit(i: number, parent: { number }) + local n = s.nodes[i] + local m + local chs = byNode[i] + if chs then + local tr = if chs.translation then evalCh(chs.translation, time, 3) else (n.translation or { 0, 0, 0 }) + local r = if chs.rotation then evalCh(chs.rotation, time, 4) else (n.rotation or { 0, 0, 0, 1 }) + local sc = if chs.scale then evalCh(chs.scale, time, 3) else (n.scale or { 1, 1, 1 }) + local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4]) + r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l } + local Mat4 = require("@formats/codecs/model/Mat4") + m = Mat4.compose(tr, r, sc) + else + m = S.nodeMatrix(n) + end + local w = S.mul(parent, m) + local key = if n.mesh then "mesh" .. n.mesh elseif n.camera then "camera" else if n.light then "light" else nil + if key then + count[key] = (count[key] or 0) + 1 + out[key .. "#" .. count[key]] = w + end + for _, c in n.children do + visit(c, w) + end + end + for _, r in s.roots do + visit(r, S.IDENTITY) + end + return out +end + +local function compare(a: any, b: any, label: string, eps: number, animTimes: { number }?) + local ma, mb = MeshOps.merge(a), MeshOps.merge(b) + local na = if ma and ma.indices then ma.indices.count // 3 else 0 + local nb = if mb and mb.indices then mb.indices.count // 3 else 0 + t:eq(nb, na, label .. ": triangles") + if na > 0 and nb > 0 then + t:check(near(triArea(ma), triArea(mb), eps), string.format("%s: area %.7g / %.7g", label, triArea(ma), triArea(mb))) + local la, ha = MeshOps.bounds(ma) + local lb, hb = MeshOps.bounds(mb) + local ok = true + for k = 1, 3 do + ok = ok and near(la[k], lb[k], eps) and near(ha[k], hb[k], eps) + end + t:check(ok, label .. ": bounds " .. bstr(la, ha) .. " / " .. bstr(lb, hb)) + end + t:eq(#b.materials, #a.materials, label .. ": materials") + for k, m in a.materials do + local m2 = b.materials[k] + if m2 then + local ok = true + for q = 1, 4 do + ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6) + end + t:check(ok, label .. ": material " .. k .. " colour") + t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture") + t:check(m.doubleSided == m2.doubleSided, label .. ": material " .. k .. " two-sided") + end + end + for _, field in { "camera", "light" } do + local pa, pb = worldOf(a, field), worldOf(b, field) + t:eq(#pb, #pa, label .. ": " .. field .. " nodes") + for k, e in pa do + local w = e.w + local w2 = pb[k] and pb[k].w + local ok = w2 ~= nil + if w2 then + -- position and view axis (3DS cameras and lights carry no scale) + for _, q in { 13, 14, 15 } do + ok = ok and near(w[q], w2[q], 1e-4) + end + if field == "camera" or a.lights[e.item].type ~= "point" then + local function z(m: { number }): (number, number, number) + local l = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) + return m[9] / l, m[10] / l, m[11] / l + end + local x1, y1, z1 = z(w) + local x2, y2, z2 = z(w2) + ok = ok and x1 * x2 + y1 * y2 + z1 * z2 > 0.9999 + end + end + t:check(ok, label .. ": " .. field .. " " .. k .. " placement") + end + end + -- the horizontal field of view (3DS stores a lens, not the aspect) + for k, c in a.cameras do + local c2 = b.cameras[k] + if c2 and c.type == "perspective" then + local function hfov(cam: any): number + return 2 * math.atan(math.tan(cam.yfov / 2) * (cam.aspect or 4 / 3)) + end + t:check(near(hfov(c), hfov(c2), 1e-5), label .. ": camera " .. k .. " fov") + end + end + -- one timeline: the first animation's node transforms + local trs = false + for _, ch in (if a.animations[1] then a.animations[1].channels else {}) :: { any } do + trs = trs or ch.path ~= "weights" + end + t:eq(#b.animations, if trs then 1 else 0, label .. ": animations") + if animTimes and #a.animations > 0 then + local bad, n = 0, 0 + for _, time in animTimes do + local pa, pb = posed(a, time), posed(b, time) + for nm, w in pa do + local w2 = pb[nm] + if w2 then + for q = 1, 16 do + if not near(w[q], w2[q], 2e-3) then + bad += 1 + end + end + n += 1 + end + end + end + t:check(bad == 0 and n > 0, string.format("%s: posed world matrices: %d values of %d nodes x times differ", label, bad, n)) + end +end + +local TIMES = { 0, 0.1, 0.5, 1, 1.5, 2, 3.3, 5, 8 } +local nrt = 0 +for i, c in Cases do + local scene = scenes[i] + if scene then + local out, err = ThreeDs.encode(scene) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer) + t:check(back, c.name .. ": decode ours: " .. tostring(berr)) + if back then + compare(scene, back, c.name, 1e-4, TIMES) + local p1, f1 = counts(scene) + local p2, f2 = counts(back) + t:check(p1 == p2 and f1 == f2, c.name .. ": primitives and faces kept") + -- the smoothing groups come back, so the normals do + local same = true + for mi, m in scene.meshes do + local m2 = back.meshes[mi] + for pi, p in m.primitives do + local p2 = m2 and m2.primitives[pi] + if not p2 or p2.attributes.POSITION.count ~= p.attributes.POSITION.count then + same = false + end + end + end + t:check(same, c.name .. ": vertex splits (smoothing groups) kept") + end + nrt += 1 + end +end + +-- glTF sample models through 3DS +local gltfScenes = {} +local ng = 0 +for gi, g in Picks do + local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr)) + if scene then + gltfScenes[gi] = scene + local out, err = ThreeDs.encode(scene, { fps = 1000 }) + t:check(out, g.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer, { fps = 1000 }) + t:check(back, g.name .. ": decode ours: " .. tostring(berr)) + if back then + -- skins and morph targets are not 3DS; STEP / CUBICSPLINE keys become linear + local linear = true + for _, an in scene.animations do + for _, ch in an.channels do + if ch.interpolation ~= "LINEAR" or ch.path == "weights" then + linear = false + end + end + end + compare(scene, back, "glTF " .. g.name, 2e-4, if linear and #scene.skins == 0 then TIMES else nil) + ng += 1 + end + end +end +t:note("%d reference files and %d glTF models through our writer and back", nrt, ng) + +-- ------------------------------------------------------------------------------------------------ cross-check +-- assimp reads our files like the originals +local nx = 0 +for _, x in Xcheck do + local a = x.assimp + t:check(not a.failed, x.name .. ": assimp reads our file") + if not a.failed then + local scene, want + if x.case then + scene, want = scenes[x.case], Cases[x.case].assimp + else + scene = gltfScenes[x.gltf] + end + if scene then + local _, faces, corners = counts(scene) + t:eq(a.faces, faces, x.name .. ": assimp faces of our file") + t:eq(a.vertices, corners, x.name .. ": assimp corners of our file") + t:eq(a.cameras, #worldOf(scene, "camera"), x.name .. ": assimp cameras of our file") + t:eq(a.lights, #worldOf(scene, "light"), x.name .. ": assimp lights of our file") + if want and not want.failed then + t:eq(a.meshes, want.meshes, x.name .. ": assimp meshes of our file") + t:eq(a.animations, want.animations, x.name .. ": assimp animations of our file") + end + if a.min and not (x.case and boundsDiffer(x.case)) then + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + t:check(lo and boundsMatch(lo, hi, a, 1e-3), x.name .. ": assimp world bounds of our file " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max)) + end + nx += 1 + end + end +end +t:note("%d of our files read back by assimp", nx) + +-- ------------------------------------------------------------------------------------------------ details +do + local byName = {} + for i, c in Cases do + byName[c.name] = scenes[i] + end + local tex = byName["assimp/models/cube_with_diffuse_texture.3DS"] + if tex then + local m = tex.materials[1] + t:check(m.baseColorTexture and tex.textures[m.baseColorTexture.texture].uri ~= nil, "diffuse map -> baseColorTexture with a uri") + t:check(tex.textures[1].data == nil, "texture files are not read") + t:check(tex.meshes[1].primitives[1].attributes.TEXCOORD_0 ~= nil and tex.meshes[1].primitives[1].attributes.NORMAL ~= nil, "uvs and normals") + t:eq(tex.meta.up, "z", "3DS is Z up") + end + local spec = byName["assimp/models/cube_with_specular_texture.3DS"] + if spec then + t:check(spec.materials[1].extras["3ds"].maps.specular ~= nil, "specular map kept in extras") + end + local alpha = byName["assimp/models/cubes_with_alpha.3DS"] + if alpha then + local blended = 0 + for _, m in alpha.materials do + if m.alphaMode == "blend" and m.baseColor[4] < 1 then + blended += 1 + end + end + t:check(blended > 0, "transparency -> alpha " .. blended) + end + local cam = byName["assimp/models/CameraRollAnim.3ds"] + if cam then + local c = cam.cameras[1] + -- 2400 / 53.33 mm = 45 degrees horizontal at 4:3 + t:check(near(2 * math.atan(math.tan(c.yfov / 2) * c.aspect), math.rad(45), 1e-4), "camera lens -> fov " .. math.deg(c.yfov)) + local paths = {} + for _, ch in cam.animations[1].channels do + paths[ch.path] = true + end + t:check(paths.rotation, "camera roll -> a rotation channel") + end + local child = byName["assimp/models/CameraRollAnimWithChildObject.3ds"] + if child then + local camNode + for _, n in child.nodes do + if n.camera then + camNode = n + end + end + t:check(camNode and #camNode.children == 1 and child.nodes[camNode.children[1]].name == "Box02", "a box linked to the camera") + end + local spin = byName["assimp/models/RotatingCube.3DS"] + if spin then + local ch = spin.animations[1].channels[1] + t:check(ch.path == "rotation" and ch.input.count > 100, "rotation keys accumulated: " .. ch.input.count) + end + local pyr = byName["assimp/models-nonbsd/pyramob.3DS"] + if pyr then + local types = {} + for _, l in pyr.lights do + types[l.type] = true + end + t:check(types.point and types.spot, "omni and spot lights") + end + -- the api + local s = F.load(Cases[1].data) + t:check(s and s.kind == "scene" and s.meta.source.format == "3ds", "F.load detects 3DS") + local viaApi = F.save(s, nil, { format = "3ds" }) + t:check(viaApi and buffer.readu16(viaApi, 0) == 0x4D4D, "F.save format 3ds") + -- normals = false keeps the file's vertices + local raw = decode(Cases[1].data, { normals = false }) + t:check(raw and raw.meshes[1].primitives[1].attributes.NORMAL == nil, "normals = false") + -- a hand-made scene: two instances of one mesh, a texture without uri goes to opts.files + local p = S.accessor(nil, "f32", 3, 3) + for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 0, 1, 0 } } do + for k = 1, 3 do + buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k]) + end + end + local uv = S.accessor(nil, "f32", 2, 3) + local tri = S.fromPrimitive({ attributes = { POSITION = p, TEXCOORD_0 = uv }, mode = "triangles", material = 1 }, "tri") + tri.materials[1] = S.material("red") + tri.materials[1].baseColor = { 1, 0, 0, 1 } + tri.materials[1].baseColorTexture = { texture = 1 } + tri.textures[1] = { data = buffer.fromstring("\137PNG"), mime = "image/png" } + tri.nodes[2] = { name = "copy", children = {}, mesh = 1, translation = { 5, 0, 0 } } + table.insert(tri.roots, 2) + local files = {} + local out = ThreeDs.encode(tri, { name = "tri.3ds", files = files }) :: buffer + t:check(files["tri_1.png"] ~= nil, "embedded texture bytes -> opts.files") + local back = decode(out) + t:check(back and #back.meshes == 1 and #back.nodes == 2 and back.nodes[2].mesh == 1, "instances share one mesh") + t:eq(back.textures[1].uri, "tri_1.png", "the texture's file name") + local lo, hi = MeshOps.bounds(MeshOps.merge(back)) + t:check(lo[1] == 0 and hi[1] == 6, "the instance stands at x = 5") + t:eq(back.nodes[2].name, "copy", "instance name") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local empty = decode("MM\6\0\0\0") + t:check(empty and #empty.meshes == 0 and #empty.nodes == 0, "an empty main chunk: an empty scene") + local data = Cases[1].data + local _, e2 = decode(string.sub(data, 1, #data // 2)) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2)) + local _, e3 = decode("not a 3ds file at all") + t:check(e3 and e3.code == Err.CORRUPT, "garbage: " .. tostring(e3)) + local _, e4 = decode(data, { maxVertices = 3 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = ThreeDs.encode({} :: any) + t:check(e5 and e5.code == Err.ARG, "encode junk") + t:check(ThreeDs.sniff(Bytes.reader(buffer.fromstring(data))) > 0.5, "sniff") + t:eq(ThreeDs.sniff(Bytes.reader(buffer.fromstring("MM junk junk junk"))), 0, "sniff junk") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for i, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = ThreeDs.decode(Bytes.reader(b)) + if s then + ThreeDs.encode(s) + MeshOps.merge(s) + end + return s + end, samples, { mutations = 12, keepHeader = 6 }) +end + +t:done() diff --git a/tests/model/ms3d.luau b/tests/model/ms3d.luau new file mode 100644 index 0000000..fc2b59c --- /dev/null +++ b/tests/model/ms3d.luau @@ -0,0 +1,430 @@ +-- model/ms3d tests: assimp's MilkShape 3D test models (groups, materials, textures, version 4 with and without the +-- sub-versioned blocks) against assimp (meshes, faces, corners, materials, world bounds); round trips through our +-- writer, of those files and of glTF sample models (world triangles, materials, textures, skins: joints, inverse bind +-- matrices, skinned vertices; animation sampled through the skeleton); assimp reading our files (meshes, faces, +-- bones, animations, bounds: ms3d_xcheck); comments and extras; errors; the fuzz no-throw pass. Fixtures: +-- tools/fixtures/ms3d.py. +local T = require("@tests/T") +local F = require("@formats") +local Ms3d = require("@formats/model/ms3d") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Mat4 = require("@formats/codecs/model/Mat4") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/ms3d_cases") +local Picks = require("@tests/gen/ms3d_gltf") +local Xcheck = require("@tests/gen/ms3d_xcheck") + +local t = T.suite("ms3d") +local S = Types.Scene + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Ms3d.decode(Bytes.reader(b), opts) +end + +t:eq(Ms3d.name, "ms3d", "name") +t:eq(Ms3d.category, "model", "category") +t:check(Ms3d.caps.decode and Ms3d.caps.encode, "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +local function counts(scene: any): (number, number, number) + local prims, faces, corners = 0, 0, 0 + for _, pl in S.flatten(scene) do + prims += 1 + faces += pl.primitive.indices.count // 3 + corners += pl.primitive.indices.count + end + return prims, faces, corners +end + +local function bstr(lo: any, hi: any): string + if not lo then + return "-" + end + return string.format("(%.4g %.4g %.4g) (%.4g %.4g %.4g)", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]) +end + +local function boundsEq(lo: { number }, hi: { number }, want: any, eps: number): boolean + for k = 1, 3 do + if not near(lo[k], want.min[k], eps) or not near(hi[k], want.max[k], eps) then + return false + end + end + return true +end + +-- the bones assimp makes: per group, the distinct strongest joints of its vertices +local function bones(scene: any): number + local n = 0 + for _, pl in S.flatten(scene) do + local A = pl.primitive.attributes + if A.JOINTS_0 then + local J, W = S.reader(A.JOINTS_0) :: any, S.reader(A.WEIGHTS_0) :: any + local seen = {} + for v = 0, A.JOINTS_0.count - 1 do + local best, bw = -1, 0 + for c = 0, 3 do + if W(v, c) > bw then + best, bw = J(v, c), W(v, c) + end + end + if best >= 0 and not seen[best] then + seen[best] = true + n += 1 + end + end + end + end + return n +end + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes = {} +for i, c in Cases do + local scene, err = decode(c.data) + local a = c.assimp + t:check(scene, c.name .. ": decode: " .. tostring(err)) + scenes[i] = scene + if scene and not a.failed then + local prims, faces, corners = counts(scene) + t:eq(prims, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, a.faces, c.name .. ": faces (assimp)") + t:eq(corners, a.vertices, c.name .. ": corners (assimp)") + t:eq(math.max(#scene.materials, 1), a.materials, c.name .. ": materials (assimp)") + t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)") + t:eq(bones(scene), a.bones, c.name .. ": bones (assimp)") + if a.min then + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + t:check(lo and boundsEq(lo, hi, a, 1e-4), c.name .. ": world bounds (assimp) " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max)) + end + end +end +t:note("%d files against assimp", #Cases) + +-- ------------------------------------------------------------------------------------------------ round trips +-- skinned world positions at a time: the skeleton posed by animations[1], vertices blended by their joints +local function skinnedPositions(s: any, time: number): { number } + local byNode: { [number]: { [string]: any } } = {} + for _, ch in (if s.animations[1] then s.animations[1].channels else {}) :: { any } do + byNode[ch.node] = byNode[ch.node] or {} + byNode[ch.node][ch.path] = ch + end + local function eval(ch: any, comps: number): { number } + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local n = ch.input.count + local cubic = ch.interpolation == "CUBICSPLINE" + local function v(k: number): { number } + local e = if cubic then k * 3 + 1 else k + local r = {} + for q = 0, comps - 1 do + r[q + 1] = OUT(e, q) + end + if comps == 4 then + local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4]) + r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l } + end + return r + end + if time <= IN(0, 0) then + return v(0) + end + for k = 0, n - 2 do + local t0, t1 = IN(k, 0), IN(k + 1, 0) + if time <= t1 then + local u = if t1 > t0 then (time - t0) / (t1 - t0) else 1 + local a0, a1 = v(k), v(k + 1) + if comps == 4 and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then + a1 = { -a1[1], -a1[2], -a1[3], -a1[4] } + end + local r = {} + for q = 1, comps do + r[q] = a0[q] + (a1[q] - a0[q]) * u + end + if comps == 4 then + local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4]) + r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l } + end + return r + end + end + return v(n - 1) + end + local world: { [number]: { number } } = {} + local function visit(i: number, parent: { number }) + local n = s.nodes[i] + local chs = byNode[i] + local m = S.nodeMatrix(n) + if chs then + m = Mat4.compose(if chs.translation then eval(chs.translation, 3) else n.translation, + if chs.rotation then eval(chs.rotation, 4) else n.rotation, n.scale) + end + world[i] = S.mul(parent, m) + for _, c in n.children do + visit(c, world[i]) + end + end + for _, r in s.roots do + visit(r, S.IDENTITY) + end + local out = {} + for _, pl in S.flatten(s) do + local prim = pl.primitive + local P = S.reader(prim.attributes.POSITION) :: any + local I = S.reader(prim.indices) :: any + local node = s.nodes[pl.node] + local skin = node.skin and s.skins[node.skin] + local J = prim.attributes.JOINTS_0 and S.reader(prim.attributes.JOINTS_0) :: any + local W = prim.attributes.WEIGHTS_0 and S.reader(prim.attributes.WEIGHTS_0) :: any + local IBM = skin and skin.inverseBindMatrices and S.reader(skin.inverseBindMatrices) :: any + local tri = {} + for k = 0, prim.indices.count - 1 do + local v = I(k, 0) + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + local wx, wy, wz = 0, 0, 0 + if skin and J and W then + for c = 0, 3 do + local w = W(v, c) + if w > 0 then + local j = J(v, c) + local ibm = {} + for q = 1, 16 do + ibm[q] = IBM(j, q - 1) + end + local m = S.mul(world[skin.joints[j + 1]], ibm) + local px, py, pz = Mat4.point(m, x, y, z) + wx, wy, wz = wx + px * w, wy + py * w, wz + pz * w + end + end + else + wx, wy, wz = Mat4.point(world[pl.node] or pl.matrix, x, y, z) + end + table.insert(tri, { wx, wy, wz }) + if #tri == 3 then + -- each triangle's corners in a fixed order (a mirrored node's winding is flipped on write) + local function r(x: number): number + return math.floor(x * 100 + 0.5) + end + table.sort(tri, function(p: { number }, q: { number }): boolean + if r(p[1]) ~= r(q[1]) then + return r(p[1]) < r(q[1]) + elseif r(p[2]) ~= r(q[2]) then + return r(p[2]) < r(q[2]) + end + return r(p[3]) < r(q[3]) + end) + for _, c in tri do + table.move(c, 1, 3, #out + 1, out) + end + tri = {} + end + end + end + return out +end + +local function compare(a: any, b: any, label: string, eps: number) + local _, fa = counts(a) + local _, fb = counts(b) + t:eq(fb, fa, label .. ": triangles") + t:eq(#b.materials, #a.materials, label .. ": materials") + for k, m in a.materials do + local m2 = b.materials[k] + if m2 then + local ok = true + for q = 1, 4 do + ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6) + end + t:check(ok, label .. ": material " .. k .. " colour") + local ta = m.baseColorTexture and a.textures[m.baseColorTexture.texture] + local tb = m2.baseColorTexture and b.textures[m2.baseColorTexture.texture] + t:check((ta == nil) == (tb == nil) and (ta == nil or ta.uri == nil or ta.uri == tb.uri), label .. ": material " .. k .. " texture") + end + end + t:eq(#b.skins, if #a.skins > 0 or #a.animations > 0 then 1 else 0, label .. ": skins (animated nodes become joints)") + if a.skins[1] then + t:eq(#b.skins[1].joints, #a.skins[1].joints, label .. ": joints") + end + -- the same posed triangles (the corners in order) at a few times + for _, time in { 0, 0.3, 0.75, 1.2, 2.5, 4 } do + local pa, pb = skinnedPositions(a, time), skinnedPositions(b, time) + local ok = #pa == #pb + local worst = 0 + if ok then + for k = 1, #pa do + local d = math.abs(pa[k] - pb[k]) / math.max(1, math.abs(pa[k])) + worst = math.max(worst, d) + end + end + t:check(ok and worst <= eps, string.format("%s: posed vertices at %.2f s (worst %.3g)", label, time, worst)) + if #a.animations == 0 then + break + end + end +end + +for i, c in Cases do + local scene = scenes[i] + if scene then + local out, err = Ms3d.encode(scene) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer) + t:check(back, c.name .. ": decode ours: " .. tostring(berr)) + if back then + compare(scene, back, c.name, 1e-6) + t:eq(#back.nodes, #scene.nodes, c.name .. ": nodes") + local same = true + for mi, m in scene.meshes do + same = same and back.meshes[mi].primitives[1].attributes.POSITION.count == m.primitives[1].attributes.POSITION.count + end + t:check(same, c.name .. ": vertices kept") + end + end +end + +local gltfScenes = {} +local ng = 0 +for gi, g in Picks do + local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr)) + if scene then + gltfScenes[gi] = scene + local out, err = Ms3d.encode(scene) + t:check(out, g.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer) + t:check(back, g.name .. ": decode ours: " .. tostring(berr)) + if back then + local lines = false + for _, m in scene.meshes do + for _, p in m.primitives do + lines = lines or p.mode == "points" or p.mode == "lines" or p.mode == "line_strip" or p.mode == "line_loop" + end + end + if not lines then + -- weights are stored in percent + compare(scene, back, "glTF " .. g.name, if #scene.skins > 0 then 1e-2 else 1e-4) + end + ng += 1 + end + end +end +t:note("%d reference files and %d glTF models through our writer and back", #Cases, ng) + +-- ------------------------------------------------------------------------------------------------ cross-check +local nx = 0 +for _, x in Xcheck do + local a = x.assimp + t:check(not a.failed, x.name .. ": assimp reads our file") + local scene = if x.case then scenes[x.case] else gltfScenes[x.gltf] + if scene and not a.failed then + local back = decode(Ms3d.encode(scene) :: buffer) + local prims, faces, corners = counts(back) + t:eq(a.meshes, prims, x.name .. ": assimp meshes of our file") + t:eq(a.faces, faces, x.name .. ": assimp faces of our file") + t:eq(a.vertices, corners, x.name .. ": assimp corners of our file") + t:eq(a.bones, bones(back), x.name .. ": assimp bones of our file") + t:eq(a.animations, if #back.nodes > #back.meshes then 1 else 0, x.name .. ": assimp animations of our file (it makes one for any joint)") + t:eq(a.materials, math.max(#back.materials, 1), x.name .. ": assimp materials of our file") + if a.min then + local lo, hi = MeshOps.bounds(MeshOps.merge(back)) + t:check(lo and boundsEq(lo, hi, a, 1e-4), x.name .. ": assimp world bounds of our file " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max)) + end + nx += 1 + end +end +t:note("%d of our files read back by assimp", nx) + +-- ------------------------------------------------------------------------------------------------ details +do + local byName = {} + for i, c in Cases do + byName[c.name] = scenes[i] + end + local jeep = byName["assimp/jeep1.ms3d"] + if jeep then + local m = jeep.materials[1] + t:check(m.baseColorTexture and jeep.textures[1].uri ~= nil and jeep.textures[1].data == nil, "texture -> uri, not loaded: " .. tostring(jeep.textures[1].uri)) + t:eq(#jeep.meshes, 7, "jeep: 7 groups") + t:eq(jeep.meta.up, "y", "MilkShape is Y up") + t:check(jeep.meta.source.vertexVersion == nil, "jeep: no sub-versioned blocks") + end + local mats = byName["assimp/twospheres_withmats.ms3d"] + if mats then + t:eq(mats.meta.source.commentVersion, 1, "comment block") + t:eq(mats.meta.source.vertexVersion, 3, "vertex extras subversion 3") + t:check(mats.materials[2].extras.ms3d.shininess > 0, "shininess in extras") + end + -- a skinned scene by hand: two joints, comments, weights split between them + local gl = gltfScenes[3] + if gl then + local out = Ms3d.encode(gl) :: buffer + local back = decode(out) + t:check(back.skins[1] and #back.skins[1].joints == #gl.skins[1].joints, "joints written") + local W = back.meshes[1].primitives[1].attributes.WEIGHTS_0 + local R = S.reader(W) :: any + local split = false + for v = 0, W.count - 1 do + split = split or (R(v, 1) > 0.05) + t:check(math.abs(R(v, 0) + R(v, 1) + R(v, 2) + R(v, 3) - 1) < 1e-6, "weights sum to 1") + end + t:check(split, "vertex extras: second bone weights") + back.nodes[1].extras.ms3d.comment = "the root" + back.materials[1] = F.Types.Scene.material("m") + back.materials[1].extras = { ms3d = { comment = "a material" } } + back.meta.source.comment = "made by a test" + local again = decode(Ms3d.encode(back) :: buffer) + t:eq(again.nodes[1].extras.ms3d.comment, "the root", "joint comment") + t:eq(again.materials[1].extras.ms3d.comment, "a material", "material comment") + t:eq(again.meta.source.comment, "made by a test", "model comment") + end + local s = F.load(Cases[1].data) + t:check(s and s.kind == "scene" and s.meta.source.format == "ms3d", "F.load detects MS3D") + local viaApi = F.save(s, nil, { format = "ms3d" }) + t:check(viaApi and buffer.readstring(viaApi, 0, 10) == "MS3D000000", "F.save format ms3d") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local data = Cases[2].data + local _, e1 = decode(string.sub(data, 1, 100)) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local _, e2 = decode("MS3D000000\9\0\0\0") + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 9: " .. tostring(e2)) + local _, e3 = decode("MS3D000001") + t:check(e3 and e3.code == Err.CORRUPT, "bad magic: " .. tostring(e3)) + local _, e4 = decode(data, { maxVertices = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = Ms3d.encode({} :: any) + t:check(e5 and e5.code == Err.ARG, "encode junk") + t:eq(Ms3d.sniff(Bytes.reader(buffer.fromstring(data))), 1, "sniff") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + for gi, g in gltfScenes do + if gi <= 4 then + table.insert(samples, buffer.tostring(Ms3d.encode(g) :: buffer)) + end + end + t:fuzz("decode", function(b: buffer) + local s = Ms3d.decode(Bytes.reader(b)) + if s then + Ms3d.encode(s) + MeshOps.merge(s) + end + return s + end, samples, { mutations = 12, keepHeader = 14 }) +end + +t:done() diff --git a/tools/fixtures/3ds.py b/tools/fixtures/3ds.py new file mode 100644 index 0000000..0a6c271 --- /dev/null +++ b/tools/fixtures/3ds.py @@ -0,0 +1,101 @@ +# 3DS fixtures (tools/fixtures.py): assimp's 3DS test models (test/models/3DS and test/models-nonbsd/3DS: meshes, +# materials, textures, keyframer hierarchies, pivots, rotation / camera / target animation, cameras, lights; read from +# the nixpkgs assimp source, never committed) and files written by assimp's 3DS exporter from glTF sample models, with +# reference values from assimp (`assimp info -r`: meshes, faces, vertices, materials, animations, cameras, lights, +# nodes; world bounds from its PreTransformVertices export). Then our encoder's output (tools/fixtures/_3ds_encode.luau, +# from every case and the glTF models) read back by assimp. (Blender 5's 3DS importer is an extension that is not +# installed by default, so assimp is the only reference.) +# tests/gen/3ds_cases.luau { name, data, assimp } +# tests/gen/3ds_gltf.luau glTF sample models for the writer round trips: { name, data, files } +# tests/gen/3ds_xcheck.luau { name, case? | gltf?, assimp } +import importlib.util, os + +INPUTS = ["src/Formats/model/3ds", "tests/fixtures/gltf", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", + "tools/fixtures/_3ds_encode.luau"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("_" + name.replace(".", "_"), os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +GLTF = ("Box", "BoxTextured", "BoxVertexColors", "Cameras", "SimpleMeshes", "RiggedSimple", "SimpleSkin", "MultiUVTest", + "NegativeScaleTest", "PointLightIntensityTest", "AnimatedTriangle", "TextureCoordinateTest", "TextureTransformTest", + "InterpolationTest", "LightVisibility") + + +def reference(ctx, M, X, paths, tmp): + out = [] + for p, a in zip(paths, M.assimp_info(ctx, paths, raw=True)): + a.update(X.assimp_extra(ctx, p)) + a.pop("min", None) + a.pop("max", None) + a.pop("perMesh", None) + if not a.get("failed"): + a.update(X.ptv_bounds(ctx, p, tmp)) + out.append(a) + return out + + +def generate(ctx): + M = load(ctx, "_model_ref") + X = load(ctx, "fbx") + tmp = M.tempdir() + src = X.assimp_src(ctx) + cases = [] + for sub in ("models", "models-nonbsd"): + d = os.path.join(src, "test", sub, "3DS") + for f in sorted(os.listdir(d)): + if f.lower().endswith(".3ds"): + cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f)}) + # assimp's exporter + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in GLTF: + d0 = os.path.join(gl, model) + if not os.path.isdir(d0): + continue + for variant in sorted(os.listdir(d0)): + d = os.path.join(d0, variant) + if not os.path.isdir(d): + continue + mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")] + if not mains: + continue + main = os.path.join(d, mains[0]) + picks.append({"name": model + "/" + variant, "data": open(main, "rb").read(), + "files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}}) + out = os.path.join(tmp, model + ".3ds") + try: + ctx.nix("assimp", ["assimp", "export", main, out, "-f3ds"]) + cases.append({"name": "assimp-export/" + model + ".3ds", "path": out}) + except Exception: + pass + break + refs = reference(ctx, M, X, [c["path"] for c in cases], tmp) + for c, a in zip(cases, refs): + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("3ds_cases", cases) + ctx.emit("3ds_gltf", picks) + + # assimp reads our files + ours = M.luau_encode(ctx, "tools/fixtures/_3ds_encode.luau") + xtmp = M.tempdir() + names = sorted(n for n in ours if n.endswith(".3ds")) + paths = [] + for n in names: + p = os.path.join(xtmp, n) + with open(p, "wb") as f: + f.write(ours[n]) + paths.append(p) + xs = [] + for n, a in zip(names, reference(ctx, M, X, paths, xtmp)): + kind, idx = n[:-4].split("_") + e = {"name": n, "assimp": a} + e["case" if kind == "case" else "gltf"] = int(idx) + xs.append(e) + ctx.emit("3ds_xcheck", xs) diff --git a/tools/fixtures/_3ds_encode.luau b/tools/fixtures/_3ds_encode.luau new file mode 100644 index 0000000..98b3b95 --- /dev/null +++ b/tools/fixtures/_3ds_encode.luau @@ -0,0 +1,44 @@ +-- tools/fixtures/_3ds_encode: run by tools/fixtures/3ds.py (luau CLI, repo root): decodes every 3DS case and every +-- glTF sample model with our readers and writes them with our 3DS writer, printing "\t" lines for assimp +-- to read back. Files: case_.3ds, gltf_.3ds. +local ThreeDs = require("@formats/model/3ds") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/3ds_cases") +local Picks = require("@tests/gen/3ds_gltf") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +local function emit(name: string, scene: any) + local out, err = ThreeDs.encode(scene) + if out then + print(name .. "\t" .. hex(out)) + else + print("encode failed " .. name .. ": " .. tostring(err)) + end +end + +for i, c in Cases do + local scene, err = ThreeDs.decode(Bytes.reader(buffer.fromstring(c.data))) + if scene then + emit(string.format("case_%d.3ds", i), scene) + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end +for i, g in Picks do + local scene = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + if scene then + emit(string.format("gltf_%d.3ds", i), scene) + end +end diff --git a/tools/fixtures/_ms3d_encode.luau b/tools/fixtures/_ms3d_encode.luau new file mode 100644 index 0000000..15977f6 --- /dev/null +++ b/tools/fixtures/_ms3d_encode.luau @@ -0,0 +1,44 @@ +-- tools/fixtures/_ms3d_encode: run by tools/fixtures/ms3d.py (luau CLI, repo root): decodes every MS3D case and every +-- glTF sample model with our readers and writes them with our MS3D writer, printing "\t" lines for assimp +-- to read back. Files: case_.ms3d, gltf_.ms3d. +local Ms3d = require("@formats/model/ms3d") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/ms3d_cases") +local Picks = require("@tests/gen/ms3d_gltf") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +local function emit(name: string, scene: any) + local out, err = Ms3d.encode(scene) + if out then + print(name .. "\t" .. hex(out)) + else + print("encode failed " .. name .. ": " .. tostring(err)) + end +end + +for i, c in Cases do + local scene, err = Ms3d.decode(Bytes.reader(buffer.fromstring(c.data))) + if scene then + emit(string.format("case_%d.ms3d", i), scene) + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end +for i, g in Picks do + local scene = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + if scene then + emit(string.format("gltf_%d.ms3d", i), scene) + end +end diff --git a/tools/fixtures/ms3d.py b/tools/fixtures/ms3d.py new file mode 100644 index 0000000..611a48a --- /dev/null +++ b/tools/fixtures/ms3d.py @@ -0,0 +1,68 @@ +# MS3D fixtures (tools/fixtures.py): assimp's MilkShape 3D test models (test/models/MS3D: groups, materials, textures, +# version 4 with and without the sub-versioned blocks; read from the nixpkgs assimp source, never committed), with +# reference values from assimp (`assimp info -r`: meshes, faces, vertices, materials, animations, bones; world bounds +# from its PreTransformVertices export). No tool writes MS3D with joints, so skins and animation are checked through +# our writer: glTF sample models (skins, animation, textures) written by tools/fixtures/_ms3d_encode.luau and read +# back by assimp. +# tests/gen/ms3d_cases.luau { name, data, assimp } +# tests/gen/ms3d_gltf.luau glTF sample models: { name, data, files } +# tests/gen/ms3d_xcheck.luau { name, case? | gltf?, assimp } +import importlib.util, os + +INPUTS = ["src/Formats/model/ms3d", "tests/fixtures/gltf", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", + "tools/fixtures/3ds.py", "tools/fixtures/_ms3d_encode.luau"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("_" + name.replace(".", "_"), os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +GLTF = ("Box", "BoxTextured", "SimpleSkin", "RiggedSimple", "SimpleMeshes", "MultiUVTest", "NegativeScaleTest", + "AnimatedTriangle", "TextureCoordinateTest", "MeshPrimitiveModes") + + +def generate(ctx): + M = load(ctx, "_model_ref") + X = load(ctx, "fbx") + R = load(ctx, "3ds") + tmp = M.tempdir() + d = os.path.join(X.assimp_src(ctx), "test", "models", "MS3D") + cases = [{"name": "assimp/" + f, "path": os.path.join(d, f)} for f in sorted(os.listdir(d)) if f.lower().endswith(".ms3d")] + for c, a in zip(cases, R.reference(ctx, M, X, [c["path"] for c in cases], tmp)): + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("ms3d_cases", cases) + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in GLTF: + d0 = os.path.join(gl, model) + if not os.path.isdir(d0): + continue + for variant in sorted(os.listdir(d0)): + dd = os.path.join(d0, variant) + mains = [f for f in sorted(os.listdir(dd)) if f.endswith(".gltf") or f.endswith(".glb")] if os.path.isdir(dd) else [] + if mains: + picks.append({"name": model + "/" + variant, "data": open(os.path.join(dd, mains[0]), "rb").read(), + "files": {f: open(os.path.join(dd, f), "rb").read() for f in sorted(os.listdir(dd)) if f != mains[0]}}) + break + ctx.emit("ms3d_gltf", picks) + ours = M.luau_encode(ctx, "tools/fixtures/_ms3d_encode.luau") + xtmp = M.tempdir() + names = sorted(n for n in ours if n.endswith(".ms3d")) + paths = [] + for n in names: + p = os.path.join(xtmp, n) + with open(p, "wb") as f: + f.write(ours[n]) + paths.append(p) + xs = [] + for n, a in zip(names, R.reference(ctx, M, X, paths, xtmp)): + kind, idx = n[:-5].split("_") + e = {"name": n, "assimp": a} + e["case" if kind == "case" else "gltf"] = int(idx) + xs.append(e) + ctx.emit("ms3d_xcheck", xs)