election-game/art/optimize-3d.mjs

99 lines
4.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 3D 模型(web/public/assets/3d,Kenney CC0)壓小:首頁、政策島、政治生涯的小鎮一開始要下載 3 MB 多的模型。
// - 角色只留程式用到的動作(static、idle、emote-yes、jump;原本每個角色 32 段)
// - 拿掉用不到的頂點資料(沒有法線貼圖就不要切線、沒用第二組貼圖座標就不要 TEXCOORD_1)
// - 量化+meshopt 壓縮(EXT_meshopt_compression,前端 game/gltf.ts 用 three.js 附的 MeshoptDecoder 解)
// 貼圖維持外部檔(Textures/*.png,好幾個模型共用一張,瀏覽器只抓一次)。已經壓過的檔案會跳過。
//
// 用法:cd art && npm i --no-save @gltf-transform/core@4 @gltf-transform/extensions@4 @gltf-transform/functions@4 meshoptimizer@0.22 && node optimize-3d.mjs
import { readdirSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { NodeIO } from "@gltf-transform/core";
import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
import { dedup, meshopt, prune, resample } from "@gltf-transform/functions";
import { MeshoptDecoder, MeshoptEncoder } from "meshoptimizer";
const ROOT = process.env.MODELS_DIR ?? new URL("../web/public/assets/3d/", import.meta.url).pathname;
/** 程式用到的角色動作(hero3d、island3d、careerBoard3d、board3d/effects 的 findByName;static 是找不到時的預設) */
const KEEP_CLIPS = new Set(["static", "idle", "emote-yes", "jump"]);
await MeshoptEncoder.ready;
await MeshoptDecoder.ready;
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ "meshopt.encoder": MeshoptEncoder, "meshopt.decoder": MeshoptDecoder });
const files = readdirSync(ROOT, { recursive: true })
.map(String)
.filter((f) => f.endsWith(".glb"))
.sort();
let before = 0;
let after = 0;
for (const rel of files) {
const path = join(ROOT, rel);
const size = statSync(path).size;
const doc = await io.read(path);
const root = doc.getRoot();
if (root.listExtensionsUsed().some((e) => e.extensionName === "EXT_meshopt_compression")) {
console.log(`跳過(已經壓過)${rel}`);
continue;
}
if (rel.startsWith("characters/"))
for (const a of root.listAnimations()) {
if (KEEP_CLIPS.has(a.getName())) continue;
// 通道、取樣器要一起丟,不然它們還指著關鍵影格,prune 不會清掉
for (const c of a.listChannels()) c.dispose();
for (const s of a.listSamplers()) s.dispose();
a.dispose();
}
const usesNormalMap = root.listMaterials().some((m) => m.getNormalTexture());
const usesUv1 = root.listMaterials().some((m) => [m.getBaseColorTextureInfo(), m.getNormalTextureInfo(), m.getOcclusionTextureInfo(), m.getEmissiveTextureInfo(), m.getMetallicRoughnessTextureInfo()].some((t) => t && t.getTexCoord() === 1));
for (const mesh of root.listMeshes())
for (const prim of mesh.listPrimitives()) {
if (!usesNormalMap) prim.setAttribute("TANGENT", null);
if (!usesUv1) prim.setAttribute("TEXCOORD_1", null);
}
await doc.transform(dedup(), prune(), resample(), meshopt({ encoder: MeshoptEncoder, level: "medium" }));
writeFileSync(path, await writeKeepingTextures(doc));
const out = statSync(path).size;
before += size;
after += out;
console.log(`${rel}:${(size / 1024).toFixed(0)} → ${(out / 1024).toFixed(0)} KB`);
}
console.log(`合計 ${(before / 1024).toFixed(0)} → ${(after / 1024).toFixed(0)} KB`);
/**
* 寫成 .glb,但外部貼圖(Textures/*.png)維持外部檔:GLB 格式一定會把圖片嵌進去,
* 所以先換成 1 byte 的佔位圖,寫完再把 JSON 裡的圖片改回原本的檔名(佔位的 1 byte 留在檔案裡沒有用到)
*/
async function writeKeepingTextures(doc) {
const textures = doc.getRoot().listTextures();
const uris = textures.map((t) => t.getURI());
for (const [i, t] of textures.entries()) if (uris[i]) t.setImage(new Uint8Array([0]));
const glb = await io.writeBinary(doc);
const view = new DataView(glb.buffer, glb.byteOffset, glb.byteLength);
const jsonLength = view.getUint32(12, true);
const json = JSON.parse(new TextDecoder().decode(glb.subarray(20, 20 + jsonLength)));
for (const [i, uri] of uris.entries()) {
const image = json.images?.[i];
if (!uri || !image) continue;
delete image.bufferView;
delete image.mimeType;
image.uri = uri;
}
let text = JSON.stringify(json);
while (text.length % 4) text += " ";
const jsonBytes = new TextEncoder().encode(text);
const rest = glb.subarray(20 + jsonLength);
const out = new Uint8Array(20 + jsonBytes.length + rest.length);
const w = new DataView(out.buffer);
w.setUint32(0, 0x46546c67, true);
w.setUint32(4, 2, true);
w.setUint32(8, out.length, true);
w.setUint32(12, jsonBytes.length, true);
w.setUint32(16, 0x4e4f534a, true);
out.set(jsonBytes, 20);
out.set(rest, 20 + jsonBytes.length);
return out;
}