ws-game: model/smd (Valve SMD read + write: skeleton, skin, weights links, frames as animation, animation SMDs); Rig.influences merges a joint listed twice

This commit is contained in:
4DBug committed 2026-10-31 14:47:06 -05:00
1 parent f14d5ac4ef
commit 08045ba813
9 files changed
+938 -2

No files matched your search

+12
View File
@@ -482,6 +482,18 @@ local list: { Entry } = {
return require("@formats/model/ply")
end,
},
{
name = "smd",
category = "model",
path = "model/smd",
extensions = { "smd" },
mime = { "model/x-smd", "text/plain" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" },
caps = { decode = true, encode = true, skins = true, animation = true },
load = function()
return require("@formats/model/smd")
end,
},
{
name = "stl",
category = "model",
+11 -2
View File
@@ -198,15 +198,24 @@ function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "w
end
-- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with
-- 0-based joint indices (into the skin's joints); the four largest weights are kept and normalised to sum 1.
-- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept
-- and normalised to sum 1.
function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor)
local n = #lists
local jb, wb = buffer.create(n * 8), buffer.create(n * 16)
for v, l in lists do
local pairs_: { { number } } = {}
local at: { [number]: { number } } = {}
for k = 1, #l - 1, 2 do
if l[k + 1] > 0 then
table.insert(pairs_, { l[k], l[k + 1] })
local same = at[l[k]]
if same then
same[2] += l[k + 1] -- the same joint twice: one influence
else
local e = { l[k], l[k + 1] }
at[l[k]] = e
table.insert(pairs_, e)
end
end
end
table.sort(pairs_, function(a: { number }, b: { number }): boolean
+275
View File
@@ -0,0 +1,275 @@
--!strict
-- model/smd/Read: Valve SMD text (GoldSrc / Source studiomdl input: version 1) to a Scene. Sections "nodes" (id,
-- "name", parent), "skeleton" ("time n" blocks of "bone px py pz rx ry rz", Euler radians, R = Rz Ry Rx; a bone
-- missing from a later frame keeps its previous pose), "triangles" (a material line, then three vertex lines "bone px
-- py pz nx ny nz u v [links (bone weight)...]": model-space positions, v up), "vertexanimation" (skipped, counted).
-- Bones -> joint nodes and a Skin (bind pose = the first skeleton frame), triangles -> one primitive per material
-- (welded vertices, counter-clockwise as stored, TEXCOORD_0 v flipped to top-left, JOINTS_0 / WEIGHTS_0: the links,
-- the rest of the weight to the parent bone; GoldSrc lines without links: the parent bone), skeleton frames beyond
-- the first -> one animation (opts.fps, default 30). An animation SMD (no triangles) is a skeleton + its animation.
local Types = require("@formats/Types")
local Rig = require("@formats/codecs/model/Rig")
local Read = {}
local Scene = Types.Scene
local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Options = { fps: number?, name: string?, maxVertices: number? }
type Bone = { id: number, name: string, parent: number }
local ZERO: { number } = { 0, 0, 0, 0, 0, 0 }
-- read(text, opts) -> Scene | nil, message
function Read.read(text: string, opts: Options?): (Types.Scene?, string?)
local lines: { string } = {}
for line in string.gmatch(text, "[^\r\n]*") do
table.insert(lines, line)
end
local i = 1
local n = #lines
local function nextLine(): string?
while i <= n do
local l = lines[i]
i += 1
local s = string.match(l, "^%s*(.-)%s*$") :: string
s = string.gsub(s, "%s*//.*$", "") :: string
if s ~= "" then
return s
end
end
return nil
end
local bones: { Bone } = {}
local byId: { [number]: number } = {} -- SMD bone id -> index into bones (1-based)
local frames: { { [number]: { number } } } = {} -- frames[f][bone index] = { px, py, pz, rx, ry, rz }
local times: { number } = {}
type Batch = { name: string, keys: { [string]: number }, verts: { { number } }, indices: { number } }
local batches: { Batch } = {}
local byMat: { [string]: Batch } = {}
local version: number? = nil
local vertexAnimations = 0
local maxV = opts and opts.maxVertices or 2 ^ 24
local total = 0
while true do
local l = nextLine()
if not l then
break
end
local kw = string.lower(string.match(l, "^(%S+)") or "")
if kw == "version" then
version = tonumber(string.match(l, "^%S+%s+(%S+)"))
elseif kw == "nodes" then
while true do
local s = nextLine()
if not s then
return nil, "truncated: nodes without end"
end
if string.lower(s) == "end" then
break
end
local id, name, parent = string.match(s, '^(%-?%d+)%s+"(.-)"%s+(%-?%d+)')
if not id then
id, name, parent = string.match(s, "^(%-?%d+)%s+(%S+)%s+(%-?%d+)")
end
if not id then
return nil, "bad node line: " .. s
end
table.insert(bones, { id = tonumber(id) :: number, name = name :: string, parent = tonumber(parent) :: number })
byId[tonumber(id) :: number] = #bones
end
elseif kw == "skeleton" then
local cur: { [number]: { number } }? = nil
while true do
local s = nextLine()
if not s then
return nil, "truncated: skeleton without end"
end
local low = string.lower(s)
if low == "end" then
break
end
local tm = string.match(low, "^time%s+(%-?[%d%.]+)")
if tm then
local prev = frames[#frames]
local f: { [number]: { number } } = {}
if prev then
for k, v in prev do
f[k] = v
end
end
table.insert(frames, f)
table.insert(times, tonumber(tm) :: number)
cur = f
else
local nums: { number } = {}
for tok in string.gmatch(s, "%S+") do
table.insert(nums, tonumber(tok) or 0 / 0)
end
local bi = byId[nums[1]]
if not cur or #nums < 7 or not bi then
return nil, "bad skeleton line: " .. s
end
cur[bi] = { nums[2], nums[3], nums[4], nums[5], nums[6], nums[7] }
end
end
elseif kw == "triangles" then
while true do
local mat = nextLine()
if not mat then
return nil, "truncated: triangles without end"
end
if string.lower(mat) == "end" then
break
end
local b = byMat[mat]
if not b then
b = { name = mat, keys = {}, verts = {}, indices = {} }
byMat[mat] = b
table.insert(batches, b)
end
for _ = 1, 3 do
local s = nextLine()
if not s then
return nil, "truncated triangle"
end
local nums: { number } = {}
for tok in string.gmatch(s, "%S+") do
local v = tonumber(tok)
if not v then
return nil, "bad vertex line: " .. s
end
table.insert(nums, v)
end
if #nums < 9 then
return nil, "short vertex line: " .. s
end
local id = b.keys[s]
if not id then
total += 1
if total > maxV then
return nil, "limit: too many vertices"
end
table.insert(b.verts, nums)
id = #b.verts - 1
b.keys[s] = id
end
table.insert(b.indices, id)
end
end
elseif kw == "vertexanimation" then
vertexAnimations += 1
while true do
local s = nextLine()
if not s or string.lower(s) == "end" then
break
end
end
else
return nil, "unknown section " .. kw
end
end
if version ~= 1 then
return nil, if version == nil then "no version line" else "unsupported: SMD version " .. tostring(version)
end
local scene = Scene.new()
scene.meta.up = "z"
local root: Types.Node = { name = opts and opts.name or "smd", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
-- skeleton (bind pose: the first frame)
local joints: { Rig.Joint } = {}
local bind: { [number]: { number } } = frames[1] or {}
for k, bn in bones do
local v: { number } = bind[k] or ZERO
local parent = if bn.parent >= 0 then byId[bn.parent] or 0 else 0
joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) }
end
local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1)
-- meshes
if #batches > 0 then
local mesh: Types.Mesh = { primitives = {} }
for _, b in batches do
local nv = #b.verts
local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8)
local lists: { { number } } = {}
for vi, v in b.verts do
local o = (vi - 1) * 12
writef32(pos, o, v[2])
writef32(pos, o + 4, v[3])
writef32(pos, o + 8, v[4])
writef32(nrm, o, v[5])
writef32(nrm, o + 4, v[6])
writef32(nrm, o + 8, v[7])
writef32(uv, (vi - 1) * 8, v[8])
writef32(uv, (vi - 1) * 8 + 4, 1 - v[9])
local l: { number } = {}
local sum = 0
local nl = if #v >= 10 then math.floor(v[10]) else 0
for k = 0, nl - 1 do
local bi, w = byId[v[11 + k * 2]], v[12 + k * 2]
if bi and w then
table.insert(l, bi - 1)
table.insert(l, w)
sum += w
end
end
local parent = byId[v[1]]
if parent and sum < 0.999 then
table.insert(l, parent - 1)
table.insert(l, 1 - sum)
end
lists[vi] = l
end
local ib = buffer.create(#b.indices * 4)
for k, id in b.indices do
writeu32(ib, (k - 1) * 4, id)
end
local attrs: { [string]: Types.Accessor } = {
POSITION = Scene.accessor(pos, "f32", 3, nv),
NORMAL = Scene.accessor(nrm, "f32", 3, nv),
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv),
}
if #bones > 0 then
attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists)
end
local mat = Scene.material(b.name)
mat.metallic = 0
table.insert(scene.textures, { name = b.name, uri = b.name })
mat.baseColorTexture = { texture = #scene.textures }
table.insert(scene.materials, mat)
table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #b.indices), mode = "triangles" :: any, material = #scene.materials })
end
table.insert(scene.meshes, mesh)
table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #bones > 0 then skinIndex else nil })
table.insert(root.children, #scene.nodes)
end
-- animation
if #frames > 1 or (#frames == 1 and #batches == 0) then
local fps = opts and opts.fps or 30
local t: { number } = {}
for k, tm in times do
t[k] = (tm - times[1]) / fps
end
local tracks: { [number]: Rig.Track } = {}
for k = 1, #bones do
local tr: { number }, rot: { number } = {}, {}
for _, f in frames do
local v: { number } = f[k] or bind[k] or ZERO
table.insert(tr, v[1])
table.insert(tr, v[2])
table.insert(tr, v[3])
local q = Rig.angles(v[4], v[5], v[6])
for c = 1, 4 do
table.insert(rot, q[c])
end
end
tracks[k] = { translation = tr, rotation = rot }
end
Rig.animation(scene, opts and opts.name or "animation", jointNodes, t, tracks, "LINEAR")
end
scene.meta.source = { format = "smd", version = version, bones = #bones, frames = #frames, vertexAnimations = vertexAnimations, kind = if #batches > 0 then "reference" else "animation" }
return scene, nil
end
return Read
+250
View File
@@ -0,0 +1,250 @@
--!strict
-- model/smd/Write: a Scene to Valve SMD text (version 1). Bones: the joints of the first skin (parents from the node
-- tree: the nearest ancestor that is also a joint), or one "root" bone for a static scene; "skeleton": the bind pose
-- (each joint node's TRS: rotation as Euler radians, R = Rz Ry Rx), or, with opts.animation = i, that animation sampled
-- at its key times (translation / scale linearly, rotation by normalised linear interpolation); "triangles": every
-- triangle of the scene in world space (codecs/model/MeshFlatten), one material line per triangle (the material
-- name, else "default"), vertex lines with the Source links (opts.links ~= false; GoldSrc style otherwise: the
-- strongest joint as the parent bone only). Animation SMDs (opts.animation set) carry no triangles unless
-- opts.triangles is true.
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Flatten = require("@formats/codecs/model/MeshFlatten")
local Write = {}
export type Options = { animation: number?, links: boolean?, triangles: boolean? }
local fmt = string.format
local function num(v: number): string
if v ~= v or v == math.huge or v == -math.huge then
return "0"
end
local s = fmt("%.6f", v)
if s == "-0.000000" then
return "0.000000"
end
return s
end
-- quaternion -> x, y, z Euler radians with R = Rz(z) Ry(y) Rx(x)
local function angles(q: { number }): (number, number, number)
local m = Mat4.fromQuat(q)
local r31, r32, r33, r21, r11 = m[3], m[7], m[11], m[2], m[1]
local y = math.asin(math.clamp(-r31, -1, 1))
local x, z
if math.abs(r31) < 0.9999999 then
x = math.atan2(r32, r33)
z = math.atan2(r21, r11)
else
x = math.atan2(-m[10], m[6])
z = 0
end
return x, y, z
end
local function lerp(a: { number }, b: { number }, t: number): { number }
local out: { number } = {}
for i = 1, #a do
out[i] = a[i] + (b[i] - a[i]) * t
end
return out
end
-- the value of channel ch at time tm (nil when the channel has no keys)
local function sample(ch: Types.Channel, tm: number): { number }?
local input, output = ch.input, ch.output
local n = input.count
if n == 0 then
return nil
end
local comps = if ch.path == "rotation" then 4 else 3
local function key(k: number): { number }
local out: { number } = {}
for c = 0, comps - 1 do
out[c + 1] = buffer.readf32(output.data, (k * comps + c) * 4)
end
return out
end
local times = input.data
if tm <= buffer.readf32(times, 0) then
return key(0)
end
for k = 1, n - 1 do
local t1 = buffer.readf32(times, k * 4)
if tm <= t1 then
local t0 = buffer.readf32(times, (k - 1) * 4)
local f = if ch.interpolation == "STEP" or t1 <= t0 then 0 else (tm - t0) / (t1 - t0)
local a, b = key(k - 1), key(k)
if comps == 4 then
if a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] < 0 then
b = { -b[1], -b[2], -b[3], -b[4] }
end
local q = lerp(a, b, f)
local l = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2)
return if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else a
end
return lerp(a, b, f)
end
end
return key(n - 1)
end
-- write(scene, opts) -> text | nil, message
function Write.write(scene: Types.Scene, opts: Options?): (string?, string?)
if type(scene) ~= "table" or scene.kind ~= "scene" then
return nil, "expected a Scene"
end
local out: { string } = { "version 1", "nodes" }
local skin = scene.skins and scene.skins[1]
local joints: { number } = if skin then skin.joints else {}
local jointOf: { [number]: number } = {} -- node index -> bone id (0-based)
for k, nd in joints do
jointOf[nd] = k - 1
end
local parentOf: { [number]: number } = {}
for ni, nd in scene.nodes do
for _, c in nd.children do
parentOf[c] = ni
end
end
if #joints == 0 then
table.insert(out, '0 "root" -1')
else
for k, nd in joints do
local p = parentOf[nd]
while p and jointOf[p] == nil do
p = parentOf[p]
end
local name = scene.nodes[nd] and scene.nodes[nd].name or ("bone" .. (k - 1))
table.insert(out, fmt('%d "%s" %d', k - 1, string.gsub(name, '"', "'"), if p then jointOf[p] else -1))
end
end
table.insert(out, "end")
table.insert(out, "skeleton")
local function pose(tr: { number }?, rot: { number }?): string
local t = tr or { 0, 0, 0 }
local x, y, z = angles(rot or { 0, 0, 0, 1 })
return table.concat({ num(t[1]), num(t[2]), num(t[3]), num(x), num(y), num(z) }, " ")
end
local animIndex = opts and opts.animation
local anim = animIndex and scene.animations[animIndex]
if animIndex and not anim then
return nil, "no animation " .. tostring(animIndex)
end
if anim then
local keyset: { [number]: boolean } = {}
for _, ch in anim.channels do
for k = 0, ch.input.count - 1 do
keyset[buffer.readf32(ch.input.data, k * 4)] = true
end
end
local keys: { number } = {}
for tm in keyset do
table.insert(keys, tm)
end
table.sort(keys)
local byNode: { [number]: { [string]: Types.Channel } } = {}
for _, ch in anim.channels do
local m = byNode[ch.node] or {}
byNode[ch.node] = m
m[ch.path] = ch
end
for f, tm in keys do
table.insert(out, "time " .. (f - 1))
for k, nd in joints do
local node = scene.nodes[nd]
local chs: { [string]: Types.Channel } = byNode[nd] or {}
local tch, rch = chs.translation, chs.rotation
local tr = if tch then sample(tch, tm) else node.translation
local rot = if rch then sample(rch, tm) else node.rotation
table.insert(out, (k - 1) .. " " .. pose(tr, rot))
end
end
else
table.insert(out, "time 0")
if #joints == 0 then
table.insert(out, "0 " .. pose(nil, nil))
else
for k, nd in joints do
local node = scene.nodes[nd]
local tr, rot = node.translation, node.rotation
if node.matrix then
local t, r = Mat4.decompose(node.matrix)
tr, rot = t, r
end
table.insert(out, (k - 1) .. " " .. pose(tr, rot))
end
end
end
table.insert(out, "end")
-- triangles
if not anim or (opts and opts.triangles) then
local m, err = Flatten.merge(scene, function(name: string): boolean
return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0"
end, { triangulate = true })
if not m then
return nil, err
end
local A = m.attrs
local P, N, UV, J, W = A.POSITION, A.NORMAL, A.TEXCOORD_0, A.JOINTS_0, A.WEIGHTS_0
local links = not (opts and opts.links == false)
local nbones = math.max(1, #joints)
if #m.corners > 0 then
table.insert(out, "triangles")
for _, part in m.parts do
local mat = part.prim.material and scene.materials[part.prim.material]
local mname = if mat and mat.name and mat.name ~= "" then mat.name else "default"
for f = part.firstFace, part.firstFace + part.faceCount - 1 do
table.insert(out, mname)
for c = 0, 2 do
local v = m.corners[f * 3 + c + 1]
local px, py, pz = P.values[v * 3 + 1], P.values[v * 3 + 2], P.values[v * 3 + 3]
local nx, ny, nz = 0, 0, 1
if N then
nx, ny, nz = N.values[v * 3 + 1], N.values[v * 3 + 2], N.values[v * 3 + 3]
end
local u, w = 0, 0
if UV then
local k = UV.components
u, w = UV.values[v * k + 1], UV.values[v * k + 2]
end
local parent = 0
local lk: { string } = {}
if J and W and #joints > 0 then
local jk, wk = J.components, W.components
local best, bestW = 0, -1
local count = 0
for c2 = 1, math.min(4, jk, wk) do
local jw = W.values[v * wk + c2]
local jj = math.clamp(math.floor(J.values[v * jk + c2] or 0), 0, nbones - 1)
if jw and jw > 0 then
count += 1
table.insert(lk, fmt("%d %s", jj, num(jw)))
if jw > bestW then
best, bestW = jj, jw
end
end
end
parent = best
if count > 0 then
table.insert(lk, 1, tostring(count))
end
end
local line = fmt("%d %s %s %s %s %s %s %s %s", parent, num(px), num(py), num(pz), num(nx), num(ny), num(nz), num(u), num(1 - w))
if links and #lk > 0 then
line ..= " " .. table.concat(lk, " ")
end
table.insert(out, line)
end
end
end
table.insert(out, "end")
end
end
table.insert(out, "")
return table.concat(out, "\n"), nil
end
return Write
+69
View File
@@ -0,0 +1,69 @@
--!strict
-- model/smd: Valve SMD (studiomdl data, GoldSrc and Source: "version 1" text), read and write. Written from the
-- Valve Developer Community "SMD file format" page; no code taken. Read: model/smd/Read (bones -> joint nodes + a
-- Skin, triangles -> a primitive per material with JOINTS_0 / WEIGHTS_0, skeleton frames -> an animation; animation
-- SMDs too). Write: model/smd/Write (the first skin's joints or one root bone, the bind pose or opts.animation,
-- world-space triangles with Source weight links). Units as stored (inches in Valve's games), z up.
-- Not supported: vertex animation (flex) sections (skipped, counted in meta.source.vertexAnimations).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Sniff = require("@formats/core/Sniff")
local Types = require("@formats/Types")
local Read = require("@formats/model/smd/Read")
local Write = require("@formats/model/smd/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Smd = {
name = "smd",
category = "model",
extensions = { "smd" },
mime = { "model/x-smd", "text/plain" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Rig" },
caps = { decode = true, encode = true, skins = true, animation = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
fps: number?, -- skeleton frames per second (default 30)
name: string?, -- the root node / animation name (the api passes the file name)
maxVertices: number?, -- default 2^24
}
export type EncodeOptions = Write.Options
-- ------------------------------------------------------------------------------------------------ sniff
function Smd.sniff(r: Bytes.Reader): number
local head = Sniff.text(r, 256, true)
head = string.gsub(head, "^//[^\n]*\n%s*", "")
if string.match(head, "^version%s+1%s") and string.find(head, "nodes", 1, true) then
return 0.9
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Smd.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local text = Sniff.dropBom(r:string(r:remaining()))
local o: any = opts and table.clone(opts :: any) or {}
if type(o.name) == "string" then
o.name = string.match(o.name, "([^/\\]+)$") or o.name
o.name = string.gsub(o.name, "%.[sS][mM][dD]$", "")
end
local scene, msg = Read.read(text, o)
if not scene then
return nil, Err.from(msg)
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Smd.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
local text, msg = Write.write(scene, opts)
if not text then
return nil, Err.new(Err.ARG, tostring(msg))
end
return buffer.fromstring(text), nil
end
return Smd