From 4c74171631c6225d3b4eb7168432c9a11d877746 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:04:40 -0500 Subject: [PATCH] ws-3d3: model/pmx: MikuMikuDance PMX 2.0 / 2.1 and PMD 1.0 reader (weights, materials, bones + skin, vertex morphs -> targets, other morphs / physics in extras); tests against assimp and synthetic models --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/pmx/Build.luau | 307 +++++++++++++++++++++++ src/Formats/model/pmx/Pmd.luau | 339 +++++++++++++++++++++++++ src/Formats/model/pmx/Read.luau | 411 +++++++++++++++++++++++++++++++ src/Formats/model/pmx/init.luau | 77 ++++++ tests/model/pmx.luau | 263 ++++++++++++++++++++ tools/fixtures/_pmx_writer.py | 265 ++++++++++++++++++++ tools/fixtures/pmx.py | 77 ++++++ 9 files changed, 1752 insertions(+) create mode 100644 src/Formats/model/pmx/Build.luau create mode 100644 src/Formats/model/pmx/Pmd.luau create mode 100644 src/Formats/model/pmx/Read.luau create mode 100644 src/Formats/model/pmx/init.luau create mode 100644 tests/model/pmx.luau create mode 100644 tools/fixtures/_pmx_writer.py create mode 100644 tools/fixtures/pmx.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..f3846c1 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -41,6 +41,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | +| model | pmx | .pmx .pmd | yes | - | materials: true, skins: true, morphTargets: true, pmd: true | `tests/model/pmx.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` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..a414daf 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -446,6 +446,18 @@ local list: { Entry } = { return require("@formats/model/ply") end, }, + { + name = "pmx", + category = "model", + path = "model/pmx", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, + load = function() + return require("@formats/model/pmx") + end, + }, { name = "stl", category = "model", diff --git a/src/Formats/model/pmx/Build.luau b/src/Formats/model/pmx/Build.luau new file mode 100644 index 0000000..213cfd9 --- /dev/null +++ b/src/Formats/model/pmx/Build.luau @@ -0,0 +1,307 @@ +--!strict +-- model/pmx/Build: the parsed PMX / PMD model (model/pmx/Read, model/pmx/Pmd) to a Scene. MMD is left-handed (y up, +-- x right, z forward), so positions / normals / bone positions get z negated and every triangle its winding reversed +-- (glTF's right-handed, counter-clockwise front faces); UVs are already top-left. One primitive per material, with +-- the material's vertices only (JOINTS_0 / WEIGHTS_0, the additional UVs as _UVA1.._UVA4 vec4, SDEF C / R0 / R1 as +-- _SDEF_C / _SDEF_R0 / _SDEF_R1 and the deform type as _DEFORM when a vertex uses SDEF / QDEF, _EDGE_SCALE); vertex +-- morphs become morph targets (POSITION deltas, names in mesh.extras.targetNames); bones become nodes (a parent-relative +-- translation each) and one skin with translation-only inverse bind matrices. +local Types = require("@formats/Types") + +local Build = {} + +local readf32, writef32, readi32, readu32 = buffer.readf32, buffer.writef32, buffer.readi32, buffer.readu32 +local S = Types.Scene + +local SPHERE = { [0] = "off", "multiply", "add", "subtexture" } +local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +-- fetch(uri) -> buffer?: opts.files (by the name as written, with "/" separators, or the base name) / opts.resolve +local function fetcher(opts: any): (string) -> buffer? + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + local slash = string.gsub(uri, "\\", "/") + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[slash] or opts.files[string.match(slash, "([^/]+)$") or slash] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, slash) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +local function lh(v: { number }?): { number }? + return if v then { v[1], v[2], -v[3] } else nil +end + +-- the scene index of a file texture index (0-based, -1 = none) +local function texIndex(m: any, i: number?): number? + return if type(i) == "number" and i >= 0 and i < #m.textures then i + 1 else nil +end + +local function material(m: any, mat: any): Types.Material + local out = S.material(mat.name) + local d = mat.diffuse + out.baseColor = { d[1], d[2], d[3], d[4] } + out.metallic = 0 + out.roughness = math.clamp(math.sqrt(2 / (math.max(mat.power or 0, 0) + 2)), 0, 1) + out.doubleSided = bit32.btest(mat.flags, 0x01) + if d[4] < 1 then + out.alphaMode = "blend" + end + local t = texIndex(m, mat.texture) + if t then + out.baseColorTexture = { texture = t } + end + local x: { [string]: any } = { + nameEn = mat.nameEn, diffuse = d, specular = mat.specular, specularPower = mat.power, ambient = mat.ambient, + flags = mat.flags, edge = bit32.btest(mat.flags, 0x10), edgeColor = mat.edgeColor, edgeSize = mat.edgeSize, + sphereTexture = texIndex(m, mat.sphere), sphereMode = SPHERE[mat.sphereMode] or mat.sphereMode, + toonTexture = texIndex(m, mat.toon), memo = mat.memo, indexCount = mat.count, + } + if mat.toonShared then + x.toonShared = mat.toonShared + x.toonFile = string.format("toon%02d.bmp", mat.toonShared + 1) + end + out.extras = { pmx = x } + return out +end + +-- bone parents that form a tree: an invalid index, the bone itself or a cycle makes a root +local function parents(bones: { any }): { number } + local nb = #bones + local par = table.create(nb, 0) + for i, b in bones do + local p = b.parent + if type(p) == "number" and p >= 0 and p < nb and p + 1 ~= i then + par[i] = p + 1 + end + end + for i = 1, nb do + local seen, j, steps = {}, i, 0 + while par[j] ~= 0 and steps <= nb do + seen[j] = true + j = par[j] + steps += 1 + if seen[j] then + par[i] = 0 + break + end + end + end + return par +end + +-- the primitive of one material: indices [first, first + n) of the face list, its vertices renumbered +local function primitive(m: any, first: number, n: number, morphs: { any }, sdef: boolean): Types.Primitive + local map: { [number]: number } = {} + local verts: { number } = {} + local ind = S.accessor(nil, "u32", 1, n) + for t = 0, n // 3 - 1 do + -- reversed winding: a, c, b + for c = 0, 2 do + local src = readu32(m.indices, (first + t * 3 + c) * 4) + local v = map[src] + if not v then + v = #verts + verts[v + 1] = src + map[src] = v + end + buffer.writeu32(ind.data, (t * 3 + (if c == 0 then 0 elseif c == 1 then 2 else 1)) * 4, v) + end + end + local nv = #verts + local nb = #m.bones + local pos, nrm, uv = S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 2, nv) + local jo, we = S.accessor(nil, "u16", 4, nv), S.accessor(nil, "f32", 4, nv) + local edge = S.accessor(nil, "f32", 1, nv) + local attrs: { [string]: Types.Accessor } = { POSITION = pos, NORMAL = nrm, TEXCOORD_0 = uv, _EDGE_SCALE = edge } + if nb > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = jo, we + end + local uvas = {} + for a = 1, #m.uva do + uvas[a] = S.accessor(nil, "f32", 4, nv) + attrs["_UVA" .. a] = uvas[a] + end + local sd: { Types.Accessor }? = nil + local deform: Types.Accessor? = nil + if sdef then + sd = { S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv) } + attrs._SDEF_C, attrs._SDEF_R0, attrs._SDEF_R1 = sd[1], sd[2], sd[3] + deform = S.accessor(nil, "u8", 1, nv) + attrs._DEFORM = deform + end + for v = 0, nv - 1 do + local src = verts[v + 1] + for c = 0, 2 do + local sgn = if c == 2 then -1 else 1 + writef32(pos.data, (v * 3 + c) * 4, sgn * readf32(m.positions, (src * 3 + c) * 4)) + writef32(nrm.data, (v * 3 + c) * 4, sgn * readf32(m.normals, (src * 3 + c) * 4)) + end + buffer.copy(uv.data, v * 8, m.uvs, src * 8, 8) + buffer.copy(edge.data, v * 4, m.edge, src * 4, 4) + for a, acc in uvas do + buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16) + end + -- weights: invalid bones get weight 0, the rest is normalized + local sum = 0 + local js, ws = table.create(4, 0), table.create(4, 0) + for c = 0, 3 do + local j = readi32(m.joints, src * 16 + c * 4) + local w = readf32(m.weights, src * 16 + c * 4) + if j >= 0 and j < nb and w > 0 and w == w then + js[c + 1], ws[c + 1] = j, w + sum += w + end + end + for c = 0, 3 do + buffer.writeu16(jo.data, (v * 4 + c) * 2, js[c + 1]) + writef32(we.data, (v * 4 + c) * 4, if sum > 0 then ws[c + 1] / sum else (if c == 0 then 1 else 0)) + end + if sd and deform then + buffer.writeu8(deform.data, v, buffer.readu8(m.deform, src)) + if m.sdef then + for q = 0, 2 do + for c = 0, 2 do + local x = readf32(m.sdef, src * 36 + q * 12 + c * 4) + writef32(sd[q + 1].data, (v * 3 + c) * 4, if c == 2 then -x else x) + end + end + end + end + end + local prim: Types.Primitive = { attributes = attrs, indices = ind, mode = "triangles" } + if #morphs > 0 then + local targets: { { [string]: Types.Accessor } } = {} + for k, mo in morphs do + local d = S.accessor(nil, "f32", 3, nv) + for o, src in mo.vertices do + local v = map[src] + if v then + for c = 0, 2 do + local x = readf32(mo.deltas, ((o - 1) * 3 + c) * 4) + writef32(d.data, (v * 3 + c) * 4, if c == 2 then -x else x) + end + end + end + targets[k] = { POSITION = d } + end + prim.targets = targets + end + return prim +end + +function Build.scene(m: any, opts: any): (any, ...any) + local scene = S.new() + scene.meta.up = "y" + local fetch = fetcher(opts) + for i, path in m.textures do + local uri = string.gsub(path, "\\", "/") + local tex: Types.Texture = { name = path, uri = uri } + local data = fetch(path) + if data then + tex.data = data + end + local ext = string.match(uri, "%.(%w+)$") + tex.mime = if ext then MIME[string.lower(ext)] else nil + scene.textures[i] = tex + end + for i, mat in m.materials do + scene.materials[i] = material(m, mat) + end + + -- vertex morphs -> targets (others stay in mesh.extras.pmx.morphs) + local vmorphs, names, others = {}, {}, {} + local wantMorphs = not (opts and opts.morphs == false) + for _, mo in m.morphs do + if mo.type == 1 and wantMorphs then + table.insert(vmorphs, mo) + table.insert(names, mo.name) + elseif mo.type ~= 1 then + table.insert(others, { name = mo.name, nameEn = mo.nameEn, panel = mo.panel, type = MORPH[mo.type] or mo.type, offsets = mo.offsets }) + end + end + local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 28 + if #vmorphs * m.vertexCount * 12 > maxBytes then + return nil, string.format("limit: %d vertex morphs on %d vertices (maxBytes; morphs = false skips them)", #vmorphs, m.vertexCount), "limit" + end + local sdef = false + for v = 0, m.vertexCount - 1 do + local k = buffer.readu8(m.deform, v) + if k == 3 or k == 4 then + sdef = true + break + end + end + local mesh: Types.Mesh = { name = m.name, primitives = {} } + local first = 0 + for i, mat in m.materials do + local n = mat.count + if type(n) ~= "number" or n < 0 or n % 3 ~= 0 or first + n > m.indexCount then + return nil, string.format("material %d: %s face indices past the face list", i, tostring(n)) + end + local prim = primitive(m, first, n, vmorphs, sdef) + prim.material = i + table.insert(mesh.primitives, prim) + first += n + end + if first < m.indexCount then + -- faces no material covers + table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef)) + end + mesh.extras = { targetNames = if #names > 0 then names else nil, pmx = if #others > 0 then { morphs = others } else nil } + if #vmorphs > 0 then + mesh.weights = table.create(#vmorphs, 0) + end + scene.meshes[1] = mesh + + -- nodes: 1 = the model, 2 = the mesh, then one per bone + scene.nodes[1] = { name = m.name, children = { 2 } } + scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + local bones = m.bones + local nb = #bones + if nb > 0 then + local par = parents(bones) + local world: { { number } } = {} + for i, b in bones do + world[i] = lh(b.pos) or { 0, 0, 0 } + end + local ibm = S.accessor(nil, "f32", 16, nb) + ibm.matrix = true + local joints: { number } = {} + for i, b in bones do + local w, p = world[i], par[i] + local t = if p ~= 0 then { w[1] - world[p][1], w[2] - world[p][2], w[3] - world[p][3] } else { w[1], w[2], w[3] } + local x: { [string]: any } = { nameEn = b.nameEn, index = i - 1, layer = b.layer, flags = b.flags, position = b.pos } + x.tail, x.inherit, x.axis, x.localX, x.localZ, x.externalKey, x.ik = b.tail, b.inherit, b.axis, b.localX, b.localZ, b.externalKey, b.ik + scene.nodes[2 + i] = { name = b.name, children = {}, translation = t, extras = { pmx = x } } + joints[i] = 2 + i + for c = 0, 15 do + local val = if c % 5 == 0 then 1 elseif c >= 12 and c <= 14 then -w[c - 11] else 0 + writef32(ibm.data, ((i - 1) * 16 + c) * 4, val) + end + end + for i = 1, nb do + local p = par[i] + table.insert(scene.nodes[if p ~= 0 then 2 + p else 1].children, 2 + i) + end + scene.skins[1] = { name = m.name, joints = joints, inverseBindMatrices = ibm } + scene.nodes[2].skin = 1 + end + scene.meta.source = { + format = "pmx", version = m.version, encoding = m.encoding, name = m.name, nameEn = m.nameEn, comment = m.comment, + commentEn = m.commentEn, additionalUV = #m.uva, displayFrames = m.frames, rigidBodies = m.rigidBodies, joints = m.jointsList, + softBodies = m.softBodies, toonTextures = m.toonTextures, + } + return scene +end + +return Build diff --git a/src/Formats/model/pmx/Pmd.luau b/src/Formats/model/pmx/Pmd.luau new file mode 100644 index 0000000..affdd3a --- /dev/null +++ b/src/Formats/model/pmx/Pmd.luau @@ -0,0 +1,339 @@ +--!strict +-- model/pmx/Pmd: the PMD 1.0 parser (MikuMikuDance's original model format), into the same model table as +-- model/pmx/Read so model/pmx/Build makes the Scene. Written from the PMD layout as documented by the MMD community +-- (MMDAgent / mmd_tools notes); no third-party code. Reads vertices (two bones, weight 0..100, edge flag), faces, +-- materials ("texture*sphere" names, toon index), bones, IK chains, skins (the base skin + vertex morphs relative to +-- it), display lists, the optional English names, toon texture names, rigid bodies and joints. Names are Shift-JIS in +-- the file: ASCII names are kept, others use the English name when there is one, else the raw bytes (in +-- extras / meta.source as `nameSjis`). Never throws: returns nil, message[, kind]. +local Bytes = require("@formats/core/Bytes") + +local Pmd = {} + +local function vec(r: Bytes.Reader, n: number): { number } + local v: { number } = {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +local function ascii(s: string): boolean + return not string.find(s, "[\128-\255]") +end + +local function counted(r: Bytes.Reader, n: number, size: number, what: string): (boolean, ...any) + if n * size > r.limit - r.pos then + return false, string.format("%d %s do not fit in the file", n, what) + end + return true +end + +function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any) + if not r:match("Pmd") then + return nil, "not a PMD file" + end + local version = r:f32le() + if version ~= 1 then + return nil, "unsupported: PMD version " .. tostring(version), "unsupported" + end + local m: { [string]: any } = { version = 1.0, encoding = "shift_jis", uva = {}, sdef = nil } + m.nameSjis, m.commentSjis = r:fixed(20), r:fixed(256) + local buf = r.buf + + -- vertices: 38 bytes each + local nv = r:u32le() + if r.err then + return nil, "truncated", "truncated" + end + local ok, e = counted(r, nv, 38, "vertices") + if not ok then + return nil, e, "truncated" + end + local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24 + if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local deform, joints, weights, edge = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16), buffer.create(nv * 4) + for v = 0, nv - 1 do + local p = r.pos + v * 38 + buffer.copy(pos, v * 12, buf, p, 12) + buffer.copy(nrm, v * 12, buf, p + 12, 12) + buffer.copy(uv, v * 8, buf, p + 24, 8) + local b0, b1 = buffer.readu16(buf, p + 32), buffer.readu16(buf, p + 34) + local w = math.clamp(buffer.readu8(buf, p + 36), 0, 100) / 100 + local single = b0 == b1 or w == 1 + buffer.writeu8(deform, v, if single then 0 else 1) + buffer.writei32(joints, v * 16, b0) + buffer.writei32(joints, v * 16 + 4, if single then -1 else b1) + buffer.writei32(joints, v * 16 + 8, -1) + buffer.writei32(joints, v * 16 + 12, -1) + buffer.writef32(weights, v * 16, if single then 1 else w) + buffer.writef32(weights, v * 16 + 4, if single then 0 else 1 - w) + buffer.writef32(edge, v * 4, if buffer.readu8(buf, p + 37) ~= 0 then 0 else 1) + end + r.pos += nv * 38 + m.vertexCount, m.positions, m.normals, m.uvs, m.deform, m.joints, m.weights, m.edge = nv, pos, nrm, uv, deform, joints, weights, edge + + -- faces: u16 indices + local ni = r:u32le() + ok, e = counted(r, ni, 2, "face indices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + for i = 0, ni - 1 do + local x = buffer.readu16(buf, r.pos + i * 2) + if x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv) + end + buffer.writeu32(ind, i * 4, x) + end + r.pos += ni * 2 + m.indexCount, m.indices = ni, ind + + -- materials: 70 bytes each; texture names collected into the texture list + local nm = r:u32le() + ok, e = counted(r, nm, 70, "materials") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.textures = {} + local texIndex: { [string]: number } = {} + local function tex(name: string): number + if name == "" then + return -1 + end + local i = texIndex[name] + if not i then + table.insert(m.textures, name) + i = #m.textures - 1 + texIndex[name] = i + end + return i + end + m.materials = table.create(nm) + local toonIdx = {} + for i = 1, nm do + local mat: { [string]: any } = { name = "material" .. (i - 1), nameEn = "material" .. (i - 1) } + local d = vec(r, 4) + mat.diffuse, mat.power, mat.specular, mat.ambient = d, r:f32le(), vec(r, 3), vec(r, 3) + local toon, edgeFlag = r:u8(), r:u8() + mat.count = r:u32le() + local file = r:fixed(20) + mat.flags = (if edgeFlag ~= 0 then 0x10 else 0) + (if d[4] < 1 then 0x01 else 0) + mat.edgeColor, mat.edgeSize, mat.memo = { 0, 0, 0, 1 }, 1, "" + mat.texture, mat.sphere, mat.sphereMode = -1, -1, 0 + for part in string.gmatch(file, "[^*]+") do + local ext = string.lower(string.match(part, "%.(%w+)$") or "") + if ext == "sph" or ext == "spa" then + mat.sphere, mat.sphereMode = tex(part), if ext == "sph" then 1 else 2 + else + mat.texture = tex(part) + end + end + toonIdx[i] = toon + m.materials[i] = mat + end + + -- bones: 39 bytes each + local nb = r:u16le() + ok, e = counted(r, nb, 39, "bones") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.bones = table.create(nb) + for i = 1, nb do + local b: { [string]: any } = { nameSjis = r:fixed(20) } + local parent, tail, kind, ikParent = r:u16le(), r:u16le(), r:u8(), r:u16le() + b.pos = vec(r, 3) + b.parent = if parent == 0xFFFF then -1 else parent + b.tail = if tail ~= 0 and tail ~= 0xFFFF then tail else { 0, 0, 0 } + b.layer, b.pmdType, b.ikParent = 0, kind, ikParent + -- PMX-style flags: tail index, rotatable, translatable (type 1), visible (not type 7), enabled + b.flags = (if type(b.tail) == "number" then 0x1 else 0) + 0x2 + (if kind == 1 then 0x4 else 0) + (if kind ~= 7 then 0x8 else 0) + 0x10 + m.bones[i] = b + end + + -- IK chains + local nik = r:u16le() + for _ = 1, nik do + local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le() + local links = table.create(len) + for l = 1, len do + links[l] = { bone = r:u16le() } + end + if r.err then + return nil, "truncated", "truncated" + end + local b = m.bones[bone + 1] + if b then + b.flags = bit32.bor(b.flags, 0x20) + -- PMD's limit is in units of 4 radians (PMX stores radians) + b.ik = { target = target, loops = loops, limit = limit * 4, links = links } + end + end + + -- skins: the base (absolute positions of every vertex a morph moves), then morphs relative to it + local ns = r:u16le() + if r.err then + return nil, "truncated", "truncated" + end + m.morphs = {} + local base: { number } = {} + for s = 1, ns do + local name = r:fixed(20) + local n, panel = r:u32le(), r:u8() + ok, e = counted(r, n, 16, "skin vertices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if s == 1 and panel == 0 then + for o = 1, n do + base[o] = r:u32le() + r:skip(12) + end + else + local vi, deltas = table.create(n), buffer.create(n * 12) + for o = 1, n do + local k = r:u32le() + local v = base[k + 1] + if not v or v >= nv then + return nil, string.format("skin %d: base vertex %d out of range", s - 1, k) + end + vi[o] = v + buffer.copy(deltas, (o - 1) * 12, buf, r.pos, 12) + r:skip(12) + end + table.insert(m.morphs, { nameSjis = name, panel = panel, type = 1, vertices = vi, deltas = deltas }) + end + end + + -- display lists (skin list, bone group names, bone groups) + local nsd = r:u8() + r:skip(nsd * 2) + local ng = r:u8() + local groups: { { [string]: any } } = {} + for g = 1, ng do + groups[g] = { nameSjis = r:fixed(50), special = false, items = {} } + end + local nbd = r:u32le() + ok, e = counted(r, nbd, 3, "bone display entries") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + for _ = 1, nbd do + local bone, g = r:u16le(), r:u8() + local grp = groups[g] + if grp then + table.insert(grp.items, { bone = bone }) + end + end + m.frames = groups + + -- optional: English names, toon textures, physics + local function name(t: { [string]: any }, en: string?) + local raw = t.nameSjis or "" + t.nameEn = en + t.name = if ascii(raw) then raw elseif en and en ~= "" then en else raw + if ascii(raw) then + t.nameSjis = nil + end + end + local en: any = {} + if r.limit - r.pos >= 1 and r:u8() == 1 then + en.name, en.comment = r:fixed(20), r:fixed(256) + en.bones = table.create(nb) + for i = 1, nb do + en.bones[i] = r:fixed(20) + end + en.morphs = {} + for i = 1, #m.morphs do + en.morphs[i] = r:fixed(20) + end + en.groups = {} + for i = 1, ng do + en.groups[i] = r:fixed(50) + end + end + local model = { nameSjis = m.nameSjis } + name(model, en.name) + m.name, m.nameEn = model.name, en.name + m.comment, m.commentEn = if ascii(m.commentSjis) then m.commentSjis else (en.comment or m.commentSjis), en.comment + if ascii(m.nameSjis) then + m.nameSjis = nil + end + for i, b in m.bones do + name(b, en.bones and en.bones[i]) + end + for i, mo in m.morphs do + name(mo, en.morphs and en.morphs[i]) + end + for i, g in groups do + name(g, en.groups and en.groups[i]) + end + local toons: { string } = {} + for i = 1, 10 do + toons[i] = string.format("toon%02d.bmp", i) + end + if r.limit - r.pos >= 1000 then + for i = 1, 10 do + toons[i] = r:fixed(100) + end + end + m.toonTextures = toons + for i, mat in m.materials do + local t = toonIdx[i] + if t < 10 then + if toons[t + 1] == string.format("toon%02d.bmp", t + 1) then + mat.toonShared = t + else + mat.toon = tex(toons[t + 1]) + end + else + mat.toon = -1 + end + end + m.rigidBodies, m.jointsList = {}, {} + if r.limit - r.pos >= 4 then + local nr = r:u32le() + ok, e = counted(r, nr, 83, "rigid bodies") + if not ok then + return nil, e, "truncated" + end + for i = 1, nr do + local b: { [string]: any } = { name = r:fixed(20), bone = r:u16le(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + if b.bone == 0xFFFF then + b.bone = -1 + end + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj = r:u32le() + ok, e = counted(r, nj, 124, "joints") + if not ok then + return nil, e, "truncated" + end + for i = 1, nj do + local j: { [string]: any } = { name = r:fixed(20), type = 0, a = r:u32le(), b = r:u32le() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Pmd diff --git a/src/Formats/model/pmx/Read.luau b/src/Formats/model/pmx/Read.luau new file mode 100644 index 0000000..cd7f90d --- /dev/null +++ b/src/Formats/model/pmx/Read.luau @@ -0,0 +1,411 @@ +--!strict +-- model/pmx/Read: the PMX 2.0 / 2.1 parser (MikuMikuDance / PmxEditor model files), into the plain model table that +-- model/pmx/Build turns into a Scene. Written from the PMX 2.0 / 2.1 specification notes that ship with PmxEditor. +-- Reads every section: header globals (UTF-16LE / UTF-8 text, additional UV count, index sizes 1 / 2 / 4), vertices +-- (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), faces, textures, materials, bones (tail, inherit, fixed / local axes, +-- external parent, IK), morphs (group, vertex, bone, UV, UV1-4, material, flip, impulse), display frames, rigid bodies, +-- joints; 2.1 soft bodies are counted, not parsed. Values stay as in the file (left-handed, 0-based indices). +-- Never throws: returns nil, message[, kind]. +local Bytes = require("@formats/core/Bytes") +local Text = require("@formats/codecs/text/Text") + +local Read = {} + +export type Model = { [string]: any } + +local readu8, readu16, readi32 = buffer.readu8, buffer.readu16, buffer.readi32 + +-- index readers: vertex indices are unsigned for sizes 1 / 2, every other index is signed (-1 = none) +local function indexReader(r: Bytes.Reader, size: number, vertex: boolean): () -> number + if size == 1 then + return if vertex then function() return r:u8() end else function() return r:i8() end + elseif size == 2 then + return if vertex then function() return r:u16le() end else function() return r:i16le() end + end + return function() return r:i32le() end +end + +local function vec(r: Bytes.Reader, n: number): { number } + local v: { number } = {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +-- a count field: i32 >= 0 and at most remaining / minSize records +local function count(r: Bytes.Reader, minSize: number, what: string): (any, ...any) + local n = r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + if n < 0 then + return nil, "negative " .. what .. " count" + end + if n * minSize > r.limit - r.pos then + return nil, string.format("%d %s do not fit in the file", n, what), "truncated" + end + return n +end + +function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any) + if not r:match("PMX ") then + return nil, "not a PMX file" + end + local version = r:f32le() + local nglobals = r:u8() + if r.err then + return nil, "truncated", "truncated" + end + if version < 1.95 or version > 2.15 then + return nil, "unsupported: PMX version " .. tostring(version), "unsupported" + end + version = if version > 2.05 then 2.1 else 2.0 + if nglobals < 8 then + return nil, "only " .. nglobals .. " header globals" + end + local g: { number } = {} + for i = 1, nglobals do + g[i] = r:u8() + end + local utf8 = g[1] == 1 + if g[1] > 1 then + return nil, "unknown text encoding " .. g[1] + end + local uva = g[2] + if uva > 4 then + return nil, uva .. " additional UVs (at most 4)" + end + for i = 3, 8 do + if g[i] ~= 1 and g[i] ~= 2 and g[i] ~= 4 then + return nil, "bad index size " .. g[i] + end + end + local vsize, tsize, msize, bsize, morsize, rsize = g[3], g[4], g[5], g[6], g[7], g[8] + local buf = r.buf + local function text(): string + local n = r:i32le() + if r.err or n < 0 or n > r.limit - r.pos then + r:need(r.limit - r.pos + 1) + return "" + end + local p = r.pos + r.pos += n + if utf8 then + return buffer.readstring(buf, p, n) + end + return Text.utf16(buf, p, n) + end + local vidx = indexReader(r, vsize, true) + local tidx = indexReader(r, tsize, false) + local midx = indexReader(r, msize, false) + local bidx = indexReader(r, bsize, false) + local moidx = indexReader(r, morsize, false) + local ridx = indexReader(r, rsize, false) + local m: Model = { version = version, encoding = if utf8 then "utf8" else "utf16", additionalUV = uva, indexSizes = { vsize, tsize, msize, bsize, morsize, rsize } } + m.name, m.nameEn, m.comment, m.commentEn = text(), text(), text(), text() + if r.err then + return nil, "truncated", "truncated" + end + + -- vertices: position, normal, uv, additional uvs, deform, edge scale + local nv, e, k = count(r, 8 * 4 + 1 + bsize + 4 + uva * 16, "vertices") + if not nv then + return nil, e, k + end + local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24 + if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv :: number, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local uvas = {} + for a = 1, uva do + uvas[a] = buffer.create(nv * 16) + end + local deform, joints, weights = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16) + local edge = buffer.create(nv * 4) + local sdef: buffer? = nil + local writef32, writei32 = buffer.writef32, buffer.writei32 + for v = 0, nv - 1 do + if not r:need(32 + uva * 16 + 1) then + return nil, "truncated", "truncated" + end + local p = r.pos + for c = 0, 2 do + writef32(pos, (v * 3 + c) * 4, buffer.readf32(buf, p + c * 4)) + writef32(nrm, (v * 3 + c) * 4, buffer.readf32(buf, p + 12 + c * 4)) + end + writef32(uv, v * 8, buffer.readf32(buf, p + 24)) + writef32(uv, v * 8 + 4, buffer.readf32(buf, p + 28)) + p += 32 + for a = 1, uva do + buffer.copy(uvas[a], v * 16, buf, p, 16) + p += 16 + end + local kind = readu8(buf, p) + r.pos = p + 1 + buffer.writeu8(deform, v, kind) + local o = v * 16 + if kind == 0 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, -1) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + writef32(weights, o, 1) + elseif kind == 1 or kind == 3 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, bidx()) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + local w = r:f32le() + writef32(weights, o, w) + writef32(weights, o + 4, 1 - w) + if kind == 3 then + local sd = sdef or buffer.create(nv * 36) + sdef = sd + for c = 0, 8 do + writef32(sd, v * 36 + c * 4, r:f32le()) + end + end + elseif kind == 2 or kind == 4 then + for c = 0, 3 do + writei32(joints, o + c * 4, bidx()) + end + for c = 0, 3 do + writef32(weights, o + c * 4, r:f32le()) + end + else + return nil, "unknown vertex deform type " .. kind + end + writef32(edge, v * 4, r:f32le()) + if r.err then + return nil, "truncated", "truncated" + end + end + m.vertexCount, m.positions, m.normals, m.uvs, m.uva = nv, pos, nrm, uv, uvas + m.deform, m.joints, m.weights, m.sdef, m.edge = deform, joints, weights, sdef, edge + + -- faces: vertex index triples + local ni + ni, e, k = count(r, vsize, "face indices") + if not ni then + return nil, e, k + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + local p = r.pos + for i = 0, ni - 1 do + local x = if vsize == 1 then readu8(buf, p + i) elseif vsize == 2 then readu16(buf, p + i * 2) else readi32(buf, p + i * 4) + if x < 0 or x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv :: number), nil + end + buffer.writeu32(ind, i * 4, x) + end + r.pos = p + ni * vsize + m.indexCount, m.indices = ni, ind + + -- textures + local nt + nt, e, k = count(r, 4, "textures") + if not nt then + return nil, e, k + end + m.textures = table.create(nt) + for i = 1, nt do + m.textures[i] = text() + end + + -- materials + local nm + nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials") + if not nm then + return nil, e, k + end + m.materials = table.create(nm) + for i = 1, nm do + local mat: { [string]: any } = { name = text(), nameEn = text() } + mat.diffuse, mat.specular, mat.power, mat.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + mat.flags = r:u8() + mat.edgeColor, mat.edgeSize = vec(r, 4), r:f32le() + mat.texture, mat.sphere, mat.sphereMode = tidx(), tidx(), r:u8() + if r:u8() == 1 then + mat.toonShared = r:u8() + else + mat.toon = tidx() + end + mat.memo, mat.count = text(), r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + m.materials[i] = mat + end + + -- bones + local nb + nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones") + if not nb then + return nil, e, k + end + m.bones = table.create(nb) + for i = 1, nb do + local b: { [string]: any } = { name = text(), nameEn = text() } + b.pos, b.parent, b.layer = vec(r, 3), bidx(), r:i32le() + local fl = r:u16le() + b.flags = fl + b.tail = if bit32.btest(fl, 0x1) then bidx() else vec(r, 3) + if bit32.btest(fl, 0x300) then + b.inherit = { bone = bidx(), influence = r:f32le(), rotation = bit32.btest(fl, 0x100), translation = bit32.btest(fl, 0x200) } + end + if bit32.btest(fl, 0x400) then + b.axis = vec(r, 3) + end + if bit32.btest(fl, 0x800) then + b.localX, b.localZ = vec(r, 3), vec(r, 3) + end + if bit32.btest(fl, 0x2000) then + b.externalKey = r:i32le() + end + if bit32.btest(fl, 0x20) then + local ik: { [string]: any } = { target = bidx(), loops = r:i32le(), limit = r:f32le() } + local nl + nl, e, k = count(r, bsize + 1, "IK links") + if not nl then + return nil, e, k + end + ik.links = table.create(nl) + for l = 1, nl do + local link: { [string]: any } = { bone = bidx() } + if r:u8() == 1 then + link.min, link.max = vec(r, 3), vec(r, 3) + end + ik.links[l] = link + end + b.ik = ik + end + if r.err then + return nil, "truncated", "truncated" + end + m.bones[i] = b + end + + -- morphs + local nmo + nmo, e, k = count(r, 8 + 2 + 4, "morphs") + if not nmo then + return nil, e, k + end + local SIZE = { [0] = morsize + 4, vsize + 12, bsize + 28, vsize + 16, vsize + 16, vsize + 16, vsize + 16, vsize + 16, msize + 1 + 112, morsize + 4, rsize + 25 } + m.morphs = table.create(nmo) + for i = 1, nmo do + local mo: { [string]: any } = { name = text(), nameEn = text(), panel = r:u8(), type = r:u8() } + local t = mo.type + local size = SIZE[t] + if not size then + return nil, "unknown morph type " .. t + end + local no + no, e, k = count(r, size, "morph offsets") + if not no then + return nil, e, k + end + if t == 1 then + -- vertex morphs: packed (index list + deltas), they become morph targets + local vi, d = table.create(no), buffer.create(no * 12) + for o = 1, no do + local x = vidx() + vi[o] = x + for c = 0, 2 do + writef32(d, ((o - 1) * 3 + c) * 4, r:f32le()) + end + end + mo.vertices, mo.deltas = vi, d + else + local offs = table.create(no) + for o = 1, no do + local off: { [string]: any } + if t == 0 or t == 9 then + off = { morph = moidx(), weight = r:f32le() } + elseif t == 2 then + off = { bone = bidx(), translation = vec(r, 3), rotation = vec(r, 4) } + elseif t <= 7 then + off = { vertex = vidx(), value = vec(r, 4) } + elseif t == 8 then + off = { material = midx(), operation = r:u8() } + off.diffuse, off.specular, off.specularPower, off.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + off.edgeColor, off.edgeSize, off.textureTint, off.sphereTint, off.toonTint = vec(r, 4), r:f32le(), vec(r, 4), vec(r, 4), vec(r, 4) + else + off = { rigidBody = ridx(), localFrame = r:u8() == 1, velocity = vec(r, 3), torque = vec(r, 3) } + end + offs[o] = off + end + mo.offsets = offs + end + if r.err then + return nil, "truncated", "truncated" + end + m.morphs[i] = mo + end + + -- display frames, rigid bodies, joints: optional at the end (some tools stop after the morphs) + m.frames, m.rigidBodies, m.jointsList = {}, {}, {} + if r.limit - r.pos >= 4 then + local nf + nf, e, k = count(r, 8 + 1 + 4, "display frames") + if not nf then + return nil, e, k + end + for i = 1, nf do + local f: { [string]: any } = { name = text(), nameEn = text(), special = r:u8() == 1 } + local nitem + nitem, e, k = count(r, 1 + math.min(bsize, morsize), "display frame items") + if not nitem then + return nil, e, k + end + f.items = table.create(nitem) + for q = 1, nitem do + local kind = r:u8() + f.items[q] = if kind == 0 then { bone = bidx() } else { morph = moidx() } + end + m.frames[i] = f + end + end + if r.limit - r.pos >= 4 then + local nr + nr, e, k = count(r, 8 + bsize + 4 + 36 + 20 + 1, "rigid bodies") + if not nr then + return nil, e, k + end + for i = 1, nr do + local b: { [string]: any } = { name = text(), nameEn = text(), bone = bidx(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj + nj, e, k = count(r, 8 + 1 + 2 * rsize + 96, "joints") + if not nj then + return nil, e, k + end + for i = 1, nj do + local j: { [string]: any } = { name = text(), nameEn = text(), type = r:u8(), a = ridx(), b = ridx() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if version >= 2.1 and r.limit - r.pos >= 4 then + m.softBodies = r:i32le() + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Read diff --git a/src/Formats/model/pmx/init.luau b/src/Formats/model/pmx/init.luau new file mode 100644 index 0000000..5a671b1 --- /dev/null +++ b/src/Formats/model/pmx/init.luau @@ -0,0 +1,77 @@ +--!strict +-- model/pmx: MikuMikuDance models, PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (the original MMD +-- format, as documented by the MMD community). New code, no third-party code. +-- Reads: UTF-16 / UTF-8 text (PMD: Shift-JIS names kept when ASCII, else the English names), vertices with BDEF1 / +-- BDEF2 / BDEF4 / SDEF / QDEF weights -> JOINTS_0 / WEIGHTS_0 (normalized; SDEF C / R0 / R1 as _SDEF_C / _SDEF_R0 / +-- _SDEF_R1, the deform type as _DEFORM, additional UVs as _UVA1.._UVA4 vec4, edge scale as _EDGE_SCALE), faces (one +-- primitive per material), textures (uri, data through opts.files / opts.resolve), materials (diffuse -> baseColor, +-- specular power -> roughness, no-cull -> doubleSided; diffuse / specular / ambient, edge, sphere map and mode, toon +-- texture or shared toon index, memo in material.extras.pmx), bones (nodes with parent-relative translations, one skin; +-- tail, inherit, axes, IK in node.extras.pmx), vertex morphs -> morph targets (POSITION deltas, mesh.extras.targetNames), +-- the other morphs (group, bone, UV, material, flip, impulse), display frames, rigid bodies and joints as extras +-- (mesh.extras.pmx.morphs, meta.source). MMD's left-handed coordinates become right-handed: z is negated and the +-- winding reversed (extras keep the file's values and 0-based indices). meta.up = "y" (one unit is about 8 cm). +-- Not supported: writing, PMX 2.1 soft bodies (counted in meta.source.softBodies), VMD motions / VPD poses. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/pmx/Read") +local Pmd = require("@formats/model/pmx/Pmd") +local Build = require("@formats/model/pmx/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Pmx = { + name = "pmx", + category = "model", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + files: { [string]: any }?, -- texture files by name (buffer or string; "/" or "\" separators, or the base name) + resolve: ((uri: string) -> any)?, -- or: reads a texture file (the api sets it for paths) + morphs: boolean?, -- vertex morphs as morph targets (default true) + maxVertices: number?, -- default 2^24 + maxBytes: number?, -- morph target bytes (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Pmx.sniff(r: Bytes.Reader): number + local head = r:peek(8) + if string.sub(head, 1, 4) == "PMX " then + return 1 + end + if string.sub(head, 1, 7) == "Pmd\0\0\128\63" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Pmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local pmd = r:peek(3) == "Pmd" + local m: any, msg: string?, kind: string? + if pmd then + m, msg, kind = Pmd.parse(r, opts) + else + m, msg, kind = Read.parse(r, opts) + end + if not m then + return nil, Err.from(msg, r.pos - r.base, kind) + end + local scene, berr, bkind = Build.scene(m, opts) + if not scene then + return nil, Err.from(berr, nil, bkind) + end + if pmd and scene.meta.source then + scene.meta.source.pmd = true + end + return scene, nil +end + +return Pmx diff --git a/tests/model/pmx.luau b/tests/model/pmx.luau new file mode 100644 index 0000000..e685dcf --- /dev/null +++ b/tests/model/pmx.luau @@ -0,0 +1,263 @@ +-- model/pmx tests: assimp's MMD model (Alicia_blade.pmx) and synthetic PMX 2.0 / 2.1 models (UTF-16 / UTF-8, index +-- sizes 1 / 2 / 4, additional UVs, BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF, every morph type, IK / inherit / axis bones, +-- display frames, rigid bodies, joints) against assimp (meshes, faces per mesh, materials, bones, world bounds) and the +-- generator's facts (vertices, weights, bones, morphs, textures); the same models as PMD against their PMX decode; +-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/pmx.py. +local T = require("@tests/T") +local F = require("@formats") +local Pmx = require("@formats/model/pmx") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/pmx_cases") +local Pmds = require("@tests/gen/pmx_pmd") + +local t = T.suite("pmx") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Pmx.decode(Bytes.reader(b), opts) +end + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +t:eq(Pmx.name, "pmx", "name") +t:eq(Pmx.category, "model", "category") +t:check(Pmx.caps.decode and not Pmx.caps.encode, "contract") + +local function faces(scene: any): (number, { number }) + local n, per = 0, {} + for i, p in scene.meshes[1].primitives do + per[i] = p.indices.count // 3 + n += per[i] + end + return n, per +end + +local function bounds(scene: any): ({ number }, { number }) + return MeshOps.bounds(MeshOps.merge(scene)) +end + +-- a file vertex in the decoded primitives: position (z negated) and uv +local function findVertex(scene: any, pos: { number }, uv: { number }): (any, number?) + for _, p in scene.meshes[1].primitives do + local P, U = p.attributes.POSITION, p.attributes.TEXCOORD_0 + for v = 0, P.count - 1 do + local x, y, z = buffer.readf32(P.data, v * 12), buffer.readf32(P.data, v * 12 + 4), buffer.readf32(P.data, v * 12 + 8) + if near(x, pos[1], 1e-6) and near(y, pos[2], 1e-6) and near(z, -pos[3], 1e-6) and near(buffer.readf32(U.data, v * 8), uv[1], 1e-6) and near(buffer.readf32(U.data, v * 8 + 4), uv[2], 1e-6) then + return p, v + end + end + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes = {} +local checked = { assimp = 0, expect = 0 } +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + scenes[i] = scene + local a = c.assimp + local nf, per = faces(scene) + if not a.skip then + t:eq(#scene.meshes[1].primitives, a.meshes, c.name .. ": meshes (assimp)") + t:eq(nf, a.faces, c.name .. ": faces (assimp)") + t:eq(#scene.materials, a.materials, c.name .. ": materials (assimp)") + local ok = true + for k, pm in a.perMesh do + ok = ok and per[k] == pm.faces + end + t:check(ok, c.name .. ": faces per material (assimp)") + t:eq(#scene.skins[1].joints * #scene.meshes[1].primitives, a.bones, c.name .. ": bones x meshes (assimp)") + if a.min then + local lo, hi = bounds(scene) + local okb = true + for k = 1, 3 do + okb = okb and near(lo[k], a.min[k], 1e-5) and near(hi[k], a.max[k], 1e-5) + end + t:check(okb, string.format("%s: world bounds (assimp) %s / %s", c.name, table.concat(lo, " "), table.concat(hi, " "))) + end + checked.assimp += 1 + end + local x = c.expect + if x then + local src = scene.meta.source + t:eq(src.version, x.version, c.name .. ": version") + t:eq(src.name, x.name, c.name .. ": model name") + t:eq(#scene.skins[1].joints, x.bones, c.name .. ": bones") + t:eq(#scene.nodes, 2 + x.bones, c.name .. ": nodes") + t:eq(#scene.textures, x.textures, c.name .. ": textures") + t:eq(#src.rigidBodies, x.rigid, c.name .. ": rigid bodies") + t:eq(#src.joints, x.joints, c.name .. ": joints") + t:eq(#src.displayFrames, x.frames, c.name .. ": display frames") + local mesh = scene.meshes[1] + local vertexMorphs = x.morphTypes["1"] or 0 + t:eq(#(mesh.extras.targetNames or {}), vertexMorphs, c.name .. ": vertex morphs -> targets") + t:eq(#mesh.primitives[1].targets, vertexMorphs, c.name .. ": targets per primitive") + t:eq(#((mesh.extras.pmx or {}).morphs or {}), x.morphs - vertexMorphs, c.name .. ": other morphs in extras") + t:check(x.uva == 0 or mesh.primitives[1].attributes["_UVA" .. x.uva] ~= nil, c.name .. ": additional UVs") + -- unique vertices: a material boundary can split a ring, so at least the file's count + local nv = 0 + for _, p in mesh.primitives do + nv += p.attributes.POSITION.count + end + t:check(nv >= x.vertices and nv <= x.vertices * 2, c.name .. ": vertices " .. nv .. " / " .. x.vertices) + for _, s in x.samples do + local p, v = findVertex(scene, s.pos, s.uv) + t:check(p ~= nil, c.name .. ": vertex " .. s.index .. " found") + if p and v then + local J, W = p.attributes.JOINTS_0, p.attributes.WEIGHTS_0 + local want: { [number]: number } = {} + local sum = 0 + local ws = if s.deform == 1 or s.deform == 3 then { s.weights[1], 1 - s.weights[1] } elseif s.deform == 0 then { 1 } else s.weights + for k, b in s.bones do + if b >= 0 and ws[k] and ws[k] > 0 then + want[b] = (want[b] or 0) + ws[k] + sum += ws[k] + end + end + local got: { [number]: number } = {} + for k = 0, 3 do + local w = buffer.readf32(W.data, (v * 4 + k) * 4) + if w > 0 then + local j = buffer.readu16(J.data, (v * 4 + k) * 2) + got[j] = (got[j] or 0) + w + end + end + local ok = true + for b, w in want do + ok = ok and got[b] ~= nil and near(got[b], w / sum, 1e-5) + end + t:check(ok, c.name .. ": vertex " .. s.index .. " weights (deform " .. s.deform .. ")") + if s.deform == 3 then + t:check(p.attributes._SDEF_C ~= nil and buffer.readu8(p.attributes._DEFORM.data, v) == 3, c.name .. ": SDEF attributes") + end + end + end + -- the texture named tex\body.png came from files["tex/body.png"] + t:check(scene.textures[1].uri == "tex/body.png" and scene.textures[1].data ~= nil and scene.textures[1].mime == "image/png", c.name .. ": texture data") + local m1 = scene.materials[1] + t:check(m1.baseColorTexture and m1.baseColorTexture.texture == 1 and m1.doubleSided, c.name .. ": material 1 texture, no-cull") + t:check(m1.extras.pmx.sphereTexture == 2 and m1.extras.pmx.sphereMode == "multiply" and m1.extras.pmx.toonShared == 3, c.name .. ": sphere / toon") + t:check(scene.materials[2].alphaMode == "blend", c.name .. ": translucent material") + local ik = nil + for _, n in scene.nodes do + if n.extras and n.extras.pmx and n.extras.pmx.ik then + ik = n.extras.pmx.ik + end + end + t:check(ik and ik.loops == 40 and #ik.links == 2, c.name .. ": IK bone") + checked.expect += 1 + end +end +t:note("%d files: %d against assimp, %d against the generator", #Cases, checked.assimp, checked.expect) + +-- skins: every joint's inverse bind matrix undoes its world translation +do + local s = scenes[2] + if s then + local skin = s.skins[1] + local ok = true + local world = {} + -- world matrices by walking from the root + local function walk(n: number, parent: { number }) + local w = Types.Scene.mul(parent, Types.Scene.nodeMatrix(s.nodes[n])) + world[n] = w + for _, c in s.nodes[n].children do + walk(c, w) + end + end + walk(1, Types.Scene.IDENTITY) + for k, j in skin.joints do + local w = world[j] + for c = 0, 2 do + ok = ok and near(buffer.readf32(skin.inverseBindMatrices.data, ((k - 1) * 16 + 12 + c) * 4), -w[13 + c], 1e-5) + end + end + t:check(ok, "inverse bind matrices = -world bone positions") + end +end + +-- ------------------------------------------------------------------------------------------------ PMD +for _, c in Pmds do + local s, err = decode(c.data) + t:check(s, c.name .. ": decode: " .. tostring(err)) + local ref = scenes[c.pmx] + if s and ref then + t:check(s.meta.source.pmd == true and s.meta.source.format == "pmx", c.name .. ": meta.source") + local a, pa = faces(s) + local b, pb = faces(ref) + t:eq(a, b, c.name .. ": faces (= PMX)") + t:eq(#pa, #pb, c.name .. ": primitives (= PMX)") + t:eq(#s.skins[1].joints, #ref.skins[1].joints, c.name .. ": bones (= PMX)") + t:eq(#s.meshes[1].extras.targetNames, #ref.meshes[1].extras.targetNames, c.name .. ": vertex morphs (= PMX)") + local lo, hi = bounds(s) + local lo2, hi2 = bounds(ref) + local ok = true + for k = 1, 3 do + ok = ok and near(lo[k], lo2[k], 1e-6) and near(hi[k], hi2[k], 1e-6) + end + t:check(ok, c.name .. ": bounds (= PMX)") + -- the same morph deltas + local d1 = s.meshes[1].primitives[1].targets[1].POSITION + local d2 = ref.meshes[1].primitives[1].targets[1].POSITION + t:check(d1.count == d2.count and buffer.tostring(d1.data) == buffer.tostring(d2.data), c.name .. ": morph deltas (= PMX)") + t:eq(s.meshes[1].extras.targetNames[1], "up", c.name .. ": English morph names") + t:eq(s.materials[1].extras.pmx.sphereMode, "multiply", c.name .. ": texture*sphere name") + end +end + +-- ------------------------------------------------------------------------------------------------ api, errors +do + local c = Cases[2] + t:eq(F.detect(c.data), "pmx", "F.detect pmx") + t:eq(F.detect(Pmds[1].data), "pmx", "F.detect pmd") + local s = F.load(c.data, { files = c.files }) + t:check(s and s.kind == "scene" and s.meta.up == "y", "F.load") + local _, e1 = decode(string.sub(c.data, 1, 300)) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local _, e2 = decode("PMX " .. "\0\0\64\64" .. string.sub(c.data, 9)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 2.0 -> 3.0: " .. tostring(e2)) + local _, e3 = decode(string.sub(c.data, 1, 11) .. "\3" .. string.sub(c.data, 13)) + t:check(e3 and e3.code == Err.CORRUPT, "index size 3: " .. tostring(e3)) + local _, e4 = decode(c.data, { maxVertices = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = decode(c.data, { maxBytes = 100 }) + t:check(e5 and e5.code == Err.LIMIT, "maxBytes (morph targets): " .. tostring(e5)) + local s2 = decode(c.data, { maxBytes = 100, morphs = false }) + t:check(s2 and s2.meshes[1].primitives[1].targets == nil, "morphs = false") + local _, e6 = decode("Pmd\0\0\0\64" .. string.rep("\0", 300)) + t:check(e6 and e6.code == Err.UNSUPPORTED, "PMD version 2: " .. tostring(e6)) + local _, e7 = decode(string.sub(Pmds[1].data, 1, 400)) + t:check(e7 and (e7.code == Err.TRUNCATED or e7.code == Err.CORRUPT), "PMD truncated: " .. tostring(e7)) +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 120000 then + table.insert(samples, c.data) + end + end + for _, c in Pmds do + table.insert(samples, c.data) + end + t:fuzz("decode", function(b: buffer) + local s = Pmx.decode(Bytes.reader(b)) + if s then + MeshOps.merge(s) + end + return s + end, samples, { mutations = 16, keepHeader = 17 }) +end + +t:done() diff --git a/tools/fixtures/_pmx_writer.py b/tools/fixtures/_pmx_writer.py new file mode 100644 index 0000000..dcace7d --- /dev/null +++ b/tools/fixtures/_pmx_writer.py @@ -0,0 +1,265 @@ +# A small PMX 2.0 / 2.1 (and PMD 1.0) writer for tools/fixtures/pmx.py: synthetic MikuMikuDance models that use every +# vertex deform type (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), both text encodings, every index size, additional UVs, +# several materials (texture / sphere / toon references), a bone chain with IK / inherit / fixed-axis / local-axis +# bones, every morph type, display frames, rigid bodies and joints. Written from the PMX 2.0 / 2.1 specification notes +# (PmxEditor's "PMX仕様") and the PMD layout; no third-party code. +import math, struct + + +def f32s(*v): + return struct.pack("<%df" % len(v), *v) + + +class Pmx: + def __init__(self, version=2.0, utf8=False, sizes=(2, 1, 1, 2, 1, 1), uva=0): + self.version, self.utf8, self.uva = version, utf8, uva + self.vsize, self.tsize, self.msize, self.bsize, self.morsize, self.rsize = sizes + + def text(self, s): + b = s.encode("utf-8") if self.utf8 else s.encode("utf-16-le") + return struct.pack("= 2.1: + out += struct.pack("= 2.1 else [])) + verts = [] + for r in range(rings): + y = r * 2.0 + for s in range(seg): + a = 2 * math.pi * s / seg + x, z = math.cos(a) * 1.5, math.sin(a) * 1.5 + 0.25 * r + b0 = min(nbones - 1, r * nbones // rings) + b1 = min(nbones - 1, b0 + 1) + k = kinds[(r * seg + s) % len(kinds)] + w = rnd.random() + if k == 0: + bones, weights = [b0], [1.0] + elif k in (1, 3): + bones, weights = [b0, b1], [w] + else: + ws = [rnd.random() + 0.1 for _ in range(4)] + bones, weights = [b0, b1, max(0, b0 - 1), -1 if k == 2 else nbones - 1], [x / sum(ws) * 0.9 for x in ws] + verts.append({ + "pos": (x, y, z), "normal": (math.cos(a), 0.0, math.sin(a)), "uv": (s / seg, r / (rings - 1)), + "uva": [(rnd.random(), rnd.random(), rnd.random(), rnd.random()) for _ in range(uva)], + "deform": k, "bones": bones, "weights": weights, "edge": 1.0, + "sdef": ((0.0, y, 0.0), (0.0, y - 1, 0.0), (0.0, y + 1, 0.0)), + }) + faces = [] + for r in range(rings - 1): + for s in range(seg): + a, b = r * seg + s, r * seg + (s + 1) % seg + c, d = a + seg, b + seg + faces += [a, c, b, b, c, d] + ntri = len(faces) // 3 + counts, left = [], ntri + for k in range(nmat): + n = left if k == nmat - 1 else max(1, ntri // nmat) + counts.append(n * 3) + left -= n + mats = [] + for k in range(nmat): + mats.append({ + "name": "材質%d" % k, "nameEn": "mat%d" % k, "diffuse": (0.8, 0.2 + 0.2 * k, 0.1, 1.0 if k != 1 else 0.5), + "specular": (0.1, 0.1, 0.1), "power": 5.0 + 10 * k, "ambient": (0.4, 0.1, 0.05), "flags": [0x01 | 0x10, 0x04 | 0x08, 0x02][k % 3], + "edgeColor": (0, 0, 0, 1), "edgeSize": 1.0, "texture": 0 if k == 0 else -1, "sphere": 1 if k == 0 else -1, + "sphereMode": 1 if k == 0 else 0, "toonShared": 3 if k != 2 else None, "toon": 2, "memo": "memo %d" % k, "count": counts[k], + }) + bones = [] + for i in range(nbones): + fl = 0x1A | (1 if i < nbones - 1 else 0) + b = {"name": "骨%d" % i, "nameEn": "bone%d" % i, "pos": (0.0, i * (rings - 1) * 2.0 / max(1, nbones - 1), 0.25 * i), "parent": i - 1, + "layer": 0, "flags": fl, "tail": i + 1 if i < nbones - 1 else (0.0, 1.0, 0.0)} + if i == 1: + b["flags"] |= 0x100 + b["inherit"] = (0, 0.5) + if i == 2: + b["flags"] |= 0x400 | 0x800 + b["axis"] = (0.0, 1.0, 0.0) + b["localX"], b["localZ"] = (1.0, 0.0, 0.0), (0.0, 0.0, 1.0) + bones.append(b) + # an IK bone at the end targeting the last chain bone + bones.append({"name": "IK", "nameEn": "leg IK", "pos": (2.0, 0.0, 0.0), "parent": -1, "layer": 1, "flags": 0x1E | 0x20, "tail": (0.0, 0.0, 1.0), + "ik": {"target": nbones - 1, "loops": 40, "limit": 2.0, "links": [{"bone": nbones - 2, "min": (-3.14, 0, 0), "max": (-0.01, 0, 0)}, {"bone": max(0, nbones - 3)}]}}) + morphs = [ + {"name": "上", "nameEn": "up", "panel": 1, "type": 1, "offsets": [(i, (0.0, 0.5, -0.25)) for i in range(0, len(verts), 3)]}, + {"name": "広", "nameEn": "wide", "panel": 2, "type": 1, "offsets": [(i, (0.3, 0.0, 0.1)) for i in range(1, len(verts), 2)]}, + {"name": "uv", "nameEn": "uv", "panel": 3, "type": 3, "offsets": [(0, (0.1, 0.2, 0, 0))]}, + {"name": "骨", "nameEn": "bonem", "panel": 4, "type": 2, "offsets": [(1, (0, 1, 0), (0, 0, 0, 1))]}, + {"name": "材", "nameEn": "matm", "panel": 4, "type": 8, "offsets": [(-1, 0, (1,) * 28)]}, + {"name": "群", "nameEn": "group", "panel": 4, "type": 0, "offsets": [(0, 0.5), (1, 1.0)]}, + ] + if uva: + morphs.append({"name": "uva", "nameEn": "uva1", "panel": 3, "type": 4, "offsets": [(2, (0.5, 0.5, 0.5, 0.5))]}) + if version >= 2.1 and flips: # assimp 6 rejects these morph types + morphs.append({"name": "flip", "nameEn": "flip", "panel": 4, "type": 9, "offsets": [(0, 1.0)]}) + morphs.append({"name": "imp", "nameEn": "impulse", "panel": 4, "type": 10, "offsets": [(0, 1, (0, 1, 0), (0, 0, 0))]}) + frames = [{"name": "Root", "nameEn": "Root", "special": 1, "items": [(0, 0)]}, + {"name": "表情", "nameEn": "Exp", "special": 1, "items": [(1, 0), (1, 1)]}] + rigid = [{"name": "rb%d" % i, "nameEn": "rb%d" % i, "bone": i, "group": i, "mask": 0xFFFF, "shape": i % 3, "size": (1, 2, 3), + "pos": (0, i, 0), "rot": (0, 0, 0), "mass": 1.0, "mode": i % 3} for i in range(2)] + joints = [{"name": "j0", "nameEn": "j0", "a": 0, "b": 1, "pos": (0, 1, 0)}] + return {"name": name, "nameEn": name + " en", "comment": "コメント", "commentEn": "comment", "vertices": verts, "indices": faces, + "textures": ["tex\\body.png", "s.sph", "toon.bmp"], "materials": mats, "bones": bones, "morphs": morphs, + "frames": frames, "rigid": rigid, "joints": joints} + + +def pmd(m): + """the same model as PMD 1.0 (BDEF2-style weights only, ASCII names, toon list, English names)""" + def name(s, n): + b = s.encode("ascii", "replace")[: n - 1] + return b + b"\0" * (n - len(b)) + out = bytearray(b"Pmd") + struct.pack("= 0 else "" + if mat["sphere"] >= 0: + tex += "*" + m["textures"][mat["sphere"]] + out += f32s(*mat["diffuse"], mat["power"], *mat["specular"], *mat["ambient"]) + out += struct.pack(" bytes }, assimp, expect? } +# tests/gen/pmx_pmd.luau { name, data, pmx (the case index of the same model) } +import importlib.util, os, struct, zlib + +INPUTS = ["tools/fixtures/_pmx_writer.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def tiny_png(): + raw = b"".join(b"\0" + bytes([200, 40, 40]) * 2 for _ in range(2)) + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 2, 2, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"") + + +def generate(ctx): + M = load(ctx, "_model_ref") + Fbx = load(ctx, "fbx") + W = load(ctx, "_pmx_writer") + tmp = M.tempdir() + cases, pmds = [], [] + src = os.path.join(Fbx.assimp_src(ctx), "test", "models-nonbsd", "MMD", "Alicia_blade.pmx") + if os.path.exists(src): + cases.append({"name": "assimp/Alicia_blade.pmx", "path": src, "files": {}}) + variants = [ + ("small_utf16_i1.pmx", dict(version=2.0, utf8=False, sizes=(1, 1, 1, 1, 1, 1), uva=0), dict(rings=4, seg=6, nbones=3, nmat=2)), + ("utf8_i2_uva2.pmx", dict(version=2.0, utf8=True, sizes=(2, 2, 2, 2, 2, 2), uva=2), dict(rings=12, seg=16, nbones=5, nmat=3)), + ("v21_utf16_i4_uva4.pmx", dict(version=2.1, utf8=False, sizes=(4, 4, 4, 4, 4, 4), uva=4), dict(rings=30, seg=20, nbones=8, nmat=3)), + ("v21_utf8_mixed.pmx", dict(version=2.1, utf8=True, sizes=(2, 1, 1, 2, 1, 1), uva=1), dict(rings=8, seg=10, nbones=4, nmat=3, deform=[4, 3, 1], flips=True)), + ] + png = tiny_png() + for fname, wopts, topts in variants: + uva = wopts["uva"] + model = W.tube(version=wopts["version"], uva=uva, seed=len(cases), name=fname[:-4], **topts) + data = W.Pmx(**wopts).build(model) + path = os.path.join(tmp, fname) + with open(path, "wb") as f: + f.write(data) + vs = model["vertices"] + samples = [] + for i in (0, 1, 2, 3, len(vs) - 1): + v = vs[i] + samples.append({"index": i, "pos": list(v["pos"]), "uv": list(v["uv"]), "deform": v["deform"], "bones": v["bones"], "weights": v["weights"]}) + types = {} + for mo in model["morphs"]: + types[str(mo["type"])] = types.get(str(mo["type"]), 0) + 1 + expect = {"vertices": len(vs), "bones": len(model["bones"]), "morphs": len(model["morphs"]), "morphTypes": types, + "textures": len(model["textures"]), "uva": uva, "samples": samples, "name": model["name"], "version": wopts["version"], + "rigid": len(model["rigid"]), "joints": len(model["joints"]), "frames": len(model["frames"])} + cases.append({"name": "gen/" + fname, "path": path, "files": {"tex/body.png": png}, "expect": expect}) + if wopts["version"] == 2.0 and wopts["sizes"][0] <= 2: + pmds.append({"name": "gen/" + fname[:-4] + ".pmd", "data": W.pmd(model), "pmx": len(cases)}) + infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True) + for c, a in zip(cases, infos): + a.update(Fbx.assimp_extra(ctx, c["path"])) + a.pop("min", None) + a.pop("max", None) + a.update(Fbx.ptv_bounds(ctx, c["path"], tmp)) + if a.get("failed") and c.get("expect", {}).get("morphTypes", {}).get("9"): + a = {"skip": True} # flip / impulse morphs: assimp's MMD reader stops there + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("pmx_cases", cases) + ctx.emit("pmx_pmd", pmds)