Merge branch 'main' into data-driven

This commit is contained in:
tresabhi committed 2026-10-31 13:38:57 -05:00
commit a15e331681
18 files changed
+552 -130

No files matched your search

+1 -1
View File
@@ -110,7 +110,7 @@ jobs:
# the PR's ref, or the manual input, or production (selected when cron)
ref: ${{ github.event.pull_request.head.sha || inputs.branch || 'production' }}
submodules: recursive
token: ${{ secrets.GH_TOKEN }}
token: ${{ secrets.GH_TOKEN || github.token }}
- name: Setup bun
uses: oven-sh/setup-bun@v2
@@ -87,14 +87,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) {
@@ -110,6 +115,7 @@ export abstract class ServerBlitzKitAPI2 extends ServerBlitzKitAPI1 {
tank_name: resolvedTankName,
tank_name_full: resolvedTankNameFull,
tank_id: tankId,
attachment: camo.kind === "customization",
};
}
+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 }> }
>;
}
>;
@@ -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;
}
+10 -7
View File
@@ -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.loaders.skin.requested !== state.loaders.skin.loaded ||
state.loaders.attachment.requested !== state.loaders.attachment.loaded,
);
const animationTime = useRef(REVEAL_ANIMATION_TIME);
@@ -63,6 +65,7 @@ export function Lighting({ hasPbr }: Props) {
useEffect(() => {
Tankopedia.mutate((draft) => {
draft.revealed = true;
draft.loaders.model.loaded = true;
});
}, []);
@@ -162,6 +165,7 @@ export function Lighting({ hasPbr }: Props) {
key={index}
position={position}
intensity={intensity}
userData={{ intensity }}
penumbra={1}
castShadow={highGraphics}
decay={1}
@@ -212,6 +216,11 @@ function Animator({
for (const child of wrapper.current.children) {
if (child instanceof SpotLight) {
child.angle = ANGLE * t * factor;
child.intensity = child.userData.intensity;
if (child.angle === 0) {
child.intensity = 0;
}
} else if (child instanceof HemisphereLight) {
child.intensity = HEMISPHERE_INTENSITY * t * factor;
}
@@ -244,12 +253,6 @@ function Animator({
draft.display = requestedDisplay;
});
}
if (x >= 1 && Tankopedia.state.skin !== Tankopedia.state.loadedSkin) {
Tankopedia.mutate((draft) => {
draft.skin = draft.loadedSkin;
});
}
});
return null;
+42 -4
View File
@@ -1,5 +1,6 @@
import { invalidate, useThree, type ThreeEvent } from "@react-three/fiber";
import { useRef } from "react";
import type { QuicklimeEvent } from "quicklime";
import { useEffect, useRef } from "react";
import { Group, Mesh, MeshStandardMaterial, Vector2 } from "three";
import { applyPitchYawLimits } from "../core/blitz/applyPitchYawLimits";
import { modelTransformEvent } from "../core/blitzkit/modelTransform";
@@ -13,6 +14,7 @@ import { useSkin } from "../hooks/useSkin";
import { useTankTransform } from "../hooks/useTankTransform";
import { Tankopedia } from "../stores/tankopedia";
import { TankopediaDisplay } from "../stores/tankopediaPersistent/constants";
import { transitionEvent } from "./Lighting";
export function TankModel() {
const protagonist = Tankopedia.use((state) => state.protagonist);
@@ -28,9 +30,45 @@ export function TankModel() {
const { gltf } = useModel(protagonist.tank);
const nodes = Object.values(gltf.nodes);
const skinGltf = useSkin(protagonist.tank);
const attachmentGltf = useSkin(protagonist.tank, "attachment");
const skins = [skinGltf, attachmentGltf].filter((skin) => skin !== undefined);
useTankTransform(track, turret, turretContainer, gunContainer);
useEffect(() => {
const emissiveMaterials = new Set<MeshStandardMaterial>();
for (const scene of [gltf.scene, ...skins.map((skin) => skin.scene)]) {
scene.traverse((object) => {
if (
object instanceof Mesh &&
object.material instanceof MeshStandardMaterial &&
object.material.emissiveMap
) {
emissiveMaterials.add(object.material);
}
});
}
// emissive parts fade with the lights instead of glowing in the dark
function applyIntensity(intensity: number) {
for (const material of emissiveMaterials) {
material.emissiveIntensity = intensity;
}
}
function handleTransitionEvent(event: QuicklimeEvent<number>) {
applyIntensity(event.data);
}
applyIntensity(transitionEvent.last!);
transitionEvent.on(handleTransitionEvent);
return () => {
transitionEvent.off(handleTransitionEvent);
};
}, [gltf, skinGltf, attachmentGltf]);
return (
<>
{nodes.map((node) => {
@@ -92,7 +130,7 @@ export function TankModel() {
window.removeEventListener("pointerup", handlePointerUp);
}
return skinTree(node, skinGltf, {
return skinTree(node, skins, {
mesh(_, props, key) {
return (
<mesh
@@ -171,7 +209,7 @@ export function TankModel() {
window.removeEventListener("pointerup", handlePointerUp);
}
return skinTree(node, skinGltf, {
return skinTree(node, skins, {
mesh(_, props, key) {
return (
<mesh
@@ -254,7 +292,7 @@ export function TankModel() {
window.removeEventListener("pointerup", handlePointerUp);
}
return skinTree(node, skinGltf, {
return skinTree(node, skins, {
mesh(_, props, key) {
return (
<mesh
@@ -44,7 +44,9 @@ export function GunFlexibilityVisualizer({
const tank = Duel.use((state) => state.protagonist.tank);
const turret = Duel.use((state) => state.protagonist.turret);
const gun = Duel.use((state) => state.protagonist.gun);
const modelRequested = Tankopedia.use((state) => state.modelRequested);
const modelRequested = Tankopedia.use(
(state) => state.loaders.model.requested,
);
const tankModel = modelDefinition.models[tank.id];
const turretModel = tankModel.turrets[turret.id];
@@ -13,18 +13,25 @@ const camouflageDefinitions = await api.camouflageDefinitions();
export function Title({ skeleton }: MaybeSkeletonComponentProps) {
const { unwrap, strings } = useLocale();
const modelRequested = Tankopedia.use((state) => state.modelRequested);
const modelRequested = Tankopedia.use(
(state) => state.loaders.model.requested,
);
const protagonist = Duel.use((state) => state.protagonist.tank);
const revealed = Tankopedia.use((state) => state.revealed);
const disturbed = Tankopedia.use((state) => state.disturbed);
const hasRevealed = useRef(false);
const skin = Tankopedia.use((state) => state.requestedSkin);
const skin = Tankopedia.use((state) => state.loaders.skin.requested);
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)
: `${tankName} ${unwrap(camouflage.name!)}`
: tankName
).replace("%(camo_num)", SKIN_NUMBER);
const fontSize = revealed
? disturbed
? "1.5rem"
@@ -102,7 +109,7 @@ export function Title({ skeleton }: MaybeSkeletonComponentProps) {
onPointerDown={(event) => event.stopPropagation()}
onClick={() => {
Tankopedia.mutate((draft) => {
draft.modelRequested = true;
draft.loaders.model.requested = true;
});
}}
>
@@ -20,7 +20,9 @@ export function HeroSection({ skeleton }: MaybeSkeletonComponentProps) {
const canvas = useRef<HTMLCanvasElement>(null!);
const isFullScreen = useFullScreen();
const protagonist = Duel.use((state) => state.protagonist.tank);
const modelRequested = Tankopedia.use((state) => state.modelRequested);
const modelRequested = Tankopedia.use(
(state) => state.loaders.model.requested,
);
const thicknessRange = useMemo(() => {
const entries = Object.values(tankDefinitions.tanks);
const filtered = entries.filter(
@@ -17,8 +17,10 @@ export function TankopediaSkinSwitcher() {
const tank = useDuel("protagonist", DuelModule.Tank);
const skin = Tankopedia.use((state) => state.requestedSkin);
const requestedDisplay = Tankopedia.use((state) => state.requestedDisplay);
const skin = Tankopedia.use((state) => state.loaders.skin.requested);
const requestedDisplay = Tankopedia.use(
(state) => state.loaders.display.requested,
);
const revealed = Tankopedia.use((state) => state.revealed);
const skins = uniqBy(
@@ -53,8 +55,8 @@ export function TankopediaSkinSwitcher() {
size="major"
onClick={() => {
Tankopedia.mutate((draft) => {
draft.requestedSkin =
draft.requestedSkin === camouflage.id
draft.loaders.skin.requested =
draft.loaders.skin.requested === camouflage.id
? undefined
: camouflage.id;
});
@@ -1,5 +1,5 @@
import type { ComponentProps, ReactNode } from "react";
import { Mesh, MeshStandardMaterial, Object3D } from "three";
import { AdditiveBlending, Mesh, MeshStandardMaterial, Object3D } from "three";
export function jsxTree(
node: Object3D,
@@ -27,6 +27,10 @@ export function jsxTree(
if (props.material instanceof MeshStandardMaterial) {
props.material.depthWrite = true;
if (props.material.userData.blending === "additive") {
props.material.blending = AdditiveBlending;
}
}
return mergers?.mesh ? (
+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;
}
+28 -17
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,26 +34,29 @@ 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
export function useSkin(id: number, loader: "skin" | "attachment" = "skin") {
const requested = Tankopedia.use((state) => state.loaders[loader].requested);
const loaded = Tankopedia.use((state) => state.loaders[loader].loaded);
useEffect(() => {
const path =
requestedSkin === undefined ? undefined : skinPath(id, requestedSkin);
if (requested === Tankopedia.state.loaders[loader].loaded) return;
const path = requested === undefined ? undefined : skinPath(id, requested);
const cached = path === undefined || loadedSkins.has(path);
let settled = false;
if (path === undefined || loadedSkins.has(path)) {
if (!cached) {
Tankopedia.mutate((draft) => {
draft.loadedSkin = requestedSkin;
draft.revealed = false;
});
return;
if (!skins.has(path)) skins.set(path, loadSkin(path));
}
if (!skins.has(path)) skins.set(path, loadSkin(path));
// swaps halfway through the lighting transition
Promise.all([
skins.get(path),
path && skins.get(path),
new Promise((resolve) =>
setTimeout(resolve, TRANSITION_ANIMATION_TIME * 1e3),
),
@@ -58,9 +65,8 @@ export function useSkin(id: number) {
settled = true;
Tankopedia.mutate((draft) => {
draft.loadedSkin = requestedSkin;
draft.skin = requestedSkin;
draft.revealed = true;
draft.loaders[loader].loaded = requested;
if (!cached) draft.revealed = true;
});
});
@@ -68,11 +74,16 @@ export function useSkin(id: number) {
if (settled) return;
settled = true;
if (cached) return;
Tankopedia.mutate((draft) => {
draft.revealed = true;
});
};
}, [id, requestedSkin]);
}, [id, loader, requested]);
return skin === undefined ? undefined : loadedSkins.get(skinPath(id, skin));
return loaded === undefined
? undefined
: loadedSkins.get(skinPath(id, loaded));
}
@@ -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 { api } from "../../../../api/dynamic";
import { mixStaticPaths } from "../../../../astro/mixStaticPaths";
import { SKIN_NUMBER } from "../../../../constants/skinNumber";
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(
@@ -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"],
};
@@ -129,7 +135,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];
@@ -359,6 +366,27 @@ 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")) {
// 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
+39 -34
View File
@@ -1,14 +1,14 @@
import { createDefaultEnvironment, type TankEnvironment } from "@blitzkit/core";
import type { ShellDefinition, TankDefinition } from "@blitzkit/protos";
import type { TankDefinition } from "@blitzkit/protos";
import { Soapstone } from "soapstone";
import type { Vector3 } from "three";
import { api } from "../api/dynamic";
import type { ArmorType } from "../components/SpacedArmorScene";
import type { ExternalModuleVariant } from "../components/SpacedArmorSceneComponent";
import type { XP_MULTIPLIERS } from "../components/Tankopedia/TechTreeSection";
import { createTankState } from "../tankopedia/createTankState";
import type { TankState } from "../tankopedia/tankState";
import { TankopediaDisplay } from "./tankopediaPersistent/constants";
import { App } from "./app";
import type { TankopediaDisplay } from "./tankopediaPersistent/constants";
export interface ShotLayerBase {
index: number;
@@ -76,6 +76,11 @@ export enum TankopediaRelativeAgainst {
All,
}
interface LoaderState<Type> {
requested: Type;
loaded: Type;
}
interface Tankopedia {
disturbed: boolean;
revealed: boolean;
@@ -86,35 +91,35 @@ interface Tankopedia {
relative_against: TankopediaRelativeAgainst;
modelRequested: boolean;
shot?: Shot;
editStatic: boolean;
highlightArmor?: {
editingPlate: boolean;
name: string;
point: Vector3;
thickness: number;
color: string;
} & (
| {
type: ArmorType.Primary | ArmorType.Spaced;
thicknessAngled: number;
angle: number;
}
| { type: ArmorType.External }
);
xpMultiplier: (typeof XP_MULTIPLIERS)[number];
customShell?: ShellDefinition;
requestedSkin?: number;
loadedSkin?: number;
skin?: number;
requestedDisplay: TankopediaDisplay;
display: TankopediaDisplay;
statSearch?: string;
loaders: {
display: LoaderState<TankopediaDisplay>;
model: LoaderState<boolean>;
skin: LoaderState<number | undefined>;
attachment: LoaderState<number | undefined>;
};
// shot?: Shot;
// editStatic: boolean;
// highlightArmor?: {
// editingPlate: boolean;
// name: string;
// point: Vector3;
// thickness: number;
// color: string;
// } & (
// | {
// type: ArmorType.Primary | ArmorType.Spaced;
// thicknessAngled: number;
// angle: number;
// }
// | { type: ArmorType.External }
// );
// xpMultiplier: (typeof XP_MULTIPLIERS)[number];
// customShell?: ShellDefinition;
// statSearch?: string;
}
const skills = await api.skills();
const models = await api.models();
export const Tankopedia = new Soapstone<Tankopedia, [TankDefinition]>(
(tank) => ({
@@ -123,17 +128,17 @@ export const Tankopedia = new Soapstone<Tankopedia, [TankDefinition]>(
protagonist: createTankState(tank),
antagonist: createTankState(tank),
model: models.models[tank.id],
environment: createDefaultEnvironment(skills),
relative_against: TankopediaRelativeAgainst.ClassAndTier,
modelRequested: false,
loaders: {
model: { requested: App.state.autoLoadModels, loaded: false },
skin: { requested: undefined, loaded: undefined },
attachment: { requested: undefined, loaded: undefined },
},
editStatic: false,
xpMultiplier: 1,
requestedDisplay: TankopediaDisplay.Model,
display: TankopediaDisplay.Model,
}),
);