fix(models): MMD 材质对齐——补回双面标志、规范化 PBR 参数、可选 unlit 着色
背景(用户反馈 + 本地用真 Assimp 6.0.4 复现): PMX 的着色模型(卡通阶梯 + 球面贴图 + 平坦环境光)与 glTF PBR 不是一回事, Assimp 转换会丢掉其中一部分。实测样本【奥黛塔】_by_原神.zip(39 个材质): 1. 主因:PMX 里 36 个材质带 drawFlag bit0(不剔除背面),而导出的 GLB 里 doubleSided 一个都没有 -> 头发/裙摆/睫毛这类薄片被单面剔除, 看起来就是颜色/贴图不对; 2. PMX 的 shininess/specular/ambient 与 PBR 无映射;Assimp 还会带上 KHR_materials_specular / KHR_materials_volume 等与 MMD 无关的扩展; 3. Assimp 把 accessor.min/max 写坏(实测 min = 2.2250738585072014e-308), Godot 等客户端用它算包围盒。 修复: 1. 新增 src/models/pmx-materials.ts:只读 PMX 材质段(布局与权威库 mmd-parser 一致,注意贴图索引宽度是 1 字节),拿到 name/diffuse/specular/shininess/ ambient/drawFlag/球面贴图/toon/faceCount; 2. 新增 src/models/glb-materials.ts:转换后按索引把 PMX 参数补回 GLB —— doubleSided、metallicFactor=0、roughnessFactor=clamp(1-shininess/100,0.5,1)、 baseColorFactor x diffuse(含 alpha);清掉与 MMD 无关的扩展; 修正全部浮点 accessor 的 min/max;支持 KHR_materials_unlit(MODEL_SHADING); 3. 抽出 src/common/glb-chunks.ts(JSON/BIN chunk 读写),vrm-writer 改为复用; 4. 能力边界写清楚:PMX 的球面贴图(该模型 15 项)与 toon 阶梯在 glTF core 里 没有对应槽位,任何转换器都无法保留,数量写进 conversion_note 供审核查看; 5. 新增 test/mmd-materials.spec.ts 9 项;规模 15 文件 / 220 项; 6. 新增 MODEL_SHADING 配置(默认 pbr,可选 unlit),文档同步(README.md/.txt、DSH.md、.env.example)。
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* GLB 容器读写:只拆/合 JSON 与 BIN 两个 chunk,不解释内容。
|
||||
*
|
||||
* 服务端有几处"只改 JSON、不动二进制"的后处理(补 VRM 扩展、内嵌贴图、
|
||||
* 修正 MMD 材质),统一走这里,避免各写一份 chunk 解析。
|
||||
*/
|
||||
|
||||
export const GLB_MAGIC = 0x46546c67; // 'glTF'
|
||||
export const CHUNK_JSON = 0x4e4f534a; // 'JSON'
|
||||
export const CHUNK_BIN = 0x004e4942; // 'BIN\0'
|
||||
|
||||
export function align4(value: number): number {
|
||||
return value + ((4 - (value % 4)) % 4);
|
||||
}
|
||||
|
||||
/** 解析 GLB 的 JSON 与 BIN;不是 GLB 或缺少 JSON chunk 时抛错(由调用方决定是否吞掉) */
|
||||
export function parseGlbChunks<T = Record<string, unknown>>(buffer: Buffer): { json: T; bin: Buffer | null } {
|
||||
if (buffer.length < 12 || buffer.readUInt32LE(0) !== GLB_MAGIC) {
|
||||
throw new Error('不是有效的 GLB(魔数不正确)');
|
||||
}
|
||||
const total = buffer.readUInt32LE(8) || buffer.length;
|
||||
const end = Math.min(total, buffer.length);
|
||||
let offset = 12;
|
||||
let json: T | null = null;
|
||||
let bin: Buffer | null = null;
|
||||
while (offset + 8 <= end) {
|
||||
const length = buffer.readUInt32LE(offset);
|
||||
const type = buffer.readUInt32LE(offset + 4);
|
||||
const start = offset + 8;
|
||||
if (start + length > buffer.length) break;
|
||||
const data = buffer.subarray(start, start + length);
|
||||
if (type === CHUNK_JSON) json = JSON.parse(data.toString('utf8')) as T;
|
||||
else if (type === CHUNK_BIN) bin = Buffer.from(data);
|
||||
offset = start + align4(length);
|
||||
}
|
||||
if (!json) throw new Error('GLB 里没有 JSON chunk');
|
||||
return { json, bin };
|
||||
}
|
||||
|
||||
/** 用新的 JSON + 原 BIN 重新拼一个 GLB(JSON 补空格、BIN 补零,都按 4 字节对齐) */
|
||||
export function buildGlbChunks(json: unknown, bin: Buffer | null): Buffer {
|
||||
const jsonBuffer = Buffer.from(JSON.stringify(json), 'utf8');
|
||||
const jsonPadded = Buffer.alloc(align4(jsonBuffer.length), 0x20);
|
||||
jsonBuffer.copy(jsonPadded);
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
const header = Buffer.alloc(12);
|
||||
header.writeUInt32LE(GLB_MAGIC, 0);
|
||||
header.writeUInt32LE(2, 4);
|
||||
chunks.push(header);
|
||||
|
||||
const jsonHeader = Buffer.alloc(8);
|
||||
jsonHeader.writeUInt32LE(jsonPadded.length, 0);
|
||||
jsonHeader.writeUInt32LE(CHUNK_JSON, 4);
|
||||
chunks.push(jsonHeader, jsonPadded);
|
||||
|
||||
if (bin && bin.length > 0) {
|
||||
const binPadded = Buffer.alloc(align4(bin.length));
|
||||
bin.copy(binPadded);
|
||||
const binHeader = Buffer.alloc(8);
|
||||
binHeader.writeUInt32LE(binPadded.length, 0);
|
||||
binHeader.writeUInt32LE(CHUNK_BIN, 4);
|
||||
chunks.push(binHeader, binPadded);
|
||||
}
|
||||
|
||||
const out = Buffer.concat(chunks);
|
||||
out.writeUInt32LE(out.length, 8);
|
||||
return out;
|
||||
}
|
||||
@@ -91,6 +91,20 @@ export class AppConfig {
|
||||
return (this.config.get<string>('modelConvertFormat') ?? 'glb') === 'vrm' ? 'vrm' : 'glb';
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换后模型的着色模式(`MODEL_SHADING`)。
|
||||
*
|
||||
* MMD 的着色模型(卡通阶梯 + 球面贴图 + 平坦环境光)在 glTF core 里没有对应实现,
|
||||
* 因此提供两种交付:
|
||||
* `pbr`(默认):标准 PBR;我们按 PMX 参数修正 doubleSided / metallic / roughness,
|
||||
* 清掉 Assimp 带出的无关扩展;
|
||||
* `unlit`:给每个材质写 `KHR_materials_unlit`,颜色 = 贴图 x baseColorFactor,
|
||||
* 与场景光照无关,最接近 MMD 的平涂观感(three.js / Godot 都支持)。
|
||||
*/
|
||||
get modelShading(): 'pbr' | 'unlit' {
|
||||
return (this.config.get<string>('modelShading') ?? 'pbr') === 'unlit' ? 'unlit' : 'pbr';
|
||||
}
|
||||
|
||||
/** 压缩包里优先选用的 PMX 文件名(大小写不敏感);找不到时按"目录最浅、文件最大"挑 */
|
||||
get modelConvertPmx(): string {
|
||||
return this.config.get<string>('modelConvertPmx') ?? 'Hatsune Miku.pmx';
|
||||
@@ -194,6 +208,7 @@ export const configuration = () => {
|
||||
uploadMaxBytes: Number(process.env.UPLOAD_MAX_BYTES ?? 512 * 1024 * 1024),
|
||||
assimpBin: process.env.ASSIMP_BIN ?? 'assimp',
|
||||
modelConvertFormat: process.env.MODEL_CONVERT_FORMAT ?? 'glb',
|
||||
modelShading: process.env.MODEL_SHADING ?? 'pbr',
|
||||
modelConvertPmx: process.env.MODEL_CONVERT_PMX ?? 'Hatsune Miku.pmx',
|
||||
modelConvertTimeoutMs: Number(process.env.MODEL_CONVERT_TIMEOUT_MS ?? 180_000),
|
||||
defaultModelId: process.env.DEFAULT_MODEL_ID ?? '',
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
/**
|
||||
* 把 MMD/PMX 的材质参数补回 Assimp 导出的 GLB。
|
||||
*
|
||||
* 为什么需要(真实故障):MMD 的着色模型与 glTF PBR 不是一回事,Assimp 转换会丢东西。
|
||||
* 实测样本 `【奥黛塔】_by_原神.zip`(PMX,39 个材质):
|
||||
* * PMX 里 **36 个材质带"不剔除背面"标志**,导出的 GLB 里 `doubleSided` **一个都没有**
|
||||
* -> 头发、裙摆、睫毛这类薄片被单面剔除,看起来"贴图/颜色不对";
|
||||
* * PMX 的 `shininess` / `specular` / `ambient` 与 PBR 的 roughness/specular 无映射,
|
||||
* Assimp 会写上 `KHR_materials_specular`(甚至 `KHR_materials_volume`)等
|
||||
* 与 MMD 无关的扩展,各渲染器解释不一致;
|
||||
* * PMX 的 **球面贴图(SPH/SPA,15 项)与 toon 贴图(卡通阶梯)** 在 glTF core 里
|
||||
* 没有对应槽位,只能记录并说明,不能凭空补出来。
|
||||
*
|
||||
* 这里做三件"有把握"的事:
|
||||
* 1. 按 PMX 的 drawFlag 补 `doubleSided`;
|
||||
* 2. 把 MMD 参数规范成可预期的 PBR:`metallicFactor = 0`、
|
||||
* `roughnessFactor = clamp(1 - shininess/100, 0.5, 1)`、`baseColorFactor` 乘上 PMX diffuse;
|
||||
* 3. 清掉 Assimp 带出的、与 MMD 无关的扩展;可选 `unlit` 模式让颜色与贴图完全一致。
|
||||
* 另外顺手修正 Assimp 写坏的 `accessor.min/max`(实测 POSITION/TEXCOORD 的 min 都被写成 2.2e-308,
|
||||
* Godot 等客户端会用它算包围盒)。
|
||||
*
|
||||
* 约定:解析不了就返回 null,绝不抛错——后处理失败不能影响入库。
|
||||
*/
|
||||
import type { PmxMaterialInfo } from './pmx-materials';
|
||||
import { buildGlbChunks, parseGlbChunks } from '../common/glb-chunks';
|
||||
|
||||
export type ShadingMode = 'pbr' | 'unlit';
|
||||
|
||||
/** 与 MMD 无关、Assimp 会顺带写出的扩展(留着只会让各渲染器表现不一致) */
|
||||
const STRIPPED_EXTENSIONS = [
|
||||
'KHR_materials_volume',
|
||||
'KHR_materials_transmission',
|
||||
'KHR_materials_ior',
|
||||
'KHR_materials_emissive_strength',
|
||||
'KHR_materials_specular',
|
||||
] as const;
|
||||
|
||||
interface LooseMaterial {
|
||||
name?: string;
|
||||
doubleSided?: boolean;
|
||||
alphaMode?: string;
|
||||
extensions?: Record<string, unknown>;
|
||||
pbrMetallicRoughness?: {
|
||||
baseColorFactor?: number[];
|
||||
metallicFactor?: number;
|
||||
roughnessFactor?: number;
|
||||
baseColorTexture?: unknown;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
interface LooseAccessor {
|
||||
bufferView?: number;
|
||||
byteOffset?: number;
|
||||
componentType?: number;
|
||||
count?: number;
|
||||
type?: string;
|
||||
min?: number[];
|
||||
max?: number[];
|
||||
sparse?: unknown;
|
||||
}
|
||||
|
||||
interface LooseBufferView {
|
||||
buffer?: number;
|
||||
byteOffset?: number;
|
||||
byteLength?: number;
|
||||
byteStride?: number;
|
||||
}
|
||||
|
||||
interface LoosePrimitive {
|
||||
attributes?: Record<string, number>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
interface LooseDocument {
|
||||
materials?: LooseMaterial[];
|
||||
meshes?: { primitives?: LoosePrimitive[] }[];
|
||||
accessors?: LooseAccessor[];
|
||||
bufferViews?: LooseBufferView[];
|
||||
extensionsUsed?: string[];
|
||||
extensions?: Record<string, unknown>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ApplyMmdMaterialsOptions {
|
||||
/** PMX 材质表(与 GLB 材质按索引一一对应;null/缺失时只做通用清理) */
|
||||
pmxMaterials?: PmxMaterialInfo[] | null;
|
||||
/** 着色模式:pbr(默认)| unlit(KHR_materials_unlit,颜色 = 贴图 x baseColorFactor) */
|
||||
shading?: ShadingMode;
|
||||
}
|
||||
|
||||
export interface ApplyMmdMaterialsResult {
|
||||
glb: Buffer;
|
||||
/** 被设为双面的材质数 */
|
||||
doubleSided: number;
|
||||
/** 按 shininess 调整过粗糙度的材质数 */
|
||||
roughnessAdjusted: number;
|
||||
/** 清掉的扩展名 */
|
||||
strippedExtensions: string[];
|
||||
/** 修正了 min/max 的浮点 accessor 数 */
|
||||
minMaxFixed: number;
|
||||
/** 是否写入了 unlit 扩展 */
|
||||
unlit: boolean;
|
||||
}
|
||||
|
||||
function clamp01(value: number): number {
|
||||
if (!Number.isFinite(value)) return 1;
|
||||
return Math.min(1, Math.max(0, value));
|
||||
}
|
||||
|
||||
function round2(value: number): number {
|
||||
return Math.round(value * 100) / 100;
|
||||
}
|
||||
|
||||
/** 按 PMX shininess 推一个 PBR 粗糙度:MMD 常见 1(很哑光),高值才是亮面 */
|
||||
function roughnessFromShininess(shininess: number): number {
|
||||
if (!Number.isFinite(shininess)) return 1;
|
||||
return round2(Math.min(1, Math.max(0.5, 1 - shininess / 100)));
|
||||
}
|
||||
|
||||
/** 读取 accessor 的浮点分量(只处理非稀疏、非交织或规范交织的 float 访问器) */
|
||||
function readAccessorFloats(
|
||||
doc: LooseDocument,
|
||||
bin: Buffer | null,
|
||||
accessorIndex: number,
|
||||
components: number,
|
||||
): Float32Array | null {
|
||||
const accessor = doc.accessors?.[accessorIndex];
|
||||
if (!accessor || accessor.sparse || typeof accessor.bufferView !== 'number') return null;
|
||||
// 注意下标:components=3 对应 'VEC3'(写成 [components] 会取到 VEC4,整段静默跳过)
|
||||
const expectedType = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'][components - 1];
|
||||
if (accessor.componentType !== 5126 || accessor.type !== expectedType) {
|
||||
return null;
|
||||
}
|
||||
const view = doc.bufferViews?.[accessor.bufferView];
|
||||
if (!view || view.buffer !== 0 || !bin) return null;
|
||||
const elementSize = components * 4;
|
||||
const stride = view.byteStride ?? elementSize;
|
||||
const base = (view.byteOffset ?? 0) + (accessor.byteOffset ?? 0);
|
||||
const count = accessor.count ?? 0;
|
||||
if (count <= 0 || base < 0) return null;
|
||||
if (base + (count - 1) * stride + elementSize > bin.length) return null;
|
||||
const out = new Float32Array(count * components);
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
for (let c = 0; c < components; c += 1) {
|
||||
out[i * components + c] = bin.readFloatLE(base + i * stride + c * 4);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修正 Assimp 写坏的 POSITION accessor min/max(实测 min 是 2.2250738585072014e-308)。
|
||||
* Godot 等客户端会用 min/max 算包围盒,坏值会导致取景异常。
|
||||
*/
|
||||
function fixAccessorMinMax(doc: LooseDocument, bin: Buffer | null): number {
|
||||
let fixed = 0;
|
||||
const componentsByType: Record<string, number> = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4 };
|
||||
for (let accessorIndex = 0; accessorIndex < (doc.accessors?.length ?? 0); accessorIndex += 1) {
|
||||
{
|
||||
const accessor = doc.accessors?.[accessorIndex];
|
||||
if (!accessor || accessor.sparse || accessor.componentType !== 5126) continue;
|
||||
const components = componentsByType[accessor.type ?? ''];
|
||||
if (!components) continue;
|
||||
const values = readAccessorFloats(doc, bin, accessorIndex, components);
|
||||
if (!values || values.length === 0) continue;
|
||||
const min = new Array(components).fill(Number.POSITIVE_INFINITY);
|
||||
const max = new Array(components).fill(Number.NEGATIVE_INFINITY);
|
||||
let usable = true;
|
||||
for (let i = 0; i < values.length; i += components) {
|
||||
for (let c = 0; c < components; c += 1) {
|
||||
const value = values[i + c];
|
||||
if (!Number.isFinite(value)) {
|
||||
usable = false;
|
||||
break;
|
||||
}
|
||||
if (value < min[c]) min[c] = value;
|
||||
if (value > max[c]) max[c] = value;
|
||||
}
|
||||
if (!usable) break;
|
||||
}
|
||||
if (!usable) continue;
|
||||
const same =
|
||||
Array.isArray(accessor.min) &&
|
||||
Array.isArray(accessor.max) &&
|
||||
accessor.min.length === components &&
|
||||
accessor.max.length === components &&
|
||||
accessor.min.every((value, index) => Math.abs(value - min[index]) < 1e-6) &&
|
||||
accessor.max.every((value, index) => Math.abs(value - max[index]) < 1e-6);
|
||||
if (same) continue;
|
||||
accessor.min = min;
|
||||
accessor.max = max;
|
||||
fixed += 1;
|
||||
}
|
||||
}
|
||||
return fixed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 MMD 材质参数补进 GLB,并做 PBR 规范化。
|
||||
* 返回 null 表示这个 GLB 解析不了(调用方应原样使用原 buffer)。
|
||||
*/
|
||||
export function applyMmdMaterials(
|
||||
glb: Buffer,
|
||||
options: ApplyMmdMaterialsOptions = {},
|
||||
): ApplyMmdMaterialsResult | null {
|
||||
let parsed: { json: LooseDocument; bin: Buffer | null };
|
||||
try {
|
||||
parsed = parseGlbChunks<LooseDocument>(glb);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const { json, bin } = parsed;
|
||||
const materials = json.materials;
|
||||
if (!Array.isArray(materials) || materials.length === 0) return null;
|
||||
|
||||
const pmxMaterials = options.pmxMaterials ?? null;
|
||||
const shading: ShadingMode = options.shading === 'unlit' ? 'unlit' : 'pbr';
|
||||
const stripped = new Set<string>();
|
||||
let doubleSided = 0;
|
||||
let roughnessAdjusted = 0;
|
||||
|
||||
for (let i = 0; i < materials.length; i += 1) {
|
||||
const material = materials[i];
|
||||
if (!material || typeof material !== 'object') continue;
|
||||
const pmx = pmxMaterials?.[i]; // Assimp 保持材质顺序(实测 39/39 对齐)
|
||||
|
||||
if (pmx) {
|
||||
// 1) 双面:PMX drawFlag bit0
|
||||
if (pmx.doubleSided) {
|
||||
if (material.doubleSided !== true) doubleSided += 1;
|
||||
material.doubleSided = true;
|
||||
} else if (material.doubleSided === true) {
|
||||
material.doubleSided = false;
|
||||
}
|
||||
|
||||
// 2) PBR 规范化
|
||||
const pbr = (material.pbrMetallicRoughness ??= {});
|
||||
pbr.metallicFactor = 0;
|
||||
const roughness = roughnessFromShininess(pmx.shininess);
|
||||
if (pbr.roughnessFactor !== roughness) {
|
||||
pbr.roughnessFactor = roughness;
|
||||
roughnessAdjusted += 1;
|
||||
}
|
||||
const diffuse = pmx.diffuse;
|
||||
const existing = Array.isArray(pbr.baseColorFactor) ? pbr.baseColorFactor : [1, 1, 1, 1];
|
||||
const merged = [
|
||||
clamp01((existing[0] ?? 1) * (diffuse[0] ?? 1)),
|
||||
clamp01((existing[1] ?? 1) * (diffuse[1] ?? 1)),
|
||||
clamp01((existing[2] ?? 1) * (diffuse[2] ?? 1)),
|
||||
clamp01((existing[3] ?? 1) * (diffuse[3] ?? 1)),
|
||||
];
|
||||
const unchanged =
|
||||
existing.length >= 4 &&
|
||||
existing[0] === merged[0] &&
|
||||
existing[1] === merged[1] &&
|
||||
existing[2] === merged[2] &&
|
||||
existing[3] === merged[3];
|
||||
if (!unchanged) pbr.baseColorFactor = merged;
|
||||
} else {
|
||||
const pbr = material.pbrMetallicRoughness;
|
||||
if (pbr && pbr.metallicFactor === undefined) pbr.metallicFactor = 0;
|
||||
}
|
||||
|
||||
// 3) 清掉与 MMD 无关的扩展(specular 为黑色时一并清掉)
|
||||
if (material.extensions) {
|
||||
const specularBlack =
|
||||
!pmx || (pmx.specular[0] === 0 && pmx.specular[1] === 0 && pmx.specular[2] === 0);
|
||||
for (const name of STRIPPED_EXTENSIONS) {
|
||||
if (name in material.extensions && (name !== 'KHR_materials_specular' || specularBlack)) {
|
||||
delete material.extensions[name];
|
||||
stripped.add(name);
|
||||
}
|
||||
}
|
||||
if (Object.keys(material.extensions).length === 0) delete material.extensions;
|
||||
}
|
||||
|
||||
// 4) 可选 unlit:颜色 = baseColorFactor x 贴图,与场景光照无关(最接近 MMD 的平涂观感)
|
||||
if (shading === 'unlit') {
|
||||
material.extensions = { ...(material.extensions ?? {}), KHR_materials_unlit: {} };
|
||||
}
|
||||
}
|
||||
|
||||
// extensionsUsed 与实际引用保持一致
|
||||
if (shading === 'unlit') {
|
||||
json.extensionsUsed = [...new Set([...(json.extensionsUsed ?? []), 'KHR_materials_unlit'])];
|
||||
}
|
||||
if (Array.isArray(json.extensionsUsed)) {
|
||||
const stillUsed = new Set<string>();
|
||||
for (const material of materials) {
|
||||
for (const name of Object.keys(material.extensions ?? {})) stillUsed.add(name);
|
||||
}
|
||||
for (const extension of Object.keys(json.extensions ?? {})) stillUsed.add(extension);
|
||||
json.extensionsUsed = json.extensionsUsed.filter((name) => stillUsed.has(name));
|
||||
if (json.extensionsUsed.length === 0) delete json.extensionsUsed;
|
||||
}
|
||||
|
||||
const minMaxFixed = fixAccessorMinMax(json, bin);
|
||||
return {
|
||||
glb: buildGlbChunks(json, bin),
|
||||
doubleSided,
|
||||
roughnessAdjusted,
|
||||
strippedExtensions: [...stripped],
|
||||
minMaxFixed,
|
||||
unlit: shading === 'unlit',
|
||||
};
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import { ModelFormat } from '../common/enums';
|
||||
import { ZipEntry, readZipEntries } from '../common/zip-reader';
|
||||
import { embedGlbImages } from './glb-textures';
|
||||
import { assimpMissingMessage, resolveAssimpBinary } from '../common/assimp';
|
||||
import { applyMmdMaterials, type ShadingMode } from './glb-materials';
|
||||
import { parsePmxMaterials } from './pmx-materials';
|
||||
import { packGltfToGlb } from './gltf-packer';
|
||||
import { VrmWrapMeta, detectGlbKind, wrapGlbAsVrm } from './vrm-writer';
|
||||
|
||||
@@ -36,6 +38,14 @@ const run = promisify(execFile);
|
||||
export interface ConvertOptions {
|
||||
/** Assimp 可执行文件(默认 `assimp`,可用 ASSIMP_BIN 覆盖) */
|
||||
assimpBin: string;
|
||||
/**
|
||||
* 着色模式(`MODEL_SHADING`):
|
||||
* pbr 默认,标准 PBR(我们会按 MMD 参数规范 metallic/roughness/双面)
|
||||
* unlit 写入 KHR_materials_unlit,颜色 = 贴图 x baseColorFactor,与场景光照无关
|
||||
*/
|
||||
shading?: ShadingMode;
|
||||
/** PMX 源文件(用于把 MMD 材质参数——尤其是双面标志——补回 GLB) */
|
||||
pmxSource?: Buffer | null;
|
||||
/** 单次转换超时(毫秒) */
|
||||
timeoutMs?: number;
|
||||
/** 优先交付的格式:`glb`(默认)或 `vrm` */
|
||||
@@ -333,6 +343,35 @@ async function runAssimpPipeline(
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 第 2.5 步:把 MMD 材质参数补回 GLB(Assimp 会丢掉双面标志与着色参数) ----
|
||||
// 实测:PMX 里 36/39 个材质是不剔除背面的,Assimp 导出的 GLB 里 doubleSided 一个都没有,
|
||||
// 头发/裙摆/睫毛这类薄片会被单面剔除 —— 看起来就是"贴图颜色不对"。
|
||||
const mmdMaterials = options.pmxSource ? parsePmxMaterials(options.pmxSource) : null;
|
||||
const applied = applyMmdMaterials(glbBuffer, {
|
||||
pmxMaterials: mmdMaterials,
|
||||
shading: options.shading ?? 'pbr',
|
||||
});
|
||||
let materialNote = '';
|
||||
if (applied) {
|
||||
glbBuffer = applied.glb;
|
||||
const bits: string[] = [];
|
||||
if (applied.doubleSided > 0) bits.push(`双面 ${applied.doubleSided} 项`);
|
||||
if (applied.roughnessAdjusted > 0) bits.push(`粗糙度按 shininess 调整 ${applied.roughnessAdjusted} 项`);
|
||||
if (applied.strippedExtensions.length > 0) bits.push(`清理扩展 ${applied.strippedExtensions.join('/')}`);
|
||||
if (applied.minMaxFixed > 0) bits.push(`修正 min/max ${applied.minMaxFixed} 项`);
|
||||
if (applied.unlit) bits.push('unlit 着色');
|
||||
if (bits.length > 0) attempts.push(`MMD 材质修正:${bits.join('、')}`);
|
||||
const sphereCount = (mmdMaterials ?? []).filter((m) => m.sphereTextureIndex >= 0).length;
|
||||
if (sphereCount > 0) {
|
||||
attempts.push(`球面贴图 ${sphereCount} 项:glTF core 无对应槽位,未保留(MMD 高光观感会有差异)`);
|
||||
}
|
||||
const noteBits: string[] = [];
|
||||
if (applied.doubleSided > 0) noteBits.push(`双面 ${applied.doubleSided} 项`);
|
||||
if (applied.unlit) noteBits.push('unlit 着色');
|
||||
if (sphereCount > 0) noteBits.push(`球面贴图 ${sphereCount} 项未保留`);
|
||||
if (noteBits.length > 0) materialNote = `;MMD 材质修正:${noteBits.join('、')}`;
|
||||
}
|
||||
|
||||
// ---- 第 3 步:按需封装成 VRM(优先 GLB,其次 VRM) ----
|
||||
if (prefer === 'vrm') {
|
||||
const wrapped = tryWrapVrm(glbBuffer, options.vrmMeta, modelLabel.replace(/\.[^.]+$/, ''));
|
||||
@@ -340,7 +379,7 @@ async function runAssimpPipeline(
|
||||
return {
|
||||
buffer: wrapped.buffer,
|
||||
format: ModelFormat.Vrm,
|
||||
note: `${modelLabel} → VRM(基于 GLB 封装${embedNote};${wrapped.detail})`,
|
||||
note: `${modelLabel} → VRM(基于 GLB 封装${embedNote}${materialNote};${wrapped.detail})`,
|
||||
attempts: [...attempts, `VRM 封装:${wrapped.detail}`],
|
||||
};
|
||||
}
|
||||
@@ -350,7 +389,7 @@ async function runAssimpPipeline(
|
||||
return {
|
||||
buffer: glbBuffer,
|
||||
format: ModelFormat.Glb,
|
||||
note: `${modelLabel} → GLB${embedNote}`,
|
||||
note: `${modelLabel} → GLB${embedNote}${materialNote}`,
|
||||
attempts,
|
||||
};
|
||||
}
|
||||
@@ -402,7 +441,11 @@ export async function convertModelArchive(
|
||||
modelPath,
|
||||
makeResolver(contents),
|
||||
candidate.entry.path.split('/').pop() ?? candidate.entry.path,
|
||||
options,
|
||||
{
|
||||
...options,
|
||||
// 只有 PMX 有 MMD 材质表;FBX 等按通用规则处理
|
||||
pmxSource: candidate.sourceFormat === 'pmx' ? candidate.entry.read() : null,
|
||||
},
|
||||
);
|
||||
return { ...result, sourceModelPath: candidate.entry.path, direct: false };
|
||||
} finally {
|
||||
@@ -423,7 +466,10 @@ export async function convertModelFile(
|
||||
try {
|
||||
const modelPath = join(workDir, basename(fileName));
|
||||
await writeFile(modelPath, buffer);
|
||||
const result = await runAssimpPipeline(modelPath, () => null, basename(fileName), options);
|
||||
const result = await runAssimpPipeline(modelPath, () => null, basename(fileName), {
|
||||
...options,
|
||||
pmxSource: extname(fileName).toLowerCase() === '.pmx' ? buffer : null,
|
||||
});
|
||||
return { ...result, sourceModelPath: basename(fileName), direct: false };
|
||||
} finally {
|
||||
await rm(workDir, { recursive: true, force: true });
|
||||
|
||||
@@ -133,6 +133,7 @@ export class ModelsService {
|
||||
timeoutMs: this.config.modelConvertTimeoutMs,
|
||||
preferFormat: this.config.modelConvertFormat,
|
||||
preferredPmx: this.config.modelConvertPmx,
|
||||
shading: this.config.modelShading,
|
||||
vrmMeta: { name, author: tuple.author ?? '', license: tuple.license },
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* 只读 PMX 的**材质段**(布局与 PMX 2.0 规范 / mmd-parser 一致)。
|
||||
*
|
||||
* 为什么需要:Assimp 6.0.4 的 PMX 导入会把 MMD 的材质参数大量丢弃——
|
||||
* 实测 `【奥黛塔】_by_原神.zip`(39 个材质)里 PMX 有 36 个材质带
|
||||
* **不剔除背面(双面)**标志,而导出的 GLB 里 `doubleSided` 一个都没有:
|
||||
* 头发、裙摆、睫毛这类薄片会被单面剔除掉,看起来就是"颜色/贴图不对"。
|
||||
* 因此转换后按 PMX 原始参数把 GLB 材质补回来(见 `glb-materials.ts`)。
|
||||
*
|
||||
* 只读、尽力而为:任何越界/未知版本都返回 null,绝不让调用方失败。
|
||||
*/
|
||||
|
||||
/** PMX 材质的关键参数(我们关心的子集) */
|
||||
export interface PmxMaterialInfo {
|
||||
name: string;
|
||||
diffuse: [number, number, number, number];
|
||||
specular: [number, number, number];
|
||||
/** 镜面反射强度(MMD 的 specular power,常见的 0~100+) */
|
||||
shininess: number;
|
||||
ambient: [number, number, number];
|
||||
/** 原始 drawFlag:bit0 = 不剔除背面(双面) */
|
||||
flag: number;
|
||||
/** 是否双面渲染(drawFlag bit0) */
|
||||
doubleSided: boolean;
|
||||
/** 球面贴图(SPH/SPA)索引,-1 表示没有 */
|
||||
sphereTextureIndex: number;
|
||||
/** 球面贴图模式:0 关闭 / 1 乘算 / 2 加算 / 3 子贴图 */
|
||||
sphereMode: number;
|
||||
/** 0 = 使用 toonIndex 指定的贴图;1 = 使用共享 toon */
|
||||
toonFlag: number;
|
||||
toonIndex: number;
|
||||
/** 该材质覆盖的三角形数 */
|
||||
faceCount: number;
|
||||
}
|
||||
|
||||
const PMX_MAGIC = 'PMX ';
|
||||
|
||||
class Cursor {
|
||||
private offset = 0;
|
||||
|
||||
constructor(private readonly buffer: Buffer) {}
|
||||
|
||||
get position(): number {
|
||||
return this.offset;
|
||||
}
|
||||
|
||||
get remaining(): number {
|
||||
return this.buffer.length - this.offset;
|
||||
}
|
||||
|
||||
u8(): number {
|
||||
const value = this.buffer.readUInt8(this.offset);
|
||||
this.offset += 1;
|
||||
return value;
|
||||
}
|
||||
|
||||
i8(): number {
|
||||
const value = this.buffer.readInt8(this.offset);
|
||||
this.offset += 1;
|
||||
return value;
|
||||
}
|
||||
|
||||
u16(): number {
|
||||
const value = this.buffer.readUInt16LE(this.offset);
|
||||
this.offset += 2;
|
||||
return value;
|
||||
}
|
||||
|
||||
i32(): number {
|
||||
const value = this.buffer.readInt32LE(this.offset);
|
||||
this.offset += 4;
|
||||
return value;
|
||||
}
|
||||
|
||||
u32(): number {
|
||||
const value = this.buffer.readUInt32LE(this.offset);
|
||||
this.offset += 4;
|
||||
return value;
|
||||
}
|
||||
|
||||
f32(): number {
|
||||
const value = this.buffer.readFloatLE(this.offset);
|
||||
this.offset += 4;
|
||||
return value;
|
||||
}
|
||||
|
||||
floats(count: number): number[] {
|
||||
const out: number[] = [];
|
||||
for (let i = 0; i < count; i += 1) out.push(this.f32());
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 按字节宽度读索引(PMX 允许 1 / 2 / 4 字节,**有符号**:-1 表示无) */
|
||||
index(size: number): number {
|
||||
if (size === 1) return this.i8();
|
||||
if (size === 2) {
|
||||
const value = this.buffer.readInt16LE(this.offset);
|
||||
this.offset += 2;
|
||||
return value;
|
||||
}
|
||||
return this.i32();
|
||||
}
|
||||
|
||||
skip(bytes: number): void {
|
||||
this.offset += bytes;
|
||||
}
|
||||
|
||||
/** PMX 文本:int32 字节长度 + 内容(UTF-16LE 或 UTF-8) */
|
||||
text(utf16: boolean): string {
|
||||
const length = this.i32();
|
||||
if (length < 0) throw new Error('PMX 文本长度非法');
|
||||
const raw = this.buffer.subarray(this.offset, this.offset + length);
|
||||
this.offset += length;
|
||||
return raw.toString(utf16 ? 'utf16le' : 'utf8');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 PMX 的材质段;不是 PMX / 结构异常一律返回 null。
|
||||
* 会跳过顶点、面、贴图段,只为拿到材质参数,不做几何解析。
|
||||
*/
|
||||
export function parsePmxMaterials(buffer: Buffer): PmxMaterialInfo[] | null {
|
||||
try {
|
||||
if (buffer.length < 32 || buffer.toString('ascii', 0, 4) !== PMX_MAGIC) return null;
|
||||
const cursor = new Cursor(buffer);
|
||||
cursor.skip(4);
|
||||
cursor.f32(); // version
|
||||
const globalCount = cursor.u8();
|
||||
if (globalCount < 8) return null;
|
||||
const globals = [];
|
||||
for (let i = 0; i < globalCount; i += 1) globals.push(cursor.u8());
|
||||
const encoding = globals[0]; // 0 = UTF-16LE, 1 = UTF-8
|
||||
const additionalUvNum = globals[1];
|
||||
const vertexIndexSize = globals[2];
|
||||
const textureIndexSize = globals[3];
|
||||
const boneIndexSize = globals[5];
|
||||
const utf16 = encoding === 0;
|
||||
|
||||
// 头部 4 段文本:name / nameEn / comment / commentEn
|
||||
for (let i = 0; i < 4; i += 1) cursor.text(utf16);
|
||||
|
||||
// 顶点段:跳过
|
||||
const vertexCount = cursor.i32();
|
||||
if (vertexCount < 0) return null;
|
||||
for (let i = 0; i < vertexCount; i += 1) {
|
||||
cursor.skip(12 + 12 + 8 + additionalUvNum * 16);
|
||||
const type = cursor.u8();
|
||||
if (type === 0) cursor.skip(boneIndexSize);
|
||||
else if (type === 1) cursor.skip(boneIndexSize * 2 + 4);
|
||||
else if (type === 2) cursor.skip(boneIndexSize * 4 + 16);
|
||||
else if (type === 3) cursor.skip(boneIndexSize * 2 + 4 + 36);
|
||||
else if (type === 4) cursor.skip(boneIndexSize * 4 + 16); // QDEF(PMX 2.1)
|
||||
else return null;
|
||||
cursor.skip(4); // edge scale
|
||||
if (cursor.remaining <= 0) return null;
|
||||
}
|
||||
|
||||
// 面段:索引个数 × 索引宽度
|
||||
const faceIndexCount = cursor.i32();
|
||||
if (faceIndexCount < 0) return null;
|
||||
cursor.skip(faceIndexCount * vertexIndexSize);
|
||||
|
||||
// 贴图段:跳过
|
||||
const textureCount = cursor.i32();
|
||||
if (textureCount < 0) return null;
|
||||
for (let i = 0; i < textureCount; i += 1) cursor.text(utf16);
|
||||
|
||||
// 材质段
|
||||
const materialCount = cursor.i32();
|
||||
if (materialCount < 0 || materialCount > 100_000) return null;
|
||||
const materials: PmxMaterialInfo[] = [];
|
||||
for (let i = 0; i < materialCount; i += 1) {
|
||||
const name = cursor.text(utf16);
|
||||
cursor.text(utf16); // englishName
|
||||
const diffuse = cursor.floats(4) as [number, number, number, number];
|
||||
const specular = cursor.floats(3) as [number, number, number];
|
||||
const shininess = cursor.f32();
|
||||
const ambient = cursor.floats(3) as [number, number, number];
|
||||
const flag = cursor.u8();
|
||||
cursor.skip(16 + 4); // edgeColor(4f) + edgeSize(1f)
|
||||
const textureIndex = cursor.index(textureIndexSize);
|
||||
const sphereTextureIndex = cursor.index(textureIndexSize);
|
||||
const sphereMode = cursor.u8();
|
||||
const toonFlag = cursor.u8();
|
||||
const toonIndex = toonFlag === 0 ? cursor.index(textureIndexSize) : cursor.i8();
|
||||
cursor.text(utf16); // comment
|
||||
const faceCount = Math.floor(cursor.u32() / 3);
|
||||
materials.push({
|
||||
name,
|
||||
diffuse,
|
||||
specular,
|
||||
shininess,
|
||||
ambient,
|
||||
flag,
|
||||
doubleSided: (flag & 0x01) !== 0,
|
||||
sphereTextureIndex,
|
||||
sphereMode,
|
||||
toonFlag,
|
||||
toonIndex,
|
||||
faceCount,
|
||||
});
|
||||
}
|
||||
return materials;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ModelFormat } from '../common/enums';
|
||||
import { buildGlbChunks, parseGlbChunks } from '../common/glb-chunks';
|
||||
import { HUMANOID_CANDIDATES, HUMANOID_REQUIRED, normalizeBoneName, boneNameVariants } from './model-inspector';
|
||||
|
||||
/**
|
||||
@@ -45,63 +46,11 @@ interface GltfJson {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
function align4(value: number): number {
|
||||
return value + ((4 - (value % 4)) % 4);
|
||||
}
|
||||
/** 解析 GLB 的 JSON 与 BIN chunk(实现见 common/glb-chunks.ts) */
|
||||
const parseGlb = (buffer: Buffer): { json: GltfJson; bin: Buffer | null } =>
|
||||
parseGlbChunks<GltfJson>(buffer);
|
||||
|
||||
/** 解析 GLB 的 JSON 与 BIN chunk */
|
||||
function parseGlb(buffer: Buffer): { json: GltfJson; bin: Buffer | null } {
|
||||
if (buffer.length < 12 || buffer.readUInt32LE(0) !== GLB_MAGIC) {
|
||||
throw new Error('不是有效的 GLB(魔数不正确)');
|
||||
}
|
||||
const total = buffer.readUInt32LE(8) || buffer.length;
|
||||
const end = Math.min(total, buffer.length);
|
||||
let offset = 12;
|
||||
let json: GltfJson | null = null;
|
||||
let bin: Buffer | null = null;
|
||||
while (offset + 8 <= end) {
|
||||
const length = buffer.readUInt32LE(offset);
|
||||
const type = buffer.readUInt32LE(offset + 4);
|
||||
const start = offset + 8;
|
||||
if (start + length > buffer.length) break;
|
||||
const data = buffer.subarray(start, start + length);
|
||||
if (type === CHUNK_JSON) json = JSON.parse(data.toString('utf8')) as GltfJson;
|
||||
else if (type === CHUNK_BIN) bin = Buffer.from(data);
|
||||
offset = start + align4(length);
|
||||
}
|
||||
if (!json) throw new Error('GLB 里没有 JSON chunk');
|
||||
return { json, bin };
|
||||
}
|
||||
|
||||
function buildGlb(json: GltfJson, bin: Buffer | null): Buffer {
|
||||
const jsonBuffer = Buffer.from(JSON.stringify(json), 'utf8');
|
||||
const jsonPadded = Buffer.alloc(align4(jsonBuffer.length), 0x20);
|
||||
jsonBuffer.copy(jsonPadded);
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
const header = Buffer.alloc(12);
|
||||
header.writeUInt32LE(GLB_MAGIC, 0);
|
||||
header.writeUInt32LE(2, 4);
|
||||
chunks.push(header);
|
||||
|
||||
const jsonHeader = Buffer.alloc(8);
|
||||
jsonHeader.writeUInt32LE(jsonPadded.length, 0);
|
||||
jsonHeader.writeUInt32LE(CHUNK_JSON, 4);
|
||||
chunks.push(jsonHeader, jsonPadded);
|
||||
|
||||
if (bin && bin.length > 0) {
|
||||
const binPadded = Buffer.alloc(align4(bin.length));
|
||||
bin.copy(binPadded);
|
||||
const binHeader = Buffer.alloc(8);
|
||||
binHeader.writeUInt32LE(binPadded.length, 0);
|
||||
binHeader.writeUInt32LE(CHUNK_BIN, 4);
|
||||
chunks.push(binHeader, binPadded);
|
||||
}
|
||||
|
||||
const out = Buffer.concat(chunks);
|
||||
out.writeUInt32LE(out.length, 8);
|
||||
return out;
|
||||
}
|
||||
const buildGlb = (json: GltfJson, bin: Buffer | null): Buffer => buildGlbChunks(json, bin);
|
||||
|
||||
/**
|
||||
* 按骨骼名把 glTF 节点映射到 VRM humanoid 规范骨。
|
||||
|
||||
Reference in New Issue
Block a user