Files
rosetta/src/Formats/model/robloxmesh/init.luau
T

579 lines
19 KiB
Luau

--!strict
-- model/robloxmesh: the Roblox FileMesh (.mesh), read + write, mapped to a Scene. Written from MaximumADHD's "Roblox Mesh
-- Format" notes (devforum.roblox.com/t/roblox-mesh-format/326114); no port.
-- Decode: 1.00 / 1.01 (ASCII; 1.00 positions halved, V flipped), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones,
-- skinning, subsets), 5.00 (+ FACS), 6.00 / 7.00 chunked (COREMESH v1, LODS, SKINNING, FACS; HSRAVIS and unknown
-- chunks kept raw in meta.source.chunks). A Draco-compressed COREMESH (v2) is Err.UNSUPPORTED until codecs/model/Draco
-- exists. One mesh, one triangle primitive (LOD 0): POSITION, NORMAL, TEXCOORD_0 (f32), TANGENT (f32 x4 from the signed
-- bytes), COLOR_0 (unorm8 x4, when the vertices carry colours), u32 indices; the other LODs as primitives in
-- mesh.extras.lods (same attributes, their own indices). Bones become joint nodes (local matrices from the files'
-- world-space CFrames; extras.culling / lodParent) under one skin with inverse bind matrices; skinning becomes
-- JOINTS_0 (u16, global joint indices through the subsets) and WEIGHTS_0 (unorm8). FACS data is kept raw
-- (meta.source.facs). meta.up = "y"; units are studs.
-- Encode: version 2.00 (default; 40-byte vertices when a COLOR_0 is not all white) or 4.00 (opts.version), from every
-- primitive of the scene in world space (codecs/model/MeshFlatten; polygons / strips fan-triangulated). 4.00 writes
-- the scene's first skin as bones + skinning (subsets of at most 26 bones, vertices duplicated across subsets, up to
-- 4 influences, weights to bytes summing to 255) and LOD offsets (mesh.extras.lods of a single unskinned primitive).
-- Missing normals are computed (area weighted), missing tangents written as (0, 0, -1, 1). Not supported: writing
-- 3.00 / 5.00+ / FACS.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Flatten = require("@formats/codecs/model/MeshFlatten")
local Parse = require("@formats/model/robloxmesh/Parse")
local Write = require("@formats/model/robloxmesh/Write")
-- ------------------------------------------------------------------------------------------------ contract
local RobloxMesh = {
name = "robloxmesh",
category = "model",
extensions = { "mesh" },
mime = { "application/x-roblox-mesh" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" },
caps = { decode = true, encode = true, skinning = true, lods = true, versions = { "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxVertices: number?, -- default 2^24
maxFaces: number?, -- default 2^25
}
export type EncodeOptions = {
version: ("2.00" | "4.00")?, -- default "2.00"
}
-- ------------------------------------------------------------------------------------------------ constants
local readf32, writef32, readu8, writeu8, writeu16 = buffer.readf32, buffer.writef32, buffer.readu8, buffer.writeu8, buffer.writeu16
local accessor = Types.Scene.accessor
-- ------------------------------------------------------------------------------------------------ sniff
function RobloxMesh.sniff(r: Bytes.Reader): number
return if string.match(r:peek(13), "^version [1-7]%.%d%d[\r\n]") then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- a bone's world matrix (column major) from its CFrame (r00 .. r22, x, y, z)
local function boneMatrix(cf: { number }): { number }
return { cf[1], cf[4], cf[7], 0, cf[2], cf[5], cf[8], 0, cf[3], cf[6], cf[9], 0, cf[10], cf[11], cf[12], 1 }
end
local function indices(r: Parse.Record, from: number, to: number): Types.Accessor
local n = math.max(0, to - from)
local d = buffer.create(n * 12)
buffer.copy(d, 0, r.faces, from * 12, n * 12)
return accessor(d, "u32", 1, n * 3)
end
function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local lim = { maxVertices = opts and opts.maxVertices or 2 ^ 24, maxFaces = opts and opts.maxFaces or 2 ^ 25 }
local r, msg = Parse.parse(rd.buf, rd.base, rd.limit, lim)
if not r then
return nil, Err.from(msg, rd.base)
end
local nv, nf = r.numVerts, r.numFaces
local attrs: { [string]: Types.Accessor } = {
POSITION = accessor(r.pos, "f32", 3, nv),
NORMAL = accessor(r.nrm, "f32", 3, nv),
TEXCOORD_0 = accessor(r.uv, "f32", 2, nv),
}
local tan = r.tan
if tan then
local t = buffer.create(nv * 16)
for i = 0, nv - 1 do
local x, y, z, w = Parse.tangent(tan, i)
writef32(t, i * 16, x)
writef32(t, i * 16 + 4, y)
writef32(t, i * 16 + 8, z)
writef32(t, i * 16 + 12, w)
end
attrs.TANGENT = accessor(t, "f32", 4, nv)
end
if r.col then
attrs.COLOR_0 = accessor(r.col, "unorm8", 4, nv)
end
-- LOD ranges (offsets clamped to the faces)
local offs = {}
for _, o in r.lods do
table.insert(offs, math.clamp(o, 0, nf))
end
if #offs < 2 then
offs = { 0, nf }
end
local scene = Types.Scene.new()
local prim: Types.Primitive = { attributes = attrs, indices = indices(r, offs[1], offs[2]), mode = "triangles" }
local lods = {}
for k = 2, #offs - 1 do
table.insert(lods, { attributes = attrs, indices = indices(r, offs[k], offs[k + 1]), mode = "triangles" })
end
local mesh: Types.Mesh = { name = "Mesh", primitives = { prim } }
if #lods > 0 then
mesh.extras = { lods = lods }
end
scene.meshes[1] = mesh
scene.nodes[1] = { name = "Mesh", children = {}, mesh = 1 }
scene.roots[1] = 1
-- bones and skinning
local nb = #r.bones
if nb > 0 then
local world: { { number } } = table.create(nb) :: any
for i, bone in r.bones do
world[i] = boneMatrix(bone.cf)
end
local joints = table.create(nb, 0)
local ibm = buffer.create(nb * 64)
for i, bone in r.bones do
local parent = if bone.parent and bone.parent < nb and bone.parent ~= i - 1 then bone.parent + 1 else nil
local m = world[i]
if parent then
local inv = Mat4.inverse(world[parent])
if inv then
m = Mat4.mul(inv, m)
end
end
local node: Types.Node = { name = bone.name, children = {}, matrix = m, extras = { culling = bone.culling, lodParent = bone.lodParent } }
table.insert(scene.nodes, node)
joints[i] = #scene.nodes
local inv = Mat4.inverse(world[i]) or Mat4.identity()
for k = 1, 16 do
writef32(ibm, (i - 1) * 64 + (k - 1) * 4, inv[k])
end
end
for i, bone in r.bones do
local parent = if bone.parent and bone.parent < nb and bone.parent ~= i - 1 then bone.parent + 1 else nil
if parent then
table.insert(scene.nodes[joints[parent]].children, joints[i])
else
table.insert(scene.roots, joints[i])
end
end
scene.skins[1] = { joints = joints, inverseBindMatrices = accessor(ibm, "f32", 16, nb) }
scene.nodes[1].skin = 1
local env = r.env
if env then
local jb, wb = buffer.create(nv * 8), buffer.create(nv * 4)
for i = 0, nv - 1 do
for k = 0, 3 do
writeu8(wb, i * 4 + k, readu8(env, i * 8 + 4 + k))
end
end
for _, s in r.subsets do
local last = math.min(s.vertsBegin + s.vertsLength, nv) - 1
for v = s.vertsBegin, last do
for k = 0, 3 do
local li = readu8(env, v * 8 + k)
local g = s.bones[li + 1]
writeu16(jb, v * 8 + k * 2, if g and g < nb and readu8(wb, v * 4 + k) > 0 then g else 0)
end
end
end
attrs.JOINTS_0 = accessor(jb, "u16", 4, nv)
attrs.WEIGHTS_0 = accessor(wb, "unorm8", 4, nv)
end
end
local subsets = {}
for _, s in r.subsets do
table.insert(subsets, { facesBegin = s.facesBegin, facesLength = s.facesLength, vertsBegin = s.vertsBegin, vertsLength = s.vertsLength, bones = s.bones })
end
scene.meta.up = "y"
scene.meta.source = {
format = "robloxmesh",
version = r.version,
lodType = r.lodType,
highQualityLods = r.highQualityLods,
lodOffsets = r.lods,
subsets = subsets,
facsFormat = r.facsFormat,
facs = r.facs,
chunks = r.chunks,
}
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function num(attr: any, i: number, c: number, default: number): number
if not attr or c >= attr.components then
return default
end
return attr.values[i * attr.components + c + 1]
end
-- area-weighted vertex normals
local function normals(pos: buffer, nv: number, corners: { number }): buffer
local acc = table.create(nv * 3, 0)
for f = 0, #corners // 3 - 1 do
local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3]
local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8)
local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az
local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
for _, v in { a, b, c } do
acc[v * 3 + 1] += nx
acc[v * 3 + 2] += ny
acc[v * 3 + 3] += nz
end
end
local out = buffer.create(nv * 12)
for v = 0, nv - 1 do
local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3]
local l = math.sqrt(x * x + y * y + z * z)
if l > 0 then
writef32(out, v * 12, x / l)
writef32(out, v * 12 + 4, y / l)
writef32(out, v * 12 + 8, z / l)
else
writef32(out, v * 12 + 4, 1)
end
end
return out
end
-- world matrices of every node (parents through children lists)
local function worlds(scene: any): { [number]: { number } }
local out: { [number]: { number } } = {}
local parent: { [number]: number } = {}
for i, n in scene.nodes do
for _, c in n.children or {} do
parent[c] = i
end
end
local function world(i: number, depth: number): { number }
if out[i] then
return out[i]
end
local m = Types.Scene.nodeMatrix(scene.nodes[i])
local p = parent[i]
if p and depth < 256 then
m = Mat4.mul(world(p, depth + 1), m)
end
out[i] = m
return m
end
for i in scene.nodes do
world(i, 0)
end
return out
end
-- the bones of a skin: Parse.Bone list, or nil, message
local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?)
local joints = skin.joints
if type(joints) ~= "table" or #joints == 0 then
return nil, "a skin without joints"
end
if #joints > 65534 then
return nil, "too many joints"
end
local w = worlds(scene)
local index: { [number]: number } = {}
for i, j in joints do
index[j] = i - 1
end
local parentOf: { [number]: number } = {}
for i, n in scene.nodes do
for _, c in n.children or {} do
parentOf[c] = i
end
end
local ibm = skin.inverseBindMatrices and Flatten.numbers(skin.inverseBindMatrices)
local out = {}
for i, j in joints do
local node = scene.nodes[j]
if not node then
return nil, "a joint names a missing node"
end
local m = w[j]
if ibm and #ibm >= i * 16 then
local inv = Mat4.inverse(table.move(ibm, (i - 1) * 16 + 1, i * 16, 1, table.create(16, 0)))
if inv then
m = inv
end
end
local ex = if type(node.extras) == "table" then node.extras else {}
local p = parentOf[j]
out[i] = {
name = if type(node.name) == "string" then node.name else "Bone" .. i,
parent = if p then index[p] else nil,
lodParent = if type(ex.lodParent) == "number" then ex.lodParent else 0xFFFF,
culling = if type(ex.culling) == "number" then ex.culling else 0,
cf = { m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11], m[13], m[14], m[15] },
}
end
return out, nil
end
-- the vertex arrays of the record from merged attributes, for the vertices `order` (new index -> merged index)
local function fill(r: Parse.Record, m: any, order: { number }, nrm: buffer?)
local nv = #order
local pos, nb, uv, tan = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4)
local P, N, U, T, C = m.attrs.POSITION, m.attrs.NORMAL, m.attrs.TEXCOORD_0, m.attrs.TANGENT, m.attrs.COLOR_0
local col = nil
if C then
local scale = if C.raw then 1 else 255
local white = true
col = buffer.create(nv * 4)
for i, src in order do
for k = 0, 3 do
local v = math.clamp(math.floor(num(C, src, k, if C.raw then 255 else 1) * scale + 0.5), 0, 255)
writeu8(col, (i - 1) * 4 + k, v)
if v ~= 255 then
white = false
end
end
end
if white then
col = nil
end
end
for i, src in order do
local o = i - 1
for k = 0, 2 do
writef32(pos, o * 12 + k * 4, num(P, src, k, 0))
end
if N then
for k = 0, 2 do
writef32(nb, o * 12 + k * 4, num(N, src, k, 0))
end
elseif nrm then
buffer.copy(nb, o * 12, nrm, src * 12, 12)
end
writef32(uv, o * 8, num(U, src, 0, 0))
writef32(uv, o * 8 + 4, num(U, src, 1, 0))
if T then
for k = 0, 3 do
local v = math.clamp(math.floor(num(T, src, k, if k == 3 then 1 else 0) * 127 + 0.5), -127, 127)
writeu8(tan, o * 4 + k, v % 256)
end
else
buffer.writeu32(tan, o * 4, 0x7F810000)
end
end
r.pos, r.nrm, r.uv, r.tan, r.col, r.numVerts = pos, nb, uv, tan, col, nv
end
function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
local version = opts and opts.version or "2.00"
if version ~= "2.00" and version ~= "4.00" then
return nil, Err.new(Err.ARG, "version must be \"2.00\" or \"4.00\"")
end
if type(scene) ~= "table" or type(scene.meshes) ~= "table" then
return nil, Err.new(Err.ARG, "expected a Scene")
end
local keep = { NORMAL = true, TEXCOORD_0 = true, TANGENT = true, COLOR_0 = true, JOINTS_0 = true, WEIGHTS_0 = true }
local m, merr = Flatten.merge(scene, function(name: string): boolean
return keep[name] == true
end, { triangulate = true })
if not m then
return nil, Err.new(Err.ARG, tostring(merr))
end
local corners = m.corners
if not m.sizes or #corners == 0 then
return nil, Err.new(Err.ARG, "no triangles to write")
end
local nv0 = m.count
if nv0 > 2 ^ 32 - 1 then
return nil, Err.new(Err.LIMIT, "too many vertices")
end
local r: Parse.Record = {
version = version,
numVerts = 0,
numFaces = #corners // 3,
pos = buffer.create(0),
nrm = buffer.create(0),
uv = buffer.create(0),
faces = buffer.create(0),
lods = {},
lodType = 0,
highQualityLods = 0,
bones = {},
subsets = {},
facsFormat = 0,
chunks = {},
}
local src = if type(scene.meta) == "table" and type(scene.meta.source) == "table" and scene.meta.source.format == "robloxmesh" then scene.meta.source else nil
if src and type(src.lodType) == "number" then
r.lodType, r.highQualityLods = src.lodType, if type(src.highQualityLods) == "number" then src.highQualityLods else 0
end
-- normals when the scene has none
local nrm: buffer? = nil
if not m.attrs.NORMAL then
local pb = buffer.create(nv0 * 12)
for i = 0, nv0 - 1 do
for k = 0, 2 do
writef32(pb, i * 12 + k * 4, num(m.attrs.POSITION, i, k, 0))
end
end
nrm = normals(pb, nv0, corners)
end
-- the skin (4.00): the first node with a mesh and a skin
local skin = nil
if version == "4.00" and m.attrs.JOINTS_0 and m.attrs.WEIGHTS_0 then
for _, n in scene.nodes or {} do
if n.mesh and n.skin and scene.skins and scene.skins[n.skin] then
skin = scene.skins[n.skin]
break
end
end
end
local nf = #corners // 3
if skin then
local bones, berr = skinBones(scene, skin)
if not bones then
return nil, Err.new(Err.ARG, berr or "bad skin")
end
r.bones = bones
local J, W = m.attrs.JOINTS_0, m.attrs.WEIGHTS_0
local wscale = if W.raw then 1 / 255 else 1
local nb = #bones
-- per vertex: up to 4 (joint, weight) pairs with weight > 0
local influences: { { { number } } } = table.create(nv0) :: any
for v = 0, nv0 - 1 do
local list = {}
for k = 0, 3 do
local wt = num(W, v, k, 0) * wscale
local j = num(J, v, k, 0)
if wt > 0 and j >= 0 and j < nb then
table.insert(list, { j, wt })
end
end
influences[v + 1] = list
end
-- subsets: faces in order, a new subset when a face's joints do not fit in 26
local faceIdx = buffer.create(nf * 12)
local order: { number } = {}
local s: any = nil
local function close()
if s then
table.insert(r.subsets, { facesBegin = s.facesBegin, facesLength = s.faceCount, vertsBegin = s.vertsBegin, vertsLength = #order - s.vertsBegin, bones = s.bones })
end
end
local function open(f: number)
s = { facesBegin = f, faceCount = 0, vertsBegin = #order, bones = {}, local_ = {}, remap = {} }
end
open(0)
for f = 0, nf - 1 do
local need = {}
local extra = 0
for c = 1, 3 do
for _, inf in influences[corners[f * 3 + c] + 1] do
if s.local_[inf[1]] == nil and not need[inf[1]] then
need[inf[1]] = true
extra += 1
end
end
end
if #s.bones + extra > 26 then
close()
open(f)
for c = 1, 3 do
for _, inf in influences[corners[f * 3 + c] + 1] do
need[inf[1]] = true
end
end
end
for j in need do
if s.local_[j] == nil then
table.insert(s.bones, j)
s.local_[j] = #s.bones - 1
end
end
for c = 1, 3 do
local v = corners[f * 3 + c]
local nvx = s.remap[v]
if not nvx then
table.insert(order, v)
nvx = #order - 1
s.remap[v] = nvx
end
buffer.writeu32(faceIdx, f * 12 + (c - 1) * 4, nvx)
end
s.faceCount += 1
end
close()
r.faces = faceIdx
fill(r, m, order, nrm)
-- envelopes: subset-local bone indices, weights summing to 255
local env = buffer.create(#order * 8)
for _, sub in r.subsets do
local loc: { [number]: number } = {}
for i, j in sub.bones do
loc[j] = i - 1
end
for o = sub.vertsBegin, sub.vertsBegin + sub.vertsLength - 1 do
local list = influences[order[o + 1] + 1]
local total = 0
for _, inf in list do
total += inf[2]
end
local bytes, sum, best = {}, 0, 1
for k, inf in list do
local b = if total > 0 then math.floor(inf[2] / total * 255 + 0.5) else 0
bytes[k] = b
sum += b
if inf[2] > list[best][2] then
best = k
end
end
if #list > 0 then
bytes[best] += 255 - sum
end
for k = 0, 3 do
local inf = list[k + 1]
writeu8(env, o * 8 + k, if inf then loc[inf[1]] or 0 else 0)
writeu8(env, o * 8 + 4 + k, if inf then math.clamp(bytes[k + 1], 0, 255) else 0)
end
end
end
r.env = env
r.lods = { 0, nf }
else
local order = table.create(nv0, 0)
for i = 1, nv0 do
order[i] = i - 1
end
fill(r, m, order, nrm)
local faces = buffer.create(nf * 12)
for i, c in corners do
buffer.writeu32(faces, (i - 1) * 4, c)
end
r.faces = faces
r.lods = { 0, nf }
-- extra LODs of a single untransformed primitive
local part = m.parts[1]
local mesh = part and part.mesh
local lods = if #m.parts == 1 and part.identity and mesh and type(mesh.extras) == "table" then mesh.extras.lods else nil
if version == "4.00" and type(lods) == "table" and #lods > 0 then
local list = {}
for _, lp in lods do
local idx = if type(lp) == "table" and lp.indices then Flatten.numbers(lp.indices) else nil
if idx and #idx % 3 == 0 then
table.insert(list, idx)
end
end
local total = nf
for _, idx in list do
total += #idx // 3
end
local all = buffer.create(total * 12)
buffer.copy(all, 0, faces, 0, nf * 12)
local at = nf
for _, idx in list do
for i, c in idx do
if c >= nv0 then
return nil, Err.new(Err.ARG, "a LOD index is out of range")
end
buffer.writeu32(all, at * 12 + (i - 1) * 4, c)
end
at += #idx // 3
table.insert(r.lods, at)
end
r.faces, r.numFaces = all, total
end
end
return Write.write(r, version), nil
end
return RobloxMesh