Fix: Legendary camouflage parts, materials, names and attachments

Fixes a batch of legendary camouflage problems in the Tankopedia viewer, adds three missing unique camouflages and lets attachments be shown together with a camouflage.

## Camouflage parts (state switchers)
- Camouflages now choose which tank pieces show the same way the game does. Each switcher's load-time scenario script runs at export time (checks for attached camouflage items, or compares the camouflage preset), along with its state-switch actions. This replaces the old guess from part names (new `core/blitzkit/switcherStates.ts`).
- Fixes missing roof MGs, fenders and fuel tanks (IS-3 Bear, Obj. 140 Terror, IS-7, IS-4, FV215b 183, AMX 50 B, KV-1S) and default parts mixed into camouflages (Pershing Speedfire, Forest Witch Fullmetal, Waffenträger Goldstreifen).
- Switchers inside camouflage parts now show one state instead of all of them stacked (Obj. Kust double net, Goldstreifen stowage, Tiger II cat).
- States are matched by original node names, because the GLTF loader renames duplicates.
- Camouflage part meshes with no LODs (`lodIndex -1`) are kept, which restores the Tiger II cat body and missing pieces on about 11 other camouflages.

## Materials
- `AlphaBlend` materials export as transparent. `AlphaBlendAdditive` materials export as additive and are applied in `jsxTree`, and unlit `Textured` materials export as unlit (IS-8 Raroh flames, dinosaur holograms, and glass and screens on a few base tanks).
- Camouflage part materials that share a name with the tank's material no longer replace the tank's camouflage material (Bisonte C45 Unbreakable).

## Names
- With a legendary camouflage selected, the title shows the tank's in-battle name ("GuP Type 95 Ha-Go", "KV-1 Warrior", "Shinobi").
- Camouflages without a name in the game files yet show "Unreleased" in orange instead of their raw string key, and no longer crash the tank names list.

## Attachments
- Attachments (`kind: customization`) are listed in their own group under the camouflages and can be turned on together with a camouflage. They load the same way as camouflages and fade with the same transition.

## Other
- Liberté, You Rock! and Ozzie (single-tank camouflages that only set a preset through `override`) are now available.
- Mastery gun mark meshes (`custom_gun_marks_*`) are no longer drawn (Helsing, HWT20 FalconFire and two camouflage guns).

## Not included
- Pixel Wave, Digital Trace and Forest Shadow are tiled pattern camouflages, which the viewer can't render yet.
- FV301 Corbie's drone position and the dinosaur heads' glow depend on camouflage animations and emissive materials, which are separate PRs.

Fixes #417
Fixes #419
Fixes #421
This commit is contained in:
Mark Greene committed 2026-10-29 15:28:11 +13:00
1 parent 091607b0a8
commit 0f299335d6
18 files changed
+559 -113

No files matched your search

@@ -3,6 +3,7 @@ import {
Sc2ReadStream,
type TankParameters,
} from "@blitzkit/core";
import locales from "@blitzkit/i18n/locales.json";
import { isEqual, times } from "lodash-es";
import { Cache } from "./0_base";
import { ServerBlitzKitAPI1 } from "./1_tankDefinitions";
@@ -87,14 +88,19 @@ export abstract class ServerBlitzKitAPI2 extends ServerBlitzKitAPI1 {
),
);
const [nation, tankKey] = vehicle.split(":");
// some unique camos only set the preset for their one tank
const preset =
yamlEntry.preset ??
yamlEntry.override?.[nation]?.override?.[tankKey]?.preset;
let hasPreset = false;
if (camo.group === "legendary" && yamlEntry.preset !== undefined) {
if (preset !== undefined) {
if (!skinPresets.has(vehicle)) {
skinPresets.set(vehicle, this.skinPresets(vehicle));
}
hasPreset = (await skinPresets.get(vehicle)!).has(yamlEntry.preset);
hasPreset = (await skinPresets.get(vehicle)!).has(preset);
}
if (resolvedParts.some(Boolean) || hasPreset) {
@@ -102,7 +108,11 @@ export abstract class ServerBlitzKitAPI2 extends ServerBlitzKitAPI1 {
}
}
const name = this.getString(camo.userString);
// unreleased camos are in the game files before their names
const name =
camo.userString in this.stringsI18n[locales.default]
? this.getString(camo.userString)
: undefined;
camouflageDefinitions.camouflages[camo.id] = {
id: camo.id,
@@ -110,6 +120,7 @@ export abstract class ServerBlitzKitAPI2 extends ServerBlitzKitAPI1 {
tank_name: resolvedTankName,
tank_name_full: resolvedTankNameFull,
tank_id: tankId,
attachment: camo.kind === "customization",
};
}
+1 -1
View File
@@ -38,7 +38,7 @@ export async function fetchTankNames(api: BlitzKitAPI) {
?.map((id) =>
locales.supported.map(
({ locale }) =>
camouflageDefinitions.camouflages[id]?.name!.locales[locale],
camouflageDefinitions.camouflages[id]?.name?.locales[locale],
),
)
.flat()
@@ -14,4 +14,5 @@ message Camouflage {
optional I18nString tank_name = 3;
optional I18nString tank_name_full = 4;
optional uint32 tank_id = 5;
optional bool attachment = 6;
}
@@ -25,6 +25,7 @@ export interface Camouflage {
tank_name?: I18nString | undefined;
tank_name_full?: I18nString | undefined;
tank_id?: number | undefined;
attachment?: boolean | undefined;
}
function createBaseCamouflageDefinitions(): CamouflageDefinitions {
@@ -192,7 +193,7 @@ export const CamouflageDefinitions_CamouflagesEntry: MessageFns<CamouflageDefini
};
function createBaseCamouflage(): Camouflage {
return { id: 0, name: undefined, tank_name: undefined, tank_name_full: undefined, tank_id: 0 };
return { id: 0, name: undefined, tank_name: undefined, tank_name_full: undefined, tank_id: 0, attachment: false };
}
export const Camouflage: MessageFns<Camouflage> = {
@@ -212,6 +213,9 @@ export const Camouflage: MessageFns<Camouflage> = {
if (message.tank_id !== undefined && message.tank_id !== 0) {
writer.uint32(40).uint32(message.tank_id);
}
if (message.attachment !== undefined && message.attachment !== false) {
writer.uint32(48).bool(message.attachment);
}
return writer;
},
@@ -262,6 +266,14 @@ export const Camouflage: MessageFns<Camouflage> = {
message.tank_id = reader.uint32();
continue;
}
case 6: {
if (tag !== 48) {
break;
}
message.attachment = reader.bool();
continue;
}
}
if ((tag & 7) === 4 || tag === 0) {
break;
@@ -278,6 +290,7 @@ export const Camouflage: MessageFns<Camouflage> = {
tank_name: isSet(object.tank_name) ? I18nString.fromJSON(object.tank_name) : undefined,
tank_name_full: isSet(object.tank_name_full) ? I18nString.fromJSON(object.tank_name_full) : undefined,
tank_id: isSet(object.tank_id) ? globalThis.Number(object.tank_id) : 0,
attachment: isSet(object.attachment) ? globalThis.Boolean(object.attachment) : false,
};
},
@@ -298,6 +311,9 @@ export const Camouflage: MessageFns<Camouflage> = {
if (message.tank_id !== undefined && message.tank_id !== 0) {
obj.tank_id = Math.round(message.tank_id);
}
if (message.attachment !== undefined && message.attachment !== false) {
obj.attachment = message.attachment;
}
return obj;
},
@@ -317,6 +333,7 @@ export const Camouflage: MessageFns<Camouflage> = {
? I18nString.fromPartial(object.tank_name_full)
: undefined;
message.tank_id = object.tank_id ?? 0;
message.attachment = object.attachment ?? false;
return message;
},
};
+2
View File
@@ -40,6 +40,8 @@ export interface ConfigArchive {
interface EnabledPresets {
AlphaTest: boolean;
AlphaBlend?: boolean;
AlphaBlendAdditive?: boolean;
}
interface Flags {
@@ -5,5 +5,10 @@ export type CamouflagesYaml = Record<
shortUserString?: string;
preset?: string;
customEntities?: Record<string, { item: string }>;
// nation -> tank
override?: Record<
string,
{ override?: Record<string, { preset?: string }> }
>;
}
>;
+3
View File
@@ -484,6 +484,9 @@
"model": {
"name": "Model"
},
"skins": {
"unreleased": "Unreleased"
},
"dynamic": {
"name": "Dynamic armor",
@@ -1,5 +1,5 @@
import { alias } from "@blitzkit/core";
import { Flex, Tooltip } from "@radix-ui/themes";
import { Flex, Text, Tooltip } from "@radix-ui/themes";
import { uniqBy } from "lodash-es";
import { SKIN_NUMBER } from "../../../../../../constants/skinNumber";
import { api } from "../../../../../../core/blitzkit/api";
@@ -14,21 +14,30 @@ const camouflageDefinitions = await api.camouflageDefinitions();
export function SkinSwitcher() {
const tank = Duel.use((state) => state.protagonist.tank);
const skin = Tankopedia.use((state) => state.requestedSkin);
const attachment = Tankopedia.use((state) => state.requestedAttachment);
const requestedDisplay = Tankopedia.use((state) => state.requestedDisplay);
const disturbed = Tankopedia.use((state) => state.disturbed);
const { unwrap } = useLocale();
const { unwrap, strings } = useLocale();
const skins = uniqBy(
Object.values(camouflageDefinitions.camouflages).filter(
(camouflage) => camouflage.tank_id === tank.id,
),
(camouflage) => unwrap(camouflage.name!),
(camouflage) =>
(camouflage.name && unwrap(camouflage.name)) || camouflage.id,
);
// attachments aren't camouflages so they get their own group
const groups = [
skins.filter((camouflage) => !camouflage.attachment),
skins.filter((camouflage) => camouflage.attachment),
].filter((group) => group.length > 0);
if (skins.length === 0) return null;
return (
<Flex
direction="column"
gap="3"
top="50%"
right={
disturbed && requestedDisplay === TankopediaDisplay.Model
@@ -42,42 +51,64 @@ export function SkinSwitcher() {
pointerEvents: "auto",
}}
>
{skins.map((camouflage, index) => {
const name = unwrap(camouflage.name!).replace(
"%(camo_num)",
SKIN_NUMBER,
);
const top = index === 0 ? "var(--radius-full)" : "0";
const bottom = index === skins.length - 1 ? "var(--radius-full)" : "0";
{groups.map((group) => (
<Flex key={group[0].id} direction="column">
{group.map((camouflage, index) => {
const rawName = camouflage.name && unwrap(camouflage.name);
const name = rawName
? rawName.replace("%(camo_num)", SKIN_NUMBER)
: strings.website.tools.tankopedia.sandbox.skins.unreleased;
const top = index === 0 ? "var(--radius-full)" : "0";
const bottom =
index === group.length - 1 ? "var(--radius-full)" : "0";
return (
<Tooltip key={camouflage.id} content={name} side="left">
<SidebarIconButton
selected={skin === camouflage.id}
alt={name}
src={alias("api", `/icons/camouflages/${camouflage.id}.webp`)}
size={{ initial: "3", sm: "4" }}
radius="full"
style={{
borderRadius: `${top} ${top} ${bottom} ${bottom}`,
}}
imageStyle={{
width: "70%",
height: "70%",
borderRadius: "50%",
}}
onClick={() => {
Tankopedia.mutate((draft) => {
draft.requestedSkin =
draft.requestedSkin === camouflage.id
? undefined
: camouflage.id;
});
}}
/>
</Tooltip>
);
})}
return (
<Tooltip
key={camouflage.id}
content={
rawName ? (
name
) : (
<Text style={{ color: "var(--orange-9)" }}>{name}</Text>
)
}
side="left"
>
<SidebarIconButton
selected={
(camouflage.attachment ? attachment : skin) ===
camouflage.id
}
alt={name}
src={alias("api", `/icons/camouflages/${camouflage.id}.webp`)}
size={{ initial: "3", sm: "4" }}
radius="full"
style={{
borderRadius: `${top} ${top} ${bottom} ${bottom}`,
}}
imageStyle={{
width: "70%",
height: "70%",
borderRadius: "50%",
}}
onClick={() => {
const slot = camouflage.attachment
? "requestedAttachment"
: "requestedSkin";
Tankopedia.mutate((draft) => {
draft[slot] =
draft[slot] === camouflage.id
? undefined
: camouflage.id;
});
}}
/>
</Tooltip>
);
})}
</Flex>
))}
</Flex>
);
}
@@ -22,9 +22,16 @@ export function Title({ skeleton }: MaybeSkeletonComponentProps) {
const camouflage =
skin === undefined ? undefined : camouflageDefinitions.camouflages[skin];
const tankName = unwrap(protagonist.name!);
const name = camouflage
? `${tankName} ${unwrap(camouflage.name!).replace("%(camo_num)", SKIN_NUMBER)}`
: tankName;
// legendary camos carry the tank's in-battle name
const name = (
camouflage
? camouflage.tank_name
? unwrap(camouflage.tank_name)
: camouflage.name
? `${tankName} ${unwrap(camouflage.name)}`
: tankName
: tankName
).replace("%(camo_num)", SKIN_NUMBER);
const fontSize = revealed
? disturbed
? "1.5rem"
@@ -48,7 +48,9 @@ export function Lighting({ hasPbr }: Props) {
const requestedDisplay = Tankopedia.use((state) => state.requestedDisplay);
const revealed = Tankopedia.use((state) => state.revealed);
const skinPending = Tankopedia.use(
(state) => state.loadedSkin !== state.skin,
(state) =>
state.loadedSkin !== state.skin ||
state.loadedAttachment !== state.attachment,
);
const animationTime = useRef(REVEAL_ANIMATION_TIME);
@@ -245,9 +247,14 @@ function Animator({
});
}
if (x >= 1 && Tankopedia.state.skin !== Tankopedia.state.loadedSkin) {
if (
x >= 1 &&
(Tankopedia.state.skin !== Tankopedia.state.loadedSkin ||
Tankopedia.state.attachment !== Tankopedia.state.loadedAttachment)
) {
Tankopedia.mutate((draft) => {
draft.skin = draft.loadedSkin;
draft.attachment = draft.loadedAttachment;
});
}
});
@@ -30,6 +30,8 @@ export function TankModel() {
const { gltf } = useModel(protagonist.tank.id);
const nodes = Object.values(gltf.nodes);
const skinGltf = useSkin(protagonist.tank.id);
const attachmentGltf = useSkin(protagonist.tank.id, "attachment");
const skins = [skinGltf, attachmentGltf].filter((skin) => skin !== undefined);
useTankTransform(track, turret, turretContainer, gunContainer);
@@ -94,7 +96,7 @@ export function TankModel() {
window.removeEventListener("pointerup", handlePointerUp);
}
return skinTree(node, skinGltf, {
return skinTree(node, skins, {
mesh(_, props, key) {
return (
<mesh
@@ -171,7 +173,7 @@ export function TankModel() {
window.removeEventListener("pointerup", handlePointerUp);
}
return skinTree(node, skinGltf, {
return skinTree(node, skins, {
mesh(_, props, key) {
return (
<mesh
@@ -252,7 +254,7 @@ export function TankModel() {
window.removeEventListener("pointerup", handlePointerUp);
}
return skinTree(node, skinGltf, {
return skinTree(node, skins, {
mesh(_, props, key) {
return (
<mesh
+14 -1
View File
@@ -1,5 +1,11 @@
import type { ComponentProps, ReactNode } from "react";
import { Mesh, MeshStandardMaterial, Object3D } from "three";
import {
AdditiveBlending,
Material,
Mesh,
MeshStandardMaterial,
Object3D,
} from "three";
export function jsxTree(
node: Object3D,
@@ -29,6 +35,13 @@ export function jsxTree(
props.material.depthWrite = true;
}
if (
props.material instanceof Material &&
props.material.userData.blending === "additive"
) {
props.material.blending = AdditiveBlending;
}
return mergers?.mesh ? (
mergers.mesh(node, props, node.uuid)
) : (
+53 -20
View File
@@ -4,17 +4,56 @@ import { jsxTree } from "./jsxTree";
type Mergers = Parameters<typeof jsxTree>[1];
export function skinTree(
node: Object3D,
skin: Skin | undefined,
mergers: Mergers,
) {
const skinNodes = new Map(
skin?.scene.children.map((node) => [node.name, node]),
);
// names get sanitized and made unique on load
function nameOf(object3d: Object3D): string {
return object3d.userData.name ?? object3d.name;
}
/**
* skins are layered in order, so an attachment's states win over the
* camouflage's
*/
export function skinTree(node: Object3D, skins: Skin[], mergers: Mergers) {
const skinNodes = new Map<string, Object3D[]>();
const materials = new Map<string, Material>();
const states: Record<string, string | null> = {};
for (const skin of skins) {
for (const node of skin.scene.children) {
skinNodes.set(node.name, [...(skinNodes.get(node.name) ?? []), node]);
}
for (const [name, material] of skin.materials) {
materials.set(name, material);
}
Object.assign(states, skin.scene.userData.states);
}
function switchChildren(object3d: Object3D, childMergers: Mergers) {
if (object3d.userData.state === undefined) return;
const name = nameOf(object3d);
const state = name in states ? states[name] : object3d.userData.state;
return object3d.children
.filter((child) => nameOf(child) === state)
.map((child) => jsxTree(child, childMergers));
}
const partMergers: Mergers = {
...mergers,
group(object3d, props, key) {
return (
<group key={key} {...props}>
{switchChildren(object3d, partMergers) ?? props.children}
</group>
);
},
};
const skinMergers: Mergers = {
mesh(mesh, props, key) {
const material = skin?.materials.get((mesh.material as Material).name);
const material = materials.get((mesh.material as Material).name);
return mergers!.mesh!(
mesh,
@@ -23,20 +62,14 @@ export function skinTree(
);
},
group(object3d, props, key) {
const skinNode = skinNodes.get(object3d.name);
const isSwitch = object3d.userData.state !== undefined;
const state = skin
? skin.scene.userData.states[object3d.name]
: object3d.userData.state;
const parts = skinNodes.get(object3d.name) ?? [];
return (
<group key={key} {...props}>
{isSwitch
? object3d.children
.filter((child) => child.name === state)
.map((child) => jsxTree(child, skinMergers))
: props.children}
{skinNode?.children.map((child) => jsxTree(child, mergers))}
{switchChildren(object3d, skinMergers) ?? props.children}
{parts.flatMap((part) =>
part.children.map((child) => jsxTree(child, partMergers)),
)}
</group>
);
},
@@ -0,0 +1,255 @@
import { parseHierarchies, type Sc2ReadStream } from "@blitzkit/core";
import { times } from "lodash-es";
interface Value {
"any.type": string;
"any.value": unknown;
}
interface ScriptNode {
type: string;
node: Record<string, unknown> & { defaults?: Record<string, Value> };
connections?: Record<
string,
{ pinIn: string; pinOut: string; target: string }
>;
}
interface Script {
nodes: Record<string, ScriptNode>;
}
interface Action {
"act.delay": number;
"act.entityName": string;
"act.event": number;
"act.switchIndex": number;
"act.type": number;
"act.userEventId": string;
}
interface Entity {
name: string;
parent?: Entity;
children: Entity[];
}
const SELF_ENTITY = "*** Self ***";
const SCENE_LOADED_EVENT = 1;
const USER_EVENT = 2;
const SWITCH_ACTIONS = [8, 9];
// what the game fires as a tank is shown in the garage, in order
const LOAD_EVENTS = ["Added", "TankAliveInHangar", "TankIsShownInNewScreen"];
const MAX_DEPTH = 64;
function findChild(entity: Entity, name: string): Entity | undefined {
for (const child of entity.children) {
if (child.name === name) return child;
const found = findChild(child, name);
if (found) return found;
}
}
function resolveTarget(owner: Entity, entityName: string) {
if (entityName === SELF_ENTITY) return owner;
const [first, ...rest] = entityName.split("->");
let target: Entity | undefined;
for (
let ancestor: Entity | undefined = owner;
ancestor && !target;
ancestor = ancestor.parent
) {
target = ancestor.name === first ? ancestor : findChild(ancestor, first);
}
for (const name of rest) target = target && findChild(target, name);
return target;
}
/**
* replays what picks each state switcher's state as a tank is shown in the
* garage, with the camo's preset applied and its items attached; delayed
* actions are skipped so states stay as they are when the tank appears
*/
export function switcherStates(
sc2: ReturnType<Sc2ReadStream["sc2"]>,
preset: string | undefined,
attachments: Map<string, string[]>,
) {
const scripts: Record<string, Script> = {};
const stateNames = new Map<Entity, string[]>();
const scenarios: { owner: Entity; script: Script }[] = [];
const actions: { owner: Entity; action: Action }[] = [];
const states: Record<string, string | null> = {};
function activateState(entity: Entity | undefined, state: number) {
const names = entity && stateNames.get(entity);
if (names) states[entity.name] = names[state] ?? null;
}
for (const component of Object.values(
sc2["#sceneComponents"] as unknown as Record<string, unknown>,
) as { "comp.typename"?: string; "ssc.scripts"?: Record<string, Script> }[]) {
if (component?.["comp.typename"] !== "ScenarioSingletonComponent") continue;
Object.assign(scripts, component["ssc.scripts"]);
}
parseHierarchies<Entity>(
sc2["#hierarchy"],
{ name: "", children: [] },
(hierarchy, components, parent) => {
const entity: Entity = { name: hierarchy.name, parent, children: [] };
parent.children.push(entity);
for (const item of attachments.get(hierarchy.name) ?? []) {
entity.children.push({ name: item, parent: entity, children: [] });
}
for (const component of components) {
switch (component["comp.typename"]) {
case "StateSwitcherComponent": {
const names = times(
component["ssc.statesCount"],
(index) => component[`ssc.state${index}`],
);
stateNames.set(entity, names);
states[entity.name] = names[component["ssc.activeState"]] ?? null;
break;
}
case "ScenarioComponent": {
const script = scripts[component["scenario.scriptId"]];
if (script) scenarios.push({ owner: entity, script });
break;
}
case "ActionComponent":
times(component["ac.actionCount"], (index) => {
actions.push({
owner: entity,
action: component[index.toString().padStart(4, "0")] as Action,
});
});
break;
}
}
return entity;
},
);
function runScenario(
{ owner, script }: (typeof scenarios)[number],
event: string,
) {
const { nodes } = script;
const links = (id: string) => Object.values(nodes[id].connections ?? {});
function input(id: string, pin: string): unknown {
const link = links(id).find((link) => link.pinIn === pin);
return link
? output(link.target, link.pinOut)
: nodes[id].node.defaults?.[pin]?.["any.value"];
}
function output(id: string, pin: string): unknown {
const { type, node } = nodes[id];
switch (type) {
case "ScenarioSceneInfoNode":
return node["scenarioSceneInfoNode.infoKind"] === "GetCurrentEntity"
? owner
: undefined;
case "ScenarioGetMemberNode":
return node["scenarioGetMemberNode.fieldName"] === "parent" &&
pin === "parent"
? (input(id, "object") as Entity | undefined)?.parent
: undefined;
case "ScenarioFunctionNode":
switch (
`${node["scenarioFunctionNode.className"]}.${node["scenarioFunctionNode.functionName"]}`
) {
case "Entity.FindChildByName": {
const entity = input(id, "entity") as Entity | undefined;
return entity && findChild(entity, input(id, "name") as string);
}
case "TankComponent.GetAppliedSkinMaterialConfigName":
return preset;
case "String.Compare":
return input(id, "1") === input(id, "2");
}
}
}
function execute(id: string, depth: number) {
if (depth > MAX_DEPTH) return;
const { type, node } = nodes[id];
let pin = "exit";
if (type === "ScenarioEventNode") {
pin = "event";
} else if (type === "ScenarioBranchNode") {
pin = input(id, "condition") ? "true" : "false";
} else if (
node["scenarioFunctionNode.functionName"] === "ActivateState"
) {
activateState(
input(id, "entity") as Entity | undefined,
Number(input(id, "state")),
);
}
for (const link of links(id)) {
if (link.pinIn === pin) execute(link.target, depth + 1);
}
}
for (const id in nodes) {
const { type, node } = nodes[id];
const name =
node["ScenarioEventNode.eventName"] === "Custom"
? node.defaults?.["Event Name"]?.["any.value"]
: node["ScenarioEventNode.eventName"];
if (type === "ScenarioEventNode" && name === event) execute(id, 0);
}
}
for (const event of LOAD_EVENTS) {
for (const { owner, action } of actions) {
if (
action["act.delay"] === 0 &&
SWITCH_ACTIONS.includes(action["act.type"]) &&
(event === LOAD_EVENTS[0]
? action["act.event"] === SCENE_LOADED_EVENT
: action["act.event"] === USER_EVENT &&
action["act.userEventId"] === event)
) {
activateState(
resolveTarget(owner, action["act.entityName"]),
action["act.switchIndex"],
);
}
}
for (const scenario of scenarios) runScenario(scenario, event);
}
return states;
}
+19 -8
View File
@@ -18,7 +18,11 @@ async function loadSkin(path: string) {
const materials: Material[] = await gltf.parser.getDependencies("material");
const skin = {
scene: gltf.scene,
materials: new Map(materials.map((material) => [material.name, material])),
materials: new Map(
materials
.filter((material) => material.userData.camouflage)
.map((material) => [material.name, material]),
),
};
loadedSkins.set(path, skin);
@@ -30,9 +34,16 @@ function skinPath(id: number, skin: number) {
return alias("models_legendary", `/${id}/skins/${skin}.glb`);
}
export function useSkin(id: number) {
const requestedSkin = Tankopedia.use((state) => state.requestedSkin);
const skin = Tankopedia.use((state) => state.skin);
// attachments load the same way as camouflages and can be shown with one
const slots = {
skin: { requested: "requestedSkin", loaded: "loadedSkin" },
attachment: { requested: "requestedAttachment", loaded: "loadedAttachment" },
} as const;
export function useSkin(id: number, slot: keyof typeof slots = "skin") {
const { requested, loaded } = slots[slot];
const requestedSkin = Tankopedia.use((state) => state[requested]);
const skin = Tankopedia.use((state) => state[slot]);
useEffect(() => {
const path =
@@ -41,7 +52,7 @@ export function useSkin(id: number) {
if (path === undefined || loadedSkins.has(path)) {
Tankopedia.mutate((draft) => {
draft.loadedSkin = requestedSkin;
draft[loaded] = requestedSkin;
});
return;
}
@@ -62,8 +73,8 @@ export function useSkin(id: number) {
settled = true;
Tankopedia.mutate((draft) => {
draft.loadedSkin = requestedSkin;
draft.skin = requestedSkin;
draft[loaded] = requestedSkin;
draft[slot] = requestedSkin;
draft.revealed = true;
});
});
@@ -76,7 +87,7 @@ export function useSkin(id: number) {
draft.revealed = true;
});
};
}, [id, requestedSkin]);
}, [id, slot, requestedSkin]);
return skin === undefined ? undefined : loadedSkins.get(skinPath(id, skin));
}
@@ -7,6 +7,7 @@ import {
} from "@blitzkit/core";
import {
Document,
Material,
Node,
NodeIO,
PropertyType,
@@ -19,6 +20,7 @@ import type { Vector3Tuple, Vector4Tuple } from "three";
import { SKIN_NUMBER } from "../../../../constants/skinNumber";
import { api } from "../../../../core/blitzkit/api";
import { mixStaticPaths } from "../../../../core/blitzkit/mixStaticPaths";
import { switcherStates } from "../../../../core/blitzkit/switcherStates";
import { vfs } from "../../../../core/blitzkit/vfs";
import {
extractMaterials,
@@ -67,8 +69,10 @@ export async function GET({ props }: APIContext<{ skin: number }>) {
const [nation, tankKey] = (
include as { vehicle: { name: string } }
).vehicle.name.split(":");
const { preset, customEntities } = camouflagesYaml[key];
const skinNumber = Number(preset?.match(/(\d+)$/)?.[1] ?? 1);
const { customEntities } = camouflagesYaml[key];
const preset =
camouflagesYaml[key].preset ??
camouflagesYaml[key].override?.[nation]?.override?.[tankKey]?.preset;
const parameters = await vfs.yaml<TankParameters>(
`Data/3d/Tanks/Parameters/${nation}/${tankKey}.yaml`,
);
@@ -88,7 +92,6 @@ export async function GET({ props }: APIContext<{ skin: number }>) {
scale: Vector3Tuple;
}
> = {};
const states: Record<string, string | null> = {};
parseHierarchies(sc2["#hierarchy"], null, (hierarchy, components) => {
for (const component of components) {
@@ -111,43 +114,50 @@ export async function GET({ props }: APIContext<{ skin: number }>) {
scale: component["sc.attachmentScale"] as Vector3Tuple,
};
}
if (component["comp.typename"] !== "StateSwitcherComponent") continue;
const active = component[`ssc.state${component["ssc.activeState"]}`];
// camos without their own variant keep the default piece, but groups
// of elements to hide stay hidden
let state: string | null =
active && !/skin\d*/.test(active) && !active.includes("hide")
? active
: null;
for (let index = 0; index < component["ssc.statesCount"]; index++) {
const name = component[`ssc.state${index}`];
const match = name.match(/skin(\d*)/);
if (
match &&
!name.includes("hide") &&
Number(match[1] || 1) === skinNumber
) {
state = name;
}
}
states[hierarchy.name] = state;
}
return null;
});
const attachments = new Map<string, string[]>();
for (const name in customEntities) {
const slot = slots[name];
if (!slot) continue;
attachments.set(slot.target, [
...(attachments.get(slot.target) ?? []),
customEntities[name].item,
]);
}
const states = switcherStates(sc2, preset, attachments);
// attachments are layered over camouflages, so they only keep what they change
if (camouflagesXml.root.camouflages[key].kind === "customization") {
const baseline = switcherStates(sc2, preset, new Map());
for (const name in states) {
if (states[name] === baseline[name]) delete states[name];
}
}
const document = new Document();
const scene = document.createScene().setExtras({ states });
const scene = document.createScene();
const targets = new Map<string, Node>();
document.createBuffer();
if (preset) await extractMaterials(document, sc2, basePath, preset);
if (preset) {
const materials = await extractMaterials(document, sc2, basePath, preset);
// parts may share these names, so mark the ones that replace the tank's
for (const material of materials.values()) {
if (!(material instanceof Material)) continue;
material.setExtras({ ...material.getExtras(), camouflage: true });
}
}
for (const name in customEntities) {
const slot = slots[name];
@@ -163,6 +173,12 @@ export async function GET({ props }: APIContext<{ skin: number }>) {
}
const part = await extractModel(vfs, path, true);
const partSc2 = new Sc2ReadStream(
(await vfs.file(`Data/3d/${path}.sc2`)).buffer as ArrayBuffer,
).sc2();
Object.assign(states, switcherStates(partSc2, preset, new Map()));
const map = mergeDocuments(document, part);
const partScene = map.get(part.getRoot().listScenes()[0]) as Scene;
const node = document
@@ -186,6 +202,8 @@ export async function GET({ props }: APIContext<{ skin: number }>) {
target.addChild(node);
}
scene.setExtras({ states });
applySkinNumber(document, SKIN_NUMBER);
await document.transform(
@@ -14,7 +14,7 @@ import {
} from "@blitzkit/core";
import type { AbstractVFS } from "@blitzkit/core/src/blitzkit/vfs/abstract";
import { Document, Material, Node, NodeIO, Scene } from "@gltf-transform/core";
import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
import { ALL_EXTENSIONS, KHRMaterialsUnlit } from "@gltf-transform/extensions";
import { dedup, prune } from "@gltf-transform/functions";
import type { APIContext } from "astro";
import { isEqual, times } from "lodash-es";
@@ -65,7 +65,13 @@ export async function GET({ props }: APIContext<{ id: number }>) {
const ERROR_ON_UNKNOWN_COMPONENT = false;
const omitMeshNames = {
start: ["chassis_chassis_", "chassis_track_crash_", "HP_"],
start: [
"chassis_chassis_",
"chassis_track_crash_",
"HP_",
// mastery marks a new tank doesn't have yet
"custom_gun_marks_",
],
end: ["_POINT"],
};
@@ -132,7 +138,8 @@ export async function extractModel(
times(renderObject["ro.batchCount"], (batchIndex): void => {
const lodIndex = renderObject[`rb${batchIndex}.lodIndex`];
if (lodIndex !== 0) return;
// -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];
@@ -345,6 +352,26 @@ export async function extractMaterials(
}
}
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")) {
material.setExtension(
"KHR_materials_unlit",
document.createExtension(KHRMaterialsUnlit).createUnlit(),
);
}
if (textures.miscMap) {
material.setOcclusionTexture(
document
@@ -106,6 +106,9 @@ interface Tankopedia {
requestedSkin?: number;
loadedSkin?: number;
skin?: number;
requestedAttachment?: number;
loadedAttachment?: number;
attachment?: number;
requestedDisplay: TankopediaDisplay;
display: TankopediaDisplay;
statSearch?: string;