From 80fd9cf1e836938650431e3568d2fefcd9938fca Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 18:49:39 -0600 Subject: [PATCH] model/sourcemdl: .vmt materials through codecs/text/KeyValues (cdmaterials search, patch include / insert / replace, $basetexture / $bumpmap as .vtf references), docs/guide scene section --- docs/guide/scene.md | 44 ++++++ src/Rosetta/Registry.luau | 2 +- src/Rosetta/model/sourcemdl/Material.luau | 163 ++++++++++++++++++++++ src/Rosetta/model/sourcemdl/init.luau | 13 +- tests/model/sourcemdl.luau | 36 ++++- tools/fixtures/docs_sourcemdl.py | 29 ++++ 6 files changed, 280 insertions(+), 7 deletions(-) create mode 100644 src/Rosetta/model/sourcemdl/Material.luau create mode 100644 tools/fixtures/docs_sourcemdl.py diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 40c3d7b..ed04aef 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -507,6 +507,49 @@ local again = assert(F.save(barney, nil, { format = "smd" })) -- SMD writes ba assert(F.model.load(again).skins[1]) ``` +## Source engine models (MDL v44-49) + +`sourcemdl` reads Source studio models (Half-Life 2 to CS:GO-era v44-49; GoldSrc v10 stays `mdl`). The geometry is +in sibling files found through `files` / `resolve` (or `vvd` / `vtx` / `phy` / `ani` buffers): `.vvd` +vertices, `.dx90.vtx` (else `.dx80` / `.sw` / `.vtx`) strips, optional `.phy` collision and the `.ani` +animation blocks; `` is the stem of `opts.name`, else of the name stored in the MDL. Without them the Scene has +the skeleton and the animations only (`meta.source.warnings` says what was missing). + +- Bones become a skin (`poseToBone` as the inverse bind matrices); procedural bones (jiggle, aim-at, ...) are data in + the joint nodes' `extras.procedural`. +- Each body part model is a mesh (one primitive per studio mesh); `bodies` picks the model per body part for the + nodes (default 1), the others are in `scene.meshes` and `meta.source.bodyParts`. `lod` picks the LOD of + `prim.indices`; every LOD's indices are in `prim.extras.lods`. +- Flexes are morph targets (stereo flexes split by side), named in `mesh.extras.targetNames`; attachments are nodes + under their bones; hitboxes, sequences (activities, events, blends), pose parameters and flex rules are in + `meta.source`. +- Each animation (decoded from the run-length / Quaternion48 / 64 data, sections and `.ani` blocks; delta + animations added to the rest pose) is named after the first sequence that plays it. +- Materials: each texture name is looked up as `materials/.vmt`; `$basetexture` / `$bumpmap` + become `.vtf` texture URIs (`F.model.loadTextures` with a `resolve` for the game's files decodes them), + `$translucent` / `$alphatest` / `$nocull` / `$color` map to the material, and every parameter is kept in + `material.extras.vmt`. + +```luau +local files = { + ["model.vvd"] = sourceVvdBytes, + ["model.dx90.vtx"] = sourceVtxBytes, + ["model.phy"] = sourcePhyBytes, + ["materials/models/test/skin_a.vmt"] = skinVmtText, +} +local model = assert(F.model.load(sourceMdlBytes, { name = "model.mdl", files = files })) +local src = model.meta.source +assert(src.format == "sourcemdl" and src.version == 49 and model.meta.up == "z") +assert(#model.skins[1].joints == 6) +local body = model.meshes[src.bodyParts[1].models[1].mesh] +assert(#body.primitives == 2 and body.extras.targetNames[1] == "AU1L") +assert(#body.primitives[1].extras.lods == 2) +assert(model.animations[1].name == "idle" and src.sequences[1].activity == "ACT_IDLE") +local skinA = model.materials[1] +assert(model.textures[skinA.baseColorTexture.texture].uri == "materials/models/test/skin_a.vtf") +assert(#src.physics.solids[1].hulls == 2) +``` + ## Blitz3D (B3D) `.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS; @@ -745,6 +788,7 @@ assert(back.meshes[1].primitives[1].indices.count == 3) | X3D (XML / classic) | yes | yes | the VRML reader plus the X3D triangle / quad / line sets; no binary `.x3db` | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | | MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | +| Source MDL (v44-49) + VVD / VTX / PHY | yes | - | skeleton, body parts, LODs, flexes, animations, VMT materials: see above | | SMD | yes | yes | Valve studiomdl data | | Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) | | Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) | diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index a39fa2e..f150157 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -1016,7 +1016,7 @@ local list: { Entry } = { path = "model/sourcemdl", extensions = { "mdl" }, mime = { "model/x-source-mdl" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Half", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Half", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim", "codecs/text/KeyValues" }, caps = { decode = true, encode = false, skins = true, morph = true, animation = true, lods = true }, load = function() return require("@rosetta/model/sourcemdl") diff --git a/src/Rosetta/model/sourcemdl/Material.luau b/src/Rosetta/model/sourcemdl/Material.luau new file mode 100644 index 0000000..c0d9795 --- /dev/null +++ b/src/Rosetta/model/sourcemdl/Material.luau @@ -0,0 +1,163 @@ +--!strict +-- model/sourcemdl/Material: the MDL's texture names through $cdmaterials to materials/.vmt (the engine's +-- search order, then the bare name), parsed with codecs/text/KeyValues; "patch" materials (include + insert / +-- replace) applied. $basetexture / $bumpmap ($normalmap) become .vtf texture references for F.model.loadTextures; +-- $translucent / $alphatest / $nocull / $color map to the PBR fields, every parameter is kept in extras.vmt. +local Types = require("@rosetta/Types") +local Input = require("@rosetta/core/Input") +local KeyValues = require("@rosetta/codecs/text/KeyValues") + +local Material = {} + +local function dir(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 + +local function path(s: string): string + local p = string.gsub(string.gsub(s, "\\", "/"), "^/+", "") + return (string.gsub(p, "%.[vV][mMtT][tTfF]$", "")) +end + +local function load(opts: any, uri: string): (string, KeyValues.Block?) + local b = Input.sibling(opts, uri) or Input.sibling(opts, string.lower(uri)) + if not b then + return uri, nil + end + local kv = KeyValues.parse(b, { escapes = false, resolve = function(name: string): (buffer | string)? + return Input.sibling(opts, name) + end }) + return uri, kv +end + +-- { shader, params (lower-case keys) } of a parsed .vmt, patch includes applied (depth 8) +local function flatten(opts: any, kv: KeyValues.Block, depth: number): (string?, { [string]: any }) + local first = kv[1] + if not first or type(first.value) ~= "table" then + return nil, {} + end + local shader, body = first.key, first.value :: KeyValues.Block + local params: { [string]: any } = {} + if string.lower(shader) == "patch" and depth < 8 then + local inc = KeyValues.get(body, "include") + local base: KeyValues.Block? = nil + if type(inc) == "string" then + local _, b = load(opts, path(inc) .. ".vmt") + base = b + end + if base then + shader, params = flatten(opts, base, depth + 1) + end + for _, p in body do + local k = string.lower(p.key) + if (k == "insert" or k == "replace") and type(p.value) == "table" then + for _, q in p.value :: KeyValues.Block do + local qk = string.lower(q.key) + if k == "insert" or params[qk] ~= nil then + params[qk] = if q.value == "" then nil else q.value + end + end + end + end + return shader, params + end + for _, p in body do + params[string.lower(p.key)] = p.value + end + return shader, params +end + +local function num(v: any): number? + return if type(v) == "number" then v elseif type(v) == "string" then tonumber(v) else nil +end + +local function color(v: any): { number }? + if type(v) ~= "string" then + return nil + end + local r, g, b = string.match(v, "^%s*[%[{]%s*([%d.eE+-]+)%s+([%d.eE+-]+)%s+([%d.eE+-]+)") + if not r then + return nil + end + local scale = if string.match(v, "^%s*{") then 1 / 255 else 1 + return { (tonumber(r) :: number) * scale, (tonumber(g) :: number) * scale, (tonumber(b) :: number) * scale } +end + +function Material.apply(scene: Types.Scene, textures: { { name: string } }, cdmaterials: { string }, opts: any?, warnings: { string }) + if type(opts) ~= "table" or (opts.files == nil and opts.resolve == nil) then + return + end + local dirs: { string } = {} + for _, d in cdmaterials do + local nd = dir(d) + if not table.find(dirs, nd) then + table.insert(dirs, nd) + end + end + if not table.find(dirs, "") then + table.insert(dirs, "") + end + local texIndex: { [string]: number } = {} + local function texture(v: any): number? + if type(v) ~= "string" or v == "" then + return nil + end + local uri = "materials/" .. path(v) .. ".vtf" + local i = texIndex[string.lower(uri)] + if not i then + table.insert(scene.textures, { name = path(v), uri = uri, mime = "image/x-vtf" }) + i = #scene.textures + texIndex[string.lower(uri)] = i + end + return i + end + for i, t in textures do + local mat = scene.materials[i] + local name = path(t.name) + local found, kv = nil, nil + for _, d in dirs do + local uri, b = load(opts, "materials/" .. d .. name .. ".vmt") + if b then + found, kv = uri, b + break + end + end + if not kv then + table.insert(warnings, "material " .. t.name .. ": no .vmt") + continue + end + local shader, p = flatten(opts, kv, 0) + local ex: { [string]: any } = mat.extras or {} + mat.extras = ex + ex.vmt = { path = found, shader = shader, params = p } + local base = texture(p["$basetexture"]) + if base then + mat.baseColorTexture = { texture = base } + end + local bump = texture(p["$bumpmap"] or p["$normalmap"]) + if bump then + mat.normalTexture = { texture = bump } + end + local c = color(p["$color2"]) or color(p["$color"]) + if c then + mat.baseColor = { c[1], c[2], c[3], num(p["$alpha"]) or 1 } + elseif num(p["$alpha"]) then + mat.baseColor[4] = num(p["$alpha"]) :: number + end + if num(p["$translucent"]) == 1 then + mat.alphaMode = "blend" + elseif num(p["$alphatest"]) == 1 then + mat.alphaMode = "mask" + mat.alphaCutoff = num(p["$alphatestreference"]) or 0.5 + end + if num(p["$nocull"]) == 1 then + mat.doubleSided = true + end + end +end + +return Material diff --git a/src/Rosetta/model/sourcemdl/init.luau b/src/Rosetta/model/sourcemdl/init.luau index c9319fc..ecf91a1 100644 --- a/src/Rosetta/model/sourcemdl/init.luau +++ b/src/Rosetta/model/sourcemdl/init.luau @@ -1,8 +1,6 @@ --!strict --- model/sourcemdl: Source engine studio models ("IDST" v44-49) with their .vvd vertices (LOD fixups), .vtx strips --- (.dx90 / .dx80 / .sw), optional .phy collision and .ani animation blocks, all through opts.resolve / opts.files. --- Skeleton, procedural bones, skin families, body parts, LODs, flexes, attachments, hitboxes, sequences and --- animations; layouts from Source SDK 2013 studio.h / optimize.h, cross-checked with srctools and SourceIO (both MIT). +-- model/sourcemdl: Source engine studio models ("IDST" v44-49) with .vvd / .vtx (.dx90 / .dx80 / .sw) and optional .phy / +-- .ani / .vmt through opts.resolve / opts.files; Source SDK 2013 studio.h / optimize.h layouts, checked with srctools. -- Not supported: v52+ frame animations, IK rules, movement, eyeball shading, $includemodel animations. -- ------------------------------------------------------------------------------------------------ requires @@ -15,6 +13,7 @@ local Vvd = require("@rosetta/model/sourcemdl/Vvd") local Vtx = require("@rosetta/model/sourcemdl/Vtx") local Phy = require("@rosetta/model/sourcemdl/Phy") local Build = require("@rosetta/model/sourcemdl/Build") +local Material = require("@rosetta/model/sourcemdl/Material") -- ------------------------------------------------------------------------------------------------ contract local SourceMdl = { @@ -22,7 +21,7 @@ local SourceMdl = { category = "model", extensions = { "mdl" }, mime = { "model/x-source-mdl" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Half", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Half", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim", "codecs/text/KeyValues" }, caps = { decode = true, encode = false, skins = true, morph = true, animation = true, lods = true }, } @@ -39,6 +38,7 @@ export type DecodeOptions = { lod: number?, -- 1-based LOD for the primitive indices, default 1 animations: boolean?, -- default true physics: boolean?, -- default true: read the .phy + materials: boolean?, -- default true: resolve materials/.vmt maxVertices: number?, -- default 2^24 maxFrames: number?, -- per animation, default 65536 } @@ -158,6 +158,9 @@ function SourceMdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, if not scene then return nil, Err.from(berr) end + if not (opts and opts.materials == false) then + Material.apply(scene, h.textures, h.cdmaterials, opts, warnings) + end local src = scene.meta.source :: { [string]: any } src.vtx = vtxName return scene, nil diff --git a/tests/model/sourcemdl.luau b/tests/model/sourcemdl.luau index e6f23a2..5ce8322 100644 --- a/tests/model/sourcemdl.luau +++ b/tests/model/sourcemdl.luau @@ -110,6 +110,40 @@ for _, c in Fx.cases do 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)") + -- materials: the .vmt srctools finds through cdmaterials, its $basetexture / $bumpmap + local seen = 0 + for _, vmt in st.textures do + local mat + for _, m in s.materials do + if m.extras and m.extras.vmt and m.extras.vmt.path == vmt then + mat = m + end + end + t:check(mat, tag .. vmt .. ": resolved as srctools") + if mat then + seen += 1 + local want = st.materials[vmt] + t:eq(mat.extras.vmt.shader, want.shader, tag .. vmt .. ": shader (srctools)") + local base = string.gsub(want.basetexture, "\\", "/") + t:eq(s.textures[mat.baseColorTexture.texture].uri, "materials/" .. base .. ".vtf", tag .. vmt .. ": $basetexture (srctools)") + if want.bumpmap ~= "" then + t:eq(s.textures[mat.normalTexture.texture].uri, "materials/" .. want.bumpmap .. ".vtf", tag .. vmt .. ": $bumpmap (srctools)") + else + t:check(mat.normalTexture == nil, tag .. vmt .. ": no bumpmap") + end + t:eq(mat.alphaMode, if want.translucent == "1" then "blend" elseif string.find(vmt, "metal") then "mask" else "opaque", tag .. vmt .. ": alpha mode") + t:eq(mat.doubleSided, string.find(vmt, "metal") ~= nil, tag .. vmt .. ": $nocull") + end + end + t:eq(seen, #s.materials, tag .. "every texture has its .vmt") + if c.version == 49 then + local Vtf = require("@tests/gen/vtf") + local loaded, errs = F.model.loadTextures(s, { resolve = function(uri: string): string? + return if string.sub(uri, -4) == ".vtf" then Vtf[1].data else nil + end }) + t:check(next(errs) == nil and loaded.textures[1].image and loaded.textures[1].image.width > 0, tag .. "F.model.loadTextures decodes the .vtf references") + end + -- skeleton local skin = s.skins[1] t:eq(#skin.joints, #e.bones, tag .. "joints") @@ -262,7 +296,7 @@ for _, c in Fx.cases do 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 + for _, name in { "model.vvd", "model.dx90.vtx", "model.phy", "materials/models/test/skin_c.vmt" } do t:fuzz(tag .. name, function(b: buffer) local files = table.clone(c.files) files[name] = buffer.tostring(b) diff --git a/tools/fixtures/docs_sourcemdl.py b/tools/fixtures/docs_sourcemdl.py new file mode 100644 index 0000000..7984691 --- /dev/null +++ b/tools/fixtures/docs_sourcemdl.py @@ -0,0 +1,29 @@ +# Docs inputs for the Source models section of docs/guide/scene.md (tools/fixtures.py; tools/docs_check.py explains +# the inputs): a v49 model with its .vvd / .dx90.vtx / .phy and a .vmt, from tools/fixtures/sourcemdl.py's writer. +# tests/gen/docs_sourcemdl.luau { files = { [name] = bytes }, vars = { sourceMdlBytes = "model.mdl", ... } } +import importlib.util, os + +INPUTS = ["tools/docs_check.py", "tools/fixtures/sourcemdl.py"] + + +def load(ctx, rel, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, rel)) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + check = load(ctx, "tools/docs_check.py", "docs_check") + smdl = load(ctx, "tools/fixtures/sourcemdl.py", "fx_sourcemdl") + rng = ctx.rng(49) + m = smdl.make(rng, 49) + checksum = rng.randrange(1 << 31) + mdl, _, _, _ = smdl.write_mdl(m, rng, checksum) + vvd, _ = smdl.write_vvd(m, rng, checksum) + vtx, _ = smdl.write_vtx(m, rng, checksum, True) + phy, _, _ = smdl.write_phy(rng, checksum) + vmt = "materials/models/test/skin_a.vmt" + files = {"model.mdl": mdl, "model.vvd": vvd, "model.dx90.vtx": vtx, "model.phy": phy, vmt: smdl.VMTS[vmt].encode()} + check.emit_inputs(ctx, files, {"sourceMdlBytes": "model.mdl", "sourceVvdBytes": "model.vvd", "sourceVtxBytes": "model.dx90.vtx", + "sourcePhyBytes": "model.phy", "skinVmtText": vmt})