Groups, materials (texture uri), joints -> nodes + skin + one animation, version 4 sub-versioned blocks (comments, vertex extras with up to four bones, joint colours, model extras). Writer: groups per placed primitive, the first skin plus animated nodes as joints (rigid meshes bound to them), weights in percent. Tested against assimp and through glTF skin models.
487 lines
17 KiB
Luau
487 lines
17 KiB
Luau
--!strict
|
|
-- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped,
|
|
-- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first
|
|
-- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2);
|
|
-- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each
|
|
-- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's
|
|
-- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials:
|
|
-- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and
|
|
-- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment),
|
|
-- joint colours and model extras are written in their sub-versioned blocks.
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Types = require("@formats/Types")
|
|
local Mat4 = require("@formats/codecs/model/Mat4")
|
|
local Flatten = require("@formats/codecs/model/MeshFlatten")
|
|
|
|
local Write = {}
|
|
|
|
local S = Types.Scene
|
|
local sqrt = math.sqrt
|
|
|
|
export type Options = { fps: number?, name: string?, files: { [string]: any }? }
|
|
|
|
local function fixedString(w: Bytes.Writer, s: string, n: number)
|
|
local v = string.sub(string.gsub(s, "%z", ""), 1, n - 1)
|
|
w:string(v)
|
|
for _ = #v + 1, n do
|
|
w:u8(0)
|
|
end
|
|
end
|
|
|
|
local function msg(s: any): string
|
|
return if type(s) == "string" then s else ""
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ tree
|
|
type Tree = { world: { [number]: { number } }, parent: { [number]: number }, order: { number } }
|
|
local function tree(scene: Types.Scene): Tree
|
|
local t: Tree = { world = {}, parent = {}, order = {} }
|
|
local function visit(i: number, p: number, pm: { number }, depth: number)
|
|
local n = scene.nodes[i]
|
|
if type(n) ~= "table" or t.world[i] or depth > 256 then
|
|
return
|
|
end
|
|
t.world[i] = S.mul(pm, S.nodeMatrix(n))
|
|
t.parent[i] = p
|
|
table.insert(t.order, i)
|
|
for _, c in n.children or {} do
|
|
visit(c, i, t.world[i], depth + 1)
|
|
end
|
|
end
|
|
for _, r in scene.roots do
|
|
visit(r, 0, S.IDENTITY, 0)
|
|
end
|
|
return t
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ joints
|
|
type Joint = { node: number, name: string, parent: string, pos: { number }, rot: { number }, quat: { number }, rotKeys: { { number } }, posKeys: { { number } } }
|
|
|
|
-- the rigid part (rotation and translation) of a matrix
|
|
local function rigid(m: { number }): { number }
|
|
local t, r = Mat4.decompose(m)
|
|
return Mat4.compose(t, r, nil)
|
|
end
|
|
|
|
-- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order;
|
|
-- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices
|
|
local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: number }, { [number]: number }, { number })
|
|
local skin = scene.skins[1]
|
|
local anim = scene.animations[1]
|
|
local out: { Joint } = {}
|
|
local bySkin: { [number]: number } = {}
|
|
local byNode: { [number]: number } = {}
|
|
local skinIndex: { [number]: number } = {}
|
|
local isJoint: { [number]: boolean } = {}
|
|
for k, ni in (if skin then skin.joints else {}) :: { number } do
|
|
skinIndex[ni] = k - 1
|
|
isJoint[ni] = true
|
|
end
|
|
local chans: { [number]: { Types.Channel } } = {}
|
|
for _, ch in (if anim then anim.channels else {}) :: { Types.Channel } do
|
|
if (ch.path == "rotation" or ch.path == "translation") and tr.world[ch.node] then
|
|
isJoint[ch.node] = true
|
|
chans[ch.node] = chans[ch.node] or {}
|
|
table.insert(chans[ch.node], ch)
|
|
end
|
|
end
|
|
-- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix
|
|
local B = S.IDENTITY
|
|
local IBM: any = if skin and skin.inverseBindMatrices then S.reader(skin.inverseBindMatrices) else nil
|
|
if skin and IBM and tr.world[skin.joints[1]] then
|
|
local m = table.create(16, 0)
|
|
for c = 1, 16 do
|
|
m[c] = (IBM :: any)(0, c - 1)
|
|
end
|
|
B = S.mul(tr.world[skin.joints[1]], m)
|
|
end
|
|
local names: { [string]: boolean } = {}
|
|
for _, ni in tr.order do
|
|
if not isJoint[ni] or #out >= 127 then
|
|
continue
|
|
end
|
|
local p = tr.parent[ni]
|
|
while p ~= 0 and byNode[p] == nil do
|
|
p = tr.parent[p]
|
|
end
|
|
-- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the
|
|
-- joint and its joint parent (C) carry over to the keys
|
|
local invP = if p ~= 0 then Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() else Mat4.identity()
|
|
local gp = tr.parent[ni]
|
|
local C = S.mul(invP, if gp ~= 0 then tr.world[gp] else S.IDENTITY)
|
|
local t, r = Mat4.decompose(S.mul(invP, rigid(tr.world[ni])))
|
|
local e = Mat4.eulerXYZ(r)
|
|
local base = string.sub(msg(scene.nodes[ni].name), 1, 27)
|
|
local name = if base ~= "" then base else "joint" .. #out
|
|
local n = 1
|
|
while names[name] do
|
|
n += 1
|
|
name = base .. "_" .. n
|
|
end
|
|
names[name] = true
|
|
local j: Joint = {
|
|
node = ni, name = name, parent = if p ~= 0 then out[byNode[p] + 1].name else "", pos = t,
|
|
rot = { math.rad(e[1]), math.rad(e[2]), math.rad(e[3]) }, quat = r, rotKeys = {}, posKeys = {},
|
|
}
|
|
table.insert(out, j)
|
|
byNode[ni] = #out - 1
|
|
if skinIndex[ni] then
|
|
bySkin[skinIndex[ni]] = #out - 1
|
|
end
|
|
-- keys relative to the rest pose: rotation rest^-1 * C * R(t), position C * T(t) - rest
|
|
local _, rc = Mat4.decompose(C)
|
|
local inv = Mat4.transpose3(Mat4.fromQuat(r))
|
|
for _, ch in chans[ni] or {} do
|
|
local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any
|
|
local cubic = ch.interpolation == "CUBICSPLINE"
|
|
for k = 0, ch.input.count - 1 do
|
|
local v = if cubic then k * 3 + 1 else k
|
|
local time = IN(k, 0)
|
|
if ch.path == "rotation" then
|
|
local q = { OUT(v, 0), OUT(v, 1), OUT(v, 2), OUT(v, 3) }
|
|
local l = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4])
|
|
q = if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else { 0, 0, 0, 1 }
|
|
local d = Mat4.eulerXYZ(Mat4.quat(S.mul(inv, S.mul(Mat4.fromQuat(rc), Mat4.fromQuat(q)))))
|
|
table.insert(j.rotKeys, { time, math.rad(d[1]), math.rad(d[2]), math.rad(d[3]) })
|
|
else
|
|
local x, y, z = Mat4.point(C, OUT(v, 0), OUT(v, 1), OUT(v, 2))
|
|
table.insert(j.posKeys, { time, x - t[1], y - t[2], z - t[3] })
|
|
end
|
|
end
|
|
end
|
|
end
|
|
return out, bySkin, byNode, B
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ geometry
|
|
type Vertex = { x: number, y: number, z: number, bones: { number }, weights: { number } }
|
|
type Tri = { v: { number }, n: { number }, uv: { number }, sg: number, group: number }
|
|
type Group = { name: string, tris: { number }, material: number, flags: number, comment: string? }
|
|
|
|
-- every placed primitive as a group: vertices, triangles; or nil, message
|
|
local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number }, byNode: { [number]: number }, B: { number }): ({ Vertex }, { Tri }, { Group }, string?)
|
|
local verts: { Vertex }, tris: { Tri }, groups: { Group } = {}, {}, {}
|
|
for _, pl in S.flatten(scene) do
|
|
local prim: any = pl.primitive
|
|
local node = scene.nodes[pl.node]
|
|
local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } }, function(): boolean
|
|
return false
|
|
end, { triangulate = true })
|
|
if not merged then
|
|
return verts, tris, groups, err
|
|
end
|
|
local corners = merged.corners
|
|
if #corners == 0 then
|
|
continue
|
|
end
|
|
local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil
|
|
-- a rigid mesh follows its nearest joint
|
|
local rigid = -1
|
|
if not skinned then
|
|
local p = pl.node
|
|
while p and p ~= 0 do
|
|
if byNode[p] then
|
|
rigid = byNode[p]
|
|
break
|
|
end
|
|
p = tr.parent[p]
|
|
end
|
|
end
|
|
local M = if skinned then B else pl.matrix
|
|
local NM = Mat4.normalMatrix(M)
|
|
local mirror = M[1] * (M[6] * M[11] - M[7] * M[10]) - M[5] * (M[2] * M[11] - M[3] * M[10]) + M[9] * (M[2] * M[7] - M[3] * M[6]) < 0
|
|
local A = prim.attributes
|
|
local POS = S.reader(A.POSITION) :: any
|
|
local zero = function(_: number, _: number): number
|
|
return 0
|
|
end
|
|
type Get = (number, number) -> number
|
|
local hasN, hasUV = A.NORMAL ~= nil, A.TEXCOORD_0 ~= nil
|
|
local NOR: Get = (if hasN then S.reader(A.NORMAL) else nil) or zero
|
|
local UV: Get = (if hasUV then S.reader(A.TEXCOORD_0) else nil) or zero
|
|
local JO: Get = (if skinned then S.reader(A.JOINTS_0) else nil) or zero
|
|
local WE: Get = (if skinned then S.reader(A.WEIGHTS_0) else nil) or zero
|
|
local base = #verts
|
|
local nv = A.POSITION.count
|
|
if base + nv > 65535 then
|
|
return verts, tris, groups, "more than 65535 vertices"
|
|
end
|
|
for v = 0, nv - 1 do
|
|
local x, y, z = Mat4.point(M, POS(v, 0), POS(v, 1), POS(v, 2))
|
|
local bones, weights = { rigid, -1, -1, -1 }, { 1, 0, 0, 0 }
|
|
if skinned then
|
|
local inf = {}
|
|
for c = 0, 3 do
|
|
local w = WE(v, c)
|
|
local j = bySkin[JO(v, c)]
|
|
if w > 0 and j then
|
|
table.insert(inf, { j, w })
|
|
end
|
|
end
|
|
table.sort(inf, function(a: { number }, b: { number }): boolean
|
|
return a[2] > b[2]
|
|
end)
|
|
local sum = 0
|
|
for _, e in inf do
|
|
sum += e[2]
|
|
end
|
|
for c = 1, 4 do
|
|
local e = inf[c]
|
|
bones[c] = if e then e[1] else -1
|
|
weights[c] = if e and sum > 0 then e[2] / sum else 0
|
|
end
|
|
end
|
|
table.insert(verts, { x = x, y = y, z = z, bones = bones, weights = weights })
|
|
end
|
|
local gi = #groups
|
|
if gi >= 255 then
|
|
return verts, tris, groups, "more than 255 groups"
|
|
end
|
|
local name = msg(node.name)
|
|
if name == "" then
|
|
name = msg(scene.meshes[pl.mesh] and scene.meshes[pl.mesh].name)
|
|
end
|
|
local x = node.extras and node.extras.ms3d
|
|
local g: Group = {
|
|
name = if name ~= "" then name else "group" .. gi, tris = {}, flags = if x and type(x.flags) == "number" then x.flags else 0,
|
|
material = if type(prim.material) == "number" and prim.material <= 127 then prim.material - 1 else -1,
|
|
comment = x and x.comment,
|
|
}
|
|
local saved = prim.extras and prim.extras.ms3d and prim.extras.ms3d.smoothing
|
|
if type(saved) ~= "table" or #saved ~= #corners // 3 then
|
|
saved = nil
|
|
end
|
|
for f = 0, #corners // 3 - 1 do
|
|
local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3]
|
|
if mirror then
|
|
b, c = c, b
|
|
end
|
|
local t: Tri = { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = if saved then saved[f + 1] else 1, group = gi }
|
|
-- the face normal for primitives without normals
|
|
local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1]
|
|
local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z
|
|
local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z
|
|
local fx, fy, fz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x
|
|
for _, v in { a, b, c } do
|
|
local nx, ny, nz = fx, fy, fz
|
|
if hasN then
|
|
local ox, oy, oz = NOR(v, 0), NOR(v, 1), NOR(v, 2)
|
|
nx = NM[1] * ox + NM[5] * oy + NM[9] * oz
|
|
ny = NM[2] * ox + NM[6] * oy + NM[10] * oz
|
|
nz = NM[3] * ox + NM[7] * oy + NM[11] * oz
|
|
end
|
|
local l = sqrt(nx * nx + ny * ny + nz * nz)
|
|
if l > 0 then
|
|
nx, ny, nz = nx / l, ny / l, nz / l
|
|
end
|
|
table.move({ nx, ny, nz }, 1, 3, #t.n + 1, t.n)
|
|
table.insert(t.uv, UV(v, 0))
|
|
table.insert(t.uv, UV(v, 1))
|
|
end
|
|
table.insert(tris, t)
|
|
table.insert(g.tris, #tris - 1)
|
|
end
|
|
if #tris > 65535 then
|
|
return verts, tris, groups, "more than 65535 triangles"
|
|
end
|
|
table.insert(groups, g)
|
|
end
|
|
return verts, tris, groups, nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ encode
|
|
function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
|
|
local o: Options = opts or {}
|
|
local tr = tree(scene)
|
|
local js, bySkin, byNode, B = joints(scene, tr)
|
|
local verts, tris, groups, gerr = geometry(scene, tr, bySkin, byNode, B)
|
|
if gerr then
|
|
return nil, gerr
|
|
end
|
|
if #scene.materials > 127 then
|
|
return nil, "more than 127 materials"
|
|
end
|
|
local src: any = scene.meta.source
|
|
local fromMs3d = src ~= nil and src.format == "ms3d"
|
|
local w = Bytes.writer(65536)
|
|
w:string("MS3D000000")
|
|
w:u32le(4)
|
|
w:u16le(#verts)
|
|
for _, v in verts do
|
|
w:u8(0)
|
|
w:f32le(v.x)
|
|
w:f32le(v.y)
|
|
w:f32le(v.z)
|
|
w:i8(v.bones[1] % 256)
|
|
w:u8(1)
|
|
end
|
|
w:u16le(#tris)
|
|
for _, t in tris do
|
|
w:u16le(0)
|
|
for k = 1, 3 do
|
|
w:u16le(t.v[k])
|
|
end
|
|
for k = 1, 9 do
|
|
w:f32le(t.n[k])
|
|
end
|
|
for k = 1, 3 do
|
|
w:f32le(t.uv[k * 2 - 1])
|
|
end
|
|
for k = 1, 3 do
|
|
w:f32le(t.uv[k * 2])
|
|
end
|
|
w:u8(math.clamp(t.sg, 0, 255))
|
|
w:u8(t.group)
|
|
end
|
|
w:u16le(#groups)
|
|
for _, g in groups do
|
|
w:u8(g.flags % 256)
|
|
fixedString(w, g.name, 32)
|
|
w:u16le(#g.tris)
|
|
for _, ti in g.tris do
|
|
w:u16le(ti)
|
|
end
|
|
w:i8(g.material % 256)
|
|
end
|
|
-- materials
|
|
w:u16le(#scene.materials)
|
|
local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture"
|
|
for i, m in scene.materials do
|
|
local x = (m.extras and m.extras.ms3d or {}) :: { [string]: any }
|
|
local bc = m.baseColor or { 1, 1, 1, 1 }
|
|
fixedString(w, msg(m.name) ~= "" and msg(m.name) or ("material" .. i), 32)
|
|
local e = m.emissive or { 0, 0, 0 }
|
|
for _, c in { x.ambient or { 0.2, 0.2, 0.2, 1 }, { bc[1], bc[2], bc[3], bc[4] or 1 }, x.specular or { 0, 0, 0, 1 }, { e[1], e[2], e[3], 1 } } do
|
|
for k = 1, 4 do
|
|
w:f32le(c[k] or 1)
|
|
end
|
|
end
|
|
local r = math.max(m.roughness or 1, 0.1)
|
|
w:f32le(x.shininess or math.clamp(2 / (r * r) - 2, 0, 128))
|
|
w:f32le(bc[4] or 1)
|
|
w:i8((tonumber(x.mode) or 0) % 256)
|
|
local file = ""
|
|
local ref: any = m.baseColorTexture
|
|
local tex: any = ref and scene.textures[ref.texture]
|
|
if tex then
|
|
file = tex.uri or ""
|
|
if file == "" or string.sub(file, 1, 5) == "data:" then
|
|
file = base .. "_" .. ref.texture .. ".png"
|
|
if o.files and tex.data then
|
|
o.files[file] = tex.data
|
|
end
|
|
end
|
|
end
|
|
fixedString(w, file, 128)
|
|
fixedString(w, msg(x.alphamap), 128)
|
|
end
|
|
-- the animation header and joints
|
|
local fps = o.fps or (if fromMs3d and type(src.fps) == "number" and src.fps > 0 then src.fps else 24)
|
|
local last = 0
|
|
for _, j in js do
|
|
for _, k in j.rotKeys do
|
|
last = math.max(last, k[1])
|
|
end
|
|
for _, k in j.posKeys do
|
|
last = math.max(last, k[1])
|
|
end
|
|
end
|
|
w:f32le(fps)
|
|
w:f32le(0)
|
|
w:u32le(math.max(1, math.ceil(last * fps)))
|
|
w:u16le(#js)
|
|
for _, j in js do
|
|
local x = scene.nodes[j.node].extras
|
|
local jx = x and x.ms3d
|
|
w:u8(if jx and type(jx.flags) == "number" then jx.flags % 256 else 0)
|
|
fixedString(w, j.name, 32)
|
|
fixedString(w, j.parent, 32)
|
|
for k = 1, 3 do
|
|
w:f32le(j.rot[k])
|
|
end
|
|
for k = 1, 3 do
|
|
w:f32le(j.pos[k])
|
|
end
|
|
w:u16le(#j.rotKeys)
|
|
w:u16le(#j.posKeys)
|
|
for _, list in { j.rotKeys, j.posKeys } do
|
|
for _, k in list do
|
|
for c = 1, 4 do
|
|
w:f32le(k[c])
|
|
end
|
|
end
|
|
end
|
|
end
|
|
-- comments
|
|
w:u32le(1)
|
|
local function comments(list: { any }, get: (any) -> string?)
|
|
local found = {}
|
|
for i, item in list do
|
|
local c = get(item)
|
|
if type(c) == "string" and c ~= "" then
|
|
table.insert(found, { i - 1, c })
|
|
end
|
|
end
|
|
w:u32le(#found)
|
|
for _, f in found do
|
|
w:u32le(f[1])
|
|
w:u32le(#f[2])
|
|
w:string(f[2])
|
|
end
|
|
end
|
|
comments(groups, function(g: any): string?
|
|
return g.comment
|
|
end)
|
|
comments(scene.materials, function(m: any): string?
|
|
return m.extras and m.extras.ms3d and m.extras.ms3d.comment
|
|
end)
|
|
comments(js, function(j: any): string?
|
|
local x: any = scene.nodes[j.node].extras
|
|
return x and x.ms3d and x.ms3d.comment
|
|
end)
|
|
local mc = if fromMs3d then msg(src.comment) else ""
|
|
w:u32le(if mc ~= "" then 1 else 0)
|
|
if mc ~= "" then
|
|
w:u32le(#mc)
|
|
w:string(mc)
|
|
end
|
|
-- vertex extras: three more bones, the weights in percent (the last one implied), an extra u32
|
|
w:u32le(2)
|
|
for _, v in verts do
|
|
local p = table.create(3, 0)
|
|
local left = 100
|
|
for c = 1, 3 do
|
|
p[c] = math.clamp(math.floor(v.weights[c] * 100 + 0.5), 0, left)
|
|
left -= p[c]
|
|
end
|
|
if v.bones[2] < 0 and v.bones[1] >= 0 then
|
|
p = { 100, 0, 0 }
|
|
end
|
|
for c = 2, 4 do
|
|
w:i8(v.bones[c] % 256)
|
|
end
|
|
for c = 1, 3 do
|
|
w:u8(p[c])
|
|
end
|
|
w:u32le(0)
|
|
end
|
|
-- joint colours, model extras
|
|
w:u32le(1)
|
|
for _, j in js do
|
|
local x: any = scene.nodes[j.node].extras
|
|
local c = x and x.ms3d and x.ms3d.color or { 1, 1, 1 }
|
|
for k = 1, 3 do
|
|
w:f32le(c[k] or 1)
|
|
end
|
|
end
|
|
w:u32le(1)
|
|
w:f32le(if fromMs3d and type(src.jointSize) == "number" then src.jointSize else 1)
|
|
w:u32le(if fromMs3d and type(src.transparencyMode) == "number" then src.transparencyMode else 0)
|
|
w:f32le(if fromMs3d and type(src.alphaRef) == "number" then src.alphaRef else 0.5)
|
|
local out = buffer.create(w.pos)
|
|
buffer.copy(out, 0, w.buf, 0, w.pos)
|
|
return out, nil
|
|
end
|
|
|
|
return Write
|