ws-3d: model/vox (MagicaVoxel read/write: every chunk, scene graph, materials, layers, render objects, cameras, notes, IMAP, META, unknown chunks kept), ops/MeshOps (triangulate, transform, normals, tangents, weld/unweld, bounds, merge, scale/setUnit/setUp, greedy voxel meshing); Types: Scene.reader/mul/nodeMatrix/flatten helpers; compat: __iter visits t[0] on LuaJIT (was skipped by ipairs)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 08:38:02 -05:00
1 parent 7e2a311aac
commit 58f6b32541
22 files changed
+3269 -1

No files matched your search

+155
View File
@@ -404,6 +404,161 @@ function Scene.fromPrimitive(prim: Primitive, name: string?): Scene
end
Types.Scene = Scene
-- reader(acc) -> get(i, c): element i (0-based), component c (0-based) as a number; normalized types are converted
-- to floats (unorm8 255 -> 1, snorm16 -32767 -> -1, glTF rules). Nil for an unknown type.
function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)?
local d, n, t = acc.data, acc.components, acc.type
local size = COMPONENT_SIZE[t]
if not size or type(d) ~= "buffer" then
return nil
end
local stride = n * size
local rb = buffer
if t == "f32" then
local f = rb.readf32
return function(i: number, c: number): number
return f(d, i * stride + c * 4)
end
elseif t == "f64" then
local f = rb.readf64
return function(i: number, c: number): number
return f(d, i * stride + c * 8)
end
elseif t == "u8" or t == "unorm8" then
local f, k = rb.readu8, if t == "unorm8" then 1 / 255 else 1
return function(i: number, c: number): number
return f(d, i * stride + c) * k
end
elseif t == "u16" or t == "unorm16" then
local f, k = rb.readu16, if t == "unorm16" then 1 / 65535 else 1
return function(i: number, c: number): number
return f(d, i * stride + c * 2) * k
end
elseif t == "u32" then
local f = rb.readu32
return function(i: number, c: number): number
return f(d, i * stride + c * 4)
end
elseif t == "i8" then
local f = rb.readi8
return function(i: number, c: number): number
return f(d, i * stride + c)
end
elseif t == "snorm8" then
local f = rb.readi8
return function(i: number, c: number): number
return math.max(f(d, i * stride + c) / 127, -1)
end
elseif t == "i16" then
local f = rb.readi16
return function(i: number, c: number): number
return f(d, i * stride + c * 2)
end
elseif t == "snorm16" then
local f = rb.readi16
return function(i: number, c: number): number
return math.max(f(d, i * stride + c * 2) / 32767, -1)
end
elseif t == "i32" then
local f = rb.readi32
return function(i: number, c: number): number
return f(d, i * stride + c * 4)
end
end
return nil
end
-- the identity and products of column-major 4x4 matrices (flat arrays of 16)
local IDENTITY = table.freeze({ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 })
Scene.IDENTITY = IDENTITY
function Scene.mul(a: { number }, b: { number }): { number }
local m = table.create(16, 0)
for col = 0, 3 do
for row = 0, 3 do
local s = 0
for k = 0, 3 do
s += a[k * 4 + row + 1] * b[col * 4 + k + 1]
end
m[col * 4 + row + 1] = s
end
end
return m
end
-- nodeMatrix(node) -> the node's local matrix (node.matrix, or T * R * S)
function Scene.nodeMatrix(node: Node): { number }
if node.matrix and #node.matrix == 16 then
return node.matrix
end
local t, r, sc = node.translation, node.rotation, node.scale
if not t and not r and not sc then
return IDENTITY
end
local tx, ty, tz = 0, 0, 0
if t then
tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0
end
local x, y, z, w = 0, 0, 0, 1
if r then
x, y, z, w = r[1] or 0, r[2] or 0, r[3] or 0, r[4] or 1
end
local sx, sy, sz = 1, 1, 1
if sc then
sx, sy, sz = sc[1] or 1, sc[2] or 1, sc[3] or 1
end
local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
return {
(1 - 2 * (yy + zz)) * sx, (2 * (xy + wz)) * sx, (2 * (xz - wy)) * sx, 0,
(2 * (xy - wz)) * sy, (1 - 2 * (xx + zz)) * sy, (2 * (yz + wx)) * sy, 0,
(2 * (xz + wy)) * sz, (2 * (yz - wx)) * sz, (1 - 2 * (xx + yy)) * sz, 0,
tx, ty, tz, 1,
}
end
export type Placed = { primitive: Primitive, matrix: { number }, node: number, mesh: number }
-- flatten(scene) -> { { primitive, matrix (world), node, mesh } } for every mesh primitive reachable from the roots
-- (depth first, in order; cycles and repeated visits are cut). Scenes without roots use every node without a parent.
function Scene.flatten(scene: Scene): { Placed }
local out: { Placed } = {}
local nodes = scene.nodes or {}
local roots = scene.roots
if not roots or #roots == 0 then
local child = {}
for _, n in nodes do
for _, c in n.children or {} do
child[c] = true
end
end
roots = {}
for i in nodes do
if not child[i] then
table.insert(roots, i)
end
end
end
local seen: { [number]: boolean } = {}
local function visit(i: number, parent: { number })
local node = nodes[i]
if not node or seen[i] then
return
end
seen[i] = true
local m = Scene.nodeMatrix(node)
local world = if parent == IDENTITY then m elseif m == IDENTITY then parent else Scene.mul(parent, m)
local mesh = node.mesh and scene.meshes[node.mesh]
if mesh then
for _, p in mesh.primitives do
table.insert(out, { primitive = p, matrix = world, node = i, mesh = node.mesh :: number })
end
end
for _, c in node.children or {} do
visit(c, world)
end
end
for _, r in roots do
visit(r, IDENTITY)
end
return out
end
-- ------------------------------------------------------------------------------------------------ Cad
-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep)
export type StepEntity = { id: number, type: string, args: { any } }
+61
View File
@@ -0,0 +1,61 @@
--!strict
--!native
-- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI
-- records. Callers check every range first; nothing here throws.
local Grid = {}
local readu8, writeu8 = buffer.readu8, buffer.writeu8
-- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the
-- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted.
-- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz.
function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number
local skipped = 0
local sxy = sx * sy
for k = 0, n - 1 do
local p = off + k * 4
local x, y, z, i = readu8(src, p), readu8(src, p + 1), readu8(src, p + 2), readu8(src, p + 3)
if x < sx and y < sy and z < sz and i ~= 0 then
writeu8(dst, x + sx * y + sxy * z, i)
else
skipped += 1
end
end
return skipped
end
-- count(data, cells) -> the number of non-empty cells in data[0, cells)
function Grid.count(data: buffer, cells: number): number
local n = 0
for k = 0, cells - 1 do
if readu8(data, k) ~= 0 then
n += 1
end
end
return n
end
-- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest).
-- The caller sizes dst with count() (sx, sy, sz <= 256).
function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number
local p = at
local k = 0
for z = 0, sz - 1 do
for y = 0, sy - 1 do
for x = 0, sx - 1 do
local i = readu8(data, k)
if i ~= 0 then
writeu8(dst, p, x)
writeu8(dst, p + 1, y)
writeu8(dst, p + 2, z)
writeu8(dst, p + 3, i)
p += 4
end
k += 1
end
end
end
return p
end
return Grid
+903
View File
@@ -0,0 +1,903 @@
--!strict
-- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt)
-- and the files MagicaVoxel 0.99.x saves (version 150 and 200).
-- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP /
-- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials,
-- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown
-- chunks are kept raw and written back.
-- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per
-- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as
-- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is
-- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes.
-- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must
-- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk.
-- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Grid = require("@formats/model/vox/Grid")
-- ------------------------------------------------------------------------------------------------ contract
local Vox = {
name = "vox",
category = "model",
extensions = { "vox" },
mime = { "model/x-vox" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, voxels = true, sceneGraph = true, materials = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxCells: number?, -- refuse files whose grids hold more cells in total (default 2^27)
}
export type EncodeOptions = {
version: number?, -- the file version (default 200, what MagicaVoxel 0.99.7 writes; 150 is the older one)
}
type Dict = { [string]: string }
type GraphNode = {
kind: string,
id: number,
attrs: Dict,
child: number?,
layer: number?,
frames: { Dict }?,
children: { number }?,
models: { { model: number, attributes: Dict } }?,
}
-- ------------------------------------------------------------------------------------------------ constants
-- the default palette (spec section 8): a 6 x 6 x 6 colour cube without black, then red, green, blue and grey ramps
local DEFAULT_PALETTE: { { number } } = {}
do
local steps = { 0xff, 0xcc, 0x99, 0x66, 0x33, 0x00 }
for _, r in steps do
for _, g in steps do
for _, b in steps do
if #DEFAULT_PALETTE < 215 then
table.insert(DEFAULT_PALETTE, { r, g, b, 255 })
end
end
end
end
local ramp = { 0xee, 0xdd, 0xbb, 0xaa, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 }
for ch = 1, 4 do
for _, v in ramp do
local c = { 0, 0, 0, 255 }
if ch == 4 then
c = { v, v, v, 255 }
else
c[ch] = v
end
table.insert(DEFAULT_PALETTE, c)
end
end
end
Vox.DEFAULT_PALETTE = DEFAULT_PALETTE
local IDENTITY_R = 4 -- _r of the identity: row 0 -> column 0, row 1 -> column 1, no signs
local MAX_DEPTH = 256
-- ------------------------------------------------------------------------------------------------ sniff
function Vox.sniff(r: Bytes.Reader): number
return if r:peek(4) == "VOX " and r:peek(4, 8) == "MAIN" then 1 elseif r:peek(4) == "VOX " then 0.8 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function str(r: Bytes.Reader): string
local n = r:i32le()
if n < 0 or n > r:remaining() then
r:fail(Err.CORRUPT, "bad string length")
return ""
end
return r:string(n)
end
local function dict(r: Bytes.Reader): Dict
local d: Dict = {}
local n = r:i32le()
if n < 0 or n * 8 > r:remaining() then
r:fail(Err.CORRUPT, "bad dictionary size")
return d
end
for _ = 1, n do
local k = str(r)
local v = str(r)
if r.err then
break
end
d[k] = v
end
return d
end
local function ints(s: string?): { number }
local out = {}
if s then
for w in string.gmatch(s, "%S+") do
table.insert(out, tonumber(w) or 0)
end
end
return out
end
-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation
local function rotation(b: number): { { number } }?
local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3)
if i0 > 2 or i1 > 2 or i0 == i1 then
return nil
end
local i2 = 3 - i0 - i1
local function sign(bit: number): number
return if bit32.band(b, bit32.lshift(1, bit)) ~= 0 then -1 else 1
end
return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } }
end
-- the node transform of a frame dictionary (_r, _t)
local function applyFrame(node: Types.Node, f: Dict)
local t = ints(f._t)
local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0
local rb = tonumber(f._r)
local rows = if rb and rb ~= IDENTITY_R then rotation(rb) else nil
if not rows then
if tx ~= 0 or ty ~= 0 or tz ~= 0 then
node.translation = { tx, ty, tz }
end
return
end
-- R[row][col], then the determinant: +1 -> a quaternion, -1 (a mirror) -> a matrix
local R = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }
for row = 1, 3 do
R[row][rows[row][1] + 1] = rows[row][2]
end
local det = R[1][1] * (R[2][2] * R[3][3] - R[2][3] * R[3][2]) - R[1][2] * (R[2][1] * R[3][3] - R[2][3] * R[3][1]) + R[1][3] * (R[2][1] * R[3][2] - R[2][2] * R[3][1])
if det < 0 then
node.matrix = {
R[1][1], R[2][1], R[3][1], 0,
R[1][2], R[2][2], R[3][2], 0,
R[1][3], R[2][3], R[3][3], 0,
tx, ty, tz, 1,
}
return
end
local m00, m11, m22 = R[1][1], R[2][2], R[3][3]
local tr = m00 + m11 + m22
local x, y, z, w
if tr > 0 then
local s = math.sqrt(tr + 1) * 2
w, x, y, z = 0.25 * s, (R[3][2] - R[2][3]) / s, (R[1][3] - R[3][1]) / s, (R[2][1] - R[1][2]) / s
elseif m00 > m11 and m00 > m22 then
local s = math.sqrt(1 + m00 - m11 - m22) * 2
w, x, y, z = (R[3][2] - R[2][3]) / s, 0.25 * s, (R[1][2] + R[2][1]) / s, (R[1][3] + R[3][1]) / s
elseif m11 > m22 then
local s = math.sqrt(1 + m11 - m00 - m22) * 2
w, x, y, z = (R[1][3] - R[3][1]) / s, (R[1][2] + R[2][1]) / s, 0.25 * s, (R[2][3] + R[3][2]) / s
else
local s = math.sqrt(1 + m22 - m00 - m11) * 2
w, x, y, z = (R[2][1] - R[1][2]) / s, (R[1][3] + R[3][1]) / s, (R[2][3] + R[3][2]) / s, 0.25 * s
end
node.rotation = { x, y, z, w }
if tx ~= 0 or ty ~= 0 or tz ~= 0 then
node.translation = { tx, ty, tz }
end
end
-- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers
local function material(d: Dict): Types.VoxelMaterial
local m: Types.VoxelMaterial = { type = "diffuse" }
for k, v in d do
local key = if string.sub(k, 1, 1) == "_" then string.sub(k, 2) else k
if key == "type" then
m.type = if string.sub(v, 1, 1) == "_" then string.sub(v, 2) else v
else
m[key] = tonumber(v) or v
end
end
return m
end
type Parsed = {
version: number,
models: { Types.Voxels },
palette: { { number } }?,
materials: { [number]: Types.VoxelMaterial },
graph: { [number]: GraphNode },
meta: { [string]: any },
skipped: number,
}
local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?)
local maxCells = opts and opts.maxCells or 2 ^ 27
if r:string(4) ~= "VOX " then
return nil, Err.new(Err.CORRUPT, "bad signature", r.base)
end
local version = r:u32le()
if r:string(4) ~= "MAIN" then
if r.err then
return nil, r.err
end
return nil, Err.new(Err.CORRUPT, "missing MAIN chunk", 8)
end
local mainN, mainM = r:i32le(), r:i32le()
if r.err then
return nil, r.err
end
if mainN < 0 or mainM < 0 or not r:skip(mainN) then
return nil, Err.new(Err.CORRUPT, "bad MAIN chunk", 12)
end
local out: Parsed = { version = version, models = {}, palette = nil, materials = {}, graph = {}, meta = {}, skipped = 0 }
local meta = out.meta
local unknown: { any } = {}
local layers, robjs, cams = {}, {}, {}
local stop = r:tell() + mainM
if stop > r:size() then
return nil, Err.new(Err.TRUNCATED, "the MAIN chunk runs past the end", r.base + 16)
end
local pending: { number }? = nil
local cells = 0
while r:tell() + 12 <= stop do
local at = r:tell()
local id = r:string(4)
local n, m = r:i32le(), r:i32le()
if n < 0 or m < 0 then
return nil, Err.new(Err.CORRUPT, "bad size of chunk " .. id, at)
elseif n > stop - r:tell() or m > stop - r:tell() - n then
return nil, Err.new(Err.TRUNCATED, "chunk " .. id .. " runs past the end", at)
end
local c = r:slice(n)
if id == "SIZE" then
local sx, sy, sz = c:i32le(), c:i32le(), c:i32le()
if c.err or sx < 1 or sy < 1 or sz < 1 then
return nil, Err.new(Err.CORRUPT, "bad model size", at)
end
cells += sx * sy * sz
if cells > maxCells then
return nil, Err.new(Err.LIMIT, string.format("models hold over %d cells", maxCells), at)
end
pending = { sx, sy, sz }
elseif id == "XYZI" then
local size = pending
if not size then
return nil, Err.new(Err.CORRUPT, "XYZI without SIZE", at)
end
pending = nil
local count = c:i32le()
if c.err or count < 0 or count * 4 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad voxel count", at)
end
local v = Types.Voxels.new(size[1], size[2], size[3], DEFAULT_PALETTE)
out.skipped += Grid.fill(v.data, size[1], size[2], size[3], c.buf, c.base + c:tell(), count)
table.insert(out.models, v)
elseif id == "RGBA" then
if n < 1024 then
return nil, Err.new(Err.CORRUPT, "short RGBA chunk", at)
end
local pal = table.create(255)
for i = 1, 255 do
pal[i] = { c:u8(), c:u8(), c:u8(), c:u8() }
end
out.palette = pal
elseif id == "MATL" then
local mid = c:i32le()
local d = dict(c)
if c.err then
return nil, Err.new(Err.CORRUPT, "bad MATL chunk", at)
end
out.materials[mid] = material(d)
elseif id == "nTRN" then
local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c), child = c:i32le() }
c:i32le() -- reserved
node.layer = c:i32le()
local nf = c:i32le()
if c.err or nf < 0 or nf * 4 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad nTRN chunk", at)
end
local frames = {}
for k = 1, nf do
frames[k] = dict(c)
end
node.frames = frames
if c.err then
return nil, Err.new(Err.CORRUPT, "bad nTRN frames", at)
end
out.graph[node.id] = node
elseif id == "nGRP" then
local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) }
local nc = c:i32le()
if c.err or nc < 0 or nc * 4 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad nGRP chunk", at)
end
local children = table.create(nc)
for k = 1, nc do
children[k] = c:i32le()
end
node.children = children
out.graph[node.id] = node
elseif id == "nSHP" then
local node: GraphNode = { kind = id, id = c:i32le(), attrs = dict(c) }
local nm = c:i32le()
if c.err or nm < 0 or nm * 8 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad nSHP chunk", at)
end
local models = {}
for k = 1, nm do
models[k] = { model = c:i32le() + 1, attributes = dict(c) }
end
if c.err then
return nil, Err.new(Err.CORRUPT, "bad nSHP models", at)
end
node.models = models
out.graph[node.id] = node
elseif id == "LAYR" then
local lid = c:i32le()
local d = dict(c)
if c.err then
return nil, Err.new(Err.CORRUPT, "bad LAYR chunk", at)
end
table.insert(layers, { id = lid, name = d._name, hidden = d._hidden == "1", attributes = d })
elseif id == "rOBJ" then
local d = dict(c)
if c.err then
return nil, Err.new(Err.CORRUPT, "bad rOBJ chunk", at)
end
table.insert(robjs, d)
elseif id == "rCAM" then
local cid = c:i32le()
local d = dict(c)
if c.err then
return nil, Err.new(Err.CORRUPT, "bad rCAM chunk", at)
end
table.insert(cams, { id = cid, attributes = d })
elseif id == "NOTE" then
local nn = c:i32le()
if c.err or nn < 0 or nn * 4 > c:remaining() then
return nil, Err.new(Err.CORRUPT, "bad NOTE chunk", at)
end
local notes = table.create(nn)
for k = 1, nn do
notes[k] = str(c)
end
if c.err then
return nil, Err.new(Err.CORRUPT, "bad NOTE names", at)
end
meta.notes = notes
elseif id == "IMAP" then
local map = {}
for k = 1, math.min(n, 256) do
map[k] = c:u8()
end
meta.indexMap = map
elseif id == "META" then
local d = dict(c)
if c.err then
return nil, Err.new(Err.CORRUPT, "bad META chunk", at)
end
meta.info = d
else
if id == "PACK" then
meta.pack = c:i32le()
end
table.insert(unknown, { id = id, content = c:sub(0, n):bytes(n), children = nil :: buffer? })
end
if m > 0 then
local kids = r:bytes(math.min(m, r:remaining()))
if #unknown > 0 and unknown[#unknown].children == nil and unknown[#unknown].id == id then
unknown[#unknown].children = kids
end
end
if r.err then
return nil, r.err
end
end
if r:tell() < stop then
return nil, Err.new(Err.TRUNCATED, "a partial chunk at the end", r.base + r:tell())
end
if #out.models == 0 then
return nil, Err.new(Err.CORRUPT, "no models")
end
if #layers > 0 then
meta.layers = layers
end
if #robjs > 0 then
meta.renderObjects = robjs
end
if #cams > 0 then
meta.cameras = cams
end
if #unknown > 0 then
meta.chunks = unknown
end
return out, nil
end
-- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node)
local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: number, depth: number, visiting: { [number]: boolean }, nmodels: number): number?
local t = graph[id]
if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then
return nil
end
visiting[id] = true
local node: Types.Node = { name = t.attrs._name, children = {} }
local index = #scene.nodes + 1
scene.nodes[index] = node
local frames = t.frames or {}
if frames[1] then
applyFrame(node, frames[1])
end
local vox: { [string]: any } = { attributes = t.attrs, layer = t.layer }
if #frames > 1 or (frames[1] and frames[1]._f) then
vox.frames = frames
end
node.extras = { vox = vox }
local child = if t.child then graph[t.child] else nil
if child and child.kind == "nGRP" then
vox.group = child.attrs
for _, c in child.children or {} do
local ci = build(scene, graph, c, depth + 1, visiting, nmodels)
if ci then
table.insert(node.children, ci)
end
end
elseif child and child.kind == "nSHP" then
local models = child.models or {}
vox.shape = { attributes = child.attrs, models = models }
local first = models[1]
if first and first.model >= 1 and first.model <= nmodels then
node.voxels = first.model
end
end
visiting[id] = nil
return index
end
-- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err
function Vox.decodeVoxels(r: Bytes.Reader, opts: DecodeOptions?): ({ Types.Voxels }?, Err.Err?)
local p, err = parse(r, opts)
if not p then
return nil, err
end
local pal = p.palette or DEFAULT_PALETTE
local mats = if next(p.materials) then p.materials else nil
for _, v in p.models do
v.palette = pal
v.materials = mats
end
return p.models, nil
end
function Vox.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local p, err = parse(r, opts)
if not p then
return nil, err
end
local scene = Types.Scene.new()
local pal = p.palette or DEFAULT_PALETTE
local mats = if next(p.materials) then p.materials else nil
for _, v in p.models do
v.palette = pal
v.materials = mats
end
scene.voxels = p.models
if p.graph[0] then
local root = build(scene, p.graph, 0, 0, {}, #p.models)
if root then
scene.roots = { root }
end
end
if #scene.nodes == 0 then
-- no scene graph (version 150 files): one node per model
for i = 1, #p.models do
scene.nodes[i] = { children = {}, voxels = i }
scene.roots[i] = i
end
end
scene.meta.up = "z"
scene.meta.vox = p.meta
scene.meta.source = { format = "vox", version = p.version, models = #p.models, palette = p.palette ~= nil, skippedVoxels = p.skipped }
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function number(v: any): string
if type(v) ~= "number" then
return tostring(v)
end
if v == math.floor(v) and math.abs(v) < 2 ^ 53 then
return string.format("%d", v)
end
for _, f in { "%.6g", "%.9g", "%.17g" } do
local s = string.format(f, v)
if tonumber(s) == v then
return s
end
end
return string.format("%.17g", v)
end
local function sortedKeys(d: { [string]: any }): { string }
local keys = {}
for k in d do
if type(k) == "string" then
table.insert(keys, k)
end
end
table.sort(keys)
return keys
end
local function wstr(w: Bytes.Writer, s: string)
w:u32le(#s)
w:string(s)
end
local function wdict(w: Bytes.Writer, d: { [string]: any }?)
if not d then
w:u32le(0)
return
end
local keys = sortedKeys(d)
w:u32le(#keys)
for _, k in keys do
wstr(w, k)
wstr(w, number(d[k]))
end
end
-- a node's transform as a frame dictionary (_r, _t) | nil, message
local function frameOf(node: Types.Node, base: Dict?): (Dict?, string?)
local f: Dict = {}
if base then
for k, v in base do
if k ~= "_r" and k ~= "_t" then
f[k] = v
end
end
end
local m = Types.Scene.nodeMatrix(node)
local cols, signs = {}, {}
for row = 0, 2 do
local best, bv, rest = 0, 0, 0
for col = 0, 2 do
local v = m[col * 4 + row + 1]
if math.abs(v) > math.abs(bv) then
rest = math.max(rest, math.abs(bv))
best, bv = col, v
else
rest = math.max(rest, math.abs(v))
end
end
if math.abs(math.abs(bv) - 1) > 1e-4 or rest > 1e-4 or table.find(cols, best) then
return nil, "node rotation is not a multiple of 90 degrees (or has a scale)"
end
table.insert(cols, best)
signs[row + 1] = if bv < 0 then 1 else 0
end
local rb = cols[1] + cols[2] * 4 + signs[1] * 16 + signs[2] * 32 + signs[3] * 64
if rb ~= IDENTITY_R then
f._r = tostring(rb)
end
local tx, ty, tz = math.floor(m[13] + 0.5), math.floor(m[14] + 0.5), math.floor(m[15] + 0.5)
if tx ~= 0 or ty ~= 0 or tz ~= 0 then
f._t = string.format("%d %d %d", tx, ty, tz)
end
return f, nil
end
type Record = { kind: string, id: number, attrs: { [string]: any }?, child: number?, layer: number?, frames: { Dict }?, children: { number }?, models: { { model: number, attributes: Dict? } }? }
function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local version = opts and opts.version or 200
if type(version) ~= "number" or version < 0 then
return nil, Err.new(Err.ARG, "bad version")
end
if type(value) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid")
end
local scene: Types.Scene
if value.kind == "voxels" then
scene = Types.Scene.new()
scene.voxels = { value }
scene.nodes[1] = { children = {}, voxels = 1 }
scene.roots[1] = 1
elseif value.kind == "scene" then
scene = value
else
return nil, Err.new(Err.ARG, "needs a Scene with voxels or a Voxels grid")
end
local models = scene.voxels
if type(models) ~= "table" or #models == 0 then
return nil, Err.new(Err.ARG, "the scene has no voxels (MeshOps cannot voxelize meshes yet)")
end
for i, v in models do
local s = v.size
if type(s) ~= "table" or type(v.data) ~= "buffer" then
return nil, Err.new(Err.ARG, "voxels " .. i .. ": not a Voxels grid")
end
for k = 1, 3 do
if type(s[k]) ~= "number" or s[k] < 1 or s[k] > 256 or s[k] ~= math.floor(s[k]) then
return nil, Err.new(Err.ARG, "voxels " .. i .. ": size must be 1..256 per axis")
end
end
if buffer.len(v.data) < s[1] * s[2] * s[3] then
return nil, Err.new(Err.ARG, "voxels " .. i .. ": data is smaller than the grid")
end
end
local meta = if type(scene.meta) == "table" and type(scene.meta.vox) == "table" then scene.meta.vox else {}
local w = Bytes.writer(65536)
w:string("VOX ")
w:u32le(version)
w:string("MAIN")
w:u32le(0)
local mAt = w:tell()
w:u32le(0)
local function chunk(id: string, body: () -> ())
w:string(id)
local at = w:tell()
w:u32le(0)
w:u32le(0)
body()
w:setU32le(at, w:tell() - at - 8)
end
if type(meta.info) == "table" then
chunk("META", function()
wdict(w, meta.info)
end)
end
-- models
for _, v in models do
local sx, sy, sz = v.size[1], v.size[2], v.size[3]
chunk("SIZE", function()
w:u32le(sx)
w:u32le(sy)
w:u32le(sz)
end)
local count = Grid.count(v.data, sx * sy * sz)
chunk("XYZI", function()
w:u32le(count)
local at = w:reserve(count * 4)
Grid.write(w.buf, at, v.data, sx, sy, sz)
w.pos = at + count * 4
end)
end
-- the scene graph
local records: { Record } = {}
local nextId = 0
local function alloc(): number
local id = nextId
nextId += 1
return id
end
local nodes = scene.nodes or {}
local visiting: { [number]: boolean } = {}
local failure: string? = nil
local function shape(model: number, vx: any?): number
local id = alloc()
local ms = {}
local saved = vx and vx.shape
if saved and type(saved.models) == "table" and saved.models[1] and saved.models[1].model == model then
for _, sm in saved.models do
if type(sm.model) == "number" and sm.model >= 1 and sm.model <= #models then
table.insert(ms, { model = sm.model - 1, attributes = sm.attributes })
end
end
end
if #ms == 0 then
ms[1] = { model = model - 1, attributes = nil }
end
table.insert(records, { kind = "nSHP", id = id, attrs = saved and saved.attributes, models = ms })
return id
end
local function visit(index: number, depth: number, layer: number?): number?
local node = nodes[index]
if not node or visiting[index] or depth > MAX_DEPTH then
failure = failure or "the node tree has a loop or is too deep"
return nil
end
visiting[index] = true
local vx = if type(node.extras) == "table" and type(node.extras.vox) == "table" then node.extras.vox else nil
local id = alloc()
local attrs: { [string]: any } = {}
if vx and type(vx.attributes) == "table" then
for k, v in vx.attributes do
attrs[k] = v
end
end
attrs._name = node.name
local saved = vx and type(vx.frames) == "table" and vx.frames or nil
local f, ferr = frameOf(node, saved and saved[1])
if not f then
failure = failure or ferr
f = {}
end
local frames = { f :: Dict }
if saved then
for k = 2, #saved do
frames[k] = saved[k]
end
end
local rec: Record = { kind = "nTRN", id = id, attrs = attrs, layer = layer or (vx and tonumber(vx.layer)) or 0, frames = frames }
table.insert(records, rec)
local kids = node.children or {}
local hasVox = type(node.voxels) == "number" and node.voxels >= 1 and node.voxels <= #models
if hasVox and #kids == 0 then
rec.child = shape(node.voxels :: number, vx)
else
local gid = alloc()
local grp: Record = { kind = "nGRP", id = gid, attrs = vx and vx.group, children = {} }
table.insert(records, grp)
rec.child = gid
if hasVox then
local tid = alloc()
local t2: Record = { kind = "nTRN", id = tid, attrs = {}, layer = 0, frames = { {} } }
table.insert(records, t2)
table.insert(grp.children :: { number }, tid)
t2.child = shape(node.voxels :: number, vx)
end
for _, c in kids do
local cid = visit(c, depth + 1, nil)
if cid then
table.insert(grp.children :: { number }, cid)
end
end
end
visiting[index] = nil
return id
end
local roots = scene.roots or {}
local single = if #roots == 1 then nodes[roots[1]] else nil
if single and single.voxels == nil then
visit(roots[1], 0, -1)
elseif #roots > 0 then
local rid = alloc()
local gid = alloc()
local rec: Record = { kind = "nTRN", id = rid, attrs = {}, child = gid, layer = -1, frames = { {} } }
local grp: Record = { kind = "nGRP", id = gid, attrs = nil, children = {} }
table.insert(records, rec)
table.insert(records, grp)
for _, ri in roots do
local cid = visit(ri, 1, nil)
if cid then
table.insert(grp.children :: { number }, cid)
end
end
end
if failure then
return nil, Err.new(Err.ARG, failure)
end
for _, rec in records do
chunk(rec.kind, function()
w:u32le(rec.id)
wdict(w, rec.attrs)
if rec.kind == "nTRN" then
w:u32le(rec.child or 0)
w:u32le(0xFFFFFFFF)
w:u32le((rec.layer or 0) % 4294967296)
local frames = rec.frames or { {} }
w:u32le(#frames)
for _, f in frames do
wdict(w, f)
end
elseif rec.kind == "nGRP" then
local ch = rec.children or {}
w:u32le(#ch)
for _, c in ch do
w:u32le(c)
end
else
local ms = rec.models or {}
w:u32le(#ms)
for _, sm in ms do
w:u32le(sm.model)
wdict(w, sm.attributes)
end
end
end)
end
-- layers
if type(meta.layers) == "table" then
for _, l in meta.layers do
chunk("LAYR", function()
w:u32le(tonumber(l.id) or 0)
local d: { [string]: any } = {}
if type(l.attributes) == "table" then
for k, v in l.attributes do
d[k] = v
end
end
d._name = l.name
d._hidden = if l.hidden then "1" elseif d._hidden ~= nil then "0" else nil
wdict(w, d)
w:u32le(0xFFFFFFFF)
end)
end
end
-- palette
local pal = models[1].palette or DEFAULT_PALETTE
chunk("RGBA", function()
for i = 1, 256 do
local c = pal[i]
if type(c) == "table" then
w:u8(math.clamp(math.floor(tonumber(c[1]) or 0), 0, 255))
w:u8(math.clamp(math.floor(tonumber(c[2]) or 0), 0, 255))
w:u8(math.clamp(math.floor(tonumber(c[3]) or 0), 0, 255))
w:u8(math.clamp(math.floor(tonumber(c[4]) or 255), 0, 255))
else
w:u32le(0)
end
end
end)
if type(meta.indexMap) == "table" then
chunk("IMAP", function()
for k = 1, 256 do
w:u8(math.clamp(math.floor(tonumber(meta.indexMap[k]) or 0), 0, 255))
end
end)
end
-- materials
local mats = models[1].materials
if type(mats) == "table" then
local ids = {}
for id in mats do
if type(id) == "number" then
table.insert(ids, id)
end
end
table.sort(ids)
for _, id in ids do
local m = mats[id]
chunk("MATL", function()
w:u32le(id)
local d: { [string]: any } = { _type = "_" .. tostring(m.type or "diffuse") }
for k, v in m do
if k ~= "type" and type(k) == "string" then
d["_" .. k] = v
end
end
wdict(w, d)
end)
end
end
if type(meta.renderObjects) == "table" then
for _, d in meta.renderObjects do
chunk("rOBJ", function()
wdict(w, d)
end)
end
end
if type(meta.cameras) == "table" then
for _, cam in meta.cameras do
chunk("rCAM", function()
w:u32le(tonumber(cam.id) or 0)
wdict(w, cam.attributes)
end)
end
end
if type(meta.notes) == "table" then
chunk("NOTE", function()
w:u32le(#meta.notes)
for _, s in meta.notes do
wstr(w, tostring(s))
end
end)
end
if type(meta.chunks) == "table" then
for _, u in meta.chunks do
if type(u.id) == "string" and #u.id == 4 and type(u.content) == "buffer" and u.id ~= "PACK" then
w:string(u.id)
w:u32le(buffer.len(u.content))
w:u32le(if u.children then buffer.len(u.children) else 0)
w:bytes(u.content)
if u.children then
w:bytes(u.children)
end
end
end
end
w:setU32le(mAt, w:tell() - mAt - 4)
return w:finish(), nil
end
return Vox
+167
View File
@@ -0,0 +1,167 @@
--!strict
--!native
-- ops/MeshOps/Greedy: greedy meshing of a dense voxel grid (one byte per cell, 0 = empty): for each axis and each
-- slice between two layers of cells, the exposed faces are masked by palette index, and runs of equal faces are merged
-- into maximal rectangles (Mikola Lysenko's "Meshing in a Minecraft game", 2012). Faces between two filled cells are
-- hidden whatever their indices. Output: 4 vertices and 2 triangles per rectangle, counter-clockwise seen from the
-- outside. Never throws; the caller checks buffer.len(data) >= sx * sy * sz.
local Greedy = {}
local readu8, readi32, writei32 = buffer.readu8, buffer.readi32, buffer.writei32
local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32
export type Out = {
positions: buffer, -- f32 x3 per vertex
normals: buffer, -- f32 x3 per vertex
index: buffer, -- u8 palette index per vertex
indices: buffer, -- u32, 6 per quad
vertices: number,
quads: number,
}
-- run(data, sx, sy, sz, ox, oy, oz, scale) -> Out: vertex position = (cell corner + (ox, oy, oz)) * scale
function Greedy.run(data: buffer, sx: number, sy: number, sz: number, ox: number, oy: number, oz: number, scale: number): Out
local cap = 1024
local pos = buffer.create(cap * 48)
local nrm = buffer.create(cap * 48)
local idx = buffer.create(cap * 4)
local tri = buffer.create(cap * 24)
local quads = 0
local maxFace = math.max(sx * sy, sy * sz, sz * sx)
local mask = buffer.create(maxFace * 4)
local corner = { 0, 0, 0 }
for d = 0, 2 do
-- u, v: the two other axes, cyclic so that e_u x e_v = e_d
local u, v = (d + 1) % 3, (d + 2) % 3
local nd = if d == 0 then sx elseif d == 1 then sy else sz
local nu = if u == 0 then sx elseif u == 1 then sy else sz
local nv = if v == 0 then sx elseif v == 1 then sy else sz
local std = if d == 0 then 1 elseif d == 1 then sx else sx * sy
local stu = if u == 0 then 1 elseif u == 1 then sx else sx * sy
local stv = if v == 0 then 1 elseif v == 1 then sx else sx * sy
for slice = -1, nd - 1 do
-- the mask of faces between layer slice and slice + 1: +index (faces +d, owned by slice), -index (faces -d)
local any = false
for j = 0, nv - 1 do
for i = 0, nu - 1 do
local base = i * stu + j * stv
local a = if slice >= 0 then readu8(data, base + slice * std) else 0
local b = if slice + 1 < nd then readu8(data, base + (slice + 1) * std) else 0
local m = 0
if a ~= 0 and b == 0 then
m = a
elseif a == 0 and b ~= 0 then
m = -b
end
if m ~= 0 then
any = true
end
writei32(mask, (i + j * nu) * 4, m)
end
end
if any then
for j = 0, nv - 1 do
local i = 0
while i < nu do
local m = readi32(mask, (i + j * nu) * 4)
if m == 0 then
i += 1
else
local w = 1
while i + w < nu and readi32(mask, (i + w + j * nu) * 4) == m do
w += 1
end
local h = 1
local grow = true
while j + h < nv and grow do
for k = 0, w - 1 do
if readi32(mask, (i + k + (j + h) * nu) * 4) ~= m then
grow = false
break
end
end
if grow then
h += 1
end
end
for jj = j, j + h - 1 do
for k = 0, w - 1 do
writei32(mask, (i + k + jj * nu) * 4, 0)
end
end
-- emit the rectangle
if quads == cap then
local ncap = cap * 2
local function grow2(b: buffer, per: number): buffer
local nb = buffer.create(ncap * per)
buffer.copy(nb, 0, b, 0, cap * per)
return nb
end
pos, nrm, idx, tri = grow2(pos, 48), grow2(nrm, 48), grow2(idx, 4), grow2(tri, 24)
cap = ncap
end
corner[d + 1] = slice + 1
corner[u + 1] = i
corner[v + 1] = j
local cx, cy, cz = corner[1], corner[2], corner[3]
-- the u and v edge vectors
local ux = if u == 0 then w else 0
local uy = if u == 1 then w else 0
local uz = if u == 2 then w else 0
local vx = if v == 0 then h else 0
local vy = if v == 1 then h else 0
local vz = if v == 2 then h else 0
local nsign = if m > 0 then 1 else -1
local nx = if d == 0 then nsign else 0
local ny = if d == 1 then nsign else 0
local nz = if d == 2 then nsign else 0
local col = if m > 0 then m else -m
local vb = quads * 48
local px0, py0, pz0 = (cx + ox) * scale, (cy + oy) * scale, (cz + oz) * scale
writef32(pos, vb, px0)
writef32(pos, vb + 4, py0)
writef32(pos, vb + 8, pz0)
writef32(pos, vb + 12, px0 + ux * scale)
writef32(pos, vb + 16, py0 + uy * scale)
writef32(pos, vb + 20, pz0 + uz * scale)
writef32(pos, vb + 24, px0 + (ux + vx) * scale)
writef32(pos, vb + 28, py0 + (uy + vy) * scale)
writef32(pos, vb + 32, pz0 + (uz + vz) * scale)
writef32(pos, vb + 36, px0 + vx * scale)
writef32(pos, vb + 40, py0 + vy * scale)
writef32(pos, vb + 44, pz0 + vz * scale)
for k = 0, 3 do
writef32(nrm, vb + k * 12, nx)
writef32(nrm, vb + k * 12 + 4, ny)
writef32(nrm, vb + k * 12 + 8, nz)
writeu8(idx, quads * 4 + k, col)
end
local v0 = quads * 4
local ib = quads * 24
if m > 0 then
writeu32(tri, ib, v0)
writeu32(tri, ib + 4, v0 + 1)
writeu32(tri, ib + 8, v0 + 2)
writeu32(tri, ib + 12, v0)
writeu32(tri, ib + 16, v0 + 2)
writeu32(tri, ib + 20, v0 + 3)
else
writeu32(tri, ib, v0)
writeu32(tri, ib + 4, v0 + 2)
writeu32(tri, ib + 8, v0 + 1)
writeu32(tri, ib + 12, v0)
writeu32(tri, ib + 16, v0 + 3)
writeu32(tri, ib + 20, v0 + 2)
end
quads += 1
i += w
end
end
end
end
end
end
return { positions = pos, normals = nrm, index = idx, indices = tri, vertices = quads * 4, quads = quads }
end
return Greedy
File diff suppressed because it is too large. Load diff