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

This commit is contained in:
4DBug committed 2026-10-31 14:04:40 -05:00
1 parent de4f14a343
commit 4c74171631
9 files changed
+1752

No files matched your search

+12
View File
@@ -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",
+307
View File
@@ -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
+339
View File
@@ -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
+411
View File
@@ -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
+77
View File
@@ -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