model/sourcemdl: tests against the writer's values and srctools (v44 / v48 / v49, fixups, strips, flexes, sections, .ani, .phy)

This commit is contained in:
4DBug committed 2026-11-01 18:43:32 -06:00
1 parent c7e0639913
commit a146611a27
4 files changed
+1103 -1

No files matched your search

+1 -1
View File
@@ -88,7 +88,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | robloxmesh | .mesh | yes | yes | 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" | `tests/model/robloxmesh.luau` |
| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` |
| model | smd | .smd | yes | yes | skins: true, animation: true | `tests/model/smd.luau` |
| model | sourcemdl | .mdl | yes | - | skins: true, morph: true, animation: true, lods: true | **missing** |
| model | sourcemdl | .mdl | yes | - | skins: true, morph: true, animation: true, lods: true | `tests/model/sourcemdl.luau` |
| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` |
| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` |
| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
+1
View File
@@ -417,6 +417,7 @@ function Build.scene(h: Mdl.Header, b: buffer, base: number, size: number, inp:
nodes = h.nodes,
rootLod = h.rootLod,
lods = if vtx then vtx.lods else 0,
lodVertices = if vvd then vvd.lodCounts else nil,
lodReplacements = if vtx then vtx.replacements else nil,
physics = phy,
warnings = inp.warnings,
+285
View File
@@ -0,0 +1,285 @@
-- model/sourcemdl tests: generated MDL v44 / v48 / v49 + VVD / VTX / PHY / ANI against the writer's exact values and
-- srctools' reading of the same files. Fixtures: tools/fixtures/sourcemdl.py.
local T = require("@tests/T")
local F = require("@rosetta")
local SourceMdl = require("@rosetta/model/sourcemdl")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Types = require("@rosetta/Types")
local Fx = require("@tests/gen/sourcemdl")
local t = T.suite("sourcemdl")
t:eq(SourceMdl.name, "sourcemdl", "name")
t:eq(SourceMdl.category, "model", "category")
local function floats(acc: any): { number }
local rd = Types.Scene.reader(acc) :: any
local out = {}
for i = 0, acc.count - 1 do
for c = 0, acc.components - 1 do
table.insert(out, rd(i, c))
end
end
return out
end
local function near(a: { number }, b: { number }, tol: number): boolean
if #a ~= #b then
return false
end
for i = 1, #b do
if math.abs(a[i] - b[i]) > tol then
return false
end
end
return true
end
local function decode(c: any, extra: { [string]: any }?): (any, any)
local o: { [string]: any } = { files = c.files }
for k, v in extra or {} do
o[k] = v
end
return SourceMdl.decode(Bytes.reader(buffer.fromstring(c.mdl)), o :: any)
end
local function normDir(s: string): string
local d = string.gsub(s, "\\", "/")
d = string.gsub(d, "^/+", "")
if d ~= "" and string.sub(d, -1) ~= "/" then
d ..= "/"
end
return d
end
for _, c in Fx.cases do
local tag = "v" .. c.version .. ": "
local e = c.expect
local st = c.srctools
local s, err = decode(c)
t:check(s, tag .. tostring(err))
if not s then
continue
end
local src = s.meta.source
t:eq(F.detect(c.mdl), "sourcemdl", tag .. "F.detect")
t:eq(#src.warnings, 0, tag .. "no warnings (" .. table.concat(src.warnings, "; ") .. ")")
t:eq(src.vtx, "model.dx90.vtx", tag .. "the dx90 strips")
-- header against srctools
t:eq(src.name, st.name, tag .. "name (srctools)")
t:eq(src.version, st.version, tag .. "version (srctools)")
t:eq(src.surfaceProp, st.surfaceprop, tag .. "surfaceprop (srctools)")
t:eq(src.keyValues, st.keyvalues, tag .. "keyvalues (srctools)")
t:check(math.abs(src.mass - st.mass) < 1e-6, tag .. "mass (srctools)")
t:check(near(src.eye, st.eye, 1e-6) and near(src.hull[1], st.hull[1], 1e-6) and near(src.hull[2], st.hull[2], 1e-6), tag .. "eye / hull (srctools)")
for i, d in src.cdmaterials do
t:eq(normDir(d), st.cdmaterials[i], tag .. "cdmaterials " .. i .. " (srctools)")
end
t:eq(#src.includeModels, #st.included, tag .. "include models (srctools)")
t:eq(src.includeModels[1].file, st.included[1][2], tag .. "include model file (srctools)")
t:eq(#src.skins, #st.skins, tag .. "skin families (srctools)")
for f, fam in src.skins do
local names = {}
for r, mi in fam do
names[r] = s.materials[mi].name
end
t:eq(table.concat(names, ","), table.concat(st.skins[f], ","), tag .. "skin family " .. f .. " (srctools)")
end
t:eq(#src.sequences, #st.sequences, tag .. "sequences (srctools)")
for i, q in st.sequences do
local ours = src.sequences[i]
t:eq(ours.name, q.label, tag .. "sequence " .. i .. " label (srctools)")
t:eq(ours.activity, q.act, tag .. "sequence " .. i .. " activity (srctools)")
t:eq(ours.flags, q.flags, tag .. "sequence " .. i .. " flags (srctools)")
t:eq(ours.weight, q.weight, tag .. "sequence " .. i .. " weight (srctools)")
t:eq(ours.keyValues, q.keyvalues, tag .. "sequence " .. i .. " keyvalues (srctools)")
t:check(near(ours.bboxMin, q.bbox[1], 1e-6) and near(ours.bboxMax, q.bbox[2], 1e-6), tag .. "sequence " .. i .. " bbox (srctools)")
t:eq(#ours.events, #q.events, tag .. "sequence " .. i .. " events (srctools)")
for k, ev in q.events do
t:check(math.abs(ours.events[k].cycle - ev[1]) < 1e-6 and ours.events[k].options == ev[2], tag .. "sequence " .. i .. " event " .. k .. " (srctools)")
end
end
local total = 0
for _, p in src.bodyParts do
for _, m in p.models do
total += m.vertices
end
end
t:eq(total, st.total_verts, tag .. "total vertices (srctools)")
t:check(string.find(src.physics.text, '"mass" "12.5', 1, true) ~= nil and st.phys_mass == 12.5, tag .. "phy keyvalues (srctools)")
-- skeleton
local skin = s.skins[1]
t:eq(#skin.joints, #e.bones, tag .. "joints")
local ibm = floats(skin.inverseBindMatrices)
for i, b in e.bones do
local node = s.nodes[skin.joints[i]]
t:eq(node.name, b.name, tag .. "bone " .. i .. " name")
t:check(near(node.translation, b.pos, 0) and near(node.rotation, b.quat, 0), tag .. "bone " .. i .. " rest pose")
if b.parent >= 0 then
t:check(table.find(s.nodes[skin.joints[b.parent + 1]].children, skin.joints[i]) ~= nil, tag .. "bone " .. i .. " parent")
end
local m = Mat4.fromRows(b.poseToBone)
local got = table.move(ibm, (i - 1) * 16 + 1, i * 16, 1, {})
t:check(near(got, m, 1e-6), tag .. "bone " .. i .. " poseToBone as the inverse bind matrix")
end
t:eq(s.nodes[skin.joints[5]].extras.procedural.type, "jiggle", tag .. "jiggle bone")
t:eq(s.nodes[skin.joints[6]].extras.procedural.type, "aimatbone", tag .. "aim-at bone")
t:check(near(src.lodVertices, e.lodCounts, 0) or (src.lodVertices[1] == e.lodCounts[1] and src.lodVertices[2] == e.lodCounts[2]), tag .. "vvd LOD vertex counts")
-- meshes
for p, part in e.parts do
for m, model in part.models do
local info = src.bodyParts[p].models[m]
t:eq(info.name, model.name, tag .. "model " .. model.name)
if #model.meshes == 0 then
t:check(info.mesh == nil, tag .. model.name .. ": no mesh")
continue
end
local mesh = s.meshes[info.mesh]
t:eq(#mesh.primitives, #model.meshes, tag .. model.name .. ": primitives")
for k, x in model.meshes do
local prim = mesh.primitives[k]
local lab = tag .. model.name .. " mesh " .. k .. ": "
t:check(near(floats(prim.attributes.POSITION), x.positions, 0), lab .. "positions")
t:check(near(floats(prim.attributes.NORMAL), x.normals, 0), lab .. "normals")
t:check(near(floats(prim.attributes.TEXCOORD_0), x.uvs, 0), lab .. "uvs")
t:check(near(floats(prim.attributes.TANGENT), x.tangents, 0), lab .. "tangents")
t:check(near(floats(prim.attributes.WEIGHTS_0), x.weights, 0), lab .. "weights")
t:check(near(floats(prim.attributes.JOINTS_0), x.joints, 0), lab .. "joints")
t:check(near(floats(prim.indices), x.lods[1], 0), lab .. "LOD 0 triangles (strips, groups, winding)")
t:check(near(floats(prim.extras.lods[2].indices), x.lods[2], 0), lab .. "LOD 1 triangles")
t:eq(prim.extras.lods[2].switchPoint, 40, lab .. "LOD 1 switch point")
t:eq(prim.material, x.material, lab .. "material through skin family 1")
t:eq(prim.extras.skinRef, x.skinRef, lab .. "skin reference")
local names = mesh.extras.targetNames
local want = 0
for d, verts in x.targets do
local slot = table.find(names, e.flexdescs[tonumber(d) :: number + 1])
t:check(slot ~= nil, lab .. "flex target " .. d)
if slot then
local pos, nrm = floats(prim.targets[slot].POSITION), floats(prim.targets[slot].NORMAL)
local ok = true
for v, dd in verts do
local vi = tonumber(v) :: number
for cc = 1, 3 do
ok = ok and math.abs(pos[vi * 3 + cc] - dd[cc]) < 1e-6 and math.abs(nrm[vi * 3 + cc] - dd[cc + 3]) < 1e-6
end
want += 1
end
t:check(ok, lab .. "flex " .. names[slot] .. " deltas")
end
end
if names then
t:eq(#prim.targets, #names, lab .. "a target per flex")
end
end
end
end
t:eq(s.nodes[s.roots[1]].name, src.name, tag .. "root node")
-- attachments
for i, a in e.attachments do
local at = src.attachments[i]
local node = s.nodes[at.node]
t:eq(node.name, a.name, tag .. "attachment " .. i .. " name")
t:check(table.find(s.nodes[skin.joints[a.bone + 1]].children, at.node) ~= nil, tag .. "attachment " .. i .. " parent bone")
local m = Mat4.compose(node.translation, node.rotation, node.scale)
t:check(near(m, Mat4.fromRows(a.matrix), 1e-5), tag .. "attachment " .. i .. " matrix")
end
t:eq(#src.hitboxSets[1].boxes, 2, tag .. "hitboxes")
t:eq(src.hitboxSets[1].boxes[2].name, "head_box", tag .. "hitbox name")
-- animations
for _, a in e.anims do
local anim
for _, x in s.animations do
if x.name == a.name then
anim = x
end
end
t:check(anim, tag .. "animation " .. a.name)
if not anim then
continue
end
for bone, want in a.bones do
local node = skin.joints[tonumber(bone) :: number]
local tr, rot
for _, ch in anim.channels do
if ch.node == node then
if ch.path == "translation" then
tr = ch
elseif ch.path == "rotation" then
rot = ch
end
end
end
t:check(tr and rot, tag .. a.name .. " bone " .. bone .. ": channels")
if tr and rot then
t:eq(tr.input.count, a.frames, tag .. a.name .. ": frames")
t:check(math.abs(floats(tr.input)[2] - 1 / a.fps) < 1e-6, tag .. a.name .. ": fps")
t:check(near(floats(tr.output), want.pos, 1e-4), tag .. a.name .. " bone " .. bone .. ": positions per frame")
t:check(near(floats(rot.output), want.rot, 1e-5), tag .. a.name .. " bone " .. bone .. ": rotations per frame")
end
end
end
if c.version == 49 then
t:check(c.files["model.ani"] ~= nil, tag .. "an .ani block")
end
-- physics
local soup = {}
for _, sol in src.physics.solids do
for _, h in sol.hulls do
for _, v in h.indices do
for cc = 1, 3 do
table.insert(soup, h.positions[v * 3 + cc])
end
end
end
end
t:check(near(soup, e.physics, 1e-3), tag .. "phy convex hulls")
-- options
local s2 = decode(c, { bodies = { 2, 2 }, lod = 2 }) :: any
local names = {}
for _, ni in s2.nodes[s2.roots[1]].children do
if s2.nodes[ni].mesh then
table.insert(names, s2.meshes[s2.nodes[ni].mesh].name)
end
end
t:eq(table.concat(names, ","), "body_lo,hat", tag .. "opts.bodies")
t:check(near(floats(s2.meshes[1].primitives[1].indices), e.parts[1].models[1].meshes[1].lods[2], 0), tag .. "opts.lod")
local s3 = SourceMdl.decode(Bytes.reader(buffer.fromstring(c.mdl))) :: any
t:check(s3 and #s3.meshes == 0 and #s3.meta.source.warnings > 0 and #s3.skins == 1, tag .. "no siblings: skeleton only, with warnings")
local s4 = decode(c, { name = "renamed.mdl", files = { ["renamed.vvd"] = c.files["model.vvd"], ["renamed.sw.vtx"] = c.files["model.dx90.vtx"] } }) :: any
t:check(s4 and #s4.meshes == 3 and s4.meta.source.vtx == "renamed.sw.vtx", tag .. "siblings named after opts.name")
-- fuzz: the mdl, and each sibling file
local samples = { c.mdl }
t:fuzz(tag .. "mdl", function(b: buffer)
return SourceMdl.decode(Bytes.reader(b), { files = c.files })
end, samples, { mutations = 40 })
for _, name in { "model.vvd", "model.dx90.vtx", "model.phy" } do
t:fuzz(tag .. name, function(b: buffer)
local files = table.clone(c.files)
files[name] = buffer.tostring(b)
return SourceMdl.decode(Bytes.reader(buffer.fromstring(c.mdl)), { files = files })
end, { c.files[name] }, { mutations = 30, garbage = 20 })
end
end
-- errors
local bad = buffer.fromstring(Fx.cases[1].mdl)
buffer.writei32(bad, 4, 52)
local _, e1 = SourceMdl.decode(Bytes.reader(bad))
t:check(e1 and e1.code == Err.UNSUPPORTED, "version 52: UNSUPPORTED")
local _, e2 = SourceMdl.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.cases[1].mdl, 1, 100))))
t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "truncated header")
local s5 = SourceMdl.decode(Bytes.reader(buffer.fromstring(Fx.cases[1].mdl)), { files = { ["model.vvd"] = "IDSV" } })
t:check(s5 == nil, "a broken .vvd is an error")
t:eq(SourceMdl.sniff(Bytes.reader(buffer.fromstring(Fx.cases[1].mdl))), 1, "sniff")
t:eq(SourceMdl.sniff(Bytes.reader(buffer.fromstring("IDST\10\0\0\0"))), 0, "sniff: GoldSrc is model/mdl")
t:done()
+816
View File
@@ -0,0 +1,816 @@
# Source MDL fixtures (tools/fixtures.py). Models written here from the Source SDK 2013 studio.h / optimize.h /
# phyfile.h layouts with random data (no Valve assets): MDL v44 / v48 / v49 with .vvd (LOD fixups, file order
# shuffled), .dx90.vtx (trilists, a tristrip, two LODs, a material replacement; v49 uses the 33 / 35-byte strip
# headers), .phy (VPHY, two convex leaves, KeyValues text), .ani (an external animation block) and .vmt materials.
# References: the writer's exact values (vertices, triangles, bones, poseToBone, flex deltas, per-frame bone poses from
# RLE values / Quaternion48 / Quaternion64 / Vector48, sections, delta animation) and srctools (nixpkgs python
# srctools.mdl.Model: header, cdmaterials, skins, sequences, events, included models, phy keyvalues, iter_textures;
# srctools.vmt.Material: $basetexture / $bumpmap).
# tests/gen/sourcemdl.luau { cases = { { version, mdl, vvd, vtx, phy, ani, files, expect, srctools }, ... } }
import json, math, os, shutil, struct, tempfile
INPUTS = []
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def f16(x):
return struct.unpack("<e", struct.pack("<e", x))[0]
def angles(x, y, z):
sy, cy = math.sin(z / 2), math.cos(z / 2)
sp, cp = math.sin(y / 2), math.cos(y / 2)
sr, cr = math.sin(x / 2), math.cos(x / 2)
return [sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy]
def qmul(a, b):
ax, ay, az, aw = a
bx, by, bz, bw = b
return [aw * bx + ax * bw + ay * bz - az * by, aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw, aw * bw - ax * bx - ay * by - az * bz]
def qmat(q):
x, y, z, w = q
return [[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]
def compose(r, t):
return [r[0] + [t[0]], r[1] + [t[1]], r[2] + [t[2]]]
def mul34(a, b):
out = []
for i in range(3):
row = [sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)]
row.append(sum(a[i][k] * b[k][3] for k in range(3)) + a[i][3])
out.append(row)
return out
def inv34(m):
r = [[m[j][i] for j in range(3)] for i in range(3)]
t = [-sum(r[i][k] * m[k][3] for k in range(3)) for i in range(3)]
return [r[i] + [t[i]] for i in range(3)]
class Buf:
def __init__(self):
self.b = bytearray()
self.strings = []
def tell(self):
return len(self.b)
def put(self, fmt, *v):
at = len(self.b)
self.b += struct.pack("<" + fmt, *v)
return at
def raw(self, data):
at = len(self.b)
self.b += data
return at
def patch(self, at, fmt, *v):
struct.pack_into("<" + fmt, self.b, at, *v)
def align(self, n=4):
while len(self.b) % n:
self.b.append(0)
def string(self, field, base, text):
self.strings.append((field, base, text))
def flush_strings(self):
seen = {}
for field, base, text in self.strings:
if text not in seen:
seen[text] = self.raw(text.encode() + b"\0")
self.patch(field, "i", seen[text] - base)
self.strings = []
def rle(values):
out, i, n = b"", 0, len(values)
while i < n:
vals = [values[i]]
total = 1
j = i + 1
while j < n and len(vals) < 255 and total < 255:
if values[j] == values[j - 1]:
while j < n and values[j] == values[j - 1] and total < 255:
total += 1
j += 1
break
vals.append(values[j])
total += 1
j += 1
out += struct.pack("<BB", len(vals), total) + struct.pack("<%dh" % len(vals), *vals)
i = j
return out
def quat48(q):
x, y, z, w = q
xs = max(0, min(65535, int(round(x * 32768 + 32768))))
ys = max(0, min(65535, int(round(y * 32768 + 32768))))
zs = max(0, min(32767, int(round(z * 16384 + 16384))))
data = struct.pack("<3H", xs, ys, zs | (0x8000 if w < 0 else 0))
dx, dy, dz = (xs - 32768) / 32768, (ys - 32768) / 32768, (zs - 16384) / 16384
dw = math.sqrt(max(0, 1 - dx * dx - dy * dy - dz * dz))
return data, [dx, dy, dz, -dw if w < 0 else dw]
def quat64(q):
x, y, z, w = q
s = [max(0, min(2097151, int(round(c * 1048576.5 + 1048576)))) for c in (x, y, z)]
v = s[0] | (s[1] << 21) | (s[2] << 42) | ((1 << 63) if w < 0 else 0)
d = [(c - 1048576) / 1048576.5 for c in s]
dw = math.sqrt(max(0, 1 - sum(c * c for c in d)))
return struct.pack("<Q", v), d + [-dw if w < 0 else dw]
# ------------------------------------------------------------------------------------------------ the model
def make(rng, version):
ext = version == 49
nb = 6
bones = []
world = []
for i in range(nb):
parent = -1 if i == 0 else rng.randrange(i)
rot = [f32(rng.uniform(-1.5, 1.5)) for _ in range(3)]
quat = [f32(c) for c in angles(*rot)]
pos = [f32(rng.uniform(-8, 8)) for _ in range(3)]
b = {"name": "bone%d" % i if i else "root", "parent": parent, "pos": pos, "quat": quat, "rot": rot,
"posscale": [f32(rng.uniform(0.001, 0.01)) for _ in range(3)], "rotscale": [f32(rng.uniform(0.0001, 0.001)) for _ in range(3)]}
local = compose(qmat(quat), pos)
w = local if parent < 0 else mul34(world[parent], local)
world.append(w)
b["poseToBone"] = [f32(c) for row in inv34(w) for c in row]
bones.append(b)
bones[4]["proc"] = ("jiggle", [f32(rng.uniform(0, 10)) for _ in range(29)])
bones[5]["proc"] = ("aimatbone", [f32(rng.uniform(-1, 1)) for _ in range(9)])
textures = ["skin_a", "skin_b", "models/shared/metal", "skin_c"]
cdmats = ["models\\test\\", "models/alt"]
nref = 3
families = [[0, 1, 2], [3, 1, 2]]
# body parts: models of meshes of (vertex count, triangle count)
layout = [("body", [("body_hi", [(30, 40), (20, 24)]), ("body_lo", [(12, 10)])]), ("head", [("blank", []), ("hat", [(10, 8)])])]
vertices = []
parts = []
counter = [0]
for pname, models in layout:
mlist = []
for mname, meshes in models:
start = len(vertices)
mm = []
off = 0
for k, (nv, nt) in enumerate(meshes):
for _ in range(nv):
nbw = rng.randrange(1, 4)
ws = [rng.random() for _ in range(nbw)]
s = sum(ws)
ws = [f32(w / s) for w in ws] + [0.0] * (3 - nbw)
ids = [rng.randrange(nb) for _ in range(nbw)] + [0] * (3 - nbw)
n = [rng.uniform(-1, 1) for _ in range(3)]
l = math.sqrt(sum(c * c for c in n)) or 1
vertices.append({"w": ws, "b": ids, "n": nbw, "pos": [f32(rng.uniform(-20, 20)) for _ in range(3)],
"nrm": [f32(c / l) for c in n], "uv": [f32(rng.random()), f32(rng.random())],
"tan": [f32(rng.uniform(-1, 1)) for _ in range(3)] + [f32(rng.choice((-1.0, 1.0)))]})
tris = []
while len(tris) < nt:
t = rng.sample(range(nv), 3)
tris.append(t)
counter[0] += 1
mm.append({"nv": nv, "off": off, "tris": tris, "material": (counter[0] - 1) % nref, "center": [f32(rng.uniform(-1, 1)) for _ in range(3)], "flexes": []})
off += nv
mlist.append({"name": mname, "start": start, "nv": off, "meshes": mm})
parts.append({"name": pname, "models": mlist})
flexdescs = ["AU1L", "AU1R", "smile", "unused"]
hi = parts[0]["models"][0]
m0 = hi["meshes"][0]
fixed = version >= 48
scale = f32(1 / 4096.0)
def deltas(nv, count, wrinkle=False):
out = []
for idx in sorted(rng.sample(range(nv), count)):
d = [rng.uniform(-2, 2) for _ in range(6)]
out.append({"index": idx, "speed": rng.randrange(256), "side": rng.randrange(256), "d": d, "wrinkle": rng.randrange(-32767, 32768) if wrinkle else 0})
return out
m0["flexes"].append({"desc": 2, "partner": 0, "kind": 0, "targets": [0.0, 0.25, 0.75, 1.0], "verts": deltas(m0["nv"], 8)})
m0["flexes"].append({"desc": 0, "partner": 1, "kind": 1, "targets": [0.0, 0.5, 0.5, 1.0], "verts": deltas(m0["nv"], 6, True)})
hi["meshes"][1]["flexes"].append({"desc": 2, "partner": 0, "kind": 0, "targets": [0.0, 1.0, 1.0, 1.0], "verts": deltas(hi["meshes"][1]["nv"], 5)})
for m in (m0, hi["meshes"][1]):
for f in m["flexes"]:
for v in f["verts"]:
if fixed:
v["raw"] = [max(-32768, min(32767, int(round(c / scale)))) for c in v["d"]]
v["val"] = [r * scale for r in v["raw"]]
else:
v["val"] = [f16(c) for c in v["d"]]
# animations
nf = {"idle": 6, "walk": 12, "gesture": 4, "fromani": 3}
anims = []
# per-anim per-bone specs (full length), split into sections by the writer
def make_specs(n, delta):
specs = []
r = [rng.randrange(-2000, 2000) for _ in range(3)]
specs.append((0, {"rot": "anim", "rv": [[rng.randrange(-3000, 3000) for _ in range(n)], [r[1]] * n, [rng.choice((5, 5, 9)) for _ in range(n)]],
"pos": "anim", "pv": [[rng.randrange(-500, 500) for _ in range(n)], None, [7] * n]}))
specs.append((1, {"rot": "raw48", "q": [f32(c) for c in normalize([rng.uniform(-1, 1) for _ in range(4)])], "pos": "raw48", "p": [f16(rng.uniform(-10, 10)) for _ in range(3)]}))
specs.append((3, {"rot": "raw64", "q": normalize([rng.uniform(-1, 1) for _ in range(4)]), "pos": None}))
specs.append((4, {"rot": None, "pos": "anim", "pv": [None, [rng.randrange(-100, 100) for _ in range(n)], None]}))
return specs
for name, delta in (("idle", False), ("walk", False), ("gesture", True), ("fromani", False)):
anims.append({"name": "@" + name, "seq": name, "frames": nf[name], "delta": delta, "specs": make_specs(nf[name], delta),
"fps": f32(rng.choice((24.0, 30.0))), "sections": 5 if name == "walk" else 0, "ani": name == "fromani"})
if version < 49:
anims.pop()
# expected poses per anim: { bone -> { pos = [...], rot = [...] } }
for a in anims:
n = a["frames"]
exp = {}
for bi, sp in a["specs"]:
b = bones[bi]
pos, rot = [], []
for fr in range(n):
if sp["rot"] == "anim":
ang = [(0 if a["delta"] else b["rot"][k]) + (sp["rv"][k][fr] * b["rotscale"][k] if sp["rv"][k] else 0) for k in range(3)]
q = angles(*ang)
elif sp["rot"] == "raw48":
q = quat48(sp["q"])[1]
elif sp["rot"] == "raw64":
q = quat64(sp["q"])[1]
else:
q = [0, 0, 0, 1] if a["delta"] else b["quat"]
if sp["pos"] == "anim":
p = [(0 if a["delta"] else b["pos"][k]) + (sp["pv"][k][fr] * b["posscale"][k] if sp["pv"][k] else 0) for k in range(3)]
elif sp["pos"] == "raw48":
p = list(sp["p"])
else:
p = [0, 0, 0] if a["delta"] else list(b["pos"])
if a["delta"]:
p = [b["pos"][k] + p[k] for k in range(3)]
q = qmul(b["quat"], q)
pos += p
rot += q
exp[bi] = {"pos": pos, "rot": rot}
a["expect"] = exp
return {"version": version, "ext": ext, "bones": bones, "textures": textures, "cdmats": cdmats, "families": families, "nref": nref,
"parts": parts, "vertices": vertices, "flexdescs": flexdescs, "fixed": fixed, "scale": scale, "anims": anims}
def normalize(q):
l = math.sqrt(sum(c * c for c in q))
return [c / l for c in q]
def anim_chain(b, a, bones, first, count):
# mstudioanim_t records for frames [first, first + count) of every spec
out = bytearray()
recs = []
for i, (bi, sp) in enumerate(a["specs"]):
flags = 0
body = bytearray()
later = []
if sp["rot"] == "raw48":
flags |= 0x02
body += quat48(sp["q"])[0]
elif sp["rot"] == "raw64":
flags |= 0x20
body += quat64(sp["q"])[0]
elif sp["rot"] == "anim":
flags |= 0x08
later.append((len(body), sp["rv"]))
body += bytes(6)
if sp["pos"] == "raw48":
flags |= 0x01
body += struct.pack("<3e", *sp["p"])
elif sp["pos"] == "anim":
flags |= 0x04
later.append((len(body), sp["pv"]))
body += bytes(6)
if a["delta"]:
flags |= 0x10
for vp, chans in later:
for k in range(3):
if chans[k] is not None:
off = 4 + len(body) - (4 + vp)
struct.pack_into("<h", body, vp + k * 2, off)
body += rle(chans[k][first:first + count])
if len(body) % 2:
body.append(0)
recs.append((bi, flags, bytes(body)))
for i, (bi, flags, body) in enumerate(recs):
nxt = 0 if i == len(recs) - 1 else 4 + len(body)
out += struct.pack("<BBh", bi, flags, nxt) + body
return bytes(out)
def write_mdl(m, rng, checksum):
v = m["version"]
w = Buf()
w.raw(bytes(408))
hdr = {}
w.patch(0, "4sii64si", b"IDST", v, checksum, b"test/model.mdl", 0)
eye = [f32(rng.uniform(-5, 5)) for _ in range(18)]
w.patch(80, "18f", *eye)
w.patch(152, "I", 0x200000 if m["fixed"] else 0)
w.patch(392, "f", m["scale"] if m["fixed"] else 0.0)
# bones
bo = w.tell()
hdr[156] = (len(m["bones"]), bo)
for b in m["bones"]:
w.put("ii6i3f4f3f3f3f12f4fiiiiii8i", 0, b["parent"], *([-1] * 6), *b["pos"], *b["quat"], *b["rot"], *b["posscale"], *b["rotscale"],
*b["poseToBone"], 0, 0, 0, 1, 0x100, 0, 0, 0, 0, 1, *([0] * 8))
for i, b in enumerate(m["bones"]):
at = bo + i * 216
w.string(at, at, b["name"])
w.string(at + 176, at, "flesh")
if "proc" in b:
kind, vals = b["proc"]
w.align()
po = w.tell()
if kind == "jiggle":
w.put("i29f", 0x41, *vals)
w.patch(at + 164, "ii", 5, po - at)
else:
w.put("ii9f", 0, 2, *vals)
w.patch(at + 164, "ii", 3, po - at)
# hitbox set
hs = w.tell()
hdr[172] = (1, hs)
w.put("iii", 0, 2, 12)
w.string(hs, hs, "default")
for k in range(2):
bb = w.tell()
w.put("ii3f3fi8i", k + 1, k, -1.0, -2.0, -3.0, 1.0, 2.0, 3.0, 0, *([0] * 8))
if k == 1:
w.string(bb + 32, bb, "head_box")
# animdescs
ad = w.tell()
hdr[184 - 4] = (len(m["anims"]), ad)
for a in m["anims"]:
w.put("iifiiii6i9ihhif", -w.tell(), 0, a["fps"], 0x4 if a["delta"] else 0, a["frames"], 0, 0, *([0] * 6), *([0] * 9), 0, 0, 0, 0.0)
anidata = bytearray(b"IDAG" + bytes(60))
for i, a in enumerate(m["anims"]):
at = ad + i * 100
w.string(at + 4, at, a["name"])
w.align()
n = a["frames"]
if a["sections"]:
sf = a["sections"]
ns = n // sf + 2
st = w.tell()
w.raw(bytes(ns * 8))
w.patch(at + 80, "ii", st - at, sf)
datas = []
for s in range(ns):
if s == ns - 1:
first, cnt = n - 1, 1
else:
first = s * sf
cnt = min(sf + 1, n - first)
if cnt <= 0:
first, cnt = n - 1, 1
w.align()
d = w.raw(anim_chain(w, a, m["bones"], first, cnt))
w.patch(st + s * 8, "ii", 0, d - at)
datas.append(d)
w.patch(at + 52, "ii", 0, datas[0] - at)
elif a["ani"]:
off = len(anidata) - 64
anidata += anim_chain(w, a, m["bones"], 0, n)
w.patch(at + 52, "ii", 1, off)
else:
d = w.raw(anim_chain(w, a, m["bones"], 0, n))
w.patch(at + 52, "ii", 0, d - at)
# sequences
w.align()
sq = w.tell()
hdr[188] = (len(m["anims"]), sq)
seqs = []
for i, a in enumerate(m["anims"]):
bmin = [f32(rng.uniform(-10, 0)) for _ in range(3)]
bmax = [f32(rng.uniform(0, 10)) for _ in range(3)]
flags = 1 if a["seq"] in ("idle", "walk") else (4 if a["delta"] else 0)
w.put("8i3f3f5i2i2f2fiff3i3f2i10i7i", -w.tell(), 0, 0, flags, -1, 1 + i, 0, 0, *bmin, *bmax, 1, 0, 0, 1, 1, -1, -1, 0.0, 0.0, 0.0, 0.0, 0,
0.2, 0.2, 0, 0, 0, 0.0, 0.0, 0.0, 0, 0, *([0] * 10), *([0] * 7))
seqs.append({"name": a["seq"], "flags": flags, "weight": 1 + i, "bmin": bmin, "bmax": bmax, "act": "ACT_" + a["seq"].upper()})
for i, a in enumerate(m["anims"]):
at = sq + i * 212
w.string(at + 4, at, a["seq"])
w.string(at + 8, at, seqs[i]["act"])
w.align()
ai = w.put("h", i)
w.align()
w.patch(at + 60, "i", ai - at)
if i == 0:
ev = w.tell()
w.put("fii64si", 0.5, 5004, 0, b"Weapon.Fire", 0)
w.put("fii64si", 0.25, 1004, 0, b"footstep", 0)
w.patch(at + 24, "ii", 2, ev - at)
seqs[i]["events"] = [[0.5, "Weapon.Fire"], [0.25, "footstep"]]
kv = w.raw(b"speed 10\0")
w.patch(at + 172, "ii", kv - at, 9)
else:
seqs[i]["events"] = []
# textures
tx = w.tell()
hdr[204] = (len(m["textures"]), tx)
for t in m["textures"]:
w.put("iiii2i10i", 0, 0, 0, 0, 0, 0, *([0] * 10))
for i, t in enumerate(m["textures"]):
w.string(tx + i * 64, tx + i * 64, t)
cd = w.tell()
hdr[212] = (len(m["cdmats"]), cd)
for c in m["cdmats"]:
w.put("i", 0)
for i, c in enumerate(m["cdmats"]):
w.string(cd + i * 4, 0, c)
sk = w.tell()
for fam in m["families"]:
w.put("%dh" % m["nref"], *fam)
w.align()
w.patch(220, "iii", m["nref"], len(m["families"]), sk)
# body parts
bp = w.tell()
hdr[232] = (len(m["parts"]), bp)
base = 0
for p in m["parts"]:
w.put("iiii", 0, len(p["models"]), max(1, base), 0)
base = max(1, base) * len(p["models"])
for pi, p in enumerate(m["parts"]):
pat = bp + pi * 16
w.string(pat, pat, p["name"])
mo = w.tell()
w.patch(pat + 12, "i", mo - pat)
for md in p["models"]:
w.put("64sifiiiiiiiiiii8i", md["name"].encode(), 0, 10.0, len(md["meshes"]), 0, md["nv"], md["start"] * 48, md["start"] * 16, 0, 0, 0, 0, 0, 0, *([0] * 8))
for mi, md in enumerate(p["models"]):
mat = mo + mi * 148
me = w.tell()
w.patch(mat + 76, "i", me - mat if md["meshes"] else 0)
for k, sm in enumerate(md["meshes"]):
w.put("iiiiiiiii3fi8i8i", sm["material"], mat - w.tell(), sm["nv"], sm["off"], len(sm["flexes"]), 0, 0, 0, k, *sm["center"], 0,
sm["nv"], sm["nv"], *([0] * 6), *([0] * 8))
for k, sm in enumerate(md["meshes"]):
mea = me + k * 116
if not sm["flexes"]:
continue
fo = w.tell()
w.patch(mea + 20, "i", fo - mea)
for f in sm["flexes"]:
w.put("i4fiiiB3x6i", f["desc"], *f["targets"], len(f["verts"]), 0, f["partner"], f["kind"], *([0] * 6))
for fi, f in enumerate(sm["flexes"]):
fa = fo + fi * 60
va = w.tell()
w.patch(fa + 24, "i", va - fa)
for vv in f["verts"]:
if m["fixed"]:
w.put("HBB6h", vv["index"], vv["speed"], vv["side"], *vv["raw"])
else:
w.put("HBB6e", vv["index"], vv["speed"], vv["side"], *vv["d"])
if f["kind"] == 1:
w.put("h", vv["wrinkle"])
w.align()
# attachments
at0 = w.tell()
atts = []
for k in range(2):
rot = angles(*[rng.uniform(-1, 1) for _ in range(3)])
mat = compose(qmat(rot), [rng.uniform(-4, 4) for _ in range(3)])
flat = [f32(c) for row in mat for c in row]
w.put("iii12f8i", 0, 0, k * 2, *flat, *([0] * 8))
atts.append({"name": "attach%d" % k, "bone": k * 2, "matrix": flat})
for k in range(2):
w.string(at0 + k * 92, at0 + k * 92, atts[k]["name"])
hdr[240] = (2, at0)
fd = w.tell()
hdr[260] = (len(m["flexdescs"]), fd)
for d in m["flexdescs"]:
w.put("i", 0)
for i, d in enumerate(m["flexdescs"]):
w.string(fd + i * 4, fd + i * 4, d)
fc = w.tell()
hdr[268] = (2, fc)
w.put("iiiff", 0, 0, 0, 0.0, 1.0)
w.put("iiiff", 0, 0, 1, -1.0, 1.0)
for i, n in enumerate(("smile", "blink")):
w.string(fc + i * 20, fc + i * 20, "eyes" if i else "mouth")
w.string(fc + i * 20 + 4, fc + i * 20, n)
fr = w.tell()
hdr[276] = (1, fr)
w.put("iii", 2, 2, 12)
w.put("if", 1, 0.5)
w.put("ii", 2, 0)
pp = w.tell()
hdr[300] = (1, pp)
w.put("iifff", 0, 0, -45.0, 45.0, 0.0)
w.string(pp, pp, "move_yaw")
sp = w.raw(b"wood\0")
w.patch(308, "i", sp)
kvtext = b'mdlkeyvalue\n{\nprop_data\n{\n"base" "Wooden.Small"\n}\n}\n'
kv = w.raw(kvtext + b"\0")
w.patch(312, "ii", kv, len(kvtext))
w.patch(328, "fi", 12.5, 1)
inc = w.tell()
w.put("ii", 0, 0)
w.string(inc, inc, "anims")
w.string(inc + 4, inc, "models/test/anims.mdl")
hdr[336] = (1, inc)
if any(a["ani"] for a in m["anims"]):
an = w.raw(b"models/test/model.ani\0")
w.align()
blk = w.put("iiii", 0, 0, 64, len(anidata))
w.patch(348, "iii", an, 2, blk)
h2 = w.tell()
w.put("iiifii64i", 0, 0, 0, 0.0, 0, 0, *([0] * 64))
w.patch(400, "i", h2)
for off, (n, at) in hdr.items():
w.patch(off, "ii", n, at)
w.flush_strings()
w.patch(76, "i", len(w.b))
return bytes(w.b), bytes(anidata), atts, seqs
def write_vvd(m, rng, checksum):
verts = m["vertices"]
n = len(verts)
cuts = sorted(rng.sample(range(1, n), 3))
chunks = []
prev = 0
for c in cuts + [n]:
chunks.append((prev, c - prev))
prev = c
lods = [0, 1, 0, 1]
order = list(range(len(chunks)))[::-1]
filepos = {}
pos = 0
for ci in order:
filepos[ci] = pos
pos += chunks[ci][1]
counts = [sum(chunks[i][1] for i in range(len(chunks)) if lods[i] >= l) for l in range(2)] + [0] * 6
vdata, tdata = bytearray(), bytearray()
for ci in order:
s, c = chunks[ci]
for vv in verts[s:s + c]:
vdata += struct.pack("<3f3BB3f3f2f", *vv["w"], *vv["b"], vv["n"], *vv["pos"], *vv["nrm"], *vv["uv"])
tdata += struct.pack("<4f", *vv["tan"])
fix = b"".join(struct.pack("<3i", lods[i], filepos[i], chunks[i][1]) for i in range(len(chunks)))
off_fix = 64
off_v = off_fix + len(fix)
off_v += (16 - off_v % 16) % 16
off_t = off_v + len(vdata)
out = struct.pack("<4siii8iiiii", b"IDSV", 4, checksum, 2, *counts, len(chunks), off_fix, off_v, off_t)
out += fix
out += bytes(off_v - len(out))
return out + vdata + tdata, counts
def write_vtx(m, rng, checksum, ext):
w = Buf()
w.raw(bytes(36))
nlod = 2
parts = m["parts"]
bp = w.tell()
for p in parts:
w.put("ii", len(p["models"]), 0)
expect = {}
for pi, p in enumerate(parts):
pat = bp + pi * 8
mo = w.tell()
w.patch(pat + 4, "i", mo - pat)
for md in p["models"]:
w.put("ii", nlod, 0)
for mi, md in enumerate(p["models"]):
mat = mo + mi * 8
lo = w.tell()
w.patch(mat + 4, "i", lo - mat)
for l in range(nlod):
w.put("iif", len(md["meshes"]), 0, [0.0, 40.0][l])
for l in range(nlod):
la = lo + l * 12
me = w.tell()
w.patch(la + 4, "i", me - la)
for sm in md["meshes"]:
w.put("iiB", 0, 0, 0)
for k, sm in enumerate(md["meshes"]):
mea = me + k * 9
tris = sm["tris"] if l == 0 else sm["tris"][:max(1, len(sm["tris"]) // 2)]
# LOD 0 of the first mesh: two strip groups, the second one a tristrip
groups = []
if l == 0 and k == 0 and pi == 0 and mi == 0:
half = len(tris) // 2
groups.append(("list", tris[:half]))
strip = [tris[half][0], tris[half][1], tris[half][2]]
for t in tris[half + 1:half + 4]:
strip.append(t[0])
groups.append(("strip", strip))
groups.append(("list", tris[half + 4:]))
else:
groups.append(("list", tris))
decoded = []
sga = w.tell()
w.patch(mea, "ii", len(groups), sga - mea)
sgstride = 33 if ext else 25
w.raw(bytes(sgstride * len(groups)))
for gi, (kind, data) in enumerate(groups):
ids = data if kind == "strip" else [c for t in data for c in t]
uniq = []
for c in ids:
if c not in uniq:
uniq.append(c)
rng.shuffle(uniq)
local = [uniq.index(c) for c in ids]
if kind == "strip":
for i in range(len(ids) - 2):
a, b, c = ids[i], ids[i + 1], ids[i + 2]
if a != b and b != c and a != c:
decoded += [a, b, c] if i % 2 == 0 else [b, a, c]
else:
decoded += ids
ga = sga + gi * sgstride
vo = w.tell()
for c in uniq:
w.put("3BBH3b", 0, 1, 2, 1, c, 0, 0, 0)
io = w.tell()
w.put("%dH" % len(local), *local)
w.align()
so = w.tell()
stflags = 2 if kind == "strip" else 1
w.put("iiiihBii", len(local), 0, len(uniq), 0, 3, stflags, 0, 0)
if ext:
w.put("ii", 0, 0)
w.patch(ga, "iiiiiiB", len(uniq), vo - ga, len(local), io - ga, 1, so - ga, 0)
expect["%d_%d_%d_%d" % (pi, mi, l, k)] = decoded
rl = w.tell()
for l in range(nlod):
w.put("ii", 0, 0)
ra = w.tell()
w.put("hi", 1, 0)
w.patch(rl + 8, "ii", 1, ra - (rl + 8))
w.string(ra + 2, ra, "models/test/skin_b_lod1")
w.flush_strings()
w.patch(0, "iiHHiiiiii", 7, 24, 53, 9, 3, checksum, nlod, rl, len(parts), bp)
return bytes(w.b), expect
def write_phy(rng, checksum):
def ledge_bytes(points, tris):
hdr = 16
body = bytearray()
for t in tris:
body += struct.pack("<I", 0)
for c in t:
body += struct.pack("<I", c)
pts = b"".join(struct.pack("<4f", *p, 0.0) for p in points)
return struct.pack("<iiIhh", hdr + len(body), 0, 0, len(tris), 0) + bytes(body) + pts
leaves = []
soup = []
for k in range(2):
pts = [[f32(rng.uniform(-0.5, 0.5)) for _ in range(3)] for _ in range(4)]
tris = [(0, 1, 2), (0, 3, 1), (1, 3, 2), (2, 3, 0)]
leaves.append(ledge_bytes(pts, tris))
for t in tris:
for c in t:
x, y, z = pts[c]
soup += [x / 0.0254, z / 0.0254, -y / 0.0254]
surf = bytearray(bytes(48))
led_at = []
for lb in leaves:
led_at.append(len(surf))
surf += lb
root = len(surf)
surf += struct.pack("<ii3ff4B", 0, 0, 0.0, 0.0, 0.0, 1.0, 0, 0, 0, 0)
left = len(surf)
surf += struct.pack("<ii3ff4B", 0, led_at[0] - left, 0.0, 0.0, 0.0, 1.0, 0, 0, 0, 0)
right = len(surf)
surf += struct.pack("<ii3ff4B", 0, led_at[1] - right, 0.0, 0.0, 0.0, 1.0, 0, 0, 0, 0)
struct.pack_into("<ii", surf, root, right - root, 0)
struct.pack_into("<3f3ffIi3i", surf, 0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, len(surf), root, 0, 0, 0)
surf[44:48] = b"IVPS"
solid = b"VPHY" + struct.pack("<HHi3fi", 0x100, 0, len(surf), 1.0, 1.0, 1.0, 0) + bytes(surf)
text = 'solid {\n"index" "0"\n"name" "root"\n"mass" "12.500000"\n"surfaceprop" "wood"\n}\neditparams {\n"rootname" ""\n"totalmass" "12.500000"\n}\n'
out = struct.pack("<iiii", 16, 0, 1, checksum) + struct.pack("<i", len(solid)) + solid + text.encode() + b"\0"
return out, soup, text
def srctools_view(ctx, tmp):
code = r'''
import json
from srctools.filesys import RawFileSystem
from srctools.mdl import Model
from srctools.vmt import Material
fs = RawFileSystem(%r)
m = Model(fs, fs["models/test/model.mdl"])
out = {
"name": m.name, "version": m.version, "cdmaterials": m.cdmaterials, "skins": m.skins, "surfaceprop": m.surfaceprop,
"keyvalues": m.keyvalues, "mass": m.mass, "total_verts": m.total_verts,
"eye": list(m.eye_pos), "hull": [list(m.hull_min), list(m.hull_max)],
"included": [[i.label, i.filename] for i in m.included_models],
"sequences": [{"label": s.label, "act": s.act_name, "flags": s.flags, "weight": s.act_weight, "bbox": [list(s.bbox_min), list(s.bbox_max)],
"events": [[e.cycle, e.options] for e in s.events], "keyvalues": s.keyvalues} for s in m.sequences],
"phys_mass": m.phys_keyvalues.find_key("solid").float("mass"),
"textures": sorted(m.iter_textures()),
}
mats = {}
for path in out["textures"]:
with fs[path].open_str() as f:
mat = Material.parse(f, path).apply_patches(fs)
mats[path] = {"shader": mat.shader, "basetexture": mat.get("$basetexture", ""), "bumpmap": mat.get("$bumpmap", ""), "translucent": mat.get("$translucent", "")}
out["materials"] = mats
print(json.dumps(out))
''' % tmp
return json.loads(ctx.python(["srctools"], code))
VMTS = {
"materials/models/test/skin_a.vmt": '"VertexLitGeneric"\n{\n\t"$basetexture" "models/test/skin_a"\n\t"$bumpmap" "models/test/skin_a_normal"\n}\n',
"materials/models/alt/skin_b.vmt": '// comment\nVertexLitGeneric\n{\n\t$basetexture "models\\alt\\skin_b"\n\t$translucent 1\n\t"Proxies" { "Sine" { "resultVar" "$alpha" } }\n}\n',
"materials/models/shared/metal.vmt": '"LightmappedGeneric"\n{\n\t"$baseTexture" "metal/plate01"\n\t"$alphatest" "1"\n\t"$nocull" "1"\n}\n',
"materials/models/test/skin_c.vmt": '"patch"\n{\n\t"include" "materials/models/test/skin_a.vmt"\n\t"replace"\n\t{\n\t\t"$basetexture" "models/test/skin_c"\n\t}\n}\n',
}
def case(ctx, rng, version):
m = make(rng, version)
checksum = rng.randrange(1 << 31)
mdl, ani, atts, seqs = write_mdl(m, rng, checksum)
vvd, lodcounts = write_vvd(m, rng, checksum)
vtx, tris = write_vtx(m, rng, checksum, m["ext"])
phy, soup, phytext = write_phy(rng, checksum)
tmp = tempfile.mkdtemp(prefix="rosetta-sourcemdl-")
try:
os.makedirs(os.path.join(tmp, "models", "test"))
for name, data in (("model.mdl", mdl), ("model.vvd", vvd), ("model.dx90.vtx", vtx), ("model.phy", phy)):
with open(os.path.join(tmp, "models", "test", name), "wb") as f:
f.write(data)
for path, text in VMTS.items():
os.makedirs(os.path.dirname(os.path.join(tmp, path)), exist_ok=True)
with open(os.path.join(tmp, path), "w") as f:
f.write(text)
st = srctools_view(ctx, tmp)
finally:
shutil.rmtree(tmp)
expect_parts = []
for pi, p in enumerate(m["parts"]):
models = []
for mi, md in enumerate(p["models"]):
meshes = []
for k, sm in enumerate(md["meshes"]):
vs = m["vertices"][md["start"] + sm["off"]:md["start"] + sm["off"] + sm["nv"]]
lods = []
for l in range(2):
t = tris["%d_%d_%d_%d" % (pi, mi, l, k)]
rev = []
for i in range(0, len(t) - 2, 3):
rev += [t[i + 2], t[i + 1], t[i]]
lods.append(rev)
fam = m["families"][0]
targets = {}
for f in sm["flexes"]:
for vv in f["verts"]:
for side in ((0, 1) if f["partner"] else (0,)):
wgt = 1 if not f["partner"] else (vv["side"] / 255 if side == 0 else 1 - vv["side"] / 255)
d = f["desc"] if side == 0 else f["partner"]
t = targets.setdefault(str(d), {})
cur = t.setdefault(str(vv["index"]), [0.0] * 6)
for c in range(6):
cur[c] = f32(cur[c] + vv["val"][c] * wgt)
meshes.append({
"positions": [c for v in vs for c in v["pos"]], "normals": [c for v in vs for c in v["nrm"]], "uvs": [c for v in vs for c in v["uv"]],
"tangents": [c for v in vs for c in v["tan"]],
"weights": [c for v in vs for c in v["w"] + [0.0]], "joints": [c if k2 < v["n"] else 0 for v in vs for k2, c in enumerate(v["b"] + [0])],
"lods": lods, "material": fam[sm["material"]] + 1, "skinRef": sm["material"], "targets": targets,
})
models.append({"name": md["name"], "meshes": meshes})
expect_parts.append({"name": p["name"], "models": models})
anims = []
for a in m["anims"]:
anims.append({"name": a["seq"], "frames": a["frames"], "fps": a["fps"], "delta": a["delta"],
"bones": {str(bi + 1): e for bi, e in a["expect"].items()}})
bones = [{"name": b["name"], "parent": b["parent"], "pos": b["pos"], "quat": b["quat"], "poseToBone": b["poseToBone"]} for b in m["bones"]]
files = {"model.vvd": vvd, "model.dx90.vtx": vtx, "model.phy": phy}
if ani and len(ani) > 64:
files["model.ani"] = ani
for path, text in VMTS.items():
files[path] = text
return {
"version": version, "mdl": mdl, "files": files, "srctools": st,
"expect": {"parts": expect_parts, "bones": bones, "anims": anims, "attachments": atts, "sequences": seqs, "physics": soup,
"flexdescs": m["flexdescs"], "lodCounts": lodcounts[:2], "checksum": checksum, "fixed": m["fixed"]},
}
def generate(ctx):
rng = ctx.rng(4449)
ctx.emit("sourcemdl", {"cases": [case(ctx, rng, v) for v in (44, 48, 49)]})