mirror of
https://github.com/blitzkit/blitzkit.git
synced 2026-12-01 05:43:22 +01:00
## Why In CI, `models_legendary` was the slowest chunk of the website build (65 min on 2026-11-08), slower than `models_tanks` (49 min) even though there are far fewer camouflages (443) than tanks (738). In the CI log, each camouflage takes longer than the last, from about 8 s at the start to about 50 s near the end, which looked like a leak. It isn't a leak: - Nothing is kept between routes (no module-level caches) and the file reader caches nothing. - The camouflages later in the list are heavier: newer tanks with more parts and textures. - All the work is JavaScript on one thread, so Astro's 4 routes at a time take turns on one core. Each route's time also includes waiting for the other three. The build only kept about 1 core busy. A CPU profile of one heavy camouflage (1224, 52 s) showed where the time goes: - **About 60% in `readTexture`:** decoding DDS textures in our own decoder (`core/src/streams/dds.ts`). - **About 16% in `crc32`:** checksumming every `.dvpl` game file with the pure-JavaScript `crc` package. - **Repeated work:** that camouflage decoded 32 textures, but only 8 different files. Every part decodes the camouflage's shared atlas again (4 textures × 7 parts). ## What changed ### DDS decoder (`packages/core/src/streams/dds.ts`) The old decoder allocated at almost every step: - for every pixel, a new 4-value array (`[...color, alpha]`), then `forEach` + `Math.round`; - for every block, a closure plus palette objects built with `.map()` and spread; - for every small read (2–8 bytes), a byte copy through `consumeUint8Array`; - every loop through lodash `times()`, adding a function call per block and per pixel. A 2048×2048 texture has 4 million pixels in 262,000 blocks, so that meant tens of millions of allocations and calls per texture, all on the single JavaScript thread. `decodeBlocks` now: - reads the file's bytes in place; - works out each block's palette once into two reused 16-byte buffers; - writes the pixels straight into the output with plain loops. The output is unchanged. Palette values use the same formulas in the same order (for example `(2 * c0 + c1) / 3`) and are rounded with the same `Math.round(value * 255)`. Rounding once per palette entry gives the same bytes as rounding once per pixel. Two old quirks are kept on purpose: - BC1 is treated as transparent when `color0 < color1` (the standard says `<=`). - BC3's 6-alpha mode stores `255` for index 7, which wraps to `1` as a byte (the standard value is opaque). This is marked in a comment and left for a separate fix, because fixing it changes some textures. ### Texture reuse (`[...chunk_models_tanks]/[id]/model.glb.ts`) `cachedImage` keeps the last 64 finished textures (encoded images), keyed by reader and file path, and wraps `readBaseColor`, `readOcclusion`, `readRoughnessMetallic` and `readNormal`. Repeat requests reuse the same image instead of decoding and encoding again. The cap keeps memory from growing over the build. The logic inside the four readers is unchanged; they're only re-indented. ### DVPL checksum (`packages/core/src/blitz/readDVPL.ts`) `Bun.hash.crc32` replaces the `crc` package and gives the same values. `readDVPL` only runs under Bun (every caller reads through `LocalVFS`, which already uses `Bun.file`). `crc` is removed from core's dependencies; the scripts package still uses it. ## Timings All local timings are on the same Mac, one after another, with nothing else heavy running. ### Full builds "Before" for a local build is CI time ÷ 1.5, which matches the real ~40-minute local camouflage build of main. | Build | CI on main (2026-11-08) | Before, local (CI ÷ 1.5) | After, local | Speed-up | |---|---|---|---|---| | models_tanks | 49 min | ~33 min | 6 min 37 s | ~4.9× | | models_legendary | 65 min | ~43 min | 4 min 52 s | ~8.9× | With the 2026-11-10 production run (58 and 57 min), it's ~5.8× for tanks and ~7.8× for camouflages. The camouflage build after each step, locally: | Stage | models_legendary | |---|---| | main (real local build) | ~40 min | | Texture reuse + checksum | 32 min 24 s | | + DDS decoder | 4 min 52 s | ### Samples (main against this change, same machine) | Sample | main | After | Speed-up | Identical | |---|---|---|---|---| | 30 DDS textures (BC1/BC2/BC3, incl. sRGB) | 6.1 s | 0.3 s | ~20× | 30/30 | | 5 heavy late camouflages from CI | 124.6 s | 13.4 s | ~9.3× | 5/5 | | 45 camouflages (every 10th in build order) | 258.5 s | 77.2 s | ~3.35× | 45/45 | | 29 tanks (15 slowest in CI + 14 spread) | 105.3 s | 43.6 s | ~2.4× | 29/29 | The 5 heavy camouflages after each step: | Camouflage | main | Texture reuse | + checksum | + DDS decoder | |---|---|---|---|---| | 1224 | 49.7 s | 6.2 s | 6.4 s | 3.2 s | | 2146 | 17.2 s | 6.3 s | 6.4 s | 2.9 s | | 2122 | 31.4 s | 7.5 s | 5.9 s | 2.6 s | | 2143 | 16.9 s | 10.1 s | 6.1 s | 2.8 s | | 2059 | 9.6 s | 5.8 s | 4.1 s | 1.9 s | | **Total** | **124.6 s** | **36.0 s** | **28.9 s** | **13.4 s** | The single-camouflage speed-up (3.35× on the 45-camouflage sample) is smaller than the full-build one (~8×). With decoding no longer holding the JavaScript thread, Astro's 4 routes at a time overlap instead of queuing, and sharp's threads run alongside them. ### Full site build (`CHUNK=*`, all chunks one after another) 36 min 36 s, 0 errors, 21,613 routes, peak memory 4.6 GB. | Chunk | Time | |---|---| | api | ~4.3 min | | models_tanks | ~6.1 min | | models_legendary | ~4.6 min | | default (pages, 9 locales) | ~21 min | ### CPU and memory - The tank build used 1,183 s of CPU in 397 s, so about 3 cores busy on average; before, it was about 1. - Peak memory was 3.5 GB for the tank build and 4.6 GB for the full site. - CI runners have 4 cores and 16 GB, so this fits. No threads or processes were added: Astro's concurrency (4) and sharp's threading are unchanged. ## What this means for CI The chunks run as parallel jobs, so the website build takes as long as its slowest chunk. Before, that was `models_legendary` at about 65 min. Using CI ≈ 1.5× local, tank models should take about 10 min and camouflages about 7–8 min. `default` (about 36 min in CI) becomes the slowest chunk, so the whole build should drop from about 65 min to about 36. This is an estimate until the next CI run. ## Checked - Byte-identical GLBs (SHA-1) for 45 camouflages and 29 tanks against main, and decoded pixels for 30 DDS textures. - A full site build finishes with no errors. - Animations and particles are unaffected: the camouflage GLBs, including their animation data, are byte-identical.
689 lines
20 KiB
TypeScript
689 lines
20 KiB
TypeScript
import {
|
|
bufferToBigInt,
|
|
DdsReadStream,
|
|
parseHierarchies,
|
|
PvrReadStream,
|
|
Sc2ReadStream,
|
|
ScgReadStream,
|
|
toUniqueId,
|
|
VertexAttribute,
|
|
type ConfigArchive,
|
|
type Hierarchy,
|
|
type TankParameters,
|
|
type Textures,
|
|
type VehicleDefinitionList,
|
|
} from "@blitzkit/core";
|
|
import type { AbstractVFS } from "@blitzkit/core/src/blitzkit/vfs/abstract";
|
|
import {
|
|
Document,
|
|
Material,
|
|
Node,
|
|
NodeIO,
|
|
Scene,
|
|
type Skin,
|
|
} from "@gltf-transform/core";
|
|
import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
|
|
import { dedup, prune } from "@gltf-transform/functions";
|
|
import type { APIContext } from "astro";
|
|
import { isEqual, times } from "lodash-es";
|
|
import { dirname } from "path";
|
|
import sharp from "sharp";
|
|
import type { Motion } from "../../../core/blitzkit/skinAnimations/motion";
|
|
import {
|
|
bindSocket,
|
|
createMotionClip,
|
|
createSkeleton,
|
|
loadMotion,
|
|
skinPrimitive,
|
|
} from "../../../core/blitzkit/skinAnimations/skeleton";
|
|
import { partGarage } from "../../../core/blitzkit/switcherStates";
|
|
import { vfs } from "../../../core/blitzkit/vfs";
|
|
import {
|
|
vertexAttributeGLTFName,
|
|
vertexAttributeGltfVectorSizes,
|
|
} from "./collision.glb";
|
|
|
|
export { getStaticPaths } from "./_index";
|
|
|
|
export async function GET({ props }: APIContext<{ id: number }>) {
|
|
const nodeIO = new NodeIO().registerExtensions(ALL_EXTENSIONS);
|
|
const nations = await vfs
|
|
.dir(`Data/XML/item_defs/vehicles`)
|
|
.then((files) => files.filter((nation) => nation !== "common"));
|
|
|
|
for (const nationIndex in nations) {
|
|
const nation = nations[nationIndex];
|
|
const tanks = await vfs.xml<{ root: VehicleDefinitionList }>(
|
|
`Data/XML/item_defs/vehicles/${nation}/list.xml`,
|
|
);
|
|
const entries = Object.entries(tanks.root);
|
|
|
|
for (const [tankKey, tank] of entries) {
|
|
if (tankKey.includes("tutorial_bot")) continue;
|
|
|
|
const id = toUniqueId(nation, tank.id);
|
|
|
|
if (id !== props.id) continue;
|
|
|
|
const parameters = await vfs.yaml<TankParameters>(
|
|
`Data/3d/Tanks/Parameters/${nation}/${tankKey}.yaml`,
|
|
);
|
|
const model = await extractModel(
|
|
vfs,
|
|
parameters.resourcesPath.blitzModelPath.replace(/\.sc2$/, ""),
|
|
);
|
|
const bytes = await nodeIO.writeBinary(model);
|
|
|
|
return new Response(bytes);
|
|
}
|
|
}
|
|
}
|
|
|
|
const ERROR_ON_UNKNOWN_COMPONENT = false;
|
|
|
|
const omitMeshNames = {
|
|
start: [
|
|
"chassis_chassis_",
|
|
"chassis_track_crash_",
|
|
"HP_",
|
|
// mastery marks a new tank doesn't have yet
|
|
"custom_gun_marks_",
|
|
],
|
|
end: ["_POINT"],
|
|
};
|
|
|
|
export async function extractModel(
|
|
vfs: AbstractVFS,
|
|
path: string,
|
|
isPart = false,
|
|
preset?: string,
|
|
) {
|
|
const sc2Path = `Data/3d/${path}.sc2`;
|
|
const scgPath = `Data/3d/${path}.scg`;
|
|
const sc2 = new Sc2ReadStream(
|
|
(await vfs.file(sc2Path)).buffer as ArrayBuffer,
|
|
).sc2();
|
|
const scg = new ScgReadStream(
|
|
(await vfs.file(scgPath)).buffer as ArrayBuffer,
|
|
).scg();
|
|
const document = new Document();
|
|
const scene = document.createScene();
|
|
const buffer = document.createBuffer();
|
|
const materials = await extractMaterials(document, sc2, path);
|
|
const skeletons = new Map<Hierarchy, ReturnType<typeof createSkeleton>>();
|
|
const jointBindings: [
|
|
owner: Node,
|
|
entity: string,
|
|
joint: Node,
|
|
skin: Skin,
|
|
][] = [];
|
|
const motions = new Map<Hierarchy, Motion>();
|
|
const garage = isPart ? partGarage(sc2, preset) : undefined;
|
|
|
|
if (isPart) {
|
|
const loading: Promise<void>[] = [];
|
|
|
|
parseHierarchies(sc2["#hierarchy"], null, (hierarchy, components) => {
|
|
for (const component of components) {
|
|
if (component["comp.typename"] !== "MotionComponent") continue;
|
|
|
|
loading.push(
|
|
loadMotion(vfs, path, component).then((motion) => {
|
|
motions.set(hierarchy, motion);
|
|
}),
|
|
);
|
|
}
|
|
|
|
return null;
|
|
});
|
|
|
|
await Promise.all(loading);
|
|
}
|
|
|
|
parseHierarchies<Scene | Node>(
|
|
sc2["#hierarchy"],
|
|
scene,
|
|
(hierarchy, components, parent) => {
|
|
if (
|
|
omitMeshNames.start.some((omit) => hierarchy.name.startsWith(omit)) ||
|
|
omitMeshNames.end.some((omit) => hierarchy.name.endsWith(omit))
|
|
)
|
|
return;
|
|
|
|
const node = document.createNode(hierarchy.name);
|
|
|
|
if (isPart) {
|
|
const skeleton = components.find(
|
|
(component) => component["comp.typename"] === "SkeletonComponent",
|
|
);
|
|
const motionComponent = components.find(
|
|
(component) => component["comp.typename"] === "MotionComponent",
|
|
);
|
|
const motion = motions.get(hierarchy);
|
|
|
|
if (skeleton) {
|
|
const created = createSkeleton(
|
|
document,
|
|
buffer,
|
|
node,
|
|
skeleton,
|
|
motion,
|
|
);
|
|
|
|
skeletons.set(hierarchy, created);
|
|
|
|
// only what loops in the garage is exported
|
|
if (motion && motionComponent && garage?.motions.has(hierarchy)) {
|
|
createMotionClip(
|
|
document,
|
|
buffer,
|
|
`motion${document.getRoot().listAnimations().length}`,
|
|
created.joints,
|
|
motion,
|
|
motionComponent,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
components.forEach((component) => {
|
|
switch (component["comp.typename"]) {
|
|
case "LodComponent":
|
|
// found and used later by transform component
|
|
// TODO: lod component always shows up before transform component; cache it before parsing transform
|
|
break;
|
|
|
|
case "TransformComponent": {
|
|
const localTranslation = component["tc.localTranslation"];
|
|
// The game resets top-level node translation to [0, 0, 0] on load.
|
|
// Child nodes and customization parts must keep their authored
|
|
// local offsets.
|
|
node.setTranslation(
|
|
parent instanceof Scene && !isPart ? [0, 0, 0] : localTranslation,
|
|
);
|
|
node.setRotation(component["tc.localRotation"]);
|
|
node.setScale(component["tc.localScale"]);
|
|
|
|
break;
|
|
}
|
|
|
|
case "StateSwitcherComponent":
|
|
node.setExtras({
|
|
// a part's scenarios can pick its state as it loads
|
|
state: garage
|
|
? (garage.states.get(hierarchy) ?? null)
|
|
: component[`ssc.state${component["ssc.activeState"]}`],
|
|
});
|
|
break;
|
|
|
|
case "SkeletonJointBindingComponent": {
|
|
const skeleton = skeletons.get(hierarchy);
|
|
|
|
if (!skeleton) break;
|
|
|
|
times(component.count, (index) => {
|
|
const binding = component.map[
|
|
index.toString().padStart(4, "0")
|
|
] as unknown as { entityUid: string; jointUid: string };
|
|
const joint = skeleton.joints.get(binding.jointUid);
|
|
|
|
if (!joint) throw new Error(`Missing joint ${binding.jointUid}`);
|
|
|
|
jointBindings.push([
|
|
node,
|
|
binding.entityUid,
|
|
joint,
|
|
skeleton.skin,
|
|
]);
|
|
});
|
|
break;
|
|
}
|
|
|
|
case "RenderComponent": {
|
|
const renderObject = component["rc.renderObj"];
|
|
|
|
times(renderObject["ro.batchCount"], (batchIndex): void => {
|
|
const lodIndex = renderObject[`rb${batchIndex}.lodIndex`];
|
|
|
|
// -1 means the batch has no lods and is always drawn
|
|
if (lodIndex !== 0 && !(isPart && lodIndex === -1)) return;
|
|
|
|
const batchKey = batchIndex.toString().padStart(4, "0");
|
|
const batch = renderObject["ro.batches"][batchKey];
|
|
const material = materials.get(batch["rb.nmatname"]);
|
|
const polygonGroup = scg.get(batch["rb.datasource"]);
|
|
|
|
if (!(material instanceof Material)) {
|
|
// probably shadow material
|
|
return;
|
|
}
|
|
if (polygonGroup === undefined) {
|
|
throw new Error(
|
|
`Missing polygon group ${batch["rb.datasource"]}`,
|
|
);
|
|
}
|
|
|
|
const lodNode = document.createNode(batchKey);
|
|
const indicesAccessor = document
|
|
.createAccessor()
|
|
.setType("SCALAR")
|
|
.setArray(new Uint16Array(polygonGroup.indices))
|
|
.setBuffer(buffer);
|
|
const primitive = document
|
|
.createPrimitive()
|
|
.setIndices(indicesAccessor)
|
|
.setMaterial(material)
|
|
.setName(batchKey);
|
|
|
|
const attributes = new Map<VertexAttribute, number[][]>();
|
|
|
|
polygonGroup.vertices.forEach((vertex) => {
|
|
vertex.forEach(({ attribute, value }) => {
|
|
if (!attributes.has(attribute)) {
|
|
attributes.set(attribute, []);
|
|
}
|
|
|
|
attributes.get(attribute)!.push(value);
|
|
});
|
|
});
|
|
|
|
attributes.forEach((value, attribute) => {
|
|
const name = vertexAttributeGLTFName[attribute];
|
|
|
|
if (
|
|
name === undefined ||
|
|
primitive.getAttribute(name) !== null
|
|
) {
|
|
return;
|
|
}
|
|
|
|
const vertexSize = vertexAttributeGltfVectorSizes[attribute];
|
|
const attributeAccessor = document
|
|
.createAccessor(name)
|
|
.setType(vertexSize === 1 ? "SCALAR" : `VEC${vertexSize}`)
|
|
.setArray(new Float32Array(value.flat()))
|
|
.setBuffer(buffer);
|
|
|
|
primitive.setAttribute(name, attributeAccessor);
|
|
});
|
|
|
|
const skeleton = skeletons.get(hierarchy);
|
|
const mesh = document
|
|
.createMesh(batch["##name"])
|
|
.addPrimitive(primitive);
|
|
lodNode.setMesh(mesh);
|
|
|
|
if (
|
|
skeleton &&
|
|
skinPrimitive(
|
|
document,
|
|
buffer,
|
|
primitive,
|
|
attributes,
|
|
renderObject[`skinnedObject.batch${batchIndex}.targetsData`],
|
|
)
|
|
) {
|
|
lodNode.setSkin(skeleton.skin);
|
|
}
|
|
node.addChild(lodNode);
|
|
});
|
|
|
|
break;
|
|
}
|
|
|
|
default: {
|
|
if (ERROR_ON_UNKNOWN_COMPONENT) {
|
|
throw new Error(
|
|
`Unhandled component type: ${component["comp.typename"]}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
parent.addChild(node);
|
|
|
|
return node;
|
|
},
|
|
);
|
|
|
|
for (const [owner, entity, joint, skin] of jointBindings) {
|
|
// the game only binds the skeleton entity's own children
|
|
const socket = owner
|
|
.listChildren()
|
|
.find(
|
|
(child) =>
|
|
child.getName() === entity && !skin.listJoints().includes(child),
|
|
);
|
|
|
|
if (!socket) throw new Error(`Missing socket ${entity}`);
|
|
|
|
bindSocket(socket, joint, skin);
|
|
}
|
|
|
|
scene.addChild(document.createNode("test"));
|
|
|
|
await document.transform(prune({ keepAttributes: true }), dedup());
|
|
|
|
return document;
|
|
}
|
|
|
|
export async function extractMaterials(
|
|
document: Document,
|
|
sc2: ReturnType<Sc2ReadStream["sc2"]>,
|
|
path: string,
|
|
config?: string,
|
|
) {
|
|
const materials = new Map<bigint, Material | bigint | undefined>();
|
|
|
|
for (const node of sc2["#dataNodes"]) {
|
|
const id = bufferToBigInt(node["#id"]);
|
|
|
|
if (node.parentMaterialKey !== undefined) {
|
|
/**
|
|
* material depends on a parent and doesn't seem to have any
|
|
* properties so we just point it to the parent
|
|
*/
|
|
materials.set(id, node.parentMaterialKey);
|
|
continue;
|
|
}
|
|
|
|
let textures: Textures | undefined = undefined;
|
|
|
|
if (config !== undefined) {
|
|
if (typeof node.configCount !== "number") continue;
|
|
|
|
const archive = times(
|
|
node.configCount,
|
|
(index) => node[`configArchive_${index}`],
|
|
).find((archive) => archive.configName === config);
|
|
|
|
if (
|
|
!archive ||
|
|
isEqual(archive.textures, node.configArchive_0.textures)
|
|
) {
|
|
continue;
|
|
}
|
|
|
|
textures = archive.textures;
|
|
} else if (node.textures) {
|
|
textures = node.textures;
|
|
} else if (typeof node.configCount === "number") {
|
|
textures = node.configArchive_0.textures;
|
|
}
|
|
|
|
const material = document.createMaterial(node.materialName);
|
|
|
|
if (textures) {
|
|
const baseColor = await readBaseColor(
|
|
`Data/3d/${dirname(path)}/${textures.baseColorMap ?? textures.albedo}`,
|
|
);
|
|
material.setBaseColorTexture(
|
|
document
|
|
.createTexture(node.materialName)
|
|
.setMimeType("image/webp")
|
|
.setImage(baseColor),
|
|
);
|
|
|
|
let defaultConfigArchive: ConfigArchive | undefined = undefined;
|
|
|
|
if (node.configCount) {
|
|
const names = times(
|
|
node.configCount,
|
|
(index) => node[`configArchive_${index}`],
|
|
);
|
|
|
|
defaultConfigArchive = names.find(
|
|
(archive) => archive.configName === "Default",
|
|
);
|
|
defaultConfigArchive ??= node.configArchive_0;
|
|
}
|
|
|
|
const customCullMode =
|
|
node.customCullMode ?? defaultConfigArchive?.customCullMode;
|
|
|
|
if (customCullMode === 0) {
|
|
material.setDoubleSided(true);
|
|
} else if (customCullMode !== undefined) {
|
|
material.setDoubleSided(false);
|
|
}
|
|
|
|
if (
|
|
node.enabledPresets?.AlphaTest &&
|
|
node.properties?.alphatestThreshold
|
|
) {
|
|
const view = new DataView(node.properties.alphatestThreshold);
|
|
const alphaCutoff =
|
|
view.byteLength < 4
|
|
? 0.5
|
|
: view.getFloat32(view.byteLength - 4, true);
|
|
|
|
material.setAlphaMode("MASK").setAlphaCutoff(alphaCutoff);
|
|
}
|
|
|
|
if (node.configCount) {
|
|
for (
|
|
let configIndex = 0;
|
|
configIndex < node.configCount;
|
|
configIndex++
|
|
) {
|
|
const archive = node[`configArchive_${configIndex}`];
|
|
|
|
if (
|
|
archive.configName !== "Default" ||
|
|
!archive.enabledPresets?.AlphaTest ||
|
|
!archive.properties?.alphatestThreshold
|
|
) {
|
|
continue;
|
|
}
|
|
|
|
const view = new DataView(archive.properties.alphatestThreshold);
|
|
const alphaCutoff =
|
|
view.byteLength < 4
|
|
? 0.5
|
|
: view.getFloat32(view.byteLength - 4, true);
|
|
|
|
material.setAlphaMode("MASK").setAlphaCutoff(alphaCutoff);
|
|
}
|
|
}
|
|
|
|
const enabledPresets =
|
|
node.enabledPresets ?? defaultConfigArchive?.enabledPresets;
|
|
const fxName = node.fxName ?? defaultConfigArchive?.fxName;
|
|
|
|
if (enabledPresets?.AlphaBlend || enabledPresets?.AlphaBlendAdditive) {
|
|
material.setAlphaMode("BLEND");
|
|
}
|
|
|
|
if (enabledPresets?.AlphaBlendAdditive) {
|
|
// gltf has no additive blending so the viewer applies it
|
|
material.setExtras({ blending: "additive" });
|
|
}
|
|
|
|
if (fxName?.endsWith("/Textured.material")) {
|
|
// unlit in game, emissive so the viewer can fade it with the lights
|
|
material
|
|
.setEmissiveTexture(material.getBaseColorTexture())
|
|
.setEmissiveFactor([1, 1, 1])
|
|
.setBaseColorFactor([0, 0, 0, 1]);
|
|
}
|
|
|
|
if (textures.miscMap) {
|
|
material.setOcclusionTexture(
|
|
document
|
|
.createTexture(node.materialName)
|
|
.setMimeType("image/webp")
|
|
.setImage(
|
|
await readOcclusion(
|
|
`Data/3d/${dirname(path)}/${textures.miscMap}`,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
if (textures.baseRMMap) {
|
|
material.setMetallicRoughnessTexture(
|
|
document
|
|
.createTexture(node.materialName)
|
|
.setMimeType("image/webp")
|
|
.setImage(
|
|
await readRoughnessMetallic(
|
|
`Data/3d/${dirname(path)}/${textures.baseRMMap}`,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
if (textures.baseNormalMap ?? textures.normalmap) {
|
|
const isBase = textures.baseNormalMap !== undefined;
|
|
|
|
material.setNormalTexture(
|
|
document
|
|
.createTexture(node.materialName)
|
|
.setMimeType("image/webp")
|
|
.setImage(
|
|
await readNormal(
|
|
`Data/3d/${dirname(path)}/${
|
|
textures.baseNormalMap ?? textures.normalmap
|
|
}`,
|
|
isBase,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
materials.set(id, material);
|
|
}
|
|
}
|
|
|
|
// replace children materials with parents
|
|
materials.forEach((material, id) => {
|
|
if (typeof material !== "bigint") return;
|
|
|
|
let resolvedMaterial: Material | bigint | undefined = material;
|
|
|
|
while (typeof resolvedMaterial === "bigint") {
|
|
const linkedParentMaterial = materials.get(resolvedMaterial);
|
|
|
|
resolvedMaterial = linkedParentMaterial;
|
|
}
|
|
|
|
materials.set(id, resolvedMaterial);
|
|
});
|
|
|
|
return materials;
|
|
}
|
|
|
|
/**
|
|
* the last few textures made, as a camouflage's parts share one atlas and a
|
|
* tank's camouflages build one after another; it's capped so the build doesn't
|
|
* keep every texture it ever made
|
|
*/
|
|
const IMAGE_CACHE_SIZE = 64;
|
|
const images = new Map<string, Promise<Buffer>>();
|
|
|
|
function cachedImage(key: string, read: () => Promise<Buffer>) {
|
|
let image = images.get(key);
|
|
|
|
if (!image) {
|
|
image = read();
|
|
images.set(key, image);
|
|
|
|
if (images.size > IMAGE_CACHE_SIZE) {
|
|
images.delete(images.keys().next().value!);
|
|
}
|
|
}
|
|
|
|
return image;
|
|
}
|
|
|
|
function readBaseColor(path: string) {
|
|
return cachedImage(`baseColor:${path}`, async () => {
|
|
const raw = await readTexture(path);
|
|
const image = await sharp(raw.data, { raw }).webp().toBuffer();
|
|
|
|
return image;
|
|
});
|
|
}
|
|
|
|
function readOcclusion(path: string) {
|
|
return cachedImage(`occlusion:${path}`, async () => {
|
|
const raw = await readTexture(path);
|
|
|
|
const image = await sharp(raw.data, { raw })
|
|
.extractChannel(3)
|
|
.webp()
|
|
.toBuffer();
|
|
|
|
return image;
|
|
});
|
|
}
|
|
|
|
function readRoughnessMetallic(path: string) {
|
|
return cachedImage(`roughnessMetallic:${path}`, async () => {
|
|
const raw = await readTexture(path);
|
|
const blitz = sharp(raw.data, { raw });
|
|
const metallicness = await blitz?.extractChannel(1).raw().toBuffer();
|
|
const roughness = await blitz?.extractChannel(3).raw().toBuffer();
|
|
|
|
const combined = Buffer.alloc(raw.width * raw.height * 3);
|
|
|
|
for (let i = 0; i < raw.width * raw.height; i++) {
|
|
combined[i * 3 + 1] = roughness[i];
|
|
combined[i * 3 + 2] = metallicness[i];
|
|
}
|
|
|
|
const image = await sharp(combined, {
|
|
raw: { width: raw.width, height: raw.height, channels: 3 },
|
|
})
|
|
.webp()
|
|
.toBuffer();
|
|
|
|
return image;
|
|
});
|
|
}
|
|
|
|
function readNormal(path: string, isBase: boolean) {
|
|
return cachedImage(`normal:${isBase}:${path}`, async () => {
|
|
const raw = await readTexture(path);
|
|
|
|
if (!isBase) {
|
|
return await sharp(raw.data, { raw }).removeAlpha().jpeg().toBuffer();
|
|
}
|
|
|
|
const bytes = 4 * raw.width * raw.height;
|
|
|
|
for (let index = 0; index < bytes; index += 4) {
|
|
/**
|
|
* Red is always 255 and blue is always 0. Only alpha and green contain
|
|
* any sort of information.
|
|
*/
|
|
let x = raw.data[index + 3] * (2 / 255) - 1;
|
|
let y = raw.data[index + 1] * (2 / 255) - 1;
|
|
let z = Math.sqrt(Math.max(0, 1 - x ** 2 - y ** 2));
|
|
|
|
raw.data[index] = Math.round((x + 1) * (255 / 2));
|
|
raw.data[index + 1] = Math.round((y + 1) * (255 / 2));
|
|
raw.data[index + 2] = Math.round((z + 1) * (255 / 2));
|
|
raw.data[index + 3] = 255;
|
|
}
|
|
|
|
return await sharp(raw.data, { raw }).webp().toBuffer();
|
|
});
|
|
}
|
|
|
|
async function readTexture(path: string) {
|
|
const ddsTexturePath = path.replace(".tex", ".dx11.dds");
|
|
const isDds = await vfs.resolve(ddsTexturePath);
|
|
const resolvedTexturePath = isDds
|
|
? ddsTexturePath
|
|
: ddsTexturePath.replace(".dds", ".pvr");
|
|
const file = await vfs.file(resolvedTexturePath);
|
|
|
|
const raw = isDds
|
|
? await new DdsReadStream(file.buffer as ArrayBuffer).dds()
|
|
: new PvrReadStream(file.buffer as ArrayBuffer).pvr();
|
|
|
|
return raw;
|
|
}
|