diff --git a/src/Rosetta/model/3ds/Build.luau b/src/Rosetta/model/3ds/Build.luau
index d01a3ea..e685888 100644
--- a/src/Rosetta/model/3ds/Build.luau
+++ b/src/Rosetta/model/3ds/Build.luau
@@ -1,11 +1,9 @@
--!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.
+-- model/3ds/Build: Read's chunk tables -> Types.Scene.
+-- 3DS transforms: mesh vertices are in world space and the mesh matrix (0x4160) is the object's world transform; a
+-- keyframer node is parent * T(pos) * R(rot) * S(scale) and draws its mesh at node * T(-pivot) * inverse(mesh matrix)
+-- (a mirroring mesh matrix also flips x, as 3ds Max writes and assimp reads). Rotation keys are clockwise axis / angle
+-- deltas from the previous key. Smoothing group 0 is flat.
local Types = require("@rosetta/Types")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Read = require("@rosetta/model/3ds/Read")
@@ -20,7 +18,6 @@ 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()
@@ -34,7 +31,6 @@ local function det3(m: { number }): number
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]
@@ -47,7 +43,7 @@ local function qmul(a: { number }, b: { number }): { number }
end
Build.qmul = qmul
--- a rotation key (angle in radians, axis) -> its quaternion (3DS angles turn clockwise)
+-- 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 }
@@ -63,7 +59,7 @@ local function normalize(x: number, y: number, z: number): (number, number, numb
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)
+-- -Z looks from pos to target, 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
@@ -73,7 +69,6 @@ function Build.lookAt(p: { number }, t: { number }, roll: number): { number }
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)
@@ -163,18 +158,14 @@ local function materials(raw: Read.Raw, scene: Types.Scene): { [string]: number
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
@@ -193,7 +184,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st
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)
@@ -248,7 +238,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st
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
@@ -321,7 +310,6 @@ local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [st
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
@@ -359,7 +347,6 @@ 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
@@ -396,7 +383,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene
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
@@ -478,7 +464,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene
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
@@ -486,7 +471,7 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene
end
end
local placedObj: { [Read.Object]: boolean } = {}
- local sceneOf: { [number]: number } = {} -- kf id -> scene node
+ local sceneOf: { [number]: number } = {}
local channels: { Types.Channel } = {}
local function channel(node: number, path: any, times: { number }, values: { number }, comps: number)
for i = 1, #times do
@@ -551,7 +536,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene
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
@@ -581,7 +565,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene
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
@@ -612,7 +595,6 @@ function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene
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
diff --git a/src/Rosetta/model/3ds/Read.luau b/src/Rosetta/model/3ds/Read.luau
index 648b4c5..31e53ea 100644
--- a/src/Rosetta/model/3ds/Read.luau
+++ b/src/Rosetta/model/3ds/Read.luau
@@ -1,10 +1,6 @@
--!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.
+-- model/3ds/Read: the 3DS chunk tree (u16 id, u32 size including the 6-byte header, little endian) -> plain tables.
+-- Unknown chunks are skipped; a chunk past the end of the data is an error, one past its parent is clipped to it.
local Read = {}
local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32
@@ -28,17 +24,14 @@ local C = {
}
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 },
@@ -59,7 +52,7 @@ export type Mesh = {
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)
+ matrix: { number }?, -- 12 floats: X, Y, Z axes, origin (world space)
}
export type Camera = { pos: { number }, target: { number }, roll: number, lens: number, near: number?, far: number? }
export type Light = {
@@ -82,13 +75,12 @@ export type Raw = {
-- ------------------------------------------------------------------------------------------------ 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
+ return nil, nil
end
local e = p + size
if e > ctx.limit then
@@ -103,7 +95,6 @@ local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, numb
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
@@ -117,7 +108,7 @@ 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)
+-- colour chunks: the first float or byte colour (the gamma-corrected 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
@@ -142,7 +133,6 @@ local function color(ctx: Ctx, p: number, stop: number): { number }?
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
@@ -472,7 +462,6 @@ local function editor(ctx: Ctx, p: number, stop: number): (string?, number?)
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
@@ -483,7 +472,6 @@ function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?,
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
diff --git a/src/Rosetta/model/3ds/Write.luau b/src/Rosetta/model/3ds/Write.luau
index 18ba0c7..38b9ee0 100644
--- a/src/Rosetta/model/3ds/Write.luau
+++ b/src/Rosetta/model/3ds/Write.luau
@@ -1,13 +1,6 @@
--!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).
+-- model/3ds/Write: Types.Scene -> 3DS. Objects split at 65535 vertices / faces; mirroring nodes written as 3ds Max does
+-- (positive keyframer transform, mirror in the mesh matrix).
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Sampler = require("@rosetta/codecs/model/Sampler")
@@ -108,7 +101,6 @@ local function unit(x: number, y: number, z: number): (number, number, number)
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)
@@ -128,7 +120,6 @@ local function conj(q: { number }): { number }
return { -q[1], -q[2], -q[3], q[4] }
end
--- a channel's value at a time (codecs/model/Sampler: STEP, LINEAR with slerp, CUBICSPLINE)
local function sample(ch: Types.Channel, t: number): { number }
local f = Sampler.channel(ch)
if not f then
@@ -191,7 +182,6 @@ local function writeMaterial(w: W, m: Types.Material, mname: string, files: { [n
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
@@ -246,7 +236,6 @@ 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"
@@ -260,7 +249,6 @@ local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?,
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
@@ -272,7 +260,6 @@ local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?,
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] }
@@ -398,7 +385,6 @@ local function writeMesh(w: W, part: Part, M: { number }, matNames: { [number]:
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])
@@ -406,7 +392,6 @@ local function aim(m: { number }, dist: number): ({ number }, { number }, number
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])
@@ -490,11 +475,10 @@ local function writeTrack(w: W, id: number, frames: { number }, values: { number
end
type KfNode = {
- chunk: number, name: string, instance: string?, parent: number, -- parent: kf index or -1
+ chunk: number, name: string, instance: string?, parent: number, -- 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 = {}, {}
@@ -558,7 +542,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
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 } = {}
@@ -578,7 +561,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
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
@@ -608,7 +590,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
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]
@@ -645,7 +626,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
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
@@ -707,7 +687,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
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]
@@ -724,7 +703,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
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])
@@ -733,7 +711,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
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)
@@ -774,7 +751,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
camLight(false)
end
close(w, ed)
- -- the keyframer
local kf = open(w, C.KEYFRAMER)
leaf(w, C.KF_HDR, function()
w:u16le(5)
diff --git a/src/Rosetta/model/3ds/init.luau b/src/Rosetta/model/3ds/init.luau
index 8b4b9ed..115c896 100644
--- a/src/Rosetta/model/3ds/init.luau
+++ b/src/Rosetta/model/3ds/init.luau
@@ -1,25 +1,7 @@
--!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).
+-- model/3ds: Autodesk 3D Studio chunked binary; layouts from the 3DS File Toolkit notes, assimp's importer (BSD-3,
+-- reference only) and lib3ds. Supports: meshes, smoothing groups, Phong materials and maps, cameras, lights, keyframer.
+-- Not supported: .prj / .mli, morph / hide tracks, TCB spline parameters, vertex colours / normals (3DS has none).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -41,16 +23,16 @@ local ThreeDs = {
-- ------------------------------------------------------------------------------------------------ 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)
+ normals: boolean?, -- default true
+ flipV: boolean?, -- default true
+ fps: number?, -- default 30 (3ds Max's default)
+ maxVertices: number?, -- 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
+ flipV: boolean?, -- default true
+ fps: number?, -- default 30
+ name: string?,
+ files: { [string]: any }?, -- receives the bytes of textures with data but no uri
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -74,7 +56,6 @@ function ThreeDs.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, E
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))
diff --git a/src/Rosetta/model/3mf/Read.luau b/src/Rosetta/model/3mf/Read.luau
index f9fc5b7..d8408a3 100644
--- a/src/Rosetta/model/3mf/Read.luau
+++ b/src/Rosetta/model/3mf/Read.luau
@@ -1,11 +1,6 @@
--!strict
--- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first
--- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items),
--- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension
--- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry,
--- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit.
--- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and
--- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ.
+-- model/3mf/Read: a 3MF package -> Scene. The root model part comes from _rels/.rels (fallback: the first *.model under
+-- 3D/); vertices are split where corners of one vertex carry different colours / texture coordinates.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Xml = require("@rosetta/codecs/text/Xml")
@@ -21,7 +16,6 @@ local MAX_DEPTH = 64
local localName = Xml.localName
--- an attribute by local name (namespaced attributes such as p:path)
local function attr(node: any, name: string): string?
local a = node.attrs
local v = a[name]
@@ -44,7 +38,7 @@ local function int(s: string?): number?
return nil
end
--- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1
+-- "#RRGGBB" / "#RRGGBBAA", sRGB
local function hexColor(s: string?): { number }?
if type(s) ~= "string" then
return nil
@@ -68,7 +62,7 @@ function Read.toLinear(c: number): number
end
local toLinear = Read.toLinear
--- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid
+-- "m00 m01 m02 m10 ... m32": 3MF's row-vector convention
local function transform(s: string?): ({ number }?, boolean)
if not s then
return nil, true
@@ -99,7 +93,6 @@ local function normPath(p: string): string
return p
end
--- one model part parsed into its resources and build
type Model = { path: string, unit: string?, metadata: { [string]: string }, res: { [number]: any }, items: { any }, required: string? }
local function parseModel(text: string, path: string, opts: any): (Model?, Err.Err?)
@@ -253,7 +246,6 @@ local function parseModel(text: string, path: string, opts: any): (Model?, Err.E
return model, nil
end
--- the root model part's path
local function rootPath(zip: any): string?
local rels = zip:readString("_rels/.rels")
if rels then
@@ -313,7 +305,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?)
scene.meta.metadata = root.metadata
scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required }
- -- textures and materials (shared across model parts by part path + resource id)
local texCache: { [string]: number } = {}
local function texture(model: Model, id: number): number?
local key = model.path .. "#" .. id
@@ -359,7 +350,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?)
return m
end
- -- property of one corner -> (group key, material index?, kind, resource, index)
local function resolve(model: Model, pid: number, p: number, depth: number?): (string, number?, string, any, number)
local r = model.res[pid]
if not r or p < 0 then
@@ -429,7 +419,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?)
return "none", nil, "none", nil, 0
end
- -- one Scene mesh per (part, object) with a mesh
local meshCache: { [string]: number } = {}
local function buildMesh(model: Model, o: any): number?
local key = model.path .. "#" .. o.id
@@ -532,7 +521,6 @@ function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?)
return #scene.meshes
end
- -- nodes: one per object instance (build items and components)
local nodeCount = 0
local maxNodes = opts.maxNodes or 2 ^ 20
local instantiate: (model: Model, oid: number, matrix: { number }?, depth: number, extra: any) -> (number?, Err.Err?)
diff --git a/src/Rosetta/model/3mf/Write.luau b/src/Rosetta/model/3mf/Write.luau
index 4f3af58..515cad1 100644
--- a/src/Rosetta/model/3mf/Write.luau
+++ b/src/Rosetta/model/3mf/Write.luau
@@ -1,10 +1,5 @@
--!strict
--- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles,
--- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the
--- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours),
--- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has
--- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/).
--- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale.
+-- model/3mf/Write: Scene -> a 3MF package; the node hierarchy is flattened into build items at world matrices.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Xml = require("@rosetta/codecs/text/Xml")
@@ -48,7 +43,6 @@ local function hex(r: number, g: number, b: number, a: number): string
return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1)))
end
--- the triangle corner list of a primitive (0-based vertex indices) or nil
local function triangles(prim: any): { number }?
local pos = prim.attributes and prim.attributes.POSITION
if type(pos) ~= "table" then
@@ -128,10 +122,9 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
nextId += 1
return nextId
end
- local res: { string } = {} -- resource XML chunks, in definition order
+ local res: { string } = {}
local files: { { name: string, data: buffer, mime: string } } = {}
- -- unit
local unitName: string, scale: number = "millimeter", 1
local mu: any = scene.meta and scene.meta.unit
if type(o.unit) == "string" and UNITS[o.unit] then
@@ -152,16 +145,14 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
end
end
- -- base materials: one group with every Scene material
local baseId: number? = nil
local nmat = #scene.materials
- local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed
+ local defaultBase = nmat
local needDefault = false
if nmat > 0 then
baseId = id()
end
- -- textures used as base colour textures
local texRes: { [number]: number } = {}
local function textureId(ti: number): number?
if texRes[ti] ~= nil then
@@ -186,7 +177,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
return rid
end
- -- objects
local objectOf: { [number]: number } = {}
local objChunks: { string } = {}
for mi, mesh in scene.meshes do
@@ -195,7 +185,7 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
local base = 0
local objPid: number?, objP: number? = nil, nil
local anyNone = false
- local triList: { { number } } = {} -- { v1, v2, v3, pid | -1, p1, p2, p3 }
+ local triList: { { number } } = {}
for _, prim in mesh.primitives do
local corners = triangles(prim)
if not corners or #corners == 0 then
@@ -210,7 +200,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
for v = 0, n - 1 do
table.insert(verts, fmt('\t\t\t\t\t\n', num(getP(v, 0)), num(if pos.components >= 2 then getP(v, 1) else 0), num(if pos.components >= 3 then getP(v, 2) else 0)))
end
- -- properties: texture group, colour group, base material, none
local pid, kind = -1, "none"
local mat = prim.material and scene.materials[prim.material]
local uv = prim.attributes.TEXCOORD_0
@@ -296,7 +285,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
table.insert(res, objChunks[#objChunks])
end
- -- the base material group goes first (its id was taken first)
if baseId then
local parts = { fmt('\t\t\n', baseId) }
for _, m in scene.materials do
@@ -310,7 +298,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
table.insert(res, 1, table.concat(parts))
end
- -- build items: every node with a mesh, at its world matrix
local items: { string } = {}
local seen: { [number]: boolean } = {}
for _, pl in Types.Scene.flatten(scene) do
@@ -342,7 +329,6 @@ function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
end
end
- -- metadata
local meta: { string } = {}
local md = scene.meta and scene.meta.metadata
if type(md) == "table" then
diff --git a/src/Rosetta/model/3mf/init.luau b/src/Rosetta/model/3mf/init.luau
index 888670e..18cdfe2 100644
--- a/src/Rosetta/model/3mf/init.luau
+++ b/src/Rosetta/model/3mf/init.luau
@@ -1,21 +1,7 @@
--!strict
--- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2,
--- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts
--- (codecs/text/Xml).
--- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from
--- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices
--- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata
--- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours
--- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to
--- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it
--- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first
--- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices
--- are split where a vertex's corners carry different colours / texture coordinates.
--- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a
--- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups,
--- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit).
--- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are
--- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none).
+-- model/3mf: 3D Manufacturing Format (core 1.3, materials extension 1.2, production extension 1.1 p:path).
+-- Supports: meshes, components, build items, base materials, colour / texture / composite / multi groups.
+-- Not supported: beam lattice, slices, displacement, volumetric and secure content, thumbnails, normals.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -37,13 +23,13 @@ local ThreeMf = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
- maxVertices: number?, -- refuse more vertices + triangle corners in total (default 2^25)
- maxNodes: number?, -- refuse more object instances (default 2^20)
+ maxVertices: number?, -- default 2^25
+ maxNodes: number?, -- default 2^20
}
export type EncodeOptions = {
unit: string?, -- "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter" (default: from meta.unit, else
- -- millimeter); positions are scaled through the build transforms when meta.unit differs
- level: number?, -- deflate level for the XML parts (default 6; 0 stores them)
+ -- millimeter)
+ level: number?, -- default 6; 0 stores
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -51,7 +37,6 @@ function ThreeMf.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "PK\3\4" then
return 0
end
- -- the central directory sits at the end: look for the model part's name there, then at the start
local n = r:size()
local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536))
if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then
diff --git a/src/Rosetta/model/b3d/Read.luau b/src/Rosetta/model/b3d/Read.luau
index 80b0534..2db075a 100644
--- a/src/Rosetta/model/b3d/Read.luau
+++ b/src/Rosetta/model/b3d/Read.luau
@@ -1,8 +1,5 @@
--!strict
--- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are
--- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes
--- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end.
--- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from).
+-- model/b3d/Read: the BB3D chunk tree (4-byte id, u32 little-endian size, no padding) -> Types.Scene.
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Chunks = require("@rosetta/containers/Chunks")
@@ -26,8 +23,8 @@ type MeshRec = { mesh: number, node: number, count: number, joints: { { number }
type Bone = { node: number, target: MeshRec?, list: { number } }
type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } }
--- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated
--- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored
+-- Blitz3D is left-handed Y up: z mirrored; quaternions are w x y z, conjugated (Blitz3D stores the inverse
+-- rotation, as assimp reads them) then mirrored
local function vec(r: Bytes.Reader): { number }
local x, y, z = r:f32le(), r:f32le(), r:f32le()
return { x, y, -z }
@@ -54,7 +51,6 @@ local function fetcher(opts: Options?): (string) -> buffer?
end
end
--- scene(r, opts) -> Scene | nil, message, kind
function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?)
local buf = src.buf
local maxVertices = opts and opts.maxVertices or 2 ^ 24
@@ -77,7 +73,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?,
local scene = Types.Scene.new()
local texs: { TexInfo } = {}
local brushes: { Brush } = {}
- local materialOf: { [number]: number } = {} -- brush index (0-based) -> material
+ local materialOf: { [number]: number } = {}
local meshes: { MeshRec } = {}
local bones: { Bone } = {}
local nodeKeys: { [number]: Keys } = {}
@@ -141,7 +137,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?,
end
end
- -- the material of brush id (0-based) | nil for -1 / out of range
local function material(id: number): number?
if id < 0 or id >= #brushes then
return nil
@@ -290,7 +285,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?,
fail(string.format("triangle %d: vertex index out of range", i))
return nil
end
- -- mirrored z: reverse the winding to keep the faces front-facing
writeu32(idx, i * 12, a)
writeu32(idx, i * 12 + 4, cc)
writeu32(idx, i * 12 + 8, b)
@@ -302,7 +296,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?,
end
end
if not attrs then
- return nil -- a mesh without vertices: the node stays a pivot
+ return nil
end
if #mesh.primitives == 0 then
table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" })
@@ -472,7 +466,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?,
end
end
end
- local self: number? = nil -- the mesh node as a joint, for vertices no bone moves
+ local self: number? = nil
local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16)
for v = 0, nv - 1 do
local e = inf[v + 1]
@@ -484,7 +478,6 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?,
buffer.writeu16(jb, v * 8, self :: number)
buffer.writef32(wb, v * 16, 1)
else
- -- the 4 strongest, normalised
local order = {}
for k = 1, #e, 2 do
table.insert(order, k)
@@ -568,7 +561,7 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?,
brushes = #brushes,
frames = if anim then anim.frames else nil,
fps = if anim then anim.fps else nil,
- handedness = "left", -- converted: z mirrored, winding reversed
+ handedness = "left",
}
return scene, nil, nil
end
diff --git a/src/Rosetta/model/b3d/init.luau b/src/Rosetta/model/b3d/init.luau
index e208d12..308453d 100644
--- a/src/Rosetta/model/b3d/init.luau
+++ b/src/Rosetta/model/b3d/init.luau
@@ -1,21 +1,7 @@
--!strict
--- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description
--- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer.
--- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler,
--- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes ->
--- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is
--- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree
--- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) /
--- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the
--- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights
--- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the
--- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps,
--- default 60) -> one animation of LINEAR channels at frame / fps seconds.
--- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding
--- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their
--- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }.
--- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the
--- extras; texture coordinate sets of 3 / 4 components keep their first two.
+-- model/b3d: Blitz3D .b3d (BB3D chunks, version 1; blitzbasic.com "b3dfile_specs.txt", checked against assimp).
+-- Supports: TEXS, BRUS, NODE / MESH / VRTS / TRIS, BONE skins, KEYS + ANIM; left-handed, so z is mirrored.
+-- Not supported: writing; several VRTS chunks in one MESH (the first is used); 3 / 4 component texture coordinates.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -35,10 +21,10 @@ local B3d = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
- resolve: ((uri: string) -> any)?, -- texture files (the api sets it for paths)
- files: { [string]: any }?, -- or: the files by name
+ resolve: ((uri: string) -> any)?,
+ files: { [string]: any }?,
maxVertices: number?, -- default 2^24
- maxDepth: number?, -- node nesting (default 256)
+ maxDepth: number?, -- default 256
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -54,7 +40,6 @@ function B3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
if r:peek(4) ~= "BB3D" then
return nil, Err.new(Err.CORRUPT, "no BB3D chunk")
end
- -- the scene builder is plain (not native) code: a bug there must not escape as an error
local ok, scene, msg, kind = pcall(Read.scene, r, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene))
diff --git a/src/Rosetta/model/bsp/Brush.luau b/src/Rosetta/model/bsp/Brush.luau
index 83fa807..f745199 100644
--- a/src/Rosetta/model/bsp/Brush.luau
+++ b/src/Rosetta/model/bsp/Brush.luau
@@ -1,13 +1,7 @@
--!strict
--- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex
--- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture
--- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the
--- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake /
--- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the
--- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from
--- opts.resolve("textures/.wal") when available, else texture coordinates stay in texels: extras.bsp.texels).
--- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken.
--- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls.
+-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the
+-- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture
+-- size.
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
@@ -20,7 +14,7 @@ local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Lump = { at: number, size: number }
export type Options = {
palette: buffer?,
- wal: ((name: string) -> buffer?)?, -- Quake II: the .wal file of a texture (for its size)
+ wal: ((name: string) -> buffer?)?, -- Quake II: a texture's .wal file (for its size)
maxPixels: number?,
maxVertices: number?,
}
@@ -32,7 +26,6 @@ local function cstr(b: buffer, at: number, n: number): string
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
end
--- miptex lump (Quake / Half-Life) -> textures
local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer?, maxPixels: number): ({ Tex }?, string?)
local out: { Tex } = {}
if l.size < 4 then
@@ -80,9 +73,6 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer
return out, nil
end
--- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message
--- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes,
--- models, miptex (q1 / hl)
function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?)
local q2 = variant == "q2"
local maxPixels = opts and opts.maxPixels or 2 ^ 24
@@ -95,9 +85,8 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
if nF > (opts and opts.maxVertices or 2 ^ 24) then
return nil, "limit: too many faces"
end
- -- textures
local texs: { Tex } = {}
- local texOf: { number } = {} -- texinfo -> texture index (1-based)
+ local texOf: { number } = {}
if q2 then
local byName: { [string]: number } = {}
for i = 0, nTI - 1 do
@@ -126,7 +115,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
texOf[i + 1] = if mt >= 0 and mt < #texs then mt + 1 else 0
end
end
- -- faces of each model
local scene = Scene.new()
scene.meta.up = "z"
local faceModel: { number } = {}
@@ -160,7 +148,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
skipped += 1
continue
end
- -- the polygon
local poly: { number } = {}
local ok = true
for k = 0, numEdges - 1 do
@@ -189,7 +176,7 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
if side ~= 0 then
nx, ny, nz = -nx, -ny, -nz
end
- -- orient counter-clockwise about the normal (Newell's normal of the polygon as stored)
+ -- Newell's normal of the polygon as stored
local n = #poly // 3
local ax, ay, az = 0, 0, 0
for k = 0, n - 1 do
@@ -239,7 +226,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
end
end
end
- -- textures, materials
for i, t in texs do
local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) }
table.insert(scene.textures, tex)
@@ -250,7 +236,6 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian
mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any
table.insert(scene.materials, mat)
end
- -- meshes and nodes
local root: Types.Node = { name = "bsp", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
diff --git a/src/Rosetta/model/bsp/Quake3.luau b/src/Rosetta/model/bsp/Quake3.luau
index 3284055..de8c1a4 100644
--- a/src/Rosetta/model/bsp/Quake3.luau
+++ b/src/Rosetta/model/bsp/Quake3.luau
@@ -1,11 +1,6 @@
--!strict
--- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a
--- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches
--- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap
--- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1
--- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as
--- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped.
--- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken.
+-- model/bsp/Quake3: Quake III Arena maps (IBSP 46; RTCW 47 has the same layout) -> Scene, from the Unofficial Quake 3
+-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped.
local Types = require("@rosetta/Types")
local Quake3 = {}
@@ -17,19 +12,18 @@ local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.wri
export type Lump = { at: number, size: number }
export type Options = { patchLevel: number?, maxVertices: number? }
-type Batch = { shader: number, lightmap: number, verts: { number } } -- vertex records (indices into the vertex lump, or -1 - k for patch vertices)
+type Batch = { shader: number, lightmap: number, verts: { number } } -- indices into the vertex lump, or -1 - k for patch vertices
local function cstr(b: buffer, at: number, n: number): string
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
end
--- decode(b, base, lumps, opts) -> Scene | nil, message
function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: Options?): (Types.Scene?, string?)
local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps
local nT, nM, nV, nMV, nF, nLM = T.size // 72, M.size // 40, VX.size // 44, MV.size // 4, F.size // 104, LM.size // 49152
local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16)
local maxV = opts and opts.maxVertices or 2 ^ 24
- -- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids
+ -- patch vertices: 12 floats + 4 colour bytes each
local extra: { number } = {}
local function vertex(i: number): { number }
local o = base + VX.at + i * 44
@@ -92,7 +86,6 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts:
local L = level
for py = 0, (h - 1) // 2 - 1 do
for px = 0, (w - 1) // 2 - 1 do
- -- the 3x3 control points of this sub-patch
local ctrl: { { number } } = {}
for j = 0, 2 do
for i = 0, 2 do
@@ -127,7 +120,7 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts:
for gx = 0, L - 1 do
local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2]
local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2]
- -- counter-clockwise for Quake's clockwise-front control grids
+ -- Quake's control grids are clockwise-front
for _, v in { a, d, c2, c2, d, e } do
table.insert(tris, v)
end
@@ -166,7 +159,6 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts:
end
local scene = Scene.new()
scene.meta.up = "z"
- -- shaders, lightmaps
for i = 0, nT - 1 do
local name = cstr(b, base + T.at + i * 72, 64)
table.insert(scene.textures, { name = name, uri = name })
diff --git a/src/Rosetta/model/bsp/init.luau b/src/Rosetta/model/bsp/init.luau
index ff2dcda..02ae8d9 100644
--- a/src/Rosetta/model/bsp/init.luau
+++ b/src/Rosetta/model/bsp/init.luau
@@ -1,11 +1,6 @@
--!strict
--- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38)
--- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a
--- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III
--- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as
--- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not
--- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey.
--- Quake II .wal sizes come from opts.resolve("textures/.wal") / opts.files. Units are map units, z up.
+-- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW
+-- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up.
-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing.
-- ------------------------------------------------------------------------------------------------ requires
@@ -28,10 +23,10 @@ local Bsp = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
- palette: (buffer | string)?, -- Quake 1: the 768-byte palette
+ palette: (buffer | string)?, -- Quake 1: 768 bytes
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
- patchLevel: number?, -- Quake III patch subdivisions (default 4)
+ patchLevel: number?, -- default 4
maxPixels: number?, -- default 2^24
maxVertices: number?, -- default 2^24
}
@@ -55,7 +50,6 @@ function Bsp.sniff(r: Bytes.Reader): number
return if v == 38 or v == 46 or v == 47 then 1 else 0.3
end
if v == 29 or v == 30 then
- -- no magic: check that the lump directory fits the file
local size = r:remaining()
for i = 0, 14 do
local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8)
@@ -69,7 +63,6 @@ function Bsp.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
--- the entities text -> { { key = value } }
local function entities(text: string): { { [string]: string } }
local out: { { [string]: string } } = {}
for block in string.gmatch(text, "%b{}") do
diff --git a/src/Rosetta/model/dae/Math.luau b/src/Rosetta/model/dae/Math.luau
index cabfc97..4da24c2 100644
--- a/src/Rosetta/model/dae/Math.luau
+++ b/src/Rosetta/model/dae/Math.luau
@@ -1,6 +1,5 @@
--!strict
--- model/dae/Math: the Collada-specific transform elements (, ); everything else (matrices,
--- quaternions, decomposition) is codecs/model/Mat4. Matrices are flat arrays of 16 in column-major order.
+-- model/dae/Math: the Collada transform elements and ; matrices are flat column-major arrays of 16.
local Mat4 = require("@rosetta/codecs/model/Mat4")
local DaeMath = {}
@@ -18,7 +17,7 @@ local function norm(a: { number }): { number }
return { a[1] / l, a[2] / l, a[3] / l }
end
--- lookat(eye, interest, up) -> the placement of an object at eye whose -Z looks at interest
+-- : an object at eye whose -Z looks at interest
function DaeMath.lookat(v: { number }): { number }
local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0
local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) })
@@ -27,14 +26,14 @@ function DaeMath.lookat(v: { number }): { number }
return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 }
end
--- skew(angle, rotation axis, translation axis) (RenderMan's skew)
+-- (RenderMan's skew)
function DaeMath.skew(v: { number }): { number }
local a = rad(v[1] or 0)
local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 })
local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 })
local s = math.tan(a)
local m = Mat4.identity()
- -- M = I + s * t * r^T (column-major: m[col*4 + row])
+ -- M = I + s * t * r^T
for row = 0, 2 do
for col = 0, 2 do
m[col * 4 + row + 1] += s * t[row + 1] * r[col + 1]
diff --git a/src/Rosetta/model/dae/Read.luau b/src/Rosetta/model/dae/Read.luau
index 8cf63f9..b7e5eae 100644
--- a/src/Rosetta/model/dae/Read.luau
+++ b/src/Rosetta/model/dae/Read.luau
@@ -1,13 +1,5 @@
--!strict
--- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons /
--- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile
--- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains,
--- images (kept encoded through the fetch callback, or embedded hex ), the visual scene's node tree (matrix /
--- translate / rotate / scale / lookat / skew, instance_node, several instances per node as child nodes), skin
--- controllers (bind shape applied, inverse bind matrices, the 4 strongest weights), morph controllers (targets as
--- deltas), cameras, lights (ambient lights as node extras) and animations (every channel on a node's transform
--- elements, resampled at the union of the key times (plus subdivisions of large rotations) into glTF-style TRS
--- channels; one animation per animation clip, else one for the file).
+-- model/dae/Read: a parsed Collada document (codecs/text/Xml DOM) -> Scene.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Xml = require("@rosetta/codecs/text/Xml")
@@ -100,8 +92,8 @@ type Ctx = {
meshes: { [string]: number },
skins: { [string]: number },
posIndex: { [any]: { number } },
- nodeOf: { [string]: { number } }, -- collada node id -> scene nodes
- info: { [number]: any }, -- scene node -> { el, xf, sid, cid }
+ nodeOf: { [string]: { number } },
+ info: { [number]: any },
pendingSkins: { any },
skipped: { [string]: number },
err: string?,
@@ -113,7 +105,6 @@ local function skip(C: Ctx, what: string)
end
-- ------------------------------------------------------------------------------------------------ sources
--- source(el) -> { data = flat numbers or strings, comps, count } (only the accessor's named params)
local function readSource(C: Ctx, el: any): any
local cached = C.sources[el]
if cached ~= nil then
@@ -279,7 +270,6 @@ local function image(C: Ctx, id: string): any
return img
end
--- the effect's newparams by sid (this level and the profile's)
local function newparams(effect: any, profile: any, technique: any): { [string]: any }
local out = {}
for _, scope in { effect, profile, technique } do
@@ -295,7 +285,6 @@ local function newparams(effect: any, profile: any, technique: any): { [string]:
return out
end
--- texture(effect params, sampler sid) -> scene texture index
local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): number?
local np = params[samplerSid]
local imageId: string? = nil
@@ -364,7 +353,6 @@ local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): n
return idx
end
--- one colour-or-texture parameter of a common technique
local function param(C: Ctx, params: { [string]: any }, el: any, uvsets: { [string]: number }): (any, any)
if not el then
return nil, nil
@@ -474,7 +462,7 @@ local function material(C: Ctx, id: string, uvsets: { [string]: number }): numbe
if type(shininess) == "number" then
mat.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1)
end
- -- opacity (Collada 1.4.1 spec section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance)
+ -- Collada 1.4.1 section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance
if transparentEl and (type(transparent) == "table" or type(transparency) == "number") then
local mode = attr(transparentEl, "opaque") or "A_ONE"
local tv = if type(transparency) == "number" then transparency else 1
@@ -531,7 +519,6 @@ end
-- ------------------------------------------------------------------------------------------------ geometry
type Input = { semantic: string, source: any, offset: number, set: number }
--- the inputs of a primitive element (VERTEX expanded into the inputs)
local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number)
local out: { Input } = {}
local stride = 0
@@ -563,7 +550,6 @@ local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number)
return out, math.max(stride, 1)
end
--- faces(primEl, kind, stride) -> corner list (tuple starts into the concatenated p), face sizes, mode
local function corners(C: Ctx, prim: any, kind: string, stride: number): ({ number }?, { number }?, { number }?, string)
local p: { number } = {}
local faces: { number } = {}
@@ -670,7 +656,6 @@ local PRIMS = { triangles = true, polylist = true, polygons = true, lines = true
type Built = { prim: Types.Primitive, symbol: string?, texSets: { number }, posIndex: { number } }
--- one primitive element -> Primitive (+ the source position index of each output vertex, for skins / morphs)
local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Built?
local ins, stride = inputs(C, prim, verticesEl)
local p, faces, starts, mode = corners(C, prim, kind, stride)
@@ -688,7 +673,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil
skip(C, "primitives without positions")
return nil
end
- -- attribute names
local named: { { input: Input, name: string, comps: number } } = {}
local texSets: { number } = {}
local texInputs: { Input } = {}
@@ -725,10 +709,9 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil
table.insert(named, { input = i, name = "_" .. s .. (if i.set ~= 0 then tostring(i.set) else ""), comps = math.max(comps, 1) })
end
end
- -- de-index
local np = #p
local keyOf: { [any]: number } = {}
- local tuples: { number } = {} -- the first p index of each output vertex's tuple
+ local tuples: { number } = {}
local corner = table.create(#starts) :: { number }
local count = 0
for ci, s in starts do
@@ -803,7 +786,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil
if allTri then
mode = "triangles"
elseif C.triangulate then
- -- fan triangulation
local tri: { number } = {}
local at = 0
for _, f in faces do
@@ -832,7 +814,6 @@ local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Buil
return { prim = out, symbol = attr(prim, "material"), texSets = texSets, posIndex = posIndex }
end
--- geometry(el) -> the built primitives (cached per geometry element)
local function geometry(C: Ctx, el: any): { Built }?
local cached = C.posIndex[el]
if cached then
@@ -863,7 +844,6 @@ local function geometry(C: Ctx, el: any): { Built }?
return out
end
--- the material bindings of an instance: symbol -> material id, and semantic -> texcoord set
local function bindings(node: any): ({ [string]: string }, { [string]: { [string]: number } })
local syms: { [string]: string } = {}
local sets: { [string]: { [string]: number } } = {}
@@ -894,7 +874,6 @@ local function copyAccessor(a: Types.Accessor): Types.Accessor
return Scene.accessor(b, a.type, a.components, a.count)
end
--- mesh(geometry element, instance element, skin?) -> scene mesh index
local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { number }?): (number?, { Built }?)
local syms, sets = bindings(inst)
local parts = { key }
@@ -915,7 +894,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: {
for _, b in built do
local prim = b.prim
if bindShape then
- -- skinned: the bind shape matrix applied to positions and normals (a copy: the geometry may be shared)
local attrs = table.clone(prim.attributes)
local pos = copyAccessor(attrs.POSITION)
for v = 0, pos.count - 1 do
@@ -961,7 +939,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: {
end
end
if target then
- -- texcoord semantic -> TEXCOORD_n index among this primitive's sets
local uv: { [string]: number } = {}
for sem, set in (sym and sets[sym]) or {} do
uv[sem] = (table.find(b.texSets, set) or 1) - 1
@@ -976,7 +953,6 @@ local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: {
return idx, built
end
--- morph controller -> mesh with targets (deltas)
local function morphMesh(C: Ctx, ctrl: any, morph: any, inst: any): number?
local base = C.ids[urlId(attr(morph, "source")) or ""]
if not base or lname(base) ~= "geometry" then
@@ -1082,7 +1058,6 @@ local function camera(C: Ctx, el: any): number?
return #C.scene.cameras
end
--- light(el) -> light index, or nil and the ambient colour
local function light(C: Ctx, el: any): (number?, { number }?)
local tc = child(el, "technique_common")
if not tc then
@@ -1124,7 +1099,6 @@ end
-- ------------------------------------------------------------------------------------------------ nodes
local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, skew = 7 }
--- the matrix of one transform element's values
local function xfMatrix(kind: string, v: { number }): { number }
if kind == "matrix" then
return Mat4.fromRows(v)
@@ -1182,7 +1156,7 @@ local function addChild(C: Ctx, parent: Types.Node, node: Types.Node): number
return idx
end
--- the instances of a node: the first of each kind on the node itself, the rest on child nodes
+-- extra instances of a node go on child nodes
local function instances(C: Ctx, el: any, node: Types.Node, idx: number)
local function slot(kind: string, name: string?): (Types.Node, number)
local n: any = node
@@ -1322,7 +1296,7 @@ visitNode = function(C: Ctx, el: any): number?
end
-- ------------------------------------------------------------------------------------------------ skins
--- the scene node for a joint name: by sid below the skeleton roots, else by sid / id / name anywhere
+-- joints: by sid below the skeleton roots, else by sid / id / name anywhere
local function findJoint(C: Ctx, name: string, roots: { number }, byId: boolean): number?
local nodes = C.scene.nodes
local function search(i: number, depth: number): number?
@@ -1410,7 +1384,7 @@ local function resolveSkins(C: Ctx)
local skin: Types.Skin = { name = attr(ps.ctrl, "name") or attr(ps.ctrl, "id"), joints = jointNodes }
if ps.bind then
local sk: any = skin
- sk.extras = { dae = { bindShapeMatrix = ps.bind } } -- already applied to the mesh's positions / normals
+ sk.extras = { dae = { bindShapeMatrix = ps.bind } }
end
if ibm and ibm.comps == 16 and ibm.count >= #names then
local b = buffer.create(#names * 64)
@@ -1432,7 +1406,6 @@ local function resolveSkins(C: Ctx)
cache[key] = si
end
C.scene.nodes[ps.node].skin = si
- -- vertex weights -> JOINTS_0 / WEIGHTS_0 (once per mesh)
local mesh = C.scene.meshes[ps.mesh]
if mesh.primitives[1] and mesh.primitives[1].attributes.JOINTS_0 then
continue
@@ -1457,7 +1430,7 @@ local function resolveSkins(C: Ctx)
local vcount = numbers(text(child(vw, "vcount") or ""), C.limit) or {}
local v = numbers(text(child(vw, "v") or ""), C.limit * 8) or {}
local wdata = wSrc and wSrc.data or {}
- local per: { { number } } = {} -- position index -> { j1, w1, j2, w2, ... } strongest 4
+ local per: { { number } } = {}
local at = 0
for pi, c in vcount do
local list = {}
@@ -1555,9 +1528,9 @@ local function sample(c: Curve, t: number): { number }
return a
end
--- resolve "id/sid/sid.member" or "id/sid(i)(j)" to a node's transform element
+-- "id/sid/sid.member" or "id/sid(i)(j)"
local function target(C: Ctx, s: string): ({ number }?, any, number?)
- -- the id may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/"
+ -- ids may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/"
local id, sids = match(s, "^([^/]*)/(.*)$")
if not id then
return nil, nil, nil
@@ -1607,7 +1580,6 @@ local function target(C: Ctx, s: string): ({ number }?, any, number?)
return nodes, xf, member
end
--- the channels of one (recursively) -> curves grouped by node
local function collect(C: Ctx, anim: any, byNode: { [number]: { Curve } }, order: { number }, depth: number)
if depth > 64 then
return
@@ -1697,7 +1669,6 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde
local tb, rb, sb = buffer.create(n * 12), buffer.create(n * 16), buffer.create(n * 12)
local prev: { number }? = nil
for i, t in times do
- -- this time's values of each animated element
local xf = {}
for k, x in info.xf do
xf[k] = { kind = x.kind, values = table.clone(x.values) }
@@ -1738,7 +1709,6 @@ local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, orde
table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel)
table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" } :: Types.Channel)
table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" } :: Types.Channel)
- -- the node is now TRS-driven
local node = C.scene.nodes[ni]
if node.matrix then
setTransform(node, node.matrix)
@@ -1821,12 +1791,11 @@ function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?
}
for _, el in Xml.descendants(root) do
local id = el.attrs.id
- -- duplicate ids: the first one, unless it is empty (some exporters write before the real one)
+ -- duplicate ids: the first, unless empty (some exporters write before the real one)
if type(id) == "string" and (C.ids[id] == nil or #C.ids[id].children == 0) then
C.ids[id] = el
end
end
- -- asset: up axis, unit
local asset = child(root, "asset")
local up = asset and child(asset, "up_axis")
local upAxis = if up then upper(match(text(up), "[%w_]+") or "Y_UP") else "Y_UP"
@@ -1834,7 +1803,6 @@ function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?
local unit = asset and child(asset, "unit")
local meter = unit and attr(unit, "meter")
scene.meta.unit = if meter then tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 else 1
- -- the instanced visual scene (else the first one)
local vsId: string? = nil
local sceneEl = child(root, "scene")
local ivs = sceneEl and child(sceneEl, "instance_visual_scene")
diff --git a/src/Rosetta/model/dae/Write.luau b/src/Rosetta/model/dae/Write.luau
index c317f42..b777d96 100644
--- a/src/Rosetta/model/dae/Write.luau
+++ b/src/Rosetta/model/dae/Write.luau
@@ -1,9 +1,6 @@
--!strict
--- model/dae/Write: Scene -> Collada 1.4.1 text. One per mesh primitive (triangles, lines or polylist; strips
--- and fans unrolled into triangles, points skipped) with POSITION / NORMAL / TEXCOORD_n (V flipped back) / COLOR_n
--- sources sharing one index; common-profile phong (or lambert / constant) effects from the PBR material and its
--- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major ; cameras;
--- lights. Not written: skins, morph targets, animations.
+-- model/dae/Write: Scene -> Collada 1.4.1 text; strips and fans unrolled, points skipped, nodes as row-major .
+-- Not written: skins, morph targets, animations.
local Types = require("@rosetta/Types")
local Xml = require("@rosetta/codecs/text/Xml")
local Base64 = require("@rosetta/core/Base64")
@@ -38,7 +35,6 @@ local function nameAttr(s: string?): string
return if s then ' name="' .. esc(s) .. '"' else ""
end
--- triangle / line corner lists of a primitive (0-based vertex indices) and the element kind
local function corners(prim: Types.Primitive): ({ number }?, string?, { number }?)
local n = prim.attributes.POSITION.count
local idx: { number } = {}
@@ -160,7 +156,6 @@ function Write.build(scene: Types.Scene, opts: any?): string?
local meta: { [string]: any } = scene.meta or {}
local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP"
w(format('rosetta1970-01-01T00:00:00Z1970-01-01T00:00:00Z%s\n', f(meta.unit or 1), up))
- -- images
local imageId: { [number]: string } = {}
if #scene.textures > 0 then
w("\n")
@@ -184,12 +179,11 @@ function Write.build(scene: Types.Scene, opts: any?): string?
end
w("\n")
end
- -- effects + materials
if #scene.materials > 0 then
w("\n")
for i, mat in scene.materials do
local ph: any = mat.extras and mat.extras.phong or {}
- local params: { [any]: any } = {} -- the newparam strings, and their sids as seen-keys
+ local params: { [any]: any } = {}
local function texParam(ref: Types.TextureRef?): (string?, number?)
if not ref or not imageId[ref.texture] then
return nil, nil
@@ -236,7 +230,6 @@ function Write.build(scene: Types.Scene, opts: any?): string?
end
w("\n")
end
- -- geometries: one per primitive
local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {}
w("\n")
for mi, mesh in scene.meshes do
@@ -289,7 +282,6 @@ function Write.build(scene: Types.Scene, opts: any?): string?
end
end
w("\n")
- -- cameras / lights
if #scene.cameras > 0 then
w("\n")
for i, cam in scene.cameras do
@@ -316,7 +308,6 @@ function Write.build(scene: Types.Scene, opts: any?): string?
end
w("\n")
end
- -- the node tree
w('\n')
local seen: { [number]: boolean } = {}
local function node(i: number, depth: number)
diff --git a/src/Rosetta/model/dae/init.luau b/src/Rosetta/model/dae/init.luau
index a3fb3de..289bfa8 100644
--- a/src/Rosetta/model/dae/init.luau
+++ b/src/Rosetta/model/dae/init.luau
@@ -1,26 +1,8 @@
--!strict
--- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos COLLADA specifications; .dae XML, and .zae: a zip holding the .dae, its
--- manifest.xml and the images). New code.
--- Reads: geometry ( triangles / polylist / polygons / lines / linestrips / tristrips / trifans with shared input
--- offsets, de-indexed per index tuple; n-gons fan-triangulated unless opts.triangulate = false keeps "polygons"),
--- common-profile materials (phong / blinn / lambert / constant -> PBR baseColor / emissive / roughness from shininess /
--- alpha from transparent + transparency; every Phong term kept in material.extras.phong; FCOLLADA / MAX3D bump ->
--- normalTexture, double_sided), images through newparam sampler2D -> surface -> image (1.4) or instance_image (1.5),
--- kept encoded (opts.resolve / opts.files, embedded hex , data: URIs), the instanced visual scene (matrix /
--- translate / rotate / scale / lookat / skew; instance_geometry / controller / camera / light / node; extra instances
--- of a node become child nodes), skin controllers (bind_shape_matrix applied to the mesh, joints by sid under
--- or by id / name, INV_BIND_MATRIX, JOINTS_0 / WEIGHTS_0 from the 4 strongest weights, normalized), morph
--- controllers (targets as POSITION / NORMAL deltas, weights), cameras (perspective: yfov from xfov / aspect;
--- orthographic), lights (directional / point / spot; attenuation in light.extras.dae; ambient lights as
--- node.extras.dae.ambientLight), animations (channels on node transform elements: whole elements, .X / .ANGLE
--- members, matrix (i)(j) elements; resampled at the union of their key times, rotations over 90 degrees subdivided,
--- into glTF TRS channels; one animation per animation_clip, else one for the file). meta.up = the up_axis ("y" / "z"
--- / "x"), meta.unit = unit meter; the data is never rotated or scaled. TEXCOORD_n V is flipped to glTF's top-left
--- origin (opts.flipV = false keeps Collada's).
--- Writes: Collada 1.4.1 (see model/dae/Write: meshes, materials, images, nodes, cameras, lights), or a .zae.
--- Not supported: / geometry, polygon holes (: the outer loop only), Bezier / Hermite curves
--- (sampled linearly at their keys), animations of non-transform targets, physics / kinematics / FX profiles other than
--- COMMON (counted in meta.source.skipped). Writing skins, morphs and animations.
+-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry,
+-- common-profile materials, images, the visual scene, skin / morph controllers, cameras, lights, transform animations.
+-- Not supported: / , polygon holes (), Bezier / Hermite curves (sampled linearly), non-transform
+-- animation targets, physics / kinematics / non-COMMON FX profiles; writing skins, morphs and animations.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -43,17 +25,17 @@ local Dae = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
- resolve: ((uri: string) -> any)?, -- image files (buffer or string); the api sets it for paths
- files: { [string]: any }?, -- or: the files by uri / base name
- triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives
- flipV: boolean?, -- TEXCOORD_n v = 1 - v (default true: glTF's convention)
- maxVertices: number?, -- refuse more output vertices / array values (default 2^25)
+ resolve: ((uri: string) -> any)?, -- image files (buffer or string)
+ files: { [string]: any }?,
+ triangulate: boolean?, -- default true
+ flipV: boolean?, -- default true
+ maxVertices: number?, -- default 2^25
}
export type EncodeOptions = {
- files: { [string]: any }?, -- receives the texture images (else they are written as data: URIs or their uri)
- name: string?, -- the destination's file name (names the image files)
- flipV: boolean?, -- default true (the inverse of decode)
- format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images); the api passes the extension
+ files: { [string]: any }?, -- receives the texture images (else data: URIs or their uri)
+ name: string?,
+ flipV: boolean?, -- default true
+ format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images)
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -107,7 +89,7 @@ local function fetcher(opts: DecodeOptions?, zip: any): Read.Fetch
end
end
--- the main .dae of a .zae: manifest.xml's , else the first .dae entry
+-- a .zae's main .dae: manifest.xml's , else the first .dae entry
local function zae(r: Bytes.Reader): (any, string?, Err.Err?)
local zip, err = Zip.open(r)
if not zip then
@@ -174,7 +156,6 @@ function Dae.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
return nil, Err.new(Err.ARG, "needs a Scene")
end
if opts and opts.format == "zae" then
- -- a zip: manifest.xml, the .dae and its images
local files = {}
local o = table.clone(opts)
o.files = files
diff --git a/src/Rosetta/model/fbx/Ascii.luau b/src/Rosetta/model/fbx/Ascii.luau
index 9975cc8..7f6f62f 100644
--- a/src/Rosetta/model/fbx/Ascii.luau
+++ b/src/Rosetta/model/fbx/Ascii.luau
@@ -1,7 +1,6 @@
--!strict
--- model/fbx/Ascii: the ASCII FBX node tree reader and writer (7.x: "Name: value, value, ... { children }", ';'
--- comments, "*N { a: ... }" arrays, " in strings). Produces the same Node / Array values as model/fbx/Binary
--- (arrays as f64 buffers; integers longer than 15 digits stay strings so ids are exact). Never throws.
+-- model/fbx/Ascii: the ASCII FBX 7.x node tree ("Name: value, ... { children }", ';' comments, "*N { a: ... }" arrays,
+-- " in strings); integers longer than 15 digits stay strings so ids are exact.
local Base64 = require("@rosetta/core/Base64")
local Ascii = {}
@@ -15,7 +14,6 @@ local function isNameStart(c: number): boolean
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
end
--- parse(text) -> root node (children = the top-level nodes), version | nil, message, offset
function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, number?)
local maxBytes = opts and opts.maxBytes or 2 ^ 30
local n = #text
@@ -36,7 +34,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n
end
end
- -- at i: a name followed by ':'? -> name, the index after ':'
local function nameAt(): (string?, number)
local c = sbyte(text, i)
if not c or not isNameStart(c) then
@@ -61,7 +58,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n
return nil, i
end
- -- the values of one node (after the ':'), up to a new name, '{' or '}'
local function values(): ({ any }?, string?)
local props: { any } = {}
while true do
@@ -163,7 +159,6 @@ function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, n
return e
end
end
- -- "*N { a: v, v, ... }" -> an Array
local p1 = props[1]
if #props == 1 and type(p1) == "table" and p1.star then
local a = node.children[1]
@@ -213,7 +208,6 @@ local function fmt(v: number): string
return string.format("%.17g", v)
end
--- write(root) -> string: the ASCII form of a tree (the same node shapes Binary.write takes)
function Ascii.write(root: any, version: number?): string
local out = { string.format("; FBX %d.%d.0 project file\n; Created by rosetta\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) }
local function node(nd: any, indent: string)
@@ -236,7 +230,7 @@ function Ascii.write(root: any, version: number?): string
elseif tv == "table" and v.array then
arr = v
elseif tv == "buffer" then
- -- raw bytes (Video Content): base64, split into lines as the FBX SDK writes them
+ -- raw bytes (Video Content): base64 split into lines as the FBX SDK writes them
local b64 = Base64.encode(v)
local chunks = {}
for k = 1, #b64, 2048 do
diff --git a/src/Rosetta/model/fbx/Binary.luau b/src/Rosetta/model/fbx/Binary.luau
index 34bb2c5..90a2cb4 100644
--- a/src/Rosetta/model/fbx/Binary.luau
+++ b/src/Rosetta/model/fbx/Binary.luau
@@ -1,10 +1,7 @@
--!strict
--!native
--- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit
--- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's
--- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/compress/Deflate when compressed and kept as Tree.Array
--- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become
--- the string "L" so ids stay exact. Never throws: errors are returned (nil, message, offset).
+-- model/fbx/Binary: the binary FBX 7.x node tree (32-bit node records before 7500, 64-bit from 7500), as documented by
+-- Blender's io_scene_fbx and assimp's FBXBinaryTokenizer. Scalar L values past 2^53 become "L" so ids stay exact.
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Binary = {}
@@ -21,7 +18,7 @@ local MAX_DEPTH = 128
local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16
local writef64 = buffer.writef64
--- a signed 64-bit integer at p: a number when exact (|v| < 2^53), else "L<16 hex digits>"
+-- signed 64-bit: a number when |v| < 2^53, else "L<16 hex digits>"
local function i64(b: buffer, p: number, asString: boolean): any
local lo, hi = readu32(b, p), readu32(b, p + 4)
if hi >= 0x80000000 then
@@ -40,7 +37,6 @@ Binary.i64 = i64
local ELEM: { [string]: number } = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 }
--- the elements of a raw array (n elements of type t at p) as f64s
local function toF64(t: string, src: buffer, p: number, n: number): buffer
local out = buffer.create(n * 8)
if t == "d" then
@@ -66,7 +62,6 @@ local function toF64(t: string, src: buffer, p: number, n: number): buffer
return out
end
--- parse(buf, base, limit, opts?) -> root node (name "", children = the top-level nodes), version | nil, message, offset
function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?)
local maxBytes = opts and opts.maxBytes or 2 ^ 30
if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then
@@ -158,7 +153,6 @@ function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes:
return out, p
end
- -- one node record at p: node | false (the null record), next offset | nil, message, offset
local function node(p: number, stop: number, depth: number): (any, any, number?)
if p + head > stop then
return nil, "truncated node record", p
@@ -230,10 +224,8 @@ function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes:
end
-- ------------------------------------------------------------------------------------------------ writer
--- write(root, version?) -> buffer: the children of root as a binary FBX file (default version 7400, the 32-bit
--- record layout; 7500+ writes 64-bit records). Values: numbers are written as D unless the node gives a type hint
--- (node.types = "ILDS..." one character per property), booleans as C, strings as S, buffers as R, Arrays by their
--- type (compressed with zlib when longer than 32 elements, unless compress = false).
+-- default version 7400 (32-bit records; 7500+ writes 64-bit); node.types = "ILDS..." gives one type character per
+-- property; arrays over 32 elements are zlib-compressed
export type WNode = { name: string, props: { any }, children: { WNode }?, types: string? }
local function sizeHint(n: WNode): number
diff --git a/src/Rosetta/model/fbx/Read.luau b/src/Rosetta/model/fbx/Read.luau
index b18510d..110b110 100644
--- a/src/Rosetta/model/fbx/Read.luau
+++ b/src/Rosetta/model/fbx/Read.luau
@@ -1,15 +1,6 @@
--!strict
--- model/fbx/Read: an FBX 7.x node tree (model/fbx/Binary or model/fbx/Ascii) -> Scene. Objects + Connections ->
--- nodes (Model, with the full FBX transform: pre / post rotation, pivots, offsets, rotation order, geometric
--- transform baked into the mesh data), meshes (polygons, layer elements for normals / uvs / colours / materials in
--- every mapping (ByPolygonVertex, ByVertice, ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode, one
--- primitive per material, vertices unwelded per polygon corner as assimp does), materials (Phong / Lambert and the
--- 3ds Max Physical / PBR compound -> PBR fields + extras.fbx), textures (embedded Video content kept encoded, or file
--- references through the fetch callback), skins (Skin + Cluster deformers -> JOINTS_0 / WEIGHTS_0, inverse bind
--- matrices), blend shapes (BlendShape / BlendShapeChannel / Shape -> morph targets), animation stacks (every layer's
--- curve nodes on Lcl Translation / Rotation / Scaling and DeformPercent, sampled at the union of key times (or
--- opts.sampleRate) and turned into glTF channels through the node transform), cameras and lights (on a child node
--- turning glTF's -Z forward into FBX's +X camera / -Y light axis). Property templates from Definitions supply defaults.
+-- model/fbx/Read: an FBX 7.x node tree -> Scene. Layer elements in every mapping (ByPolygonVertex, ByVertice,
+-- ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode; vertices unwelded per polygon corner as assimp does.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Base64 = require("@rosetta/core/Base64")
@@ -50,7 +41,7 @@ local function isArray(v: any): boolean
return type(v) == "table" and v.array == true
end
--- the array under n. (or inline numbers: old ASCII files)
+-- old ASCII files have inline numbers
local function array(n: Node?, name: string): Array?
local c = child(n, name)
if not c then
@@ -87,7 +78,7 @@ local function at(a: Array, i: number): number
return buffer.readf64(a.data, i * 8)
end
--- "Name\0\1Class" (binary) / "Class::Name" (ASCII) -> name
+-- "Name\0\1Class" (binary) / "Class::Name" (ASCII)
local function objectName(s: any): string
if type(s) ~= "string" then
return ""
@@ -104,7 +95,7 @@ local function objectName(s: any): string
end
Read.objectName = objectName
--- Properties70 (P: name, type, label, flags, values...) -> { [name] = { type, v1, v2, ... } }
+-- Properties70: P: name, type, label, flags, values...
local function properties(n: Node?, into: { [string]: { any } }?): { [string]: { any } }
local out = into or {}
local p70 = child(n, "Properties70")
@@ -155,7 +146,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
local maxVertices = opts and opts.maxVertices or 2 ^ 25
local scene = Types.Scene.new()
- -- property templates (Definitions/ObjectType/PropertyTemplate) by object class
+ -- Definitions/ObjectType/PropertyTemplate
local templates: { [string]: { [string]: { any } } } = {}
local defs = child(root, "Definitions")
if defs then
@@ -169,7 +160,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
end
- -- objects
local objects: { [any]: Obj } = {}
local order: { Obj } = {}
local objs = child(root, "Objects")
@@ -187,7 +177,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
end
- -- connections: children (sources) of each parent, parents of each child, in file order
local kids: { [any]: { Conn } } = {}
local parents: { [any]: { Conn } } = {}
local conns = child(root, "Connections")
@@ -236,7 +225,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
return out
end
- -- global settings
local gs = properties(child(root, "GlobalSettings"))
local upAxis = pnum(gs, "UpAxis", 1)
local unitScale = pnum(gs, "UnitScaleFactor", 1)
@@ -280,7 +268,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
return p
end
end
- -- ASCII: base64 strings (possibly split into several)
+ -- ASCII: base64, possibly split into several strings
local parts = {}
for _, p in c.props do
if type(p) == "string" then
@@ -384,7 +372,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
if opacity < 1 then
m.alphaMode = "blend"
end
- -- 3ds Max Physical / PBR materials
local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"]
if pbr then
local prefix = if p["3dsMax|main|basecolor"] then "3dsMax|main|" else "3dsMax|Parameters|"
@@ -504,7 +491,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
nd.scale = s
end
nd.extras = { fbx = { type = o.sub, id = o.id } }
- -- parent
local parentModel: Obj? = nil
for _, t2 in targets(o.id, "Model") do
parentModel = t2.obj
@@ -517,7 +503,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
table.insert(scene.roots, ni)
end
end
- -- break parent cycles (a node reachable from itself is not a valid tree): cut children already placed
+ -- break parent cycles: cut children already placed
do
local placed: { [number]: boolean } = {}
local function visit(i: number)
@@ -537,13 +523,11 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
for i in scene.nodes do
if not placed[i] then
- -- part of a parent cycle: make it a root
table.insert(scene.roots, i)
visit(i)
end
end
end
- -- world matrices (rest pose)
local worldM: { [number]: Mat4.M4 } = {}
local function world(i: number, parent: Mat4.M4)
worldM[i] = Mat4.mul(parent, localM[i] or Mat4.identity())
@@ -559,7 +543,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
-- ------------------------------------------------------------------------------------------ meshes
local corners = 0
- -- per geometry: skin (control point -> { joint node, weight }) and blend shape channels
local function skinOf(geo: Obj): ({ { { number } } }?, Types.Skin?)
local skin = sources(geo.id, "Deformer", "Skin")[1]
if not skin then
@@ -645,7 +628,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
local meshCache: { [string]: number } = {}
- local shapeChannels: { [number]: { Obj } } = {} -- mesh index -> blend shape channel objects (for weights curves)
+ local shapeChannels: { [number]: { Obj } } = {}
local nodeSkin: { [number]: number } = {}
local skinCache: { [any]: number } = {}
@@ -662,7 +645,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
if corners > maxVertices or ncp > maxVertices then
return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices")
end
- -- polygons: corner -> control point, polygon of each corner, polygon starts
local cp = table.create(nc, 0)
local polyOf = table.create(nc, 0)
local starts: { number } = { 0 }
@@ -688,7 +670,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
np += 1
starts[np + 1] = nc
end
- -- layer elements
type Elem = { data: Array, index: Array?, mapping: string, comps: number, name: string?, order: number }
local function elems(kind: string, dataName: string, indexName: string, comps: number): { Elem }
local out: { Elem } = {}
@@ -711,7 +692,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end)
return out
end
- -- the data element of a corner (c 0-based), or -1
local function lookup(e: Elem, c: number): number
local m = e.mapping
local i
@@ -742,7 +722,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4)
local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3)
local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1]
- -- the normals index name varies ("NormalsIndex" / "NormalIndex")
+ -- "NormalsIndex" / "NormalIndex"
for _, e in normals do
if not e.index then
local c = nil
@@ -758,7 +738,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
end
end
- -- polygons by material slot
local groups: { [number]: { number } } = {}
local slots: { number } = {}
for p = 0, np - 1 do
@@ -785,7 +764,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
table.sort(slots)
local perCp, skin = skinOf(geo)
local shapes = shapesOf(geo)
- local N3: Mat4.M4? = nil -- normal matrix (inverse transpose of G)
+ local N3: Mat4.M4? = nil -- inverse transpose of G
if G then
local inv = Mat4.inverse(G)
if inv then
@@ -1004,12 +983,11 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
for _, o in models do
local ni = nodeOf[o.id]
local nd = scene.nodes[ni]
- -- materials of the model, in connection order
local mats: { number } = {}
for _, m in sources(o.id, "Material") do
table.insert(mats, material(m))
end
- -- geometric transform (not inherited: baked into the mesh)
+ -- geometric transform: not inherited, baked into the mesh
local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 })
local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 })
local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 })
@@ -1047,7 +1025,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
end
end
- -- cameras and lights: on a child node rotated from glTF's -Z forward to FBX's axis
+ -- cameras / lights: a child node rotated from glTF's -Z forward to FBX's +X camera / -Y light axis
for _, a in sources(o.id, "NodeAttribute") do
local p = a.props
if a.sub == "Camera" then
@@ -1120,7 +1098,7 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
times[k + 1] = at(kt, k) / TICKS
values[k + 1] = at(kv, k)
end
- -- per-key attribute flags (expanded through KeyAttrRefCount)
+ -- expanded through KeyAttrRefCount
local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat")
local flags = table.create(n, 4)
local slopes: { { number } } = {}
@@ -1223,11 +1201,10 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
for _, stack in order do
if stack.class == "AnimationStack" then
local anim: Types.Animation = { name = stack.name, channels = {} }
- -- model id -> { T/R/S -> { axis -> curve } , defaults }
type Track = { curves: { [string]: { [number]: Curve } }, defaults: { [string]: { number } } }
local tracks: { [any]: Track } = {}
local trackOrder: { any } = {}
- local morph: { [any]: Curve } = {} -- blend shape channel id -> DeformPercent curve
+ local morph: { [any]: Curve } = {}
local layers = sources(stack.id, "AnimationLayer")
for _, layer in layers do
for _, cn in sources(layer.id, "AnimationCurveNode") do
@@ -1328,7 +1305,6 @@ function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Typ
end
end
end
- -- morph target weights: every node whose mesh has an animated blend shape channel
if next(morph) then
for ni, nd in scene.nodes do
local chans = nd.mesh and shapeChannels[nd.mesh]
diff --git a/src/Rosetta/model/fbx/Write.luau b/src/Rosetta/model/fbx/Write.luau
index e48613a..7311530 100644
--- a/src/Rosetta/model/fbx/Write.luau
+++ b/src/Rosetta/model/fbx/Write.luau
@@ -1,11 +1,6 @@
--!strict
--- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types
--- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f).
--- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one
--- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals
--- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material;
--- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets ->
--- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve.
+-- model/fbx/Write: Scene -> an FBX 7.4 node tree. Property types follow what Blender's and the FBX SDK's readers check
+-- (ids L, ints I, doubles D, KTime L, arrays d / i / l / f); rotations as Euler XYZ degrees.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Mat4 = require("@rosetta/codecs/model/Mat4")
@@ -28,7 +23,7 @@ local function arr(t: string, list: { number }): any
end
return { array = true, type = t, count = n, data = d }
end
--- P: name, type, label, flags, values (vt: one type character per value)
+-- P: name, type, label, flags, values
local function P(name: string, ptype: string, label: string, flags: string, vt: string, ...: any): WNode
return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } }
end
@@ -64,7 +59,6 @@ local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) ->
return Types.Scene.reader(acc)
end
--- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based)
local function faces(prim: Types.Primitive): { { number } }?
local pos = prim.attributes.POSITION
if not pos then
@@ -235,7 +229,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
link(m.baseColorTexture, "DiffuseColor")
link(m.normalTexture, "NormalMap")
link(m.emissiveTexture, "EmissiveColor")
- -- the other textures the FBX material had (specular, metalness, ... maps), under their property names
local linked = {
[m.baseColorTexture and m.baseColorTexture.texture or -1] = true,
[m.normalTexture and m.normalTexture.texture or -1] = true,
@@ -260,7 +253,7 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
-- ------------------------------------------------------------------------------------------ models
local modelIds: { [number]: number } = {}
local skip: { [number]: boolean } = {}
- local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there)
+ local attrHost: { [number]: number } = {}
local parentOf: { [number]: number } = {}
for i, nd in nodes do
for _, c in nd.children or {} do
@@ -283,7 +276,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
attrHost[i] = p
end
end
- -- world matrices (rest pose) for clusters and the bind pose
local worldM: { [number]: Mat4.M4 } = {}
local visiting: { [number]: boolean } = {}
local function world(i: number): Mat4.M4
@@ -390,7 +382,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
local euler = Mat4.eulerXYZ(r)
local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type
local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null"
- -- an orientation child folded into this node gives it its attribute
local folded: number? = nil
for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array)
if host == i then
@@ -430,9 +421,9 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
-- ------------------------------------------------------------------------------------------ geometry
local geoIds: { [number]: number } = {}
- local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot
+ local geoSlots: { [number]: { number } } = {}
local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {}
- local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation)
+ local geoChannels: any = {}
local geoCount: { [number]: number } = {}
local function geometry(mi: number): number?
if geoIds[mi] then
@@ -625,7 +616,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
geoSlots[mi] = if anyMat then slots else {}
geoVerts[mi] = layout
geoCount[mi] = offset
- -- morph targets
local prims = mesh.primitives
local ntargets = 0
for _, l in layout do
@@ -717,7 +707,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
OO(pm, mid)
end
end
- -- skin: one Skin per (geometry, skin)
local skin = nd.skin and scene.skins[nd.skin]
local key = tostring(gid) .. ":" .. tostring(nd.skin)
if skin and not skinned[key] then
@@ -728,7 +717,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
local meshWorld = world(i)
pose(mid, meshWorld)
local ibm = accessorReader(skin.inverseBindMatrices)
- -- per joint: control points and weights
local perJoint: { { idx: { number }, w: { number } } } = {}
for j in skin.joints do
perJoint[j] = { idx = {}, w = {} }
@@ -878,7 +866,6 @@ function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
end
table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step })
else
- -- weights: one DeformPercent curve per blend shape channel of the node's mesh
local nd = nodes[ch.node]
local gc: any = geoChannels
local chans = nd.mesh and gc[nd.mesh]
diff --git a/src/Rosetta/model/fbx/Xform.luau b/src/Rosetta/model/fbx/Xform.luau
index abe251b..b7376ff 100644
--- a/src/Rosetta/model/fbx/Xform.luau
+++ b/src/Rosetta/model/fbx/Xform.luau
@@ -1,7 +1,6 @@
--!strict
--- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model
--- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, with FBX's numbered Euler orders. The
--- matrix / quaternion arithmetic is codecs/model/Mat4.
+-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"):
+-- local = T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Xform = {}
@@ -12,7 +11,6 @@ function Xform.euler(x: number, y: number, z: number, order: number?): Mat4.M4
return Mat4.euler(x, y, z, ORDERS[order or 0] or "xyz")
end
--- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers
export type Props = {
T: { number }, R: { number }, S: { number },
Rpre: { number }, Rpost: { number }, Roff: { number }, Rp: { number }, Soff: { number }, Sp: { number },
@@ -28,7 +26,6 @@ function Xform.localMatrix(p: Props): Mat4.M4
end
m = Mat4.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order))
if not isZero(p.Rpost) then
- -- the inverse of a rotation is its transpose
m = Mat4.mul(m, Mat4.transpose3(Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0)))
end
m = Mat4.mul(m, Mat4.translation(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3]))
diff --git a/src/Rosetta/model/fbx/init.luau b/src/Rosetta/model/fbx/init.luau
index db1f96d..b266afd 100644
--- a/src/Rosetta/model/fbx/init.luau
+++ b/src/Rosetta/model/fbx/init.luau
@@ -1,24 +1,7 @@
--!strict
--- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays
--- through codecs/compress/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and
--- assimp's FBX importer, and the FBX SDK's documentation of the transform model.
--- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl
--- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms
--- baked into the mesh), meshes (polygons fan-triangulated by default or kept as "polygons"; layer elements for normals,
--- tangents, uvs (TEXCOORD_n, flipped to glTF's top-left origin), colours and materials in every mapping and reference
--- mode), Phong / Lambert materials (-> PBR approximations + the Phong values in extras.fbx) and 3ds Max Physical PBR
--- materials, textures (embedded Video content kept encoded, or the file through opts.resolve / opts.files), skins
--- (clusters -> JOINTS_0 / WEIGHTS_0, the 4 strongest influences, inverse bind matrices), blend shapes (morph targets
--- + weights), animation stacks (curves on T / R / S and DeformPercent sampled at their keys, or opts.sampleRate, and
--- turned into glTF translation / rotation / scale / weights channels), cameras and lights (on child nodes oriented for
--- glTF's -Z forward axis), the axis system and unit (meta.up, meta.unit = UnitScaleFactor / 100; nothing is rotated).
--- Writes binary FBX 7.4 (or ASCII with opts.ascii): the node hierarchy, meshes (one Geometry per mesh, its primitives
--- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields),
--- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster +
--- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler
--- XYZ curves; arrays zlib-compressed unless opts.compress = false). Checked with assimp and Blender (not the FBX SDK).
--- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered
--- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear).
+-- model/fbx: Autodesk FBX 7.x binary and ASCII, from Blender's io_scene_fbx, assimp and the FBX SDK transform docs.
+-- Supports: Model transforms, meshes, Phong / Physical materials, textures, skins, blend shapes, animation, cameras.
+-- Not supported: FBX 6.x and older, NURBS / patches / lines, constraints, animation layer blending.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -41,21 +24,21 @@ local Fbx = {
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
- triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
- flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's convention)
- sampleRate: number?, -- also sample animation curves at this many samples per second (default: their keys only)
- resolve: ((uri: string) -> any)?, -- external texture files (the api sets it for paths)
- files: { [string]: any }?, -- or: the files by name
- maxBytes: number?, -- refuse arrays over this many bytes in total (default 2^30)
- maxVertices: number?, -- refuse more polygon corners (default 2^25)
+ triangulate: boolean?, -- default true
+ flipV: boolean?, -- default true
+ sampleRate: number?, -- samples per second (default: the keys only)
+ resolve: ((uri: string) -> any)?, -- external texture files
+ files: { [string]: any }?,
+ maxBytes: number?, -- default 2^30 bytes of arrays
+ maxVertices: number?, -- default 2^25 polygon corners
}
export type EncodeOptions = {
- ascii: boolean?, -- write ASCII FBX (default binary)
+ ascii: boolean?, -- default binary
version: number?, -- 7400 (default) or 7500 (64-bit records)
- flipV: boolean?, -- default true (the inverse of decode)
- embedTextures: boolean?, -- embed texture.data as Video content (default true)
- compress: boolean?, -- zlib-compress arrays over 32 elements (default true; false writes ~3x faster, ~2x bigger)
- name: string?, -- the destination's file name (names textures without a uri)
+ flipV: boolean?, -- default true
+ embedTextures: boolean?, -- default true
+ compress: boolean?, -- arrays over 32 elements (default true)
+ name: string?,
creator: string?,
}
@@ -100,8 +83,6 @@ end
local toErr = Err.from
--- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err.
--- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }.
function Fbx.tree(r: Bytes.Reader, opts: DecodeOptions?): (any, any, boolean?)
if r:peek(21) == MAGIC then
local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts)
@@ -129,7 +110,6 @@ function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
if not root then
return nil, version
end
- -- the scene builder is plain (not native) code: a bug there must not escape as an error
local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene))
diff --git a/src/Rosetta/model/gltf/Pack.luau b/src/Rosetta/model/gltf/Pack.luau
index 470d384..998eb9b 100644
--- a/src/Rosetta/model/gltf/Pack.luau
+++ b/src/Rosetta/model/gltf/Pack.luau
@@ -1,15 +1,11 @@
--!strict
--!native
--- model/gltf/Pack: the byte loops of glTF accessors: strided / column-padded elements into tightly packed Scene
--- accessor data (gather), the reverse for writing (scatter), and sparse substitution. Callers check every range
--- first (offsets, strides and counts against the buffer lengths); nothing here throws.
+-- model/gltf/Pack: the byte loops of glTF accessors (gather strided elements, scatter, sparse substitution); callers
+-- check every range first. glTF pads matrix columns to 4 bytes.
local Pack = {}
local bcopy, readu8, readu16, readu32 = buffer.copy, buffer.readu8, buffer.readu16, buffer.readu32
--- gather(dst, src, off, count, elem, stride, cols, colBytes, colStride): element i starts at off + i * stride; an element is
--- cols columns of colBytes bytes, colStride apart (glTF pads matrix columns to 4 bytes); dst gets them packed (elem =
--- cols * colBytes bytes each)
function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number)
if cols == 1 or colBytes == colStride then
if stride == elem then
@@ -30,7 +26,6 @@ function Pack.gather(dst: buffer, src: buffer, off: number, count: number, elem:
end
end
--- scatter(dst, at, src, count, elem, stride, cols, colBytes, colStride): the reverse of gather (dst zero-filled)
function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem: number, stride: number, cols: number, colBytes: number, colStride: number)
if cols == 1 or colBytes == colStride then
if stride == elem then
@@ -51,8 +46,6 @@ function Pack.scatter(dst: buffer, at: number, src: buffer, count: number, elem:
end
end
--- sparse(dst, count, elem, idx, idxOff, idxSize, values, valOff, n) -> false when an index is out of range: element
--- idx[k] of dst becomes value k (values packed, elem bytes each)
function Pack.sparse(dst: buffer, count: number, elem: number, idx: buffer, idxOff: number, idxSize: number, values: buffer, valOff: number, n: number): boolean
for k = 0, n - 1 do
local i
diff --git a/src/Rosetta/model/gltf/Read.luau b/src/Rosetta/model/gltf/Read.luau
index 7159685..f3d1176 100644
--- a/src/Rosetta/model/gltf/Read.luau
+++ b/src/Rosetta/model/gltf/Read.luau
@@ -1,10 +1,6 @@
--!strict
--- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. Accessors of every component type
--- (normalized ones as unorm / snorm, matrices with their column padding removed, byte strides, sparse substitution,
--- accessors without a bufferView as zeros), images kept encoded (bufferView / data: URI / external file through the
--- fetch callback), samplers, PBR materials with every material extension (textureInfo objects -> TextureRefs), the
--- KHR_texture_transform of every texture reference, cameras, KHR_lights_punctual, skins, animations, morph targets,
--- scenes. glTF extras and unhandled extensions are kept in