Compare commits

..
58 Commits
Author SHA1 Message Date
TrèsAbhi fc0916ff7f New translations en.json (Russian)
[ci skip]
2026-12-06 01:31:42 -06:00
TrèsAbhi 661aeb5067 New translations en.json (Russian)
[ci skip]
2026-12-04 19:54:13 -06:00
TrèsAbhi cb106d5ed9 New translations en.json (French)
[ci skip]
2026-12-04 17:31:07 -06:00
TrèsAbhi 3e3763a928 New translations en.json (Chinese Simplified)
[ci skip]
2026-12-04 01:32:35 -06:00
TrèsAbhi 471e036072 New translations en.json (Portuguese)
[ci skip]
2026-12-04 01:32:34 -06:00
TrèsAbhi b59365d5d3 New translations en.json (Polish)
[ci skip]
2026-12-04 01:32:32 -06:00
TrèsAbhi fa6a6dee8d New translations en.json (Japanese)
[ci skip]
2026-12-04 01:32:31 -06:00
TrèsAbhi fe7671f276 New translations en.json (French)
[ci skip]
2026-12-04 01:32:30 -06:00
TrèsAbhi d9e58bd6f5 New translations en.json (Ukrainian)
[ci skip]
2026-12-04 01:32:28 -06:00
TrèsAbhi f070641019 New translations en.json (Russian)
[ci skip]
2026-12-04 01:32:26 -06:00
TrèsAbhi 6edaf587a0 New translations en.json (Spanish)
[ci skip]
2026-12-04 01:32:25 -06:00
TrèsAbhi cf1640e042 New translations en.json (Ukrainian)
[ci skip]
2026-12-02 19:55:20 -06:00
TrèsAbhi 09af25819c New translations en.json (Ukrainian)
[ci skip]
2026-12-02 18:53:13 -06:00
TrèsAbhi 86391bd9d0 New translations en.json (Ukrainian)
[ci skip]
2026-12-02 17:55:38 -06:00
TrèsAbhi c71b41b848 New translations en.json (Russian)
[ci skip]
2026-12-02 17:55:36 -06:00
TrèsAbhi ca12a3879e New translations en.json (Russian)
[ci skip]
2026-12-02 16:21:51 -06:00
TrèsAbhi a9dafbac85 New translations en.json (Spanish)
[ci skip]
2026-11-28 20:00:16 -06:00
TrèsAbhi 91bdf538de New translations en.json (Ukrainian)
[ci skip]
2026-11-14 21:32:15 -06:00
TrèsAbhi 6bb707a0cd New translations en.json (Ukrainian)
[ci skip]
2026-11-14 19:47:44 -06:00
TrèsAbhi 05c5bf21cf New translations en.json (Russian)
[ci skip]
2026-11-14 04:32:19 -06:00
TrèsAbhi b9e5a2c7fd New translations en.json (Spanish)
[ci skip]
2026-11-10 17:35:19 -06:00
TrèsAbhi 8d07be57d0 New translations en.json (French)
[ci skip]
2026-11-09 13:21:31 -06:00
TrèsAbhi a8dab47452 New translations en.json (Chinese Simplified)
[ci skip]
2026-11-08 22:31:58 -06:00
TrèsAbhi cd665349e3 New translations en.json (French)
[ci skip]
2026-11-07 04:36:03 -06:00
TrèsAbhi 2557f06f01 New translations en.json (French)
[ci skip]
2026-11-07 03:37:51 -06:00
TrèsAbhi bbdb63fd7d New translations en.json (French)
[ci skip]
2026-11-06 14:51:30 -06:00
TrèsAbhi 7a9a1360f9 New translations en.json (Polish)
[ci skip]
2026-11-05 15:24:40 -06:00
TrèsAbhi bd26c172e3 New translations en.json (Polish)
[ci skip]
2026-11-05 13:03:38 -06:00
TrèsAbhi eeb65d926a New translations en.json (Polish)
[ci skip]
2026-11-05 11:00:48 -06:00
TrèsAbhi 9c82e846a1 New translations en.json (Polish)
[ci skip]
2026-11-05 09:17:22 -06:00
TrèsAbhi 44431c4011 New translations en.json (Polish)
[ci skip]
2026-11-05 07:40:11 -06:00
TrèsAbhi 051d846525 New translations en.json (Spanish)
[ci skip]
2026-11-03 17:18:23 -06:00
TrèsAbhi 31d77d395f New translations en.json (French)
[ci skip]
2026-11-03 13:23:59 -06:00
TrèsAbhi 056e0bead9 New translations en.json (French)
[ci skip]
2026-11-03 11:54:07 -06:00
TrèsAbhi 1db426399c New translations en.json (Russian)
[ci skip]
2026-11-01 13:52:17 -06:00
TrèsAbhi 6d98216a96 New translations en.json (Portuguese)
[ci skip]
2026-11-01 13:52:16 -06:00
TrèsAbhi cbe6e9ca48 New translations en.json (Polish)
[ci skip]
2026-11-01 13:52:14 -06:00
TrèsAbhi c7b21b8dfb New translations en.json (Japanese)
[ci skip]
2026-11-01 13:52:13 -06:00
TrèsAbhi cc8f893293 New translations en.json (Spanish)
[ci skip]
2026-11-01 13:52:11 -06:00
TrèsAbhi 0f5a5d275d New translations en.json (French)
[ci skip]
2026-11-01 13:52:10 -06:00
TrèsAbhi e787f00804 New translations en.json (Chinese Simplified)
[ci skip]
2026-11-01 13:52:08 -06:00
TrèsAbhi d30ccdcd6a New translations en.json (Ukrainian)
[ci skip]
2026-11-01 13:52:06 -06:00
TrèsAbhi 206733542f New translations en.json (Ukrainian)
[ci skip]
2026-11-01 09:32:25 -06:00
TrèsAbhi b9b4adde42 New translations en.json (Ukrainian)
[ci skip]
2026-10-31 07:32:22 -05:00
TrèsAbhi e2bfd1b688 New translations en.json (Ukrainian)
[ci skip]
2026-10-29 07:47:51 -05:00
TrèsAbhi 1d95f95155 New translations en.json (Ukrainian)
[ci skip]
2026-10-28 08:43:10 -05:00
TrèsAbhi a6f49c19f6 New translations en.json (Ukrainian)
[ci skip]
2026-10-27 20:08:01 -05:00
TrèsAbhi 74038e83fb New translations en.json (Russian)
[ci skip]
2026-10-27 19:08:55 -05:00
TrèsAbhi f5a5879d03 New translations en.json (Russian)
[ci skip]
2026-10-27 12:20:24 -05:00
TrèsAbhi a4e168dae9 New translations en.json (Russian)
[ci skip]
2026-10-27 10:57:49 -05:00
TrèsAbhi 29077d313b New translations en.json (Chinese Simplified)
[ci skip]
2026-10-25 19:10:38 -05:00
TrèsAbhi 3bdfc42754 New translations en.json (Ukrainian)
[ci skip]
2026-10-25 19:10:36 -05:00
TrèsAbhi b7c0eac30c New translations en.json (Russian)
[ci skip]
2026-10-25 19:10:35 -05:00
TrèsAbhi 4c6880bbdf New translations en.json (Portuguese)
[ci skip]
2026-10-25 19:10:33 -05:00
TrèsAbhi 9b1131e42f New translations en.json (Polish)
[ci skip]
2026-10-25 19:10:32 -05:00
TrèsAbhi 54432c1a25 New translations en.json (Japanese)
[ci skip]
2026-10-25 19:10:31 -05:00
TrèsAbhi 0e8db43eb5 New translations en.json (Spanish)
[ci skip]
2026-10-25 19:10:29 -05:00
TrèsAbhi f85daaf61b New translations en.json (French)
[ci skip]
2026-10-25 19:10:28 -05:00
125 changed files with 6103 additions and 8761 deletions

No files matched your search

-1
View File
@@ -26,7 +26,6 @@ body:
description: What branch of BlitzKit were you using? Please see the "Branch" section of the footer at the very bottom of any page.
options:
- Production
- Beta
- Preview
- OpenTest
default: 0
+3 -3
View File
@@ -30,8 +30,8 @@ jobs:
- name: Setup bun
uses: oven-sh/setup-bun@v2
- name: Set up script
run: scripts/setup.sh
- name: Install dependencies
run: bun install
- name: Setup Git
run: |
@@ -39,7 +39,7 @@ jobs:
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
- name: Discover IDs
run: scripts/discover-ids.sh
run: bun run discover-ids
env:
PUBLIC_WARGAMING_APPLICATION_ID: ${{ secrets.PUBLIC_WARGAMING_APPLICATION_ID }}
GH_TOKEN: ${{ secrets.IDS_TOKEN }}
+18 -20
View File
@@ -43,10 +43,9 @@ on:
type: choice
required: true
default: wgc
default: steam
options:
- wgc
- steam
- zip
- wgpkg
@@ -66,13 +65,10 @@ concurrency:
cancel-in-progress: true
env:
# workflow
HAS_ROOT_REPO_CONTEXT: ${{ github.event_name != 'pull_request' }}
# client
STEAM_USERNAME: ${{ secrets.STEAM_USERNAME }}
STEAM_PASSWORD: ${{ secrets.STEAM_PASSWORD }}
CLIENT_PROVIDER: ${{ inputs.client_provider || (github.event_name != 'pull_request' && 'steam' || 'wgc') }}
CLIENT_PROVIDER: ${{ inputs.client_provider || 'steam' }}
CLIENT_SOURCE: ${{ inputs.client_source || '444200/windows' }}
CLIENT_DIR: ../../temp/game
@@ -82,6 +78,11 @@ env:
PUBLIC_STATIC_ASSET_BASE: https://assets.blitzkit.app
PUBLIC_GUIDE_WEBSITE: https://guidesblitz.com
# blitz
WOTB_GLOSSARY: ${{ secrets.WOTB_GLOSSARY }}
WOTB_GLOSSARY_DOMAIN: ${{ secrets.WOTB_GLOSSARY_DOMAIN }}
WOTB_GLOSSARY_PATH: ${{ secrets.WOTB_GLOSSARY_PATH }}
# google
PUBLIC_GOOGLE_TAG_MANAGER_ID: ${{ secrets.PUBLIC_GOOGLE_TAG_MANAGER_ID }}
@@ -106,10 +107,10 @@ jobs:
- name: Checkout
uses: actions/checkout@v6
with:
# the PR's ref, or the manual input, or production (selected when cron)
ref: ${{ github.event.pull_request.head.sha || inputs.branch || 'production' }}
# the only submodule is closed, which needs secrets
submodules: ${{ env.HAS_ROOT_REPO_CONTEXT == 'true' && 'recursive' || 'false' }}
token: ${{ secrets.GH_TOKEN || github.token }}
submodules: recursive
token: ${{ secrets.GH_TOKEN }}
- name: Setup bun
uses: oven-sh/setup-bun@v2
@@ -124,21 +125,19 @@ jobs:
sudo apt-get update
sudo apt-get install -y aria2 libarchive-tools
- name: Set up script
run: scripts/setup.sh
- name: Lint
run: scripts/lint.sh
- name: Install dependencies
run: bun install
- name: Download client
run: scripts/download-client.sh
run: bun run download-client
- name: Download SmartDLC
if: ${{ env.HAS_ROOT_REPO_CONTEXT == 'true' }}
run: scripts/download-smart-dlc.sh
if: ${{ env.CLIENT_PROVIDER == 'steam' }}
run: bun run download-smart-dlc
- name: Build
run: scripts/build-website.sh
run: bun run --bun build
env:
CHUNK: ${{ matrix.chunk }}
@@ -157,8 +156,7 @@ jobs:
# - is by manual and is on anything: triggering to anything
if: >-
${{
env.HAS_ROOT_REPO_CONTEXT == 'true'
|| (github.event_name == 'schedule' && github.ref == 'refs/heads/main')
(github.event_name == 'schedule' && github.ref == 'refs/heads/main')
|| (github.event_name == 'push' && github.ref == 'refs/heads/production')
|| (github.event_name == 'workflow_dispatch')
}}
-9
View File
@@ -1,9 +0,0 @@
# BlitzKit
## Layout
- Hooks live in `src/hooks/useName.ts` (`.tsx` if they render JSX), one hook per file named after it, never inside a component's folder.
## TypeScript
- When an `if`/`else if` chain checks one value against several candidates (`x === "a"`, `x === b`, ...), use a `switch` on that value instead. Inside a loop, end each case with `continue`, and put the checks a `switch` can't express (`startsWith`, ranges, ...) as an `if` after it, not in `default`.
+6 -6
View File
@@ -44,16 +44,16 @@ cd blitzkit
> [!NOTE]
> There is a closed source submodule under `packages/closed` that you can safely ignore. This sole purpose of this submodule is to provide `dvp.ts`, a proprietary Wargaming game asset tree compression tool. You will not need this at any point.
Then, grand execution permission to the setup script.
Then, download the dependencies with Bun.
```bash
chmod +x scripts/setup.sh
bun install
```
Finally, run the setup script.
Finally, compile the proto files into TypeScript.
```bash
scripts/setup.sh
build build-protos
```
## Developing: Environment
@@ -65,11 +65,11 @@ Go through the different packages in the `packages` directory and clone their re
Launching the website is as easy as running the `dev` script.
```bash
scripts/dev-website.sh
bun dev
```
If you ever make a change to any proto file, make sure to rebuild them.
```bash
scripts/build-protos.sh
build build-protos
```
+7 -1
View File
@@ -35,6 +35,7 @@
"@types/lz4js": "^0.2.1",
"@types/three": "^0.180.0",
"adm-zip": "^0.5.16",
"crc": "^4.3.2",
"dotenv": "^17.2.2",
"fast-xml-parser": "^5.3.2",
"lodash-es": "^4.17.21",
@@ -54,6 +55,7 @@
"packages/scripts": {
"name": "@blitzkit/scripts",
"dependencies": {
"@blitzkit/closed": "workspace:*",
"@blitzkit/core": "workspace:*",
"@blitzkit/i18n": "workspace:*",
"@gltf-transform/core": "^4.2.1",
@@ -1641,6 +1643,8 @@
"jimp": ["[email protected]", "", { "dependencies": { "@jimp/core": "1.6.0", "@jimp/diff": "1.6.0", "@jimp/js-bmp": "1.6.0", "@jimp/js-gif": "1.6.0", "@jimp/js-jpeg": "1.6.0", "@jimp/js-png": "1.6.0", "@jimp/js-tiff": "1.6.0", "@jimp/plugin-blit": "1.6.0", "@jimp/plugin-blur": "1.6.0", "@jimp/plugin-circle": "1.6.0", "@jimp/plugin-color": "1.6.0", "@jimp/plugin-contain": "1.6.0", "@jimp/plugin-cover": "1.6.0", "@jimp/plugin-crop": "1.6.0", "@jimp/plugin-displace": "1.6.0", "@jimp/plugin-dither": "1.6.0", "@jimp/plugin-fisheye": "1.6.0", "@jimp/plugin-flip": "1.6.0", "@jimp/plugin-hash": "1.6.0", "@jimp/plugin-mask": "1.6.0", "@jimp/plugin-print": "1.6.0", "@jimp/plugin-quantize": "1.6.0", "@jimp/plugin-resize": "1.6.0", "@jimp/plugin-rotate": "1.6.0", "@jimp/plugin-threshold": "1.6.0", "@jimp/types": "1.6.0", "@jimp/utils": "1.6.0" } }, "sha512-YcwCHw1kiqEeI5xRpDlPPBGL2EOpBKLwO4yIBJcXWHPj5PnA5urGq0jbyhM5KoNpypQ6VboSoxc9D8HyfvngSg=="],
"jiti": ["[email protected]", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-VXe6RjJkBPj0ohtqaO8vSWP3ZhAKo66fKrFNCll4BTcwljPLz03pCbaNKfzGP5MbrCYcbJ7v0nOYYwUzTEIdXQ=="],
"jpeg-js": ["[email protected]", "", {}, "sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg=="],
"js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
@@ -1947,7 +1951,7 @@
"potpack": ["[email protected]", "", {}, "sha512-choctRBIV9EMT9WGAZHn3V7t0Z2pMQyl0EZE6pFc/6ml3ssw7Dlf/oAOvFwjm1HVsqfQN8GfeFyJ+d8tRzqueQ=="],
"prettier": ["prettier@2.8.7", "", { "bin": { "prettier": "bin-prettier.js" } }, "sha512-yPngTo3aXUUmyuTjeTUT75txrf+aMh9FiD7q9ZE/i6r0bPb22g4FsE6Y338PQX1bmfy08i9QQCB7/rcUAVntfw=="],
"prettier": ["prettier@3.6.2", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ=="],
"pretty-bytes": ["[email protected]", "", {}, "sha512-mQUvGU6aUFQ+rNvTIAcZuWGRT9a6f6Yrg9bHs4ImKF+HZCEK+plBvnAZYSIQztknZF2qnzNtr6F8s0+IuptdlQ=="],
@@ -2729,6 +2733,8 @@
"wrap-ansi/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA=="],
"yaml-language-server/prettier": ["[email protected]", "", { "bin": { "prettier": "bin-prettier.js" } }, "sha512-yPngTo3aXUUmyuTjeTUT75txrf+aMh9FiD7q9ZE/i6r0bPb22g4FsE6Y338PQX1bmfy08i9QQCB7/rcUAVntfw=="],
"yaml-language-server/request-light": ["[email protected]", "", {}, "sha512-3Zjgh+8b5fhRJBQZoy+zbVKpAQGLyka0MPgW3zruTF4dFFJ8Fqcfu9YsAvi/rvdcaTeWG3MkbZv4WKxAn/84Lg=="],
"yaml-language-server/vscode-languageserver": ["[email protected]", "", { "dependencies": { "vscode-languageserver-protocol": "3.16.0" }, "bin": { "installServerIntoExtension": "bin/installServerIntoExtension" } }, "sha512-60HTx5ID+fLRcgdHfmz0LDZAXYEV68fzwG0JWwEPBode9NuMYTIxuYXPg4ngO8i8+Ou0lM7y6GzaYWbiDL0drw=="],
-21
View File
@@ -1,21 +0,0 @@
# BlitzKit 1.33.0
Thank you to [HitJack](https://github.com/Hitjack007) for your contributions this update.
## Features
- Added legendary camouflages to Tankopedia [HitJack]
- The rank bars below every statistic in Tankopedia now shows the distribution of every other tank [HitJack]
- Added a Credits page for everyone who has contributed to BlitzKit
- Added an option to synchronize shells across tanks in Compare [HitJack]
## Fixes
- The tank selector popups are now properly sized vertically, stopping them from clipping the top of the page [HitJack]
- When the lights recede, there is no longer a 1-pixel spot where the light still shines
## Technical Changes
- The BlitzKit API is now split across `legendary.models.blitzkit.app`, `tanks.models.blitzkit.app`, `maps.models.blitzkit.app`, and `api.models.blitzkit.app`
- Added some compatibility for the new tier XI tanks
- More work is needed in this area to implement the new mechanics they bring
-21
View File
@@ -1,21 +0,0 @@
# BlitzKit 1.33.1
Thank you to [HitJack](https://github.com/Hitjack007) for your contributions this update.
## Features
- Legendary camouflages in Tankopedia are now animated and loop their garage animations [HitJack]
- Tankopedia's 3D viewer is now much faster as tank models, armor, and legendary camouflages are drawn in batches
- Shadows are now only redrawn when something in the scene changes instead of every frame, saving battery and GPU time
## Fixes
- Unused parts of legendary camouflages are now hidden, fixing camouflages like the Maus' [HitJack]
- Legendary camouflage parts with no LODs are no longer missing, like the Tiger II's cat and the BDT-5A's engine rings [HitJack]
- The ground in Tankopedia is no longer transparent, so it fades out cleanly instead of blending with things behind it
## Technical Changes
- Tank and legendary camouflage models build much faster thanks to a faster DDS decoder and native CRC32 checksums [HitJack]
- The game client is now downloaded from Wargaming Game Center by default
- Added a zip-backed virtual file system for reading game files
-3
View File
@@ -1,3 +0,0 @@
# BlitzKit 1.33.2
Fixed an issue that caused the armor of some tanks like the Type 71 to crash BlitzKit.
+12 -1
View File
@@ -1,8 +1,19 @@
{
"name": "blitzkit",
"version": "1.33.2",
"version": "1.33.0-beta.1",
"license": "BlitzKit License",
"private": true,
"scripts": {
"dev": "cd packages/website && bun --bun run dev",
"build": "cd packages/website && bun --bun run build",
"discover-ids": "cd packages/scripts && bun run discover-ids",
"build-protos": "cd packages/scripts && bun run build-protos",
"record-performance": "cd packages/scripts && bun run record-performance",
"download-client": "cd packages/scripts && bun run download-client",
"download-smart-dlc": "cd packages/scripts && bun run download-smart-dlc",
"clean-astro": "rm -rf packages/website/.astro packages/website/node_modules/.astro packages/website/node_modules/.vite",
"vfs": "cd packages/scripts && bun run vfs"
},
"type": "module",
"workspaces": [
"packages/*"
+1
View File
@@ -14,6 +14,7 @@
"@types/lz4js": "^0.2.1",
"@types/three": "^0.180.0",
"adm-zip": "^0.5.16",
"crc": "^4.3.2",
"dotenv": "^17.2.2",
"fast-xml-parser": "^5.3.2",
"lodash-es": "^4.17.21",
+8 -12
View File
@@ -1,15 +1,11 @@
import { BlitzGlossary } from "../types";
export const WOTB_GLOSSARY_DOMAIN = "https://na.wotblitz.com";
export const WOTB_GLOSSARY_PATH = "api/glossary/stuff";
import { assertSecret } from "../blitzkit";
import type { BlitzGlossary } from "../types";
export async function fetchGlossary(locale: string) {
// const response = await fetch(
// `${assertSecret(
// import.meta.env.WOTB_GLOSSARY_DOMAIN,
// )}/${locale}${assertSecret(import.meta.env.WOTB_GLOSSARY_PATH)}`,
// );
// return (await response.json()) as BlitzGlossary;
return {} as BlitzGlossary;
const response = await fetch(
`${assertSecret(
import.meta.env.WOTB_GLOSSARY_DOMAIN,
)}/${locale}${assertSecret(import.meta.env.WOTB_GLOSSARY_PATH)}`,
);
return (await response.json()) as BlitzGlossary;
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { crc32 } from "crc";
import { decompressBlock } from "lz4js";
/**
@@ -25,7 +26,7 @@ export function readDVPL(buffer: Buffer) {
if (targetBlock.length !== footerData.cSize) {
throw new RangeError("DVPL size mismatch");
}
if (Bun.hash.crc32(targetBlock) !== footerData.crc32) {
if (crc32(targetBlock) !== footerData.crc32) {
throw new TypeError("DVPL CRC32 mismatch");
}
@@ -106,7 +106,6 @@ export abstract class ServerBlitzKitAPI0 extends BlitzKitAPI {
protected gameTypeSelectorStyles?: SquadBattleTypeStylesYaml;
protected combatRoles?: CombatRolesYaml;
protected tierEqualizer?: string[][];
protected version?: string;
constructor(vfs: AbstractVFS) {
super();
@@ -117,6 +116,9 @@ export abstract class ServerBlitzKitAPI0 extends BlitzKitAPI {
const { existsSync } = await import("fs");
const { readFile, writeFile, mkdir } = await import("fs/promises");
console.log("Initializing virtual file system...");
await this.vfs.init();
console.log("Fetching game data...");
this.nationsDir = await this.vfs
.dir("Data/XML/item_defs/vehicles")
@@ -154,13 +156,11 @@ export abstract class ServerBlitzKitAPI0 extends BlitzKitAPI {
{ delimiter: ";" },
);
this.version = (await this.vfs.text("Data/version.txt")).split(" ")[0];
console.log("Fetching game localizations...");
await Promise.all(
locales.supported.map(async ({ locale }) => {
const root = `../../temp/game-strings/${this.version}`;
const root = "../../temp/game-strings";
const cachePath = `${root}/${locale}.json`;
if (existsSync(cachePath)) {
@@ -87,19 +87,14 @@ 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 (preset !== undefined) {
if (camo.group === "legendary" && yamlEntry.preset !== undefined) {
if (!skinPresets.has(vehicle)) {
skinPresets.set(vehicle, this.skinPresets(vehicle));
}
hasPreset = (await skinPresets.get(vehicle)!).has(preset);
hasPreset = (await skinPresets.get(vehicle)!).has(yamlEntry.preset);
}
if (resolvedParts.some(Boolean) || hasPreset) {
@@ -115,7 +110,6 @@ export abstract class ServerBlitzKitAPI2 extends ServerBlitzKitAPI1 {
tank_name: resolvedTankName,
tank_name_full: resolvedTankNameFull,
tank_id: tankId,
attachment: camo.kind === "customization",
};
}
@@ -79,8 +79,14 @@ export abstract class ServerBlitzKitAPI3 extends ServerBlitzKitAPI2 {
I_HAT,
-MathUtils.degToRad(turretRotation.pitch),
)
.applyAxisAngle(J_HAT, -MathUtils.degToRad(turretRotation.roll))
.applyAxisAngle(K_HAT, -MathUtils.degToRad(turretRotation.yaw));
.applyAxisAngle(
J_HAT,
-MathUtils.degToRad(turretRotation.roll),
)
.applyAxisAngle(
K_HAT,
-MathUtils.degToRad(turretRotation.yaw),
);
}
const coordinates = position.toArray();
@@ -292,29 +298,23 @@ export abstract class ServerBlitzKitAPI3 extends ServerBlitzKitAPI2 {
turret.userString;
let turretCollisionName = parsePath(
const turretCollisionName = parsePath(
turret.hitTester.collisionModel,
).name.toLowerCase();
const isFullYaw = -turretYaw[0] + turretYaw[1] === 360;
if (!collisionBoundingBoxes[turretCollisionName] && isFullYaw) {
turretCollisionName = "turret_01";
console.warn(
`HACK: Missing turret collision mesh for ${nation}/${tankKey}; turret key: ${
turretKey
}; collision model: ${turretCollisionName}; available options: ${Object.keys(
collisionBoundingBoxes,
).join(", ")}; using ${turretCollisionName} instead`,
throw new Error(
`Missing turret collision mesh for ${nation}-${tankKey} ${turretKey}`,
);
}
let turretBoundingBox = collisionBoundingBoxes[turretCollisionName];
if (turretBoundingBox === undefined) {
console.warn("HACK: missing collision; using 0's");
turretBoundingBox = { min: [0, 0, 0], max: [0, 0, 0] };
}
const turretBoundingBox = collisionBoundingBoxes[
turretCollisionName
] ?? {
min: [0, 0, 0] as Vector3Tuple,
max: [0, 0, 0] as Vector3Tuple,
};
modelDefinitions.models[tankId].turrets[turretId] = {
armor: turretArmor,
@@ -342,18 +342,9 @@ export abstract class ServerBlitzKitAPI3 extends ServerBlitzKitAPI2 {
)
.split(" ")
.map(Number) as [number, number];
let gunModel = Number(
const gunModel = Number(
parsePath(gun.models.undamaged).name.split("_")[1],
);
if (tankId === 30497) {
console.warn(
"HACK: using gun_02 for hacker tank instead of gun_01... hehe, that's quite appropriate for this tank haha",
);
gunModel = 2;
}
const front = gun.extraPitchLimits?.front
? gun.extraPitchLimits.front.split(" ").map(Number)
: undefined;
@@ -15,7 +15,7 @@ export abstract class ServerBlitzKitAPI6 extends ServerBlitzKitAPI5 {
const entry: Consumable = {
id: consumable.id,
game_mode_exclusive: "gameModeFilter" in consumable,
cooldown: consumable.script.cooldown ?? 0,
cooldown: consumable.script.cooldown,
duration: consumable.script.duration,
name: this.getString(consumable.userString),
exclude: [],
@@ -19,7 +19,9 @@ export abstract class ServerBlitzKitAPI9 extends ServerBlitzKitAPI8 {
provisionNativeNames[key] = provision.id;
});
gameDefinitions.version = this.version!;
const version = (await this.vfs.text("Data/version.txt")).split(" ")[0];
gameDefinitions.version = version;
gameDefinitions.nations = (
await this.vfs.yaml<AvailableNationsYaml>("Data/available_nations.yaml")
).available_nations;
-18
View File
@@ -1,18 +0,0 @@
import { assertSecret } from "@blitzkit/core";
import { AbstractVFS } from "./abstract";
import { LocalVFS } from "./local";
import { ZipVFS } from "./zip";
export async function createClientVFS() {
let vfs: AbstractVFS;
if (import.meta.env.CLIENT_PROVIDER === "zip") {
vfs = new ZipVFS(assertSecret(import.meta.env.CLIENT_SOURCE));
} else {
vfs = new LocalVFS(assertSecret(import.meta.env.CLIENT_DIR));
}
await vfs.init();
return vfs;
}
@@ -14,5 +14,4 @@ message Camouflage {
optional I18nString tank_name = 3;
optional I18nString tank_name_full = 4;
optional uint32 tank_id = 5;
optional bool attachment = 6;
}
@@ -25,7 +25,6 @@ export interface Camouflage {
tank_name?: I18nString | undefined;
tank_name_full?: I18nString | undefined;
tank_id?: number | undefined;
attachment?: boolean | undefined;
}
function createBaseCamouflageDefinitions(): CamouflageDefinitions {
@@ -193,7 +192,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, attachment: false };
return { id: 0, name: undefined, tank_name: undefined, tank_name_full: undefined, tank_id: 0 };
}
export const Camouflage: MessageFns<Camouflage> = {
@@ -213,9 +212,6 @@ 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;
},
@@ -266,14 +262,6 @@ 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;
@@ -290,7 +278,6 @@ 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,
};
},
@@ -311,9 +298,6 @@ 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;
},
@@ -333,7 +317,6 @@ 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;
},
};
+200 -142
View File
@@ -1,4 +1,5 @@
import { times } from "lodash-es";
import type { Vector3Tuple, Vector4Tuple } from "three";
import { WindowsReadStream } from "./windows";
enum DxgiFormat {
@@ -126,16 +127,6 @@ enum DxgiFormat {
FORCE_UINT = 0xffffffff,
}
enum BlockFormat {
BC1,
BC2,
BC3,
}
// red, green and blue of a packed 5:6:5 color
const CHANNEL_SHIFTS = [11, 5, 0];
const CHANNEL_MAXIMUMS = [31, 63, 31];
enum DdsDimension {
UNKNOWN = 0,
BUFFER = 1,
@@ -189,18 +180,44 @@ export class DdsReadStream extends WindowsReadStream {
switch (dxgiFormat) {
case DxgiFormat.BC1_TYPELESS:
case DxgiFormat.BC1_UNORM:
case DxgiFormat.BC1_UNORM_SRGB:
return this.decodeBlocks(header.width, header.height, BlockFormat.BC1);
case DxgiFormat.BC1_UNORM_SRGB: {
return this.iterateBlocks(header.width, header.height, () => {
const colorInterpolations = this.bc1ColorInterpolations();
const colorKeys = this.bc1ColorKeys();
return (index) => colorInterpolations[colorKeys[index]];
});
}
case DxgiFormat.BC2_TYPELESS:
case DxgiFormat.BC2_UNORM:
case DxgiFormat.BC2_UNORM_SRGB:
return this.decodeBlocks(header.width, header.height, BlockFormat.BC2);
case DxgiFormat.BC2_UNORM_SRGB: {
return this.iterateBlocks(header.width, header.height, () => {
const alphaInterpolations = this.bc2AlphaInterpolations();
const colorInterpolations = this.bc2ColorInterpolations();
const colorKeys = this.bc1ColorKeys();
return (index) => {
return [
...colorInterpolations[colorKeys[index]],
alphaInterpolations[index],
];
};
});
}
case DxgiFormat.BC3_TYPELESS:
case DxgiFormat.BC3_UNORM:
case DxgiFormat.BC3_UNORM_SRGB:
return this.decodeBlocks(header.width, header.height, BlockFormat.BC3);
case DxgiFormat.BC3_UNORM_SRGB: {
return this.iterateBlocks(header.width, header.height, () => {
const alphaInterpolations = this.bc3AlphaInterpolations();
const alphaKeys = this.bc3AlphaKeys();
const colorInterpolations = this.bc2ColorInterpolations();
const colorKeys = this.bc1ColorKeys();
return (index) => [
...colorInterpolations[colorKeys[index]],
alphaInterpolations[alphaKeys[index]],
];
});
}
default:
throw new TypeError(
@@ -282,148 +299,189 @@ export class DdsReadStream extends WindowsReadStream {
throw new RangeError("Width and height must be divisible by 4");
}
}
/**
* writes each 4x4 block straight into the image; a block's palette is worked
* out from 0 to 1 and rounded to bytes once, as each pixel would round it
*/
decodeBlocks(width: number, height: number, format: BlockFormat) {
iterateBlocks(
width: number,
height: number,
blockIterator: () => (index: number) => Vector4Tuple
) {
this.assetFactor4(width, height);
const data = Buffer.alloc(width * height * 4);
const bytes = new Uint8Array(this.buffer);
// 4 colors of red, green, blue and alpha
const colors = new Uint8Array(16);
// BC2 has an alpha per pixel, BC3 a palette of 8
const alphas = new Uint8Array(16);
const blocksX = width / 4;
const blocksY = height / 4;
for (let blockY = 0; blockY < height; blockY += 4) {
for (let blockX = 0; blockX < width; blockX += 4) {
let index = this.index;
// BC3's 3 bit alpha keys, 8 pixels to each half
let alphaKeysLow = 0;
let alphaKeysHigh = 0;
times(blocksX * blocksY, (index) => {
const blockPosX = (index % blocksX) * 4;
const blockPosY = Math.floor(index / blocksX) * 4;
const pixelIterator = blockIterator();
if (format === BlockFormat.BC2) {
for (let pixel = 0; pixel < 16; pixel++) {
const alpha =
(bytes[index + (pixel >> 1)] >> ((pixel & 1) * 4)) & 0b1111;
times(16, (pixelIndex) => {
const pixelPosX = pixelIndex % 4;
const pixelPosY = Math.floor(pixelIndex / 4);
const x = blockPosX + pixelPosX;
const y = blockPosY + pixelPosY;
const bufferIndex = 4 * (y * width + x);
alphas[pixel] = Math.round((alpha / 15) * 255);
}
index += 8;
} else if (format === BlockFormat.BC3) {
this.bc3Alphas(bytes[index] / 255, bytes[index + 1] / 255, alphas);
alphaKeysLow =
bytes[index + 2] |
(bytes[index + 3] << 8) |
(bytes[index + 4] << 16);
alphaKeysHigh =
bytes[index + 5] |
(bytes[index + 6] << 8) |
(bytes[index + 7] << 16);
index += 8;
}
const int0 = bytes[index] | (bytes[index + 1] << 8);
const int1 = bytes[index + 2] | (bytes[index + 3] << 8);
const colorKeys =
bytes[index + 4] |
(bytes[index + 5] << 8) |
(bytes[index + 6] << 16) |
(bytes[index + 7] << 24);
// only BC1 has a transparent color
this.blockColors(
int0,
int1,
format === BlockFormat.BC1 && int0 < int1,
colors
);
this.index = index + 8;
for (let pixel = 0; pixel < 16; pixel++) {
const offset =
4 * ((blockY + (pixel >> 2)) * width + blockX + (pixel & 3));
const color = 4 * ((colorKeys >>> (pixel * 2)) & 0b11);
data[offset] = colors[color];
data[offset + 1] = colors[color + 1];
data[offset + 2] = colors[color + 2];
if (format === BlockFormat.BC1) {
data[offset + 3] = colors[color + 3];
} else if (format === BlockFormat.BC2) {
data[offset + 3] = alphas[pixel];
} else {
const alphaKey =
pixel < 8
? (alphaKeysLow >> (pixel * 3)) & 0b111
: (alphaKeysHigh >> ((pixel - 8) * 3)) & 0b111;
data[offset + 3] = alphas[alphaKey];
}
}
}
}
pixelIterator(pixelIndex).forEach((channel, index) => {
data[bufferIndex + index] = Math.round(channel * 255);
});
});
});
return { data, width, height, channels: 4 as const };
}
blockColors(
int0: number,
int1: number,
transparent: boolean,
colors: Uint8Array
) {
for (let channel = 0; channel < 3; channel++) {
const shift = CHANNEL_SHIFTS[channel];
const maximum = CHANNEL_MAXIMUMS[channel];
const value0 = ((int0 >> shift) & maximum) / maximum;
const value1 = ((int1 >> shift) & maximum) / maximum;
readR5G6B5Int() {
return new DataView(this.read(2)).getUint16(0, true);
}
R5G6B5() {
const buffer = this.consumeUint8Array(2);
const r = (buffer[1] & 0b11111000) >>> 3;
const g = ((buffer[1] & 0b111) << 3) | ((buffer[0] & 0b11100000) >>> 5);
const b = buffer[0] & 0b11111;
colors[channel] = Math.round(value0 * 255);
colors[4 + channel] = Math.round(value1 * 255);
colors[8 + channel] = Math.round(
(transparent ? (value0 + value1) / 2 : (2 * value0 + value1) / 3) * 255
return [r / 31, g / 63, b / 31] as Vector3Tuple;
}
R5G6B5A0() {
return [...this.R5G6B5(), 1] as Vector4Tuple;
}
A8() {
return this.uint8() / 255;
}
bc1ColorInterpolations() {
const int0 = this.readR5G6B5Int();
const color0 = this.R5G6B5A0();
const int1 = this.readR5G6B5Int();
const color1 = this.R5G6B5A0();
const alpha = int0 < int1;
const color2 = alpha
? (color0.map(
(channel0, index) => (channel0 + color1[index]) / 2
) as Vector4Tuple)
: (color0.map(
(channel0, index) => (2 * channel0 + color1[index]) / 3
) as Vector4Tuple);
const color3 = alpha
? ([0, 0, 0, 0] as Vector4Tuple)
: (color0.map(
(channel0, index) => (channel0 + 2 * color1[index]) / 3
) as Vector4Tuple);
return {
[0b00]: color0,
[0b01]: color1,
[0b10]: color2,
[0b11]: color3,
} as Record<number, Vector4Tuple>;
}
bc1ColorKeys() {
const buffer = this.consumeUint8Array(4);
const d = (buffer[0] & 0b11000000) >>> 6;
const c = (buffer[0] & 0b110000) >>> 4;
const b = (buffer[0] & 0b1100) >>> 2;
const a = buffer[0] & 0b11;
const h = (buffer[1] & 0b11000000) >>> 6;
const g = (buffer[1] & 0b110000) >>> 4;
const f = (buffer[1] & 0b1100) >>> 2;
const e = buffer[1] & 0b11;
const l = (buffer[2] & 0b11000000) >>> 6;
const k = (buffer[2] & 0b110000) >>> 4;
const j = (buffer[2] & 0b1100) >>> 2;
const i = buffer[2] & 0b11;
const p = (buffer[3] & 0b11000000) >>> 6;
const o = (buffer[3] & 0b110000) >>> 4;
const n = (buffer[3] & 0b1100) >>> 2;
const m = buffer[3] & 0b11;
return [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p];
}
bc2AlphaInterpolations() {
const buffer = this.consumeUint8Array(8);
const d = (buffer[1] & 0b11110000) >>> 4;
const c = buffer[1] & 0b1111;
const b = (buffer[0] & 0b11110000) >>> 4;
const a = buffer[0] & 0b1111;
const h = (buffer[3] & 0b11110000) >>> 4;
const g = buffer[3] & 0b1111;
const f = (buffer[2] & 0b11110000) >>> 4;
const e = buffer[2] & 0b1111;
const l = (buffer[5] & 0b11110000) >>> 4;
const k = buffer[5] & 0b1111;
const j = (buffer[4] & 0b11110000) >>> 4;
const i = buffer[4] & 0b1111;
const p = (buffer[7] & 0b11110000) >>> 4;
const o = buffer[7] & 0b1111;
const n = (buffer[6] & 0b11110000) >>> 4;
const m = buffer[6] & 0b1111;
return [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p].map(
(alpha) => alpha / 15
);
colors[12 + channel] = transparent
? 0
: Math.round(((value0 + 2 * value1) / 3) * 255);
}
bc2ColorInterpolations() {
const color0 = this.R5G6B5();
const color1 = this.R5G6B5();
const color2 = color0.map(
(channel0, index) => (2 * channel0 + color1[index]) / 3
) as Vector3Tuple;
const color3 = color0.map(
(channel0, index) => (channel0 + 2 * color1[index]) / 3
) as Vector3Tuple;
colors[3] = 255;
colors[7] = 255;
colors[11] = 255;
colors[15] = transparent ? 0 : 255;
return {
[0b00]: color0,
[0b01]: color1,
[0b10]: color2,
[0b11]: color3,
} as Record<number, Vector3Tuple>;
}
bc3Alphas(alpha0: number, alpha1: number, alphas: Uint8Array) {
bc3AlphaInterpolations() {
const alpha0 = this.A8();
const alpha1 = this.A8();
const full = alpha0 > alpha1;
const values = full
? [
alpha0,
alpha1,
(6 * alpha0 + 1 * alpha1) / 7,
(5 * alpha0 + 2 * alpha1) / 7,
(4 * alpha0 + 3 * alpha1) / 7,
(3 * alpha0 + 4 * alpha1) / 7,
(2 * alpha0 + 5 * alpha1) / 7,
(1 * alpha0 + 6 * alpha1) / 7,
]
: [
alpha0,
alpha1,
(4 * alpha0 + 1 * alpha1) / 5,
(3 * alpha0 + 2 * alpha1) / 5,
(2 * alpha0 + 3 * alpha1) / 5,
(1 * alpha0 + 4 * alpha1) / 5,
0,
// kept as the decoder always had it, which wraps to 1 as a byte
255,
];
for (let key = 0; key < 8; key++) {
alphas[key] = Math.round(values[key] * 255);
return {
[0b000]: alpha0,
[0b001]: alpha1,
...(full
? {
[0b010]: (6 * alpha0 + 1 * alpha1) / 7,
[0b011]: (5 * alpha0 + 2 * alpha1) / 7,
[0b100]: (4 * alpha0 + 3 * alpha1) / 7,
[0b101]: (3 * alpha0 + 4 * alpha1) / 7,
[0b110]: (2 * alpha0 + 5 * alpha1) / 7,
[0b111]: (1 * alpha0 + 6 * alpha1) / 7,
}
: {
[0b010]: (4 * alpha0 + 1 * alpha1) / 5,
[0b011]: (3 * alpha0 + 2 * alpha1) / 5,
[0b100]: (2 * alpha0 + 3 * alpha1) / 5,
[0b101]: (1 * alpha0 + 4 * alpha1) / 5,
[0b110]: 0,
[0b111]: 255,
}),
} as Record<number, number>;
}
bc3AlphaKeys() {
const buffer = this.consumeUint8Array(6);
const h = (buffer[2] & 0b11100000) >>> 5;
const g = (buffer[2] & 0b11100) >>> 2;
const f = ((buffer[2] & 0b11) << 1) | ((buffer[1] & 0b10000000) >>> 7);
const e = (buffer[1] & 0b1110000) >>> 4;
const d = (buffer[1] & 0b1110) >>> 1;
const c = ((buffer[1] & 0b1) << 2) | ((buffer[0] & 0b11000000) >>> 6);
const b = (buffer[0] & 0b111000) >>> 3;
const a = buffer[0] & 0b111;
const p = (buffer[5] & 0b11100000) >>> 5;
const o = (buffer[5] & 0b11100) >>> 2;
const n = ((buffer[5] & 0b11) << 1) | ((buffer[4] & 0b10000000) >>> 7);
const m = (buffer[4] & 0b1110000) >>> 4;
const l = (buffer[4] & 0b1110) >>> 1;
const k = ((buffer[4] & 0b1) << 2) | ((buffer[3] & 0b11000000) >>> 6);
const j = (buffer[3] & 0b111000) >>> 3;
const i = buffer[3] & 0b111;
return [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p];
}
}
+2 -8
View File
@@ -40,8 +40,6 @@ export interface ConfigArchive {
interface EnabledPresets {
AlphaTest: boolean;
AlphaBlend?: boolean;
AlphaBlendAdditive?: boolean;
}
interface Flags {
@@ -158,11 +156,7 @@ export type Component =
"ro.notShadowOnly": boolean;
"ro.sOclCull": boolean;
"ro.sOclIndex": number;
} & Record<`rb${number}.${"lodIndex" | "switchIndex"}`, number> &
Record<
`skinnedObject.batch${number}.targetsData`,
ArrayBuffer | undefined
>;
} & Record<`rb${number}.${"lodIndex" | "switchIndex"}`, number>;
}
| {
"comp.typename": "SlotComponent";
@@ -266,7 +260,7 @@ export type Component =
}
| {
"comp.typename": "MotionComponent";
"motion.filepath"?: string;
"motion.filepath": string;
"motion.playbackRate": number;
"simpleMotion.repeatsCount": number;
}
@@ -5,10 +5,5 @@ export type CamouflagesYaml = Record<
shortUserString?: string;
preset?: string;
customEntities?: Record<string, { item: string }>;
// nation -> tank
override?: Record<
string,
{ override?: Record<string, { preset?: string }> }
>;
}
>;
+1 -1
View File
@@ -15,7 +15,7 @@ export interface ConsumablesCommon {
script: {
"#text": string;
automatic?: boolean;
cooldown?: number;
cooldown: number;
duration?: number;
shotEffect?: string;
bonusValues?: { [key: string]: number };
+1 -2
View File
@@ -744,8 +744,7 @@
"none": "No deltas",
"percentage": "Percentage",
"absolute": "Absolute"
},
"sync_shells": "Sync shells"
}
},
"no_tanks": {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+9
View File
@@ -1,7 +1,16 @@
{
"name": "@blitzkit/scripts",
"private": true,
"scripts": {
"discover-ids": "bun src/discoverIds/index.ts",
"build-protos": "bun src/protos.ts",
"record-performance": "bun src/recordPerformance/index.ts",
"download-client": "bun src/downloadClient/index.ts",
"download-smart-dlc": "bun src/downloadSmartDLC/index.ts",
"vfs": "bun src/vfs/index.ts"
},
"dependencies": {
"@blitzkit/closed": "workspace:*",
"@blitzkit/core": "workspace:*",
"@blitzkit/i18n": "workspace:*",
"@gltf-transform/core": "^4.2.1",
-4
View File
@@ -1,4 +0,0 @@
export const WGC_CLIENT_GUID = "WOTB.WW.PRODUCTION";
export const WGC_CLIENT_URL = "https://wgus-eu.wargaming.net";
export const WGC_METADATA_PROTOCOL_VERSION = "7.10";
export const WGC_PATCHES_CHAIN_PROTOCOL_VERSION = "1.11";
+104 -24
View File
@@ -1,37 +1,117 @@
import { assertSecret } from "@blitzkit/core";
import { $ } from "bun";
import { mkdir, rm } from "node:fs/promises";
import { downloadSteamClient } from "./steam";
import { downloadWGCClient } from "./wgc";
import { downloadWGPKGClient } from "./wgpkg";
import {
DEPOT_DOWNLOADER_EXECUTABLE,
DEPOT_DOWNLOADER_MAX_DOWNLOADS,
DEPOT_DOWNLOADER_OUTPUT,
WGPKG_DIR,
} from "./constants";
import { QuickGitHubRelease } from "./types";
export const DEPOT_DOWNLOADER_RETRY_TIME = 30_000;
const DEPOT_DOWNLOADER_RETRY_TIME = 30_000;
const provider = import.meta.env.CLIENT_PROVIDER;
export const source = import.meta.env.CLIENT_SOURCE;
export const dir = assertSecret(import.meta.env.CLIENT_DIR);
const provider = assertSecret(import.meta.env.CLIENT_PROVIDER);
const source = assertSecret(import.meta.env.CLIENT_SOURCE);
const dir = assertSecret(import.meta.env.CLIENT_DIR);
await rm(dir, { recursive: true, force: true });
await mkdir(dir, { recursive: true });
switch (provider) {
// steam, identical to wgc
case "steam":
await downloadSteamClient();
break;
if (provider === "steam") {
const [id, platform] = source.split("/");
// from zip, read remotely by ZipVFS at build time; nothing to download
case "zip":
console.log("Zip client provider; skipping download in favor of ZipVFS");
break;
console.log("Downloading Depot Downloader...");
// effectively the same as wgc, but direct for preview
case "wgpkg":
await downloadWGPKGClient();
break;
const releases = await fetch(
"https://api.github.com/repos/SteamRE/DepotDownloader/releases/latest",
).then((response) => response.json() as Promise<QuickGitHubRelease>);
const asset = releases.assets.find((asset) =>
asset.name.includes("linux-x64"),
);
default:
console.log("Unknown client provider specified, using latest wgc client");
case "wgc":
await downloadWGCClient();
if (!asset) {
throw new Error("No linux-x64 asset found for Steam DepotDownloader");
}
await rm(DEPOT_DOWNLOADER_OUTPUT, { recursive: true, force: true });
await $`curl -L "${asset.browser_download_url}" -o "${DEPOT_DOWNLOADER_OUTPUT}.zip"`;
await $`unzip "${DEPOT_DOWNLOADER_OUTPUT}.zip" -d "${DEPOT_DOWNLOADER_OUTPUT}"`;
await $`chmod +x "${DEPOT_DOWNLOADER_EXECUTABLE}"`;
console.log("Downloading client...");
const username = assertSecret(import.meta.env.STEAM_USERNAME);
const password = assertSecret(import.meta.env.STEAM_PASSWORD);
while (true) {
const result = await $`${
DEPOT_DOWNLOADER_EXECUTABLE
} -os ${platform} -app ${id} -username ${
username
} -password ${password} -dir ${dir} -max-downloads ${
DEPOT_DOWNLOADER_MAX_DOWNLOADS
}`.nothrow();
if (result.exitCode === 0) {
console.log("Client downloaded successfully!");
break;
}
console.error(
`DepotDownloader failed (exit ${result.exitCode}). Retrying in ${DEPOT_DOWNLOADER_RETRY_TIME / 1000} seconds...`,
);
await new Promise((resolve) =>
setTimeout(resolve, DEPOT_DOWNLOADER_RETRY_TIME),
);
}
} else if (provider === "zip") {
const url = assertSecret(import.meta.env.CLIENT_SOURCE);
console.log("Downloading and extracting zipped client...");
await mkdir(dir, { recursive: true });
await $`curl -L "${url}" | bsdtar -xf- --strip-components=1 -C ${dir}`;
} else if (provider === "wgpkg") {
let index = 1;
const urls: string[] = [];
console.log("Discovering packages...");
while (true) {
const url = `${source}.${index.toString().padStart(3, "0")}`;
const response = await fetch(url);
if (response.status === 200) {
urls.push(url);
} else if (response.status === 404) {
break;
} else {
throw new Error(`Wargaming response error status: ${response.status}`);
}
index++;
}
console.log(`Downloading ${urls.length} packages...`);
await rm(WGPKG_DIR, { recursive: true, force: true });
await mkdir(WGPKG_DIR, { recursive: true });
const inputContent = urls
.map((url) => {
const name = url.split("/").pop()!;
return `${url}\n out=${name}\n dir=${WGPKG_DIR}`;
})
.join("\n");
await $`echo ${inputContent} | aria2c -j ${urls.length} -x 2 -s 2 -i -`;
const firstChunk = `${WGPKG_DIR}/${urls[0].split("/").pop()!}`;
await $`7z x "${firstChunk}" -o${dir} -y`;
await rm(WGPKG_DIR, { recursive: true });
} else {
throw new Error(`Unknown provider: ${provider}`);
}
@@ -1,57 +0,0 @@
import { assertSecret } from "@blitzkit/core";
import { $ } from "bun";
import { rm } from "node:fs/promises";
import { DEPOT_DOWNLOADER_RETRY_TIME, dir, source } from ".";
import {
DEPOT_DOWNLOADER_EXECUTABLE,
DEPOT_DOWNLOADER_MAX_DOWNLOADS,
DEPOT_DOWNLOADER_OUTPUT,
} from "./constants";
import { QuickGitHubRelease } from "./types";
export async function downloadSteamClient() {
const [id, platform] = source.split("/");
console.log("Downloading Depot Downloader...");
const releases = await fetch(
"https://api.github.com/repos/SteamRE/DepotDownloader/releases/latest",
).then((response) => response.json() as Promise<QuickGitHubRelease>);
const asset = releases.assets.find((asset) =>
asset.name.includes("linux-x64"),
);
if (!asset) {
throw new Error("No linux-x64 asset found for Steam DepotDownloader");
}
await rm(DEPOT_DOWNLOADER_OUTPUT, { recursive: true, force: true });
await $`curl -L "${asset.browser_download_url}" -o "${DEPOT_DOWNLOADER_OUTPUT}.zip"`;
await $`unzip "${DEPOT_DOWNLOADER_OUTPUT}.zip" -d "${DEPOT_DOWNLOADER_OUTPUT}"`;
await $`chmod +x "${DEPOT_DOWNLOADER_EXECUTABLE}"`;
console.log("Downloading client...");
const username = assertSecret(import.meta.env.STEAM_USERNAME);
const password = assertSecret(import.meta.env.STEAM_PASSWORD);
while (true) {
const result =
await $`${DEPOT_DOWNLOADER_EXECUTABLE} -os ${platform} -app ${id} -username ${username} -password ${password} -dir ${dir} -max-downloads ${DEPOT_DOWNLOADER_MAX_DOWNLOADS}`.nothrow();
if (result.exitCode === 0) {
console.log("Client downloaded successfully!");
break;
}
console.error(
`DepotDownloader failed (exit ${result.exitCode}). Retrying in ${
DEPOT_DOWNLOADER_RETRY_TIME / 1000
} seconds...`,
);
await new Promise((resolve) =>
setTimeout(resolve, DEPOT_DOWNLOADER_RETRY_TIME),
);
}
}
@@ -1,62 +0,0 @@
import locales from "@blitzkit/i18n/locales.json";
import { XMLParser } from "fast-xml-parser";
import {
WGC_CLIENT_GUID,
WGC_CLIENT_URL,
WGC_METADATA_PROTOCOL_VERSION,
WGC_PATCHES_CHAIN_PROTOCOL_VERSION,
} from "../../config/wgcClient";
import { downloadWgParts } from "../wgpkg";
import { ClientMetadata, PatchesChain } from "./types";
const parser = new XMLParser();
export async function downloadWGCClient() {
const metadataUrl = new URL("api/v1/metadata", WGC_CLIENT_URL);
metadataUrl.searchParams.set("guid", WGC_CLIENT_GUID);
metadataUrl.searchParams.set("chain_id", "unknown");
metadataUrl.searchParams.set(
"protocol_version",
WGC_METADATA_PROTOCOL_VERSION,
);
const metadata = await fetch(`${metadataUrl}`)
.then((response) => response.text())
.then((text) => parser.parse(text) as Promise<ClientMetadata>);
const patchesChainUrl = new URL("api/v1/patches_chain", WGC_CLIENT_URL);
patchesChainUrl.searchParams.set(
"protocol_version",
WGC_PATCHES_CHAIN_PROTOCOL_VERSION,
);
patchesChainUrl.searchParams.set("client_type", "full");
patchesChainUrl.searchParams.set("lang", locales.default);
patchesChainUrl.searchParams.set(
"metadata_version",
`${metadata.protocol.version}`,
);
patchesChainUrl.searchParams.set(
"metadata_protocol_version",
WGC_METADATA_PROTOCOL_VERSION,
);
patchesChainUrl.searchParams.set(
"chain_id",
metadata.protocol.predefined_section.chain_id,
);
patchesChainUrl.searchParams.set("game_installation", "true");
patchesChainUrl.searchParams.set("game_id", WGC_CLIENT_GUID);
patchesChainUrl.searchParams.set("client_current_version", "0");
const patchesChain = await fetch(`${patchesChainUrl}`)
.then((response) => response.text())
.then((text) => parser.parse(text) as Promise<PatchesChain>);
const urls = patchesChain.protocol.patches_chain.patch.files.file.map(
(file) =>
new URL(file.name, patchesChain.protocol.web_seeds.url).toString(),
);
await downloadWgParts(urls);
}
@@ -1,87 +0,0 @@
export interface ClientMetadata {
protocol: {
version: number;
predefined_section: PredefinedSection;
generated_section: GeneratedSection;
};
}
interface GeneratedSection {
launch_forbidden: string;
stop_supporting: string;
}
interface PredefinedSection {
app_id: string;
chain_id: string;
supported_languages: string;
default_language: string;
name: string;
fs_name: string;
shortcut_name: string;
executables: { executable: string };
keep_patches_interval: number;
client_types: { client_type: ClientType };
login_enabled: boolean;
realms_settings: RealmsSettings;
localization: Localization;
}
interface ClientType {
initial_app_type: string;
final_app_type: string;
min_supported_os: string;
client_parts: { client_part: string };
}
interface Localization {
item: { text: string[] };
}
interface RealmsSettings {
instances: { instance: Instance[] };
}
interface Instance {
game_id: string;
title_id: string;
platform_realm_id: string;
options: { option: string };
content_service_url: string;
}
export interface PatchesChain {
protocol: {
parts_info: { part: Part };
patches_chain: { patch: Patch };
delay_preload: string;
web_seeds: { url: string };
meta_need_update: string;
version_name: string;
};
}
interface Part {
name: string;
version: number;
status: string;
}
interface Patch {
files: { file: File[] };
torrent: Torrent;
part: string;
version_from: number;
version_to: string;
}
interface File {
name: string;
size: number;
unpacked_size: number;
}
interface Torrent {
hash: string;
urls: { url: string };
}
@@ -1,49 +0,0 @@
import { $ } from "bun";
import { mkdir, rm } from "node:fs/promises";
import { dir, source } from ".";
import { WGPKG_DIR } from "./constants";
export async function downloadWGPKGClient() {
let index = 1;
const urls: string[] = [];
console.log("Discovering packages...");
while (true) {
const url = `${source}.${index.toString().padStart(3, "0")}`;
const response = await fetch(url);
if (response.status === 200) {
urls.push(url);
} else if (response.status === 404) {
break;
} else {
throw new Error(`Wargaming response error status: ${response.status}`);
}
index++;
}
console.log(`Downloading ${urls.length} packages...`);
await downloadWgParts(urls);
}
export async function downloadWgParts(urls: string[]) {
await rm(WGPKG_DIR, { recursive: true, force: true });
await mkdir(WGPKG_DIR, { recursive: true });
const inputContent = urls
.map((url) => {
const name = url.split("/").pop()!;
return `${url}\n out=${name}\n dir=${WGPKG_DIR}`;
})
.join("\n");
await $`echo ${inputContent} | aria2c -j ${urls.length} -x 2 -s 2 -i -`;
const firstChunk = `${WGPKG_DIR}/${urls[0].split("/").pop()!}`;
await $`7z x "${firstChunk}" -o${dir} -y`;
await rm(WGPKG_DIR, { recursive: true });
}
@@ -1,13 +0,0 @@
import { assertSecret } from "@blitzkit/core";
import { $ } from "bun";
import { mkdir } from "node:fs/promises";
import { dir } from ".";
export async function downloadZipClient() {
const url = assertSecret(import.meta.env.CLIENT_SOURCE);
console.log("Downloading and extracting zipped client...");
await mkdir(dir, { recursive: true });
await $`curl -L "${url}" | bsdtar -xf- --strip-components=1 -C ${dir}`;
}
@@ -0,0 +1,90 @@
import { dvp } from "@blitzkit/closed";
import { assertSecret } from "@blitzkit/core";
import { mkdir, writeFile } from "fs/promises";
import { parse as parsePath } from "path";
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
import { RegionsPublish } from "../types/regionsPublish";
import { vfs } from "../vfs/vfs";
const CLIENT_DIR = assertSecret(import.meta.env.CLIENT_DIR);
const regionsPublish = await vfs.yaml<RegionsPublish>(
"Data/regions_publish.yaml",
);
const [smartDlcUrl] = regionsPublish.Common.smartDlcUrls;
const versionTextFile = await vfs.text(`Data/version.txt`);
const currentVersion = versionTextFile
.split(" ")[0]
.split(".")
.slice(0, 3)
.join(".");
console.log(`Installing patches for ${currentVersion}...`);
let patchIndex = 1;
while (true) {
const response = await fetch(
`${smartDlcUrl}/s${currentVersion}_${patchIndex}.yaml`,
);
console.log(patchIndex, response.status);
if (!response.ok) break;
console.log(`Applying patch ${patchIndex}...`);
const data = parseYaml(await response.text());
const dvpm = await fetch(`${smartDlcUrl}/${data.dx11}`).then((response) =>
response.arrayBuffer(),
);
const dvpd = await fetch(
`${smartDlcUrl}/${data.dx11.replace(".dvpm", ".dvpd")}`,
).then((response) => response.arrayBuffer());
const files = await dvp(dvpm, dvpd);
for (const { path, data } of files) {
console.log(`Patching "${path}"...`);
const { dir } = parsePath(path);
await mkdir(`${CLIENT_DIR}/Data/${dir}`, { recursive: true });
const buffer = Buffer.from(data);
await writeFile(`${CLIENT_DIR}/Data/${path}`, new Uint8Array(buffer));
}
console.log("patches done for patch");
if ("dynamicContentLocalizationsDir" in data) {
console.log(
`${smartDlcUrl}/${data.dynamicContentLocalizationsDir}/en.yaml`,
);
const localizationsResponse = await fetch(
`${smartDlcUrl}/${data.dynamicContentLocalizationsDir}/en.yaml`,
);
console.log("fetched");
const newStrings = parseYaml(await localizationsResponse.text());
console.log("got new strings");
const oldStrings =
await vfs.yaml<Record<string, string>>(`Data/Strings/en.yaml`);
console.log("got old strings");
const patchedStrings = { ...oldStrings, ...newStrings };
const patchedContent = stringifyYaml(patchedStrings);
console.log("stringified");
await mkdir(`${CLIENT_DIR}/Data/Strings`, { recursive: true });
console.log("mkdir");
await writeFile(
`${CLIENT_DIR}/Data/Strings/en.yaml`,
new Uint8Array(Buffer.from(patchedContent)),
);
console.log("file");
}
patchIndex++;
}
vfs.dispose();
process.exit(0);
+3 -2
View File
@@ -1,3 +1,4 @@
import { createClientVFS } from "@blitzkit/core/src/blitzkit/vfs/client";
import { assertSecret } from "@blitzkit/core";
import { LocalVFS } from "@blitzkit/core/src/blitzkit/vfs/local";
export const vfs = await createClientVFS();
export const vfs = new LocalVFS(assertSecret(import.meta.env.CLIENT_DIR));
+7
View File
@@ -1,6 +1,13 @@
{
"name": "@blitzkit/website",
"type": "module",
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"lint": "astro check",
"astro": "astro"
},
"dependencies": {
"@astrojs/check": "^0.9.4",
"@astrojs/node": "^9.4.4",
@@ -1,7 +1,9 @@
import { memo, useRef } from "react";
import { Group } from "three";
import { correctZYTuple } from "../../../core/blitz/correctZYTuple";
import { useArmorPlates } from "../../../hooks/useArmorPlates";
import { nameToArmorId } from "../../../core/blitzkit/nameToArmorId";
import { resolveArmor } from "../../../core/blitzkit/resolveThickness";
import { useArmor } from "../../../hooks/useArmor";
import { useTankModelDefinition } from "../../../hooks/useTankModelDefinition";
import { useTankTransform } from "../../../hooks/useTankTransform";
import { Duel } from "../../../stores/duel";
@@ -12,9 +14,12 @@ export const PrimaryArmorScene = memo(() => {
const wrapper = useRef<Group>(null);
const turretContainer = useRef<Group>(null!);
const gunContainer = useRef<Group>(null!);
const tank = Duel.use((state) => state.protagonist.tank);
const track = Duel.use((state) => state.protagonist.track);
const turret = Duel.use((state) => state.protagonist.turret);
const gun = Duel.use((state) => state.protagonist.gun);
const armorGltf = useArmor(tank.id).gltf;
const armorNodes = Object.values(armorGltf.nodes);
const tankModelDefinition = useTankModelDefinition();
const trackModelDefinition = tankModelDefinition.tracks[track.id];
const turretModelDefinition = tankModelDefinition.turrets[turret.id];
@@ -26,30 +31,107 @@ export const PrimaryArmorScene = memo(() => {
state.protagonist.consumables.includes(73),
);
const hiddenState = isDynamicArmorActive ? "state_01" : "state_00";
const plates = useArmorPlates(hiddenState);
useTankTransform(track, turret, turretContainer, gunContainer);
return (
<ModelTankWrapper ref={wrapper}>
<group position={hullOrigin}>
<PrimaryArmorSceneComponent plates={plates.hull.primary} />
{armorNodes.map((node) => {
const isHull = node.name.startsWith("hull_");
const isVisible = isHull;
const armorId = nameToArmorId(node.name);
const { spaced, thickness } = resolveArmor(
tankModelDefinition.armor!,
armorId,
);
if (
!isVisible ||
spaced ||
thickness === undefined ||
(isDynamicArmorActive && node.name.includes("state_01")) ||
(!isDynamicArmorActive && node.name.includes("state_00"))
)
return null;
return (
<PrimaryArmorSceneComponent
key={node.uuid}
thickness={thickness}
node={node}
/>
);
})}
</group>
<group ref={turretContainer}>
<group position={hullOrigin}>
{armorNodes.map((node) => {
const isCurrentTurret = node.name.startsWith(
`turret_${turretModelDefinition.model_id
.toString()
.padStart(2, "0")}`,
);
const isVisible = isCurrentTurret;
const armorId = nameToArmorId(node.name);
const { spaced, thickness } = resolveArmor(
turretModelDefinition.armor!,
armorId,
);
if (
!isVisible ||
spaced ||
thickness === undefined ||
(isDynamicArmorActive && node.name.includes("state_01")) ||
(!isDynamicArmorActive && node.name.includes("state_00"))
)
return null;
return (
<group position={hullOrigin} key={node.uuid}>
<group position={turretOrigin}>
<PrimaryArmorSceneComponent plates={plates.turret.primary} />
<PrimaryArmorSceneComponent
key={node.uuid}
thickness={thickness}
node={node}
/>
</group>
</group>
);
})}
<group ref={gunContainer}>
<group position={hullOrigin}>
{armorNodes.map((node) => {
const isCurrentGun = node.name.startsWith(
`gun_${gunModelDefinition.model_id.toString().padStart(2, "0")}`,
);
const isVisible = isCurrentGun;
const armorId = nameToArmorId(node.name);
const { spaced, thickness } = resolveArmor(
gunModelDefinition.armor!,
armorId,
);
if (
!isVisible ||
spaced ||
thickness === undefined ||
(isDynamicArmorActive && node.name.includes("state_01")) ||
(!isDynamicArmorActive && node.name.includes("state_00"))
)
return null;
return (
<group position={hullOrigin} key={node.uuid}>
<group position={turretOrigin.clone().add(gunOrigin)}>
<PrimaryArmorSceneComponent plates={plates.gun.primary} />
<PrimaryArmorSceneComponent
thickness={thickness}
node={node}
/>
</group>
</group>
);
})}
</group>
</group>
</ModelTankWrapper>
@@ -9,6 +9,7 @@ import { useEffect, useRef } from "react";
import {
MeshBasicMaterial,
NormalBlending,
Object3D,
ShaderMaterial,
SubtractiveBlending,
UniformsLib,
@@ -17,19 +18,18 @@ import {
} from "three";
import { degToRad } from "three/src/math/MathUtils.js";
import { hasEquipment } from "../../../../core/blitzkit/hasEquipment";
import type { ArmorPlate } from "../../../../hooks/useArmorPlates";
import { usePlateItems } from "../../../../hooks/usePlateItems";
import { jsxTree } from "../../../../core/blitzkit/jsxTree";
import { Duel } from "../../../../stores/duel";
import { Tankopedia } from "../../../../stores/tankopedia";
import { TankopediaPersistent } from "../../../../stores/tankopediaPersistent";
import { Batch } from "../../../Batch";
import { transitionEvent } from "../../../Tankopedia/HeroSection/components/TankSandbox/components/Lighting";
import fragmentShader from "./shaders/fragment.glsl?raw";
import vertexShader from "./shaders/vertex.glsl?raw";
import { spacedArmorRenderTarget } from "./target";
interface PrimaryArmorSceneComponentProps {
plates: ArmorPlate[];
thickness: number;
node: Object3D;
}
const excludeMaterial = new MeshBasicMaterial({
@@ -40,7 +40,8 @@ const date = new Date();
const isHalloween = date.getMonth() === 9 && date.getDate() === 31;
export function PrimaryArmorSceneComponent({
plates,
node,
thickness,
}: PrimaryArmorSceneComponentProps) {
const material = useRef(
new ShaderMaterial({
@@ -57,7 +58,7 @@ export function PrimaryArmorSceneComponent({
UniformsLib.fog,
{
thicknessCoefficient: { value: null },
thickness: { value: null },
penetration: { value: null },
caliber: { value: null },
ricochet: { value: null },
@@ -130,8 +131,8 @@ export function PrimaryArmorSceneComponent({
? Duel.state.protagonist.tank.equalizer?.armor
: undefined) ?? 1;
material.current.uniforms.thicknessCoefficient.value =
(hasEnhancedArmor ? 1.04 : 1) * equalizer;
material.current.uniforms.thickness.value =
thickness * (hasEnhancedArmor ? 1.04 : 1) * equalizer;
if (!noInvalidate) invalidate();
}
@@ -222,12 +223,32 @@ export function PrimaryArmorSceneComponent({
camera.projectionMatrixInverse;
});
const items = usePlateItems(plates);
return (
<>
<Batch items={items} material={excludeMaterial} renderOrder={0} />
<Batch items={items} material={material.current} renderOrder={1} />
{jsxTree(node, {
mesh(_, props, key) {
return (
<mesh
{...props}
key={`${key}-exclude`}
renderOrder={0}
material={excludeMaterial}
/>
);
},
})}
{jsxTree(node, {
mesh(_, props, key) {
return (
<mesh
{...props}
key={`${key}-include`}
renderOrder={1}
material={material.current}
/>
);
},
})}
</>
);
}
@@ -1,9 +1,10 @@
precision mediump float;
varying vec3 vNormal;
varying vec3 vViewPosition;
uniform float opacity;
uniform float thicknessCoefficient;
varying float vThickness;
uniform float thickness;
uniform float penetration;
uniform float caliber;
uniform float ricochet;
@@ -42,8 +43,6 @@ vec3 getPenetrationColor(bool isThreeCalibersRule, bool couldHaveRicochet) {
void main() {
#include <clipping_planes_fragment>
float thickness = vThickness * thicknessCoefficient;
vec2 screenCoord = gl_FragCoord.xy / resolution;
vec4 spacedArmorData = texture2D(spacedArmorBuffer, screenCoord);
bool isUnderSpacedArmor = spacedArmorData.a != 0.0;
@@ -1,30 +1,13 @@
precision mediump float;
varying vec3 vNormal;
varying vec3 vViewPosition;
varying float vThickness;
#include <batching_pars_vertex>
void main() {
vec4 localPosition = vec4(position, 1.0);
vec3 localNormal = normal;
#ifdef USE_BATCHING
#include <batching_vertex>
localPosition = batchingMatrix * localPosition;
localNormal = normalize(mat3(batchingMatrix) * localNormal);
#endif
#ifdef USE_BATCHING_COLOR
vThickness = getBatchingColor(getIndirectIndex(gl_DrawID)).r;
#else
vThickness = 0.0;
#endif
vec4 mvPosition = modelViewMatrix * localPosition;
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
vViewPosition = mvPosition.xyz;
vNormal = normalMatrix * localNormal;
vNormal = normalMatrix * normal;
gl_Position = projectionMatrix * mvPosition;
}
@@ -1,19 +1,15 @@
import { memo, useMemo, useRef } from "react";
import { Group, Plane, Scene, Vector3, type Object3D } from "three";
import { memo, useRef } from "react";
import { Group, Plane, Scene, Vector3 } from "three";
import { correctZYTuple } from "../../../core/blitz/correctZYTuple";
import { type ArmorPlate, useArmorPlates } from "../../../hooks/useArmorPlates";
import { useModelNodes } from "../../../hooks/useModelNodes";
import { nameToArmorId } from "../../../core/blitzkit/nameToArmorId";
import { resolveArmor } from "../../../core/blitzkit/resolveThickness";
import { useArmor } from "../../../hooks/useArmor";
import { useModel } from "../../../hooks/useModel";
import { useTankModelDefinition } from "../../../hooks/useTankModelDefinition";
import { useTankTransform } from "../../../hooks/useTankTransform";
import { Duel } from "../../../stores/duel";
import { ModelTankWrapper } from "./ModelTankWrapper";
import {
SpacedArmorSceneComponent,
type ExternalModuleVariant,
} from "./SpacedArmorSceneComponent";
import { SpacedArmorSubExternal } from "./SpacedArmorSceneComponent/components/SpacedArmorSubExternal";
import { SpacedArmorSubPrimary } from "./SpacedArmorSceneComponent/components/SpacedArmorSubPrimary";
import { SpacedArmorSubSpaced } from "./SpacedArmorSceneComponent/components/SpacedArmorSubSpaced";
import { SpacedArmorSceneComponent } from "./SpacedArmorSceneComponent";
export enum ArmorType {
Primary,
@@ -25,90 +21,18 @@ interface SpacedArmorSceneProps {
scene: Scene;
}
interface ArmorSectionProps {
primary: ArmorPlate[];
spaced: ArmorPlate[];
scene: Scene;
}
function ArmorSection({ primary, spaced, scene }: ArmorSectionProps) {
return (
<>
<SpacedArmorSubPrimary plates={primary} />
<SpacedArmorSubSpaced plates={spaced} />
{primary.map(({ node, thickness }) => (
<SpacedArmorSceneComponent
scene={scene}
key={node.uuid}
type={ArmorType.Primary}
thickness={thickness}
node={node}
/>
))}
{spaced.map(({ node, thickness }) => (
<SpacedArmorSceneComponent
scene={scene}
key={node.uuid}
type={ArmorType.Spaced}
thickness={thickness}
node={node}
/>
))}
</>
);
}
interface ExternalSectionProps {
nodes: Object3D[];
thickness: number;
variant: ExternalModuleVariant;
clip?: Plane;
scene: Scene;
}
function ExternalSection({
nodes,
thickness,
variant,
clip,
scene,
}: ExternalSectionProps) {
const plates = useMemo(
() => nodes.map((node) => ({ node, thickness })),
[nodes, thickness],
);
return (
<>
<SpacedArmorSubExternal
plates={plates}
thickness={thickness}
clip={clip}
/>
{nodes.map((node) => (
<SpacedArmorSceneComponent
scene={scene}
key={node.uuid}
type={ArmorType.External}
thickness={thickness}
variant={variant}
node={node}
clip={clip}
/>
))}
</>
);
}
export const SpacedArmorScene = memo<SpacedArmorSceneProps>(({ scene }) => {
const wrapper = useRef<Group>(null);
const turretContainer = useRef<Group>(null!);
const gunContainer = useRef<Group>(null!);
const tank = Duel.use((state) => state.protagonist.tank);
const track = Duel.use((state) => state.protagonist.track);
const turret = Duel.use((state) => state.protagonist.turret);
const gun = Duel.use((state) => state.protagonist.gun);
const { gltf: armorGltf } = useArmor(tank.id);
const { gltf: modelGltf } = useModel(tank.id);
const armorNodes = Object.values(armorGltf.nodes);
const modelNodes = Object.values(modelGltf.nodes);
const tankModelDefinition = useTankModelDefinition();
const trackModelDefinition = tankModelDefinition.tracks[track.id];
const turretModelDefinition = tankModelDefinition.turrets[turret.id];
@@ -123,63 +47,156 @@ export const SpacedArmorScene = memo<SpacedArmorSceneProps>(({ scene }) => {
const isDynamicArmorActive = Duel.use((state) =>
state.protagonist.consumables.includes(73),
);
const clip = useMemo(
() =>
maskOrigin === undefined
? undefined
: new Plane(new Vector3(0, 0, -1), -maskOrigin),
[maskOrigin],
);
const hiddenState = isDynamicArmorActive ? "state_00" : "state_01";
const plates = useArmorPlates(hiddenState);
const modelNodes = useModelNodes();
const hasMask = Boolean(gunModelDefinition.mask);
const trackNodes = useMemo(
() => [...modelNodes.wheels, ...modelNodes.tracks],
[modelNodes],
);
const gunNodes = useMemo(
() => (hasMask ? [...modelNodes.gun, ...modelNodes.mask] : modelNodes.gun),
[modelNodes, hasMask],
);
useTankTransform(track, turret, turretContainer, gunContainer);
return (
<ModelTankWrapper ref={wrapper}>
<group position={hullOrigin}>
<ArmorSection {...plates.hull} scene={scene} />
{armorNodes.map((node) => {
const isHull = node.name.startsWith("hull_");
const isVisible = isHull;
const armorId = nameToArmorId(node.name);
const { spaced, thickness } = resolveArmor(
tankModelDefinition.armor!,
armorId,
);
if (
!isVisible ||
thickness === undefined ||
(isDynamicArmorActive && node.name.includes("state_00")) ||
(!isDynamicArmorActive && node.name.includes("state_01"))
)
return null;
return (
<SpacedArmorSceneComponent
scene={scene}
key={`${node.uuid}-hull`}
type={spaced ? ArmorType.Spaced : ArmorType.Primary}
thickness={thickness}
node={node}
/>
);
})}
</group>
<ExternalSection
nodes={trackNodes}
{modelNodes.map((node) => {
const isWheel = node.name.startsWith("chassis_wheel_");
const isTrack = node.name.startsWith("chassis_track_");
const isVisible = isWheel || isTrack;
if (!isVisible) return null;
return (
<SpacedArmorSceneComponent
scene={scene}
key={`${node.uuid}-track`}
type={ArmorType.External}
thickness={trackModelDefinition.thickness}
variant="track"
scene={scene}
node={node}
/>
);
})}
<group ref={turretContainer}>
<group position={hullOrigin}>
{armorNodes.map((node) => {
const isCurrentTurret = node.name.startsWith(
`turret_${turretModelDefinition.model_id.toString().padStart(2, "0")}`,
);
const isVisible = isCurrentTurret;
const armorId = nameToArmorId(node.name);
const { spaced, thickness } = resolveArmor(
turretModelDefinition.armor!,
armorId,
);
if (
!isVisible ||
thickness === undefined ||
(isDynamicArmorActive && node.name.includes("state_00")) ||
(!isDynamicArmorActive && node.name.includes("state_01"))
)
return null;
return (
<group position={hullOrigin} key={node.uuid}>
<group position={turretOrigin}>
<ArmorSection {...plates.turret} scene={scene} />
<SpacedArmorSceneComponent
scene={scene}
key={`${node.uuid}-turret`}
type={spaced ? ArmorType.Spaced : ArmorType.Primary}
thickness={thickness}
node={node}
/>
</group>
</group>
);
})}
<group ref={gunContainer}>
<group position={hullOrigin}>
<group position={turretOrigin.clone().add(gunOrigin)}>
<ArmorSection {...plates.gun} scene={scene} />
</group>
</group>
{armorNodes.map((node) => {
const isCurrentGun = node.name.startsWith(
`gun_${gunModelDefinition.model_id.toString().padStart(2, "0")}`,
);
const isVisible = isCurrentGun;
const armorId = nameToArmorId(node.name);
const { spaced, thickness } = resolveArmor(
gunModelDefinition.armor!,
armorId,
);
<ExternalSection
nodes={gunNodes}
if (
!isVisible ||
thickness === undefined ||
(isDynamicArmorActive && node.name.includes("state_00")) ||
(!isDynamicArmorActive && node.name.includes("state_01"))
)
return null;
return (
<group position={hullOrigin} key={`${node.uuid}-gun-spaced}`}>
<group position={turretOrigin.clone().add(gunOrigin)}>
<SpacedArmorSceneComponent
scene={scene}
type={spaced ? ArmorType.Spaced : ArmorType.Primary}
thickness={thickness}
node={node}
/>
</group>
</group>
);
})}
{modelNodes.map((node) => {
const gunString = `gun_${gunModelDefinition.model_id
.toString()
.padStart(2, "0")}`;
const isCurrentGun = gunModelDefinition.mask
? node.name.startsWith(gunString)
: node.name === gunString;
const isVisible = isCurrentGun;
if (!isVisible) return null;
return (
<SpacedArmorSceneComponent
scene={scene}
key={`${node.uuid}-gun-external`}
type={ArmorType.External}
thickness={gunModelDefinition.thickness}
variant="gun"
clip={clip}
scene={scene}
node={node}
clip={
maskOrigin === undefined
? undefined
: new Plane(new Vector3(0, 0, -1), -maskOrigin)
}
/>
);
})}
</group>
</group>
</ModelTankWrapper>
@@ -1,44 +1,35 @@
import { resolvePenetrationCoefficient } from "@blitzkit/core";
import { useEffect, useMemo } from "react";
import { useEffect } from "react";
import {
AdditiveBlending,
MeshBasicMaterial,
Object3D,
Plane,
ShaderMaterial,
} from "three";
import type { ArmorUserData, ExternalModuleVariant } from "../..";
import { hasEquipment } from "../../../../../../core/blitzkit/hasEquipment";
import type { ArmorPlate } from "../../../../../../hooks/useArmorPlates";
import { usePlateItems } from "../../../../../../hooks/usePlateItems";
import { jsxTree } from "../../../../../../core/blitzkit/jsxTree";
import { Duel } from "../../../../../../stores/duel";
import { Tankopedia } from "../../../../../../stores/tankopedia";
import { Batch } from "../../../../../Batch";
import { ArmorType } from "../../../SpacedArmorScene";
import fragmentShader from "./shaders/fragment.glsl?raw";
import vertexShader from "./shaders/vertex.glsl?raw";
interface SpacedArmorSubExternalProps {
plates: ArmorPlate[];
node: Object3D;
thickness: number;
variant: ExternalModuleVariant;
clip?: Plane;
}
export function SpacedArmorSubExternal({
plates,
node,
thickness,
variant,
clip,
}: SpacedArmorSubExternalProps) {
const excludeMaterial = useMemo(
() =>
new MeshBasicMaterial({
colorWrite: false,
depthTest: true,
depthWrite: true,
...(clip ? { clippingPlanes: [clip] } : {}),
}),
[clip],
);
const material = useMemo(
() =>
new ShaderMaterial({
const material = new ShaderMaterial({
fragmentShader,
vertexShader,
@@ -52,9 +43,7 @@ export function SpacedArmorSubExternal({
thickness: { value: null },
penetration: { value: null },
},
}),
[clip],
);
});
useEffect(() => {
function handleShellChange() {
@@ -132,14 +121,62 @@ export function SpacedArmorSubExternal({
return () => {
unsubscribes.forEach((unsubscribe) => unsubscribe());
};
}, [material, thickness]);
const items = usePlateItems(plates);
});
return (
<>
<Batch items={items} material={excludeMaterial} renderOrder={3} />
<Batch items={items} material={material} renderOrder={4} />
{jsxTree(node, {
group(_, props, key) {
return (
<group {...props} key={`${key}-spaced-sub-external-exclude`} />
);
},
mesh(_, props, key) {
return (
<mesh
{...props}
onClick={() => {}}
key={`${key}-spaced-sub-external-exclude`}
renderOrder={3}
material={
new MeshBasicMaterial({
colorWrite: false,
depthTest: true,
depthWrite: true,
...(clip ? { clippingPlanes: [clip] } : {}),
})
}
userData={
{
type: ArmorType.External,
thickness,
variant,
} satisfies ArmorUserData
}
/>
);
},
})}
{jsxTree(node, {
group(_, props, key) {
return (
<group {...props} key={`${key}-spaced-sub-external-include`} />
);
},
mesh(_, props, key) {
return (
<mesh
{...props}
key={`${key}-spaced-sub-external-include`}
renderOrder={4}
material={material}
/>
);
},
})}
</>
);
}
@@ -1,3 +1,5 @@
precision mediump float;
uniform float thickness;
uniform float penetration;
@@ -1,8 +1,8 @@
#include <batching_pars_vertex>
precision mediump float;
#include <clipping_planes_pars_vertex>
void main() {
#include <batching_vertex>
#include <begin_vertex>
#include <project_vertex>
#include <clipping_planes_vertex>
@@ -1,19 +0,0 @@
import { MeshBasicMaterial } from "three";
import type { ArmorPlate } from "../../../../../../hooks/useArmorPlates";
import { usePlateItems } from "../../../../../../hooks/usePlateItems";
import { Batch } from "../../../../../Batch";
interface SpacedArmorSubPrimaryProps {
plates: ArmorPlate[];
}
const omitMaterial = new MeshBasicMaterial({
colorWrite: false,
depthWrite: true,
});
export function SpacedArmorSubPrimary({ plates }: SpacedArmorSubPrimaryProps) {
const items = usePlateItems(plates);
return <Batch items={items} material={omitMaterial} renderOrder={0} />;
}
@@ -1,18 +1,24 @@
import { isExplosive, resolvePenetrationCoefficient } from "@blitzkit/core";
import { useEffect, useMemo } from "react";
import { AdditiveBlending, MeshBasicMaterial, ShaderMaterial } from "three";
import { useEffect } from "react";
import {
AdditiveBlending,
MeshBasicMaterial,
ShaderMaterial,
type Object3D,
} from "three";
import { degToRad } from "three/src/math/MathUtils.js";
import type { ArmorUserData } from "../..";
import { hasEquipment } from "../../../../../../core/blitzkit/hasEquipment";
import type { ArmorPlate } from "../../../../../../hooks/useArmorPlates";
import { usePlateItems } from "../../../../../../hooks/usePlateItems";
import { jsxTree } from "../../../../../../core/blitzkit/jsxTree";
import { Duel } from "../../../../../../stores/duel";
import { Tankopedia } from "../../../../../../stores/tankopedia";
import { Batch } from "../../../../../Batch";
import { ArmorType } from "../../../SpacedArmorScene";
import fragmentShader from "./shaders/fragment.glsl?raw";
import vertexShader from "./shaders/vertex.glsl?raw";
interface SpacedArmorSubSpacedProps {
plates: ArmorPlate[];
node: Object3D;
thickness: number;
}
const depthWriteMaterial = new MeshBasicMaterial({
@@ -20,10 +26,11 @@ const depthWriteMaterial = new MeshBasicMaterial({
colorWrite: false,
});
export function SpacedArmorSubSpaced({ plates }: SpacedArmorSubSpacedProps) {
const material = useMemo(
() =>
new ShaderMaterial({
export function SpacedArmorSubSpaced({
node,
thickness,
}: SpacedArmorSubSpacedProps) {
const material = new ShaderMaterial({
fragmentShader,
vertexShader,
@@ -32,15 +39,13 @@ export function SpacedArmorSubSpaced({ plates }: SpacedArmorSubSpacedProps) {
blending: AdditiveBlending,
uniforms: {
thicknessCoefficient: { value: null },
thickness: { value: null },
penetration: { value: null },
caliber: { value: null },
ricochet: { value: null },
normalization: { value: null },
},
}),
[],
);
});
useEffect(() => {
function handleShellChange() {
@@ -69,8 +74,8 @@ export function SpacedArmorSubSpaced({ plates }: SpacedArmorSubSpacedProps) {
? Duel.state.protagonist.tank.equalizer?.armor
: undefined) ?? 1;
material.uniforms.thicknessCoefficient.value =
(hasEnhancedArmor ? 1.04 : 1) * equalizer;
material.uniforms.thickness.value =
thickness * (hasEnhancedArmor ? 1.04 : 1) * equalizer;
}
function handleAntagonistEquipmentChange() {
const equipment = Duel.state.antagonist.equipmentMatrix;
@@ -126,14 +131,50 @@ export function SpacedArmorSubSpaced({ plates }: SpacedArmorSubSpacedProps) {
return () => {
unsubscribes.forEach((unsubscribe) => unsubscribe());
};
}, [material]);
const items = usePlateItems(plates);
});
return (
<>
<Batch items={items} material={material} renderOrder={2} />
<Batch items={items} material={depthWriteMaterial} renderOrder={5} />
{jsxTree(node, {
group(_, props, key) {
return <group {...props} key={`${key}-spaced-sub-spaced-exclude`} />;
},
mesh(_, props, key) {
return (
<mesh
{...props}
key={`${key}-spaced-sub-spaced-exclude`}
renderOrder={2}
material={material}
onClick={() => {}}
userData={
{
type: ArmorType.Spaced,
thickness,
} satisfies ArmorUserData
}
/>
);
},
})}
{jsxTree(node, {
group(_, props, key) {
return <group {...props} key={`${key}-spaced-sub-spaced-include`} />;
},
mesh(_, props, key) {
return (
<mesh
{...props}
key={`${key}-spaced-sub-spaced-include`}
renderOrder={5}
material={depthWriteMaterial}
/>
);
},
})}
</>
);
}
@@ -1,15 +1,15 @@
precision mediump float;
varying vec3 vNormal;
varying vec3 vViewPosition;
uniform float thicknessCoefficient;
varying float vThickness;
uniform float thickness;
uniform float penetration;
uniform float caliber;
uniform float ricochet;
uniform float normalization;
void main() {
float thickness = vThickness * thicknessCoefficient;
float angle = acos(dot(vNormal, -vViewPosition) / length(vViewPosition));
bool threeCalibersRule = caliber > thickness * 3.0;
@@ -1,30 +1,13 @@
precision mediump float;
varying vec3 vNormal;
varying vec3 vViewPosition;
varying float vThickness;
#include <batching_pars_vertex>
void main() {
vec4 localPosition = vec4(position, 1.0);
vec3 localNormal = normal;
#ifdef USE_BATCHING
#include <batching_vertex>
localPosition = batchingMatrix * localPosition;
localNormal = normalize(mat3(batchingMatrix) * localNormal);
#endif
#ifdef USE_BATCHING_COLOR
vThickness = getBatchingColor(getIndirectIndex(gl_DrawID)).r;
#else
vThickness = 0.0;
#endif
vec4 vViewPosition4 = modelViewMatrix * localPosition;
vec4 vViewPosition4 = modelViewMatrix * vec4(position, 1.0);
vViewPosition = vViewPosition4.xyz;
vNormal = normalMatrix * localNormal;
vNormal = normalMatrix * normal;
gl_Position = projectionMatrix * vViewPosition4;
}
@@ -4,7 +4,7 @@ import {
resolvePenetrationCoefficient,
} from "@blitzkit/core";
import { useThree } from "@react-three/fiber";
import { useCallback, useMemo } from "react";
import { useCallback } from "react";
import {
type Intersection,
MeshBasicMaterial,
@@ -32,6 +32,8 @@ import {
Tankopedia,
} from "../../../../stores/tankopedia";
import { ArmorType } from "../SpacedArmorScene";
import { SpacedArmorSubExternal } from "./components/SpacedArmorSubExternal";
import { SpacedArmorSubSpaced } from "./components/SpacedArmorSubSpaced";
type SpacedArmorSceneComponentProps = {
node: Object3D;
@@ -91,14 +93,12 @@ function resolvePenetrationChance(shoot: (scale: number) => Shot | null) {
);
}
const proxyMaterial = new MeshBasicMaterial({ visible: false });
const omitMaterial = new MeshBasicMaterial({
colorWrite: false,
depthWrite: true,
});
/**
* Plates are drawn in batches by SpacedArmorSubPrimary, SpacedArmorSubSpaced
* and SpacedArmorSubExternal; this only renders invisible per plate proxies
* so raycasts still resolve each plate's userData. Raycasting ignores
* material visibility.
*
* Render orders allocations:
* - 0 : core omission
* - 1-2: spaced without depth buffer write but do test to allow additive blending
@@ -433,36 +433,36 @@ export function SpacedArmorSceneComponent({
[camera],
);
const clippedProxyMaterial = useMemo(
() =>
clip
? new MeshBasicMaterial({ visible: false, clippingPlanes: [clip] })
: proxyMaterial,
[clip],
);
const userData: ArmorUserData =
props.type === ArmorType.External
? { type: ArmorType.External, thickness, variant: props.variant }
: { type: props.type, thickness };
return jsxTree(node, {
mesh(_, meshProps, key) {
return (
<>
{props.type === ArmorType.Primary &&
jsxTree(node, {
mesh(_, props, key) {
return (
<mesh
{...meshProps}
key={`${key}-proxy`}
material={clippedProxyMaterial}
userData={userData}
{...props}
key={`${key}-spaced-component`}
renderOrder={0}
material={omitMaterial}
userData={
{
type: ArmorType.Primary,
thickness,
} satisfies ArmorUserData
}
onClick={(event) => {
// other layers only need to be in the intersections
if (props.type !== ArmorType.Primary) return;
event.stopPropagation();
const shot = shoot(event.point, event.intersections, true)!;
shot.penetrationChance = resolvePenetrationChance((scale) =>
shoot(event.point, event.intersections, true, undefined, scale),
shoot(
event.point,
event.intersections,
true,
undefined,
scale,
),
);
Tankopedia.mutate((draft) => {
@@ -472,5 +472,20 @@ export function SpacedArmorSceneComponent({
/>
);
},
});
})}
{props.type === ArmorType.Spaced && (
<SpacedArmorSubSpaced node={node} thickness={thickness} />
)}
{props.type === ArmorType.External && (
<SpacedArmorSubExternal
node={node}
thickness={thickness}
variant={props.variant}
clip={clip}
/>
)}
</>
);
}
@@ -24,7 +24,6 @@ import {
} from "../../../core/blitzkit/modelTransform";
import { defaultEqualizer } from "../../../core/blitzkit/tankToDuelMember";
import { discardClippingPlane } from "../../../core/three/discardClippingPlane";
import { sceneChangeEvent } from "../../../core/three/sceneChange";
import { useEquipment } from "../../../hooks/useEquipment";
import { Duel } from "../../../stores/duel";
import { Tankopedia } from "../../../stores/tankopedia";
@@ -155,13 +154,6 @@ export function StaticArmorSceneComponent({
[hasEnhancedArmor, equalize],
);
// these cast shadows
useEffect(() => {
sceneChangeEvent.dispatch();
return () => sceneChangeEvent.dispatch();
}, [node]);
useEffect(() => {
function handleHighlightArmor(selectedName?: string) {
if (selectedName === undefined) {
@@ -1,68 +0,0 @@
import { invalidate } from "@react-three/fiber";
import { useEffect, useMemo, type ComponentProps } from "react";
import { BatchedMesh, Color, type Matrix4, type Mesh } from "three";
import { sceneChangeEvent } from "../../core/three/sceneChange";
export interface BatchItem {
mesh: Mesh;
matrix: Matrix4;
// red channel of the instance color, read in shaders with getBatchingColor
thickness?: number;
}
type BatchProps = Omit<ComponentProps<"primitive">, "object"> & {
items: BatchItem[];
};
/**
* One draw call for all items. Only the geometry is memoized, on the identity
* of items; material, renderOrder, shadows, events and so on are plain props.
*/
export function Batch({ items, ...props }: BatchProps) {
const batch = useMemo(() => {
if (items.length === 0) return null;
let vertices = 0;
let indices = 0;
for (const { mesh } of items) {
vertices += mesh.geometry.attributes.position.count;
indices += mesh.geometry.index!.count;
}
const batch = new BatchedMesh(items.length, vertices, indices);
const color = new Color();
// otherwise the draw list is re-culled, re-sorted and re-uploaded every draw
batch.perObjectFrustumCulled = false;
batch.sortObjects = false;
for (const { mesh, matrix, thickness } of items) {
const instanceId = batch.addInstance(batch.addGeometry(mesh.geometry));
batch.setMatrixAt(instanceId, matrix);
if (thickness !== undefined) {
batch.setColorAt(instanceId, color.setRGB(thickness, 0, 0));
}
}
return batch;
}, [items]);
useEffect(() => {
if (!batch) return;
invalidate();
sceneChangeEvent.dispatch();
return () => {
batch.dispose();
sceneChangeEvent.dispatch();
};
}, [batch]);
if (!batch) return null;
return <primitive object={batch} {...props} />;
}
@@ -2,7 +2,7 @@ import { alias } from "@blitzkit/core";
import { Flex, Heading, IconButton, Table } from "@radix-ui/themes";
import type { TankCharacteristics } from "../../core/blitzkit/tankCharacteristics";
import { useLocale } from "../../hooks/useLocale";
import { CompareEphemeral, syncShellSlot } from "../../stores/compareEphemeral";
import { CompareEphemeral } from "../../stores/compareEphemeral";
import { CompareCellDirection } from "../CompareCell";
import { StickyColumnHeaderCell } from "../StickyColumnHeaderCell";
import { CompareRow } from "./CompareRow";
@@ -50,11 +50,7 @@ export function Body({ stats }: BodyProps) {
}}
onClick={() => {
CompareEphemeral.mutate((draft) => {
if (draft.syncShells) {
syncShellSlot(draft.members, shellIndex);
} else {
draft.members[index].shell = thisShell;
}
});
}}
>
@@ -1,17 +1,9 @@
import { PlusIcon, TrashIcon } from "@radix-ui/react-icons";
import {
Button,
Checkbox,
Dialog,
Flex,
SegmentedControl,
Text,
} from "@radix-ui/themes";
import { DIALOG_MAX_HEIGHT } from "../../constants/dialog";
import { Button, Dialog, Flex, SegmentedControl } from "@radix-ui/themes";
import { api } from "../../core/blitzkit/api";
import { tankToCompareMember } from "../../core/blitzkit/tankToCompareMember";
import { useLocale } from "../../hooks/useLocale";
import { CompareEphemeral, syncShellSlot } from "../../stores/compareEphemeral";
import { CompareEphemeral } from "../../stores/compareEphemeral";
import {
ComparePersistent,
type DeltaMode,
@@ -30,7 +22,6 @@ export function Controls({
onAddTankDialogOpenChange,
}: ControlsProps) {
const deltaMode = ComparePersistent.use((state) => state.deltaMode);
const syncShells = CompareEphemeral.use((state) => state.syncShells);
const { strings } = useLocale();
return (
@@ -45,11 +36,11 @@ export function Controls({
</Button>
</Dialog.Trigger>
<Dialog.Content maxHeight={DIALOG_MAX_HEIGHT}>
<Dialog.Content>
<Dialog.Title align="center">
{strings.website.tools.compare.actions.add.title}
</Dialog.Title>
<Dialog.Description align="center" mb="4">
<Dialog.Description align="center">
{strings.website.tools.compare.actions.add.description}
</Dialog.Description>
@@ -120,31 +111,6 @@ export function Controls({
{strings.website.tools.compare.actions.deltas.absolute}
</SegmentedControl.Item>
</SegmentedControl.Root>
<Flex
align="center"
gap="2"
style={{ cursor: "pointer" }}
onClick={() => {
CompareEphemeral.mutate((draft) => {
draft.syncShells = !draft.syncShells;
if (!draft.syncShells || draft.members.length === 0) return;
const [first] = draft.members;
syncShellSlot(
draft.members,
first.gun.shells.findIndex(({ id }) => id === first.shell.id),
);
});
}}
>
<Checkbox variant="classic" checked={syncShells} />
<Text size="2">
{strings.website.tools.compare.actions.sync_shells}
</Text>
</Flex>
</Flex>
);
}
@@ -1,7 +1,6 @@
import { ExternalLinkIcon, LoopIcon, TrashIcon } from "@radix-ui/react-icons";
import { Dialog, Flex, IconButton } from "@radix-ui/themes";
import { useState } from "react";
import { DIALOG_MAX_HEIGHT } from "../../constants/dialog";
import { api } from "../../core/blitzkit/api";
import { tankToCompareMember } from "../../core/blitzkit/tankToCompareMember";
import { useLocale } from "../../hooks/useLocale";
@@ -44,7 +43,7 @@ export function TankControl({ index, slug }: TankControlProps) {
</IconButton>
</Dialog.Trigger>
<Dialog.Content maxHeight={DIALOG_MAX_HEIGHT}>
<Dialog.Content>
<Dialog.Title align="center">
{strings.website.common.tank_search.swap_dialog_title}
</Dialog.Title>
@@ -3,8 +3,7 @@ import { useEffect, useState, type ReactNode } from "react";
import type { MaybeSkeletonComponentProps } from "../types/maybeSkeletonComponentProps";
import { InlineSkeleton } from "./InlineSkeleton";
const TIME = 1794675600 * 1000;
const HREF = "https://preview.blitzkit.app/tanks";
const TIME = 1792598400 * 1000;
export function Countdown({ skeleton }: MaybeSkeletonComponentProps) {
const [timeLeft, setTimeLeft] = useState<number>(TIME - Date.now());
@@ -32,7 +31,7 @@ export function Countdown({ skeleton }: MaybeSkeletonComponentProps) {
string = (
<>
in{" "}
revealed in{" "}
<Code highContrast>
{hours}h {minutes}m {seconds}s
</Code>
@@ -48,7 +47,7 @@ export function Countdown({ skeleton }: MaybeSkeletonComponentProps) {
color="gray"
highContrast
style={{ display: "content" }}
href={timeLeft <= 0 ? HREF : undefined}
href="https://preview.blitzkit.app/tanks"
underline="none"
>
<Flex
@@ -76,11 +75,11 @@ export function Countdown({ skeleton }: MaybeSkeletonComponentProps) {
<Flex direction="column">
<Heading size={{ initial: "4", sm: "6" }}>
All 9 Tier XIs {!skeleton && string}{" "}
Tier XIs {!skeleton && string}{" "}
{skeleton && <InlineSkeleton width="10rem" />}
</Heading>
<Text size={{ initial: "2", sm: "3" }}>
Catch all 9 tanks on BlitzKit Preview
Get ready to go to the Tankopedia!
</Text>
</Flex>
</Flex>
@@ -1,9 +1,9 @@
import { useModel } from "../hooks/useModel";
import { Guess, GuessState } from "../stores/guess";
import { SmartCanvas } from "./SmartCanvas";
import { TankModel } from "./TankModel";
import { Controls } from "./Tankopedia/HeroSection/components/TankSandbox/components/Control";
import { Lighting } from "./Tankopedia/HeroSection/components/TankSandbox/components/Lighting";
import { TankModel } from "./Tankopedia/HeroSection/components/TankSandbox/components/TankModel";
const BRIGHTNESS = 2 ** -5.5;
const CONTRAST = 2 ** 2;
@@ -9,7 +9,6 @@ import {
type ModelTransformEventData,
} from "../../../core/blitzkit/modelTransform";
import { controlsEnabledEvent } from "../../../core/controlsEnabled";
import { sceneChangeEvent } from "../../../core/three/sceneChange";
import { useModel } from "../../../hooks/useModel";
import { Mixer } from "../../../stores/mixer";
@@ -83,8 +82,6 @@ export function Model() {
window.removeEventListener("pointerup", handlePointerUp);
}, []);
useEffect(() => sceneChangeEvent.dispatch(), [hull, turret, gun]);
useEffect(() => {
function handleModelTransform(
event: QuicklimeEvent<ModelTransformEventData>,
@@ -1,232 +0,0 @@
import { invalidate, useThree, type ThreeEvent } from "@react-three/fiber";
import type { QuicklimeEvent } from "quicklime";
import { useEffect, useMemo, useRef } from "react";
import type { Object3D, Texture } from "three";
import { Group, Mesh, MeshStandardMaterial, Vector2 } from "three";
import { applyPitchYawLimits } from "../core/blitz/applyPitchYawLimits";
import { hasEquipment } from "../core/blitzkit/hasEquipment";
import { modelTransformEvent } from "../core/blitzkit/modelTransform";
import { controlsEnabledEvent } from "../core/controlsEnabled";
import { useBatchGroups } from "../hooks/useBatchGroups";
import { useModelNodes } from "../hooks/useModelNodes";
import { useSkin, type Skin } from "../hooks/useSkin";
import { useSkinAnimation } from "../hooks/useSkinAnimation";
import { useTankModelDefinition } from "../hooks/useTankModelDefinition";
import { useTankTransform } from "../hooks/useTankTransform";
import { Duel } from "../stores/duel";
import { Tankopedia } from "../stores/tankopedia";
import { TankopediaDisplay } from "../stores/tankopediaPersistent/constants";
import { ModelTankWrapper } from "./Armor/components/ModelTankWrapper";
import { Batch } from "./Batch";
import { transitionEvent } from "./Tankopedia/HeroSection/components/TankSandbox/components/Lighting";
interface SectionProps {
nodes: Object3D[];
skins: Skin[];
// dragging scrolls the track textures
scrollTracks?: boolean;
// dragging turns the turret
yaw?: boolean;
// dragging raises and lowers the gun
pitch?: boolean;
}
// emissive parts fade with the lights instead of glowing in the dark
function fadeEmissive(materials: MeshStandardMaterial[]) {
const emissiveMaterials = materials.filter(
(material) => material.emissiveMap,
);
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);
};
}
function Section({ nodes, skins, scrollTracks, yaw, pitch }: SectionProps) {
const turret = Duel.use((state) => state.protagonist.turret);
const gun = Duel.use((state) => state.protagonist.gun);
const tankModelDefinition = useTankModelDefinition();
const turretModelDefinition = tankModelDefinition.turrets[turret.id];
const gunModelDefinition = turretModelDefinition.guns[gun.id];
const { groups, parts, materials } = useBatchGroups(nodes, skins);
const position = useRef(new Vector2());
const delta = useRef(new Vector2());
const pitchAngle = useRef(0);
const yawAngle = useRef(0);
const textures = useRef(new Set<Texture | null>());
const canvas = useThree((state) => state.gl.domElement);
const rotates = yaw || pitch;
function handlePointerMove(event: PointerEvent) {
delta.current.set(event.clientX, event.clientY).sub(position.current);
position.current.set(event.clientX, event.clientY);
if (scrollTracks) {
const offset =
delta.current.x / window.innerWidth +
delta.current.y / window.innerHeight;
for (const texture of textures.current) {
if (!texture) continue;
texture.offset.y += offset;
}
invalidate();
}
if (rotates) {
const hasImprovedVerticalStabilizer = hasEquipment(
122,
Duel.state.protagonist.tank.equipment_preset,
Duel.state.protagonist.equipmentMatrix,
);
const hasDownImprovedVerticalStabilizer = hasEquipment(
124,
Duel.state.protagonist.tank.equipment_preset,
Duel.state.protagonist.equipmentMatrix,
);
const boundingRect = canvas.getBoundingClientRect();
const pitchDelta = pitch
? delta.current.y * (Math.PI / boundingRect.height)
: 0;
const yawDelta = yaw
? delta.current.x * (Math.PI / boundingRect.width)
: 0;
[pitchAngle.current, yawAngle.current] = applyPitchYawLimits(
pitchAngle.current - pitchDelta,
yawAngle.current + yawDelta,
gunModelDefinition.pitch!,
turretModelDefinition.yaw,
hasImprovedVerticalStabilizer,
hasDownImprovedVerticalStabilizer,
);
modelTransformEvent.dispatch({
pitch: pitchAngle.current,
yaw: yawAngle.current,
});
}
}
function handlePointerUp() {
controlsEnabledEvent.dispatch(true);
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handlePointerUp);
}
function handlePointerDown(event: ThreeEvent<PointerEvent>) {
// tracks only scroll while looking at the model, not the armor
if (scrollTracks && Tankopedia.state.display !== TankopediaDisplay.Model) {
return;
}
event.stopPropagation();
if (!scrollTracks && !rotates) return;
if (scrollTracks) {
const material = (event.object as Mesh).material as MeshStandardMaterial;
textures.current = new Set([
material.map,
material.aoMap,
material.normalMap,
material.roughnessMap,
material.metalnessMap,
]);
}
if (rotates) {
Tankopedia.mutate((draft) => {
draft.shot = undefined;
draft.highlightArmor = undefined;
});
pitchAngle.current = modelTransformEvent.last!.pitch;
yawAngle.current = modelTransformEvent.last!.yaw;
}
position.current.set(event.clientX, event.clientY);
controlsEnabledEvent.dispatch(false);
window.addEventListener("pointermove", handlePointerMove);
window.addEventListener("pointerup", handlePointerUp);
}
useEffect(() => fadeEmissive(materials), [materials]);
return (
<group onPointerDown={handlePointerDown}>
{groups.map(({ material, items }) => (
<Batch
key={material.uuid}
items={items}
material={material}
castShadow
receiveShadow
/>
))}
{parts.map(({ part, matrix }) => (
<group key={part.uuid} matrix={matrix} matrixAutoUpdate={false}>
<primitive object={part} />
</group>
))}
</group>
);
}
export function TankModel() {
const protagonist = Duel.use((draft) => draft.protagonist);
const track = Duel.use((state) => state.protagonist.track);
const turret = Duel.use((state) => state.protagonist.turret);
const hullContainer = useRef<Group>(null);
const turretContainer = useRef<Group>(null!);
const gunContainer = useRef<Group>(null!);
const nodes = useModelNodes();
const skinGltf = useSkin(protagonist.tank.id);
const attachmentGltf = useSkin(protagonist.tank.id, "attachment");
const skins = useMemo(
() => [skinGltf, attachmentGltf].filter((skin) => skin !== undefined),
[skinGltf, attachmentGltf],
);
const hullNodes = useMemo(() => [...nodes.hull, ...nodes.wheels], [nodes]);
const gunNodes = useMemo(() => [...nodes.gun, ...nodes.mask], [nodes]);
useTankTransform(track, turret, turretContainer, gunContainer);
useSkinAnimation(skins);
return (
<ModelTankWrapper ref={hullContainer}>
<Section nodes={nodes.tracks} skins={skins} scrollTracks />
<Section nodes={hullNodes} skins={skins} />
<group ref={turretContainer}>
<Section nodes={nodes.turret} skins={skins} yaw />
<group ref={gunContainer}>
<Section nodes={gunNodes} skins={skins} yaw pitch />
</group>
</group>
</ModelTankWrapper>
);
}
@@ -44,9 +44,7 @@ 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.loaders.model.requested,
);
const modelRequested = Tankopedia.use((state) => state.modelRequested);
const tankModel = modelDefinition.models[tank.id];
const turretModel = tankModel.turrets[turret.id];
@@ -1,5 +1,5 @@
import { createDefaultSkills } from "@blitzkit/core";
import { Box, Flex, Progress, Text } from "@radix-ui/themes";
import { Flex, Progress, Text } from "@radix-ui/themes";
import { clamp } from "lodash-es";
import { memo, useMemo, type ComponentProps, type ReactNode } from "react";
import { api } from "../../../../../../core/blitzkit/api";
@@ -16,7 +16,6 @@ import {
TankopediaRelativeAgainst,
} from "../../../../../../stores/tankopedia";
import { Info, type InfoProps } from "./Info";
import { StatScale } from "./StatScale";
type InfoWithDeltaProps = Omit<InfoProps, "name"> & {
stats: TankCharacteristics;
@@ -123,15 +122,6 @@ export const InfoWithDelta = memo<InfoWithDeltaProps>(
return othersValue !== undefined;
}) as TankCharacteristics[];
}, [relativeAgainst, shellIndex, equipmentMatrix, equalize]);
const values = useMemo(
() =>
others.map((tank) =>
typeof props.value === "function"
? props.value(tank)!
: (tank[props.value] as number),
),
[others],
);
const betterTanks = others.filter((tank) => {
const othersValue =
typeof props.value === "function"
@@ -171,25 +161,13 @@ export const InfoWithDelta = memo<InfoWithDeltaProps>(
{!noRanking && (
<Flex pl={indent ? "2" : "0"} align="center" gap="2">
<Box position="relative" flexGrow="1">
<StatScale
values={values}
value={uhWhatDoICallThisVariable}
lowerIsBetter={deltaType === "lowerIsBetter"}
/>
<Progress
variant="soft"
size="1"
value={goodness * 100}
color={color}
style={{
position: "relative",
height: "0.125rem",
opacity: 0.75,
}}
style={{ height: "0.125rem", opacity: 0.5 }}
/>
</Box>
<Text color="gray" size="1">
{clamp(betterTanks.length + 1, 1, others.length)} /{" "}
@@ -1,91 +0,0 @@
import { memo, useEffect, useMemo, useRef } from "react";
const RESOLUTION = 1000;
const HEIGHT = 8;
const DENSE_TICKS = 100;
interface StatScaleProps {
values: number[];
value: number;
lowerIsBetter?: boolean;
}
export const StatScale = memo<StatScaleProps>(
({ values, value, lowerIsBetter }) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const ticks = useMemo(() => {
const min = Math.min(value, ...values);
const max = Math.max(value, ...values);
const range = max - min;
const positions = new Set<number>();
for (const other of values) {
const raw = range === 0 ? 0.5 : (other - min) / range;
const x = Math.round((lowerIsBetter ? 1 - raw : raw) * RESOLUTION);
if (x === 0 || x === RESOLUTION) continue;
positions.add(x);
}
return Array.from(positions, (x) => ({ x }));
}, [values, value, lowerIsBetter]);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const draw = () => {
const { width } = canvas.getBoundingClientRect();
const pixelRatio = window.devicePixelRatio || 1;
const canvasWidth = Math.ceil(width * pixelRatio);
const canvasHeight = Math.ceil(HEIGHT * pixelRatio);
if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {
canvas.width = canvasWidth;
canvas.height = canvasHeight;
}
const context = canvas.getContext("2d");
if (!context) return;
context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
context.clearRect(0, 0, width, HEIGHT);
const styles = getComputedStyle(canvas);
for (const { x } of ticks) {
context.fillStyle = styles.getPropertyValue("--gray-a6").trim();
context.fillRect((x / RESOLUTION) * width, 0, 1, HEIGHT);
}
};
const observer = new ResizeObserver(draw);
observer.observe(canvas);
window.addEventListener("resize", draw);
draw();
return () => {
observer.disconnect();
window.removeEventListener("resize", draw);
};
}, [ticks]);
return (
<canvas
ref={canvasRef}
aria-hidden="true"
style={{
position: "absolute",
top: 0,
bottom: 0,
left: 0,
width: "100%",
height: HEIGHT,
margin: "auto 0",
opacity: Math.min(1, Math.sqrt(DENSE_TICKS / ticks.length)),
pointerEvents: "none",
}}
/>
);
},
);
@@ -13,10 +13,7 @@ const camouflageDefinitions = await api.camouflageDefinitions();
export function SkinSwitcher() {
const tank = Duel.use((state) => state.protagonist.tank);
const skin = Tankopedia.use((state) => state.loaders.skin.requested);
const attachment = Tankopedia.use(
(state) => state.loaders.attachment.requested,
);
const skin = Tankopedia.use((state) => state.requestedSkin);
const requestedDisplay = Tankopedia.use((state) => state.requestedDisplay);
const disturbed = Tankopedia.use((state) => state.disturbed);
const { unwrap } = useLocale();
@@ -27,18 +24,11 @@ export function SkinSwitcher() {
(camouflage) => unwrap(camouflage.name!),
);
// 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
@@ -52,24 +42,18 @@ export function SkinSwitcher() {
pointerEvents: "auto",
}}
>
{groups.map((group) => (
<Flex key={group[0].id} direction="column">
{group.map((camouflage, index) => {
{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 === group.length - 1 ? "var(--radius-full)" : "0";
const bottom = index === skins.length - 1 ? "var(--radius-full)" : "0";
return (
<Tooltip key={camouflage.id} content={name} side="left">
<SidebarIconButton
selected={
(camouflage.attachment ? attachment : skin) ===
camouflage.id
}
selected={skin === camouflage.id}
alt={name}
src={alias("api", `/icons/camouflages/${camouflage.id}.webp`)}
size={{ initial: "3", sm: "4" }}
@@ -84,13 +68,8 @@ export function SkinSwitcher() {
}}
onClick={() => {
Tankopedia.mutate((draft) => {
const loader =
draft.loaders[
camouflage.attachment ? "attachment" : "skin"
];
loader.requested =
loader.requested === camouflage.id
draft.requestedSkin =
draft.requestedSkin === camouflage.id
? undefined
: camouflage.id;
});
@@ -100,7 +79,5 @@ export function SkinSwitcher() {
);
})}
</Flex>
))}
</Flex>
);
}
@@ -27,7 +27,6 @@ import {
Tooltip,
} from "@radix-ui/themes";
import { Suspense, useState, type RefObject } from "react";
import { DIALOG_MAX_HEIGHT } from "../../../../../constants/dialog";
import { Pose, poseEvent } from "../../../../../core/blitzkit/pose";
import { useEquipment } from "../../../../../hooks/useEquipment";
import { useFullScreen } from "../../../../../hooks/useFullScreen";
@@ -83,9 +82,7 @@ export function Options({ thicknessRange, canvas, skeleton }: OptionsProps) {
const revealed = Tankopedia.use((state) => state.revealed);
const disturbed = Tankopedia.use((state) => state.disturbed);
const highGraphics = TankopediaPersistent.use((state) => state.highGraphics);
const modelRequested = Tankopedia.use(
(state) => state.loaders.model.requested,
);
const modelRequested = Tankopedia.use((state) => state.modelRequested);
const equalize = Duel.use((state) => state.equalize);
const equalizer = Duel.use((state) => state.antagonist.tank.equalizer);
@@ -475,7 +472,7 @@ export function Options({ thicknessRange, canvas, skeleton }: OptionsProps) {
</Button>
</Dialog.Trigger>
<Dialog.Content maxHeight={DIALOG_MAX_HEIGHT}>
<Dialog.Content>
<Dialog.Title align="center">
{strings.website.common.tank_search.select_dialog_title}
</Dialog.Title>
@@ -13,25 +13,18 @@ const camouflageDefinitions = await api.camouflageDefinitions();
export function Title({ skeleton }: MaybeSkeletonComponentProps) {
const { unwrap, strings } = useLocale();
const modelRequested = Tankopedia.use(
(state) => state.loaders.model.requested,
);
const modelRequested = Tankopedia.use((state) => state.modelRequested);
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.loaders.skin.requested);
const skin = Tankopedia.use((state) => state.requestedSkin);
const camouflage =
skin === undefined ? undefined : camouflageDefinitions.camouflages[skin];
const tankName = unwrap(protagonist.name!);
// 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 name = camouflage
? `${tankName} ${unwrap(camouflage.name!).replace("%(camo_num)", SKIN_NUMBER)}`
: tankName;
const fontSize = revealed
? disturbed
? "1.5rem"
@@ -109,7 +102,7 @@ export function Title({ skeleton }: MaybeSkeletonComponentProps) {
onPointerDown={(event) => event.stopPropagation()}
onClick={() => {
Tankopedia.mutate((draft) => {
draft.loaders.model.requested = true;
draft.modelRequested = true;
});
}}
>
@@ -1,4 +1,5 @@
import { blueDark, orangeDark } from "@radix-ui/colors";
import { ContactShadows } from "@react-three/drei";
import { invalidate, useFrame } from "@react-three/fiber";
import { clamp, times } from "lodash-es";
import { Quicklime } from "quicklime";
@@ -11,12 +12,9 @@ import {
} from "react";
import { HemisphereLight, SpotLight, type Group } from "three";
import { degToRad, lerp } from "three/src/math/MathUtils.js";
import { sceneChangeEvent } from "../../../../../../core/three/sceneChange";
import { useShadowsOnDemand } from "../../../../../../hooks/useShadowsOnDemand";
import { Tankopedia } from "../../../../../../stores/tankopedia";
import { TankopediaPersistent } from "../../../../../../stores/tankopediaPersistent";
import { TankopediaDisplay } from "../../../../../../stores/tankopediaPersistent/constants";
import { TankopediaContactShadows } from "../../../../../TankopediaContactShadows";
const ANGLE = degToRad(15);
const REVEAL_ANIMATION_TIME = 3;
@@ -50,9 +48,7 @@ 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.loaders.skin.requested !== state.loaders.skin.loaded ||
state.loaders.attachment.requested !== state.loaders.attachment.loaded,
(state) => state.loadedSkin !== state.skin,
);
const animationTime = useRef(REVEAL_ANIMATION_TIME);
@@ -64,14 +60,9 @@ export function Lighting({ hasPbr }: Props) {
const [animate, setAnimate] = useState(true);
useShadowsOnDemand();
useEffect(() => sceneChangeEvent.dispatch(), [highGraphics]);
useEffect(() => {
Tankopedia.mutate((draft) => {
draft.revealed = true;
draft.loaders.model.loaded = true;
});
}, []);
@@ -119,7 +110,17 @@ export function Lighting({ hasPbr }: Props) {
return (
<>
<TankopediaContactShadows />
<ContactShadows
width={1.5}
height={1.5}
near={0}
far={1}
opacity={2 ** 1}
blur={2 ** 1}
resolution={2 ** 9}
depthWrite={false}
renderOrder={1}
/>
{animate && (
<Animator
@@ -161,7 +162,6 @@ export function Lighting({ hasPbr }: Props) {
key={index}
position={position}
intensity={intensity}
userData={{ intensity }}
penumbra={1}
castShadow={highGraphics}
decay={1}
@@ -212,19 +212,12 @@ 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;
}
}
transitionEvent.dispatch(t);
// spotlight angles shape their shadows
sceneChangeEvent.dispatch();
}, []);
useFrame(({ invalidate }) => {
@@ -251,6 +244,12 @@ function Animator({
draft.display = requestedDisplay;
});
}
if (x >= 1 && Tankopedia.state.skin !== Tankopedia.state.loadedSkin) {
Tankopedia.mutate((draft) => {
draft.skin = draft.loadedSkin;
});
}
});
return null;
@@ -47,9 +47,11 @@ export function SceneProps() {
${shader.fragmentShader}
`.replace(
"#include <dithering_fragment>",
"#include <color_fragment>",
`
#include <color_fragment>
vec3 scaled = vWorldPosition / size;
float radius = length(scaled.xz);
@@ -57,13 +59,7 @@ export function SceneProps() {
discard;
}
float x = 1.0 - radius;
float y = x * x;
gl_FragColor.rgb *= y;
// after the falloff, so its gradient doesn't band
#include <dithering_fragment>
diffuseColor.a *= (1.0 - radius);
`,
);
},
@@ -82,7 +78,7 @@ export function SceneProps() {
<meshStandardMaterial
color={mauveDark.mauve6}
roughness={1}
dithering
transparent
onBeforeCompile={handleBeforeCompile}
/>
</mesh>
@@ -0,0 +1,273 @@
import { invalidate, useThree, type ThreeEvent } from "@react-three/fiber";
import { useRef } from "react";
import { Group, Mesh, MeshStandardMaterial, Vector2 } from "three";
import { applyPitchYawLimits } from "../../../../../../core/blitz/applyPitchYawLimits";
import { hasEquipment } from "../../../../../../core/blitzkit/hasEquipment";
import { modelTransformEvent } from "../../../../../../core/blitzkit/modelTransform";
import { skinTree } from "../../../../../../core/blitzkit/skinTree";
import { controlsEnabledEvent } from "../../../../../../core/controlsEnabled";
import { useModel } from "../../../../../../hooks/useModel";
import { useSkin } from "../../../../../../hooks/useSkin";
import { useTankModelDefinition } from "../../../../../../hooks/useTankModelDefinition";
import { useTankTransform } from "../../../../../../hooks/useTankTransform";
import { Duel } from "../../../../../../stores/duel";
import { Tankopedia } from "../../../../../../stores/tankopedia";
import { TankopediaDisplay } from "../../../../../../stores/tankopediaPersistent/constants";
import { ModelTankWrapper } from "../../../../../Armor/components/ModelTankWrapper";
export function TankModel() {
const protagonist = Duel.use((draft) => draft.protagonist);
const track = Duel.use((state) => state.protagonist.track);
const turret = Duel.use((state) => state.protagonist.turret);
const canvas = useThree((state) => state.gl.domElement);
const hullContainer = useRef<Group>(null);
const turretContainer = useRef<Group>(null!);
const gunContainer = useRef<Group>(null!);
const tankModelDefinition = useTankModelDefinition();
const turretModelDefinition =
tankModelDefinition.turrets[protagonist.turret.id];
const gunModelDefinition = turretModelDefinition.guns[protagonist.gun.id];
const { gltf } = useModel(protagonist.tank.id);
const nodes = Object.values(gltf.nodes);
const skinGltf = useSkin(protagonist.tank.id);
useTankTransform(track, turret, turretContainer, gunContainer);
return (
<ModelTankWrapper ref={hullContainer}>
{nodes.map((node) => {
const isHull = node.name === "hull";
const isWheel = node.name.startsWith("chassis_wheel_");
const isTrack = node.name.startsWith("chassis_track_");
const isVisible = isHull || isWheel || isTrack;
const position = new Vector2();
const delta = new Vector2();
if (!isVisible) return null;
function translateTexture(offset: number) {
const mesh = node.children[0] as Mesh;
const material = mesh?.material as MeshStandardMaterial;
if (!material) return;
invalidate();
const textures = new Set([
material.map,
material.aoMap,
material.normalMap,
material.roughnessMap,
material.metalnessMap,
]);
for (const texture of textures) {
if (texture) texture.offset.y += offset;
}
}
function onPointerDown(event: ThreeEvent<PointerEvent>) {
if (isTrack && Tankopedia.state.display === TankopediaDisplay.Model) {
position.set(event.clientX, event.clientY);
event.stopPropagation();
controlsEnabledEvent.dispatch(false);
window.addEventListener("pointermove", handlePointerMove);
window.addEventListener("pointerup", handlePointerUp);
} else {
event.stopPropagation();
}
}
function handlePointerMove(event: PointerEvent) {
delta.set(event.clientX, event.clientY).sub(position);
position.set(event.clientX, event.clientY);
const deltaX = delta.x / window.innerWidth;
const deltaY = delta.y / window.innerHeight;
translateTexture(deltaX + deltaY);
}
function handlePointerUp() {
controlsEnabledEvent.dispatch(true);
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handlePointerUp);
}
return skinTree(node, skinGltf, {
mesh(_, props, key) {
return (
<mesh
{...props}
key={key}
onPointerDown={onPointerDown}
castShadow
receiveShadow
/>
);
},
});
})}
<group ref={turretContainer}>
{nodes.map((node) => {
const isTurret = node.name.startsWith("turret_");
const isCurrentTurret =
node.name ===
`turret_${turretModelDefinition.model_id
.toString()
.padStart(2, "0")}`;
const isVisible = isCurrentTurret;
const position = new Vector2();
const delta = new Vector2();
if (!isVisible) return null;
function onPointerDown(event: ThreeEvent<PointerEvent>) {
event.stopPropagation();
if (!isTurret) return;
position.set(event.clientX, event.clientY);
controlsEnabledEvent.dispatch(false);
Tankopedia.mutate((draft) => {
draft.shot = undefined;
draft.highlightArmor = undefined;
});
window.addEventListener("pointermove", handlePointerMove);
window.addEventListener("pointerup", handlePointerUp);
}
function handlePointerMove(event: PointerEvent) {
const hasImprovedVerticalStabilizer = hasEquipment(
122,
Duel.state.protagonist.tank.equipment_preset,
Duel.state.protagonist.equipmentMatrix,
);
const hasDownImprovedVerticalStabilizer = hasEquipment(
124,
Duel.state.protagonist.tank.equipment_preset,
Duel.state.protagonist.equipmentMatrix,
);
const boundingRect = canvas.getBoundingClientRect();
delta.set(event.clientX, event.clientY).sub(position);
position.set(event.clientX, event.clientY);
const [pitch, yaw] = applyPitchYawLimits(
modelTransformEvent.last!.pitch,
modelTransformEvent.last!.yaw +
delta.x * (Math.PI / boundingRect.width),
gunModelDefinition.pitch!,
turretModelDefinition.yaw,
hasImprovedVerticalStabilizer,
hasDownImprovedVerticalStabilizer,
);
modelTransformEvent.dispatch({ pitch, yaw });
}
function handlePointerUp() {
controlsEnabledEvent.dispatch(true);
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handlePointerUp);
}
return skinTree(node, skinGltf, {
mesh(_, props, key) {
return (
<mesh
{...props}
key={key}
onPointerDown={onPointerDown}
castShadow
receiveShadow
/>
);
},
});
})}
<group ref={gunContainer}>
{nodes.map((node) => {
const isCurrentMantlet =
node.name ===
`gun_${gunModelDefinition.model_id
.toString()
.padStart(2, "0")}_mask`;
const isCurrentGun =
node.name ===
`gun_${gunModelDefinition.model_id.toString().padStart(2, "0")}`;
const isVisible = isCurrentGun || isCurrentMantlet;
const position = new Vector2();
const delta = new Vector2();
if (!isVisible) return null;
let pitch = 0;
let yaw = 0;
function onPointerDown(event: ThreeEvent<PointerEvent>) {
event.stopPropagation();
controlsEnabledEvent.dispatch(false);
Tankopedia.mutate((draft) => {
draft.shot = undefined;
draft.highlightArmor = undefined;
});
position.set(event.clientX, event.clientY);
pitch = modelTransformEvent.last!.pitch;
yaw = modelTransformEvent.last!.yaw;
window.addEventListener("pointermove", handlePointerMove);
window.addEventListener("pointerup", handlePointerUp);
}
function handlePointerMove(event: PointerEvent) {
const hasImprovedVerticalStabilizer = hasEquipment(
122,
Duel.state.protagonist.tank.equipment_preset,
Duel.state.protagonist.equipmentMatrix,
);
const hasDownImprovedVerticalStabilizer = hasEquipment(
124,
Duel.state.protagonist.tank.equipment_preset,
Duel.state.protagonist.equipmentMatrix,
);
const boundingRect = canvas.getBoundingClientRect();
delta.set(event.clientX, event.clientY).sub(position);
position.set(event.clientX, event.clientY);
[pitch, yaw] = applyPitchYawLimits(
pitch - delta.y * (Math.PI / boundingRect.height),
yaw + delta.x * (Math.PI / boundingRect.width),
gunModelDefinition.pitch!,
turretModelDefinition.yaw,
hasImprovedVerticalStabilizer,
hasDownImprovedVerticalStabilizer,
);
modelTransformEvent.dispatch({ pitch, yaw });
}
function handlePointerUp() {
controlsEnabledEvent.dispatch(true);
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handlePointerUp);
}
return skinTree(node, skinGltf, {
mesh(_, props, key) {
return (
<mesh
{...props}
key={key}
onPointerDown={onPointerDown}
castShadow
receiveShadow
/>
);
},
});
})}
</group>
</group>
</ModelTankWrapper>
);
}
@@ -0,0 +1,153 @@
import { useRef } from "react";
import { Group, ShaderMaterial, UniformsLib, UniformsUtils } from "three";
import { correctZYTuple } from "../../../../../../../core/blitz/correctZYTuple";
import { jsxTree } from "../../../../../../../core/blitzkit/jsxTree";
import { useArmor } from "../../../../../../../hooks/useArmor";
import { useModel } from "../../../../../../../hooks/useModel";
import { useTankModelDefinition } from "../../../../../../../hooks/useTankModelDefinition";
import { useTankTransform } from "../../../../../../../hooks/useTankTransform";
import { Duel } from "../../../../../../../stores/duel";
import { ModelTankWrapper } from "../../../../../../Armor/components/ModelTankWrapper";
import fragmentShader from "./shaders/fragment.glsl?raw";
import vertexShader from "./shaders/vertex.glsl?raw";
const skeletonMaterial = new ShaderMaterial({
vertexShader,
fragmentShader,
wireframe: true,
fog: true,
transparent: true,
uniforms: UniformsUtils.merge([UniformsLib.common, UniformsLib.fog]),
depthWrite: false,
});
export function TransitionSkeleton() {
const tank = Duel.use((state) => state.protagonist.tank);
const gun = Duel.use((state) => state.protagonist.gun);
const track = Duel.use((state) => state.protagonist.track);
const turret = Duel.use((state) => state.protagonist.turret);
const turretContainer = useRef<Group>(null!);
const gunContainer = useRef<Group>(null!);
const { gltf: armorGltf } = useArmor(tank.id);
const { gltf: modelGltf } = useModel(tank.id);
const modelNodes = Object.values(modelGltf.nodes);
const armorNodes = Object.values(armorGltf.nodes);
const tankModelDefinition = useTankModelDefinition();
const turretModelDefinition = tankModelDefinition.turrets[turret.id];
const gunModelDefinition = turretModelDefinition.guns[gun.id];
const trackModelDefinition = tankModelDefinition.tracks[track.id];
const wrapper = useRef<Group>(null);
const hullOrigin = correctZYTuple(trackModelDefinition.origin!);
const turretOrigin = correctZYTuple(tankModelDefinition.turret_origin!);
const gunOrigin = correctZYTuple(turretModelDefinition.gun_origin!);
useTankTransform(track, turret, turretContainer, gunContainer);
return (
<ModelTankWrapper ref={wrapper}>
<group position={hullOrigin}>
{armorNodes.map((node) => {
const isHull = node.name.startsWith("hull_");
const isVisible = isHull;
if (!isVisible) return null;
return jsxTree(node, {
mesh(_, props, key) {
return <mesh {...props} key={key} material={skeletonMaterial} />;
},
});
})}
</group>
{modelNodes.map((node) => {
const isWheel = node.name.startsWith("chassis_wheel_");
const isTrack = node.name.startsWith("chassis_track_");
const isVisible = isWheel || isTrack;
if (!isVisible) return null;
return jsxTree(node, {
mesh(_, props, key) {
return <mesh {...props} key={key} material={skeletonMaterial} />;
},
});
})}
<group ref={turretContainer}>
{armorNodes.map((node) => {
const isCurrentTurret = node.name.startsWith(
`turret_${turretModelDefinition.model_id.toString().padStart(2, "0")}`,
);
const isVisible = isCurrentTurret;
if (!isVisible) {
return null;
}
return (
<group key={node.uuid} position={hullOrigin}>
<group position={turretOrigin}>
{jsxTree(node, {
mesh(_, props, key) {
return (
<mesh {...props} key={key} material={skeletonMaterial} />
);
},
})}
</group>
</group>
);
})}
<group ref={gunContainer}>
{armorNodes.map((node) => {
const isCurrentGun = node.name.startsWith(
`gun_${gunModelDefinition.model_id.toString().padStart(2, "0")}`,
);
const isVisible = isCurrentGun;
if (!isVisible) return null;
return (
<group key={node.uuid} position={hullOrigin}>
<group position={turretOrigin.clone().add(gunOrigin)}>
{jsxTree(node, {
mesh(_, props, key) {
return (
<mesh
{...props}
key={key}
material={skeletonMaterial}
/>
);
},
})}
</group>
</group>
);
})}
{modelNodes.map((node) => {
const gunString = `gun_${gunModelDefinition.model_id
.toString()
.padStart(2, "0")}`;
const isCurrentGun = gunModelDefinition.mask
? node.name.startsWith(gunString)
: node.name === gunString;
const isVisible = isCurrentGun;
if (!isVisible) return null;
return jsxTree(node, {
mesh(_, props, key) {
return (
<mesh {...props} key={key} material={skeletonMaterial} />
);
},
});
})}
</group>
</group>
</ModelTankWrapper>
);
}
@@ -0,0 +1,11 @@
precision mediump float;
#define USE_FOG
#include <fog_pars_fragment>
void main() {
float fogFactor = smoothstep(fogNear, fogFar, vFogDepth);
gl_FragColor = vec4(0.5, 0.5, 0.5, fogFactor);
gl_FragColor.rgb = mix(fogColor, gl_FragColor.rgb, fogFactor);
}
@@ -0,0 +1,19 @@
precision mediump float;
#define USE_FOG
#include <fog_pars_vertex>
varying vec3 vNormal;
varying vec3 vViewPosition;
void main() {
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
vViewPosition = mvPosition.xyz;
vNormal = normalMatrix * normal;
gl_Position = projectionMatrix * mvPosition;
#include <fog_vertex>
}
@@ -23,12 +23,12 @@ import {
type ThicknessRange,
} from "../../../../Armor/components/StaticArmor";
import { SmartCanvas } from "../../../../SmartCanvas";
import { TankModel } from "../../../../TankModel";
import { AutoClear } from "./components/AutoClear";
import { Controls } from "./components/Control";
import { InitialAligner } from "./components/InitialAligner";
import { Lighting } from "./components/Lighting";
import { SceneProps } from "./components/SceneProps";
import { TankModel } from "./components/TankModel";
interface TankSandboxProps {
thicknessRange: ThicknessRange;
@@ -20,9 +20,7 @@ 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.loaders.model.requested,
);
const modelRequested = Tankopedia.use((state) => state.modelRequested);
const thicknessRange = useMemo(() => {
const entries = Object.values(tankDefinitions.tanks);
const filtered = entries.filter(
@@ -1,27 +0,0 @@
import { ContactShadows } from "@react-three/drei";
import { Tankopedia } from "../stores/tankopedia";
import { TankopediaDisplay } from "../stores/tankopediaPersistent/constants";
/**
* drei's ContactShadows, but only redrawn when the scene changes instead of
* every frame. drei resets its frame count on every render, so re-rendering
* with frames={1} draws it once more.
*/
export function TankopediaContactShadows() {
const display = Tankopedia.use((state) => state.display);
if (display === TankopediaDisplay.StaticArmor) return null;
return (
<ContactShadows
frames={1}
width={1.5}
height={1.5}
near={0}
far={1}
opacity={2 ** 1}
blur={2 ** 1}
resolution={2 ** 6}
/>
);
}
-3
View File
@@ -1,3 +0,0 @@
import { NAVBAR_HEIGHT } from "./navbar";
export const DIALOG_MAX_HEIGHT = `calc(100svh - 2 * (${NAVBAR_HEIGHT}px + var(--space-4) + var(--space-2)))`;
@@ -1,6 +1,4 @@
export function isHalloween() {
return false;
const data = new Date();
return data.getMonth() === 9 && data.getDate() === 31;
}
+4 -19
View File
@@ -1,21 +1,5 @@
import type { ComponentProps, ReactNode } from "react";
import {
AdditiveBlending,
Mesh,
MeshStandardMaterial,
Object3D,
type Material,
} from "three";
export function prepareMaterial(material: Material | Material[]) {
if (!(material instanceof MeshStandardMaterial)) return;
material.depthWrite = true;
if (material.userData.blending === "additive") {
material.blending = AdditiveBlending;
}
}
import { Mesh, MeshStandardMaterial, Object3D } from "three";
export function jsxTree(
node: Object3D,
@@ -30,7 +14,6 @@ export function jsxTree(
props: ComponentProps<"group">,
key: string,
) => ReactNode;
primitive?: (object3d: Object3D, key: string) => ReactNode;
},
): ReactNode {
if (node instanceof Mesh) {
@@ -42,7 +25,9 @@ export function jsxTree(
scale: node.scale,
};
prepareMaterial(props.material);
if (props.material instanceof MeshStandardMaterial) {
props.material.depthWrite = true;
}
return mergers?.mesh ? (
mergers.mesh(node, props, node.uuid)
@@ -1,51 +0,0 @@
import type {
Accessor,
Buffer,
Document,
TypedArray,
} from "@gltf-transform/core";
/**
* The website batches primitives into BatchedMeshes, which need every
* primitive in them to have the same attributes. Batches cross materials (the
* armor view batches wheels with tracks), so a primitive missing an attribute
* any other in the document has (say TEXCOORD_1) gets it zero-filled, which is
* what the shader read for the missing attribute anyway.
*/
export function polyfillAttributes(document: Document, buffer: Buffer) {
const primitives = document
.getRoot()
.listMeshes()
.flatMap((mesh) => mesh.listPrimitives());
const references = new Map<string, Accessor>();
for (const primitive of primitives) {
for (const name of primitive.listSemantics()) {
if (!references.has(name)) {
references.set(name, primitive.getAttribute(name)!);
}
}
}
for (const primitive of primitives) {
const count = primitive.getAttribute("POSITION")!.getCount();
for (const [name, reference] of references) {
if (primitive.getAttribute(name) !== null) continue;
const Array = reference.getArray()!.constructor as new (
length: number,
) => TypedArray;
primitive.setAttribute(
name,
document
.createAccessor(name)
.setType(reference.getType())
.setNormalized(reference.getNormalized())
.setArray(new Array(count * reference.getElementSize()))
.setBuffer(buffer),
);
}
}
}
@@ -1,64 +0,0 @@
import { ReadStream } from "@blitzkit/core";
import { times } from "lodash-es";
const HEADER_SIZE = 16;
export enum MotionChannel {
Translation,
Rotation,
Scale,
}
export interface MotionKeys {
times: number[];
values: number[];
}
export interface Motion {
duration: number;
tracks: Map<string, Map<MotionChannel, MotionKeys>>;
}
export class MotionReadStream extends ReadStream {
motion(): Motion {
this.seek(HEADER_SIZE);
const duration = this.float32();
const tracks: Motion["tracks"] = new Map();
times(this.uint32(), () => {
const uid = this.paddedString();
const channels = new Map<MotionChannel, MotionKeys>();
this.paddedString();
this.seek(4);
times(this.uint32(), () => {
const type = this.uint32() & 0xff;
this.seek(4);
const dimension = this.uint32() & 0xff;
const keys: MotionKeys = { times: [], values: [] };
times(this.uint32(), () => {
keys.times.push(this.float32());
times(dimension, () => keys.values.push(this.float32()));
});
channels.set(type, keys);
});
tracks.set(uid, channels);
});
return { duration, tracks };
}
paddedString() {
const end = new Uint8Array(this.buffer).indexOf(0, this.index);
const value = this.utf8(end - this.index);
this.index = (end + 4) & ~3;
return value;
}
}
@@ -1,287 +0,0 @@
import { VertexAttribute, type Component } from "@blitzkit/core";
import type { AbstractVFS } from "@blitzkit/core/src/blitzkit/vfs/abstract";
import {
MathUtils,
type Buffer,
type Document,
type mat4,
type Node,
type Primitive,
type Skin,
type TypedArray,
type vec3,
type vec4,
} from "@gltf-transform/core";
import { isEqual, times } from "lodash-es";
import { dirname, normalize } from "path/posix";
import { Matrix4 } from "three";
import { MotionChannel, MotionReadStream, type Motion } from "./motion";
type SkeletonComponent = Extract<
Component,
{ "comp.typename": "SkeletonComponent" }
>;
type MotionComponent = Extract<
Component,
{ "comp.typename": "MotionComponent" }
>;
type AccessorType = "SCALAR" | "VEC3" | "VEC4" | "MAT4";
const JOINT_ROOT = 0xffffff;
const MOTION_PATHS = {
[MotionChannel.Translation]: "translation",
[MotionChannel.Rotation]: "rotation",
[MotionChannel.Scale]: "scale",
} as const;
function createAccessor(
document: Document,
buffer: Buffer,
type: AccessorType,
array: TypedArray,
) {
return document
.createAccessor()
.setType(type)
.setArray(array)
.setBuffer(buffer);
}
export async function loadMotion(
vfs: AbstractVFS,
path: string,
component: MotionComponent,
) {
const file = await vfs.file(
normalize(`Data/3d/${dirname(path)}/${component["motion.filepath"]}`),
);
return new MotionReadStream(
file.buffer.slice(
file.byteOffset,
file.byteOffset + file.byteLength,
) as ArrayBuffer,
).motion();
}
export function createSkeleton(
document: Document,
buffer: Buffer,
node: Node,
skeleton: SkeletonComponent,
motion: Motion | undefined,
) {
const joints = times(
skeleton.jointsCount,
(index) => skeleton.joints[index.toString().padStart(4, "0")],
);
const jointNodes = joints.map((joint) => {
const translation: vec3 = [0, 0, 0];
const rotation: vec4 = [0, 0, 0, 1];
const scale: vec3 = [1, 1, 1];
const track = motion?.tracks.get(joint["joint.uid"]);
const trackScale = track?.get(MotionChannel.Scale)?.values[0];
MathUtils.decompose(
joint["joint.bindPose"].flat() as mat4,
translation,
rotation,
scale,
);
// rest on the first frame so the static pose matches the animation
return document
.createNode(joint["joint.name"])
.setTranslation(
(track?.get(MotionChannel.Translation)?.values.slice(0, 3) as vec3) ??
translation,
)
.setRotation(
(track?.get(MotionChannel.Rotation)?.values.slice(0, 4) as vec4) ??
rotation,
)
.setScale(
trackScale === undefined ? scale : [trackScale, trackScale, trackScale],
);
});
joints.forEach((joint, index) => {
const parent = joint["joint.parentIndex"];
(parent === JOINT_ROOT ? node : jointNodes[parent]).addChild(
jointNodes[index],
);
});
const skin = document
.createSkin()
.setInverseBindMatrices(
createAccessor(
document,
buffer,
"MAT4",
new Float32Array(
joints.flatMap((joint) => joint["joint.invBindPose"].flat()),
),
),
);
jointNodes.forEach((jointNode) => skin.addJoint(jointNode));
return {
skin,
joints: new Map(
joints.map((joint, index) => [joint["joint.uid"], jointNodes[index]]),
),
};
}
export function createMotionClip(
document: Document,
buffer: Buffer,
clip: string,
joints: Map<string, Node>,
motion: Motion,
component: MotionComponent,
) {
const animation = document.createAnimation(clip);
const playbackRate = component["motion.playbackRate"];
const duration = motion.duration / playbackRate;
for (const [uid, track] of motion.tracks) {
const joint = joints.get(uid);
if (!joint) continue;
for (const [type, { times, values }] of track) {
const keyTimes = times.map((time) => time / playbackRate);
const keyValues =
type === MotionChannel.Scale
? values.flatMap((value) => [value, value, value])
: [...values];
// the game loops over the clip's duration, which can outlast its keys
if (keyTimes[keyTimes.length - 1] < duration) {
const size = keyValues.length / keyTimes.length;
keyTimes.push(duration);
keyValues.push(...keyValues.slice(-size));
}
const sampler = document
.createAnimationSampler()
.setInput(
createAccessor(
document,
buffer,
"SCALAR",
new Float32Array(keyTimes),
),
)
.setOutput(
createAccessor(
document,
buffer,
type === MotionChannel.Rotation ? "VEC4" : "VEC3",
new Float32Array(keyValues),
),
)
.setInterpolation("LINEAR");
animation
.addSampler(sampler)
.addChannel(
document
.createAnimationChannel()
.setTargetNode(joint)
.setTargetPath(MOTION_PATHS[type])
.setSampler(sampler),
);
}
}
}
/**
* Makes a socket follow a joint. The game replaces the socket's own transform
* with the joint's, so it sits right on the joint.
*/
export function bindSocket(socket: Node, joint: Node, skin: Skin) {
joint.addChild(socket);
socket.setMatrix(new Matrix4().toArray() as mat4);
socket.traverse((child) => {
const childSkin = child.getSkin();
// skinned meshes carrying a copy of the owner's skeleton deform with it
if (
childSkin &&
isEqual(
childSkin.listJoints().map((joint) => joint.getName()),
skin.listJoints().map((joint) => joint.getName()),
)
) {
child.setSkin(skin);
}
});
}
export function skinPrimitive(
document: Document,
buffer: Buffer,
primitive: Primitive,
attributes: Map<VertexAttribute, number[][]>,
targetsData: ArrayBuffer | undefined,
) {
const jointIndices =
attributes.get(VertexAttribute.JOINTINDEX) ??
attributes.get(VertexAttribute.HARD_JOINTINDEX);
if (!jointIndices || !targetsData) return false;
const targets = new Uint32Array(new Uint8Array(targetsData).slice().buffer);
const weights =
attributes.get(VertexAttribute.JOINTWEIGHT) ?? jointIndices.map(() => [1]);
primitive
.setAttribute(
"JOINTS_0",
createAccessor(
document,
buffer,
"VEC4",
new Uint16Array(
jointIndices.flatMap((indices) =>
times(4, (index) => {
if (index >= indices.length) return 0;
const target = targets[indices[index]];
if (target === undefined) {
throw new Error(`Missing joint target ${indices[index]}`);
}
return target;
}),
),
),
),
)
.setAttribute(
"WEIGHTS_0",
createAccessor(
document,
buffer,
"VEC4",
new Float32Array(
weights.flatMap((vertexWeights) => {
const padded = times(4, (index) => vertexWeights[index] ?? 0);
// some game weights sum below 1; glTF requires normalized weights
const sum = padded.reduce((total, weight) => total + weight, 0);
return padded.map((weight) => (sum > 0 ? weight / sum : weight));
}),
),
),
);
return true;
}
+19 -46
View File
@@ -4,66 +4,39 @@ import { jsxTree } from "./jsxTree";
type Mergers = Parameters<typeof jsxTree>[1];
// names get sanitized and made unique on load
export 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; `primitive` renders customization parts as they are so their
* bones can animate
*/
export function skinTree(
node: Object3D,
skins: Skin[],
mergers: NonNullable<Mergers>,
skin: Skin | undefined,
mergers: Mergers,
) {
const materials = new Map<string, Material>();
const states: Record<string, string | null> = {};
for (const skin of skins) {
for (const [name, material] of skin.materials) {
materials.set(name, material);
}
Object.assign(states, skin.scene.userData.states);
}
function switchChildren(object3d: Object3D) {
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, skinMergers));
}
const skinNodes = new Map(
skin?.scene.children.map((node) => [node.name, node]),
);
const skinMergers: Mergers = {
mesh(mesh, props, key) {
const material = materials.get((mesh.material as Material).name);
const material = skin?.materials.get((mesh.material as Material).name);
return mergers.mesh!(
return mergers!.mesh!(
mesh,
material ? { ...props, material } : props,
key,
);
},
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;
return (
<group key={key} {...props}>
{switchChildren(object3d) ?? props.children}
{skins.flatMap((skin) =>
(skin.parts.get(object3d.name) ?? []).map((part) =>
mergers.primitive ? (
mergers.primitive(part, part.uuid)
) : (
<primitive key={part.uuid} object={part} />
),
),
)}
{isSwitch
? object3d.children
.filter((child) => child.name === state)
.map((child) => jsxTree(child, skinMergers))
: props.children}
{skinNode?.children.map((child) => jsxTree(child, mergers))}
</group>
);
},
@@ -1,540 +0,0 @@
import {
parseHierarchies,
type Hierarchy,
type Sc2ReadStream,
} from "@blitzkit/core";
import { sortBy, 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>;
variables?: Record<string, Value>;
}
interface Action {
"act.delay": number;
"act.entityName": string;
"act.event": number;
"act.eventToTrigger": string;
"act.stopAfterNRepeats": number;
"act.switchIndex": number;
"act.type": number;
"act.userEventId": string;
}
interface Entity {
name: string;
parent?: Entity;
children: Entity[];
hierarchy?: Hierarchy;
repeats?: number;
}
const SELF_ENTITY = "*** Self ***";
const SCENE_LOADED_EVENT = 1;
const USER_EVENT = 2;
const ANIMATION_END_EVENTS = [3, 8];
const START_ANIMATION_ACTION = 6;
const SWITCH_ACTIONS = [8, 9];
const TRIGGER_EVENT_ACTION = 10;
// 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 the game does as a tank is shown in the garage, with the camo's
* preset applied and its items attached; `animate` follows customization parts
* through their motions, delays and alarms until they settle
*/
function replay(
sc2: ReturnType<Sc2ReadStream["sc2"]>,
preset: string | undefined,
attachments: Map<string, string[]>,
animate: boolean,
) {
const scripts: Record<string, Script> = {};
const root: Entity = { name: "", children: [] };
const stateNames = new Map<Entity, string[]>();
const scenarios: {
owner: Entity;
script: Script;
variables: Map<string, unknown>;
}[] = [];
const actions: { owner: Entity; action: Action }[] = [];
// names can repeat, so states are kept per entity
const states = new Map<Entity, string | null>();
const looping = new Set<Entity>();
const finished = new Set<Entity>();
const pending: (() => void)[] = [];
const fired = new Set<unknown>();
function activateState(entity: Entity | undefined, state: number) {
const names = entity && stateNames.get(entity);
if (!names) return;
const previous = states.get(entity);
states.set(entity, names[state] ?? null);
if (!animate || previous === states.get(entity)) return;
for (const scenario of scenarios) {
if (scenario.owner === entity) {
runScenario(scenario, "State Activated", state);
}
}
}
function isShown(entity: Entity) {
for (let child = entity; child.parent; child = child.parent) {
if (
stateNames.get(child.parent)?.includes(child.name) &&
states.get(child.parent) !== child.name
) {
return false;
}
}
return true;
}
function startAnimation(entity: Entity, repeats?: number) {
if (entity.repeats === undefined) {
for (const child of entity.children) startAnimation(child, repeats);
return;
}
if (looping.has(entity)) return;
looping.add(entity);
// some clips restart themselves when they end, so each finishes once
if ((repeats ?? entity.repeats) > 0 && !finished.has(entity)) {
pending.push(() => finishAnimation(entity));
}
}
function finishAnimation(entity: Entity) {
const statesBefore = new Map(states);
const shownBefore = [...looping].filter(isShown);
looping.delete(entity);
finished.add(entity);
for (const { owner, action } of actions) {
if (
owner === entity &&
ANIMATION_END_EVENTS.includes(action["act.event"])
) {
runAction(owner, action);
}
}
for (
let ancestor: Entity | undefined = entity;
ancestor;
ancestor = ancestor.parent
) {
const owned = scenarios.filter(({ owner }) => owner === ancestor);
for (const scenario of owned) {
runScenario(scenario, "Motion Fragment Stop");
runScenario(scenario, "Motion Sequence Stop");
}
if (owned.length > 0) break;
}
// as in game, a clip stops on whatever it switched to or revealed; one that
// changes nothing is the only animation there is, so it keeps looping
if (
[...states].every(
([other, state]) => statesBefore.get(other) === state,
) &&
[...looping].every(
(other) => !isShown(other) || shownBefore.includes(other),
)
) {
looping.add(entity);
}
}
function runAction(owner: Entity, action: Action) {
const target = resolveTarget(owner, action["act.entityName"]);
if (SWITCH_ACTIONS.includes(action["act.type"])) {
// what shows for a while in game stays, as its animation loops here
if (action["act.delay"] > 0 && action["act.switchIndex"] < 0) return;
activateState(target, action["act.switchIndex"]);
} else if (animate && action["act.type"] === START_ANIMATION_ACTION) {
if (target) {
const repeats = action["act.stopAfterNRepeats"];
startAnimation(target, repeats > 0 ? repeats : undefined);
}
} else if (animate && action["act.type"] === TRIGGER_EVENT_ACTION) {
fireEvent(action["act.eventToTrigger"]);
}
}
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"],
root,
(hierarchy, components, parent) => {
const entity: Entity = {
name: hierarchy.name,
parent,
children: [],
hierarchy,
};
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.set(entity, names[component["ssc.activeState"]] ?? null);
break;
}
case "ScenarioComponent": {
const script = scripts[component["scenario.scriptId"]];
if (script) {
scenarios.push({
owner: entity,
script,
variables: new Map(
Object.entries(script.variables ?? {}).map(
([name, variable]) => [name, variable["any.value"]],
),
),
});
}
break;
}
case "ActionComponent":
times(component["ac.actionCount"], (index) => {
actions.push({
owner: entity,
action: component[index.toString().padStart(4, "0")] as Action,
});
});
break;
case "MotionComponent":
if (animate) {
entity.repeats = component["simpleMotion.repeatsCount"];
}
break;
}
}
return entity;
},
);
function runScenario(
scenario: (typeof scenarios)[number],
event: string,
value?: number,
) {
const { owner, script, variables } = scenario;
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":
switch (node["scenarioSceneInfoNode.infoKind"]) {
case "GetCurrentEntity":
return owner;
case "GetCurrentScene":
return root;
}
return undefined;
case "ScenarioGetVarNode":
return variables.get(node["scenarioGetVarNode.varPath"] as string);
case "ScenarioSetVarNode":
return variables.get(node["scenarioSetVarNode.varPath"] as string);
case "ScenarioGetMemberNode": {
const object = input(id, "object") as Entity | undefined;
switch (node["scenarioGetMemberNode.fieldName"]) {
case "parent":
return pin === "parent" ? object?.parent : undefined;
case "name":
return object?.name;
case "stateSwitcherVisibility":
return object && isShown(object);
}
return undefined;
}
case "ScenarioFunctionNode": {
const name = node["scenarioFunctionNode.functionName"] as string;
const number = (pin: string) => Number(input(id, pin) ?? 0);
switch (`${node["scenarioFunctionNode.className"]}.${name}`) {
case "Entity.FindChildByName": {
const entity = input(id, "entity") as Entity | undefined;
return entity && findChild(entity, input(id, "name") as string);
}
case "Entity.GetVisibility": {
const entity = input(id, "arg0") as Entity | undefined;
return entity ? isShown(entity) : false;
}
case "TankComponent.GetAppliedSkinMaterialConfigName":
return preset;
case "String.Compare":
return input(id, "1") === input(id, "2");
case "String.Merge":
// graphs use Separator as the prefix and Postfix as the number
return ["Suffix", "Separator", "Postfix"]
.map((pin) => input(id, pin) ?? "")
.join("");
case "bool.Or":
return Boolean(input(id, "a")) || Boolean(input(id, "b"));
case "Random.Random":
case "Random.RandomFloat":
case "TankComponent.GetSpeed":
case "TankComponent.GetTurretAngle":
case "TankComponent.GetGunAngle":
return 0;
}
if (name === "==") return number("a") === number("b");
if (name === ">") return number("a") > number("b");
if (name === ">=") return number("a") >= number("b");
if (name === "<=") return number("a") <= number("b");
if (name.startsWith("Add")) return number("a") + number("b");
if (name.startsWith("Subtract")) return number("a") - number("b");
}
}
}
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 (type === "ScenarioSetVarNode") {
variables.set(
node["scenarioSetVarNode.varPath"] as string,
input(id, "set"),
);
} else if (type === "ScenarioSetAlarmClockNode") {
const entity = (input(id, "entity") as Entity | undefined) ?? owner;
// alarms re-arm themselves
if (animate && !fired.has(node)) {
fired.add(node);
pending.push(() => {
for (const other of scenarios) {
if (other.owner === entity) runScenario(other, "Alarm Clock");
}
});
}
} else {
const entity = input(id, "entity") as Entity | undefined;
switch (node["scenarioFunctionNode.functionName"]) {
case "ActivateState":
activateState(entity, Number(input(id, "state")));
break;
case "StartAnimation":
if (animate && entity) {
startAnimation(entity, Number(input(id, "repeats") ?? 0));
}
break;
case "TriggerCustomEvent":
if (animate) fireEvent(input(id, "event name") as string);
break;
}
}
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 &&
(event !== "State Activated" ||
Number(node.defaults?.State?.["any.value"] ?? 0) === value)
) {
execute(id, 0);
}
}
}
function fireEvent(event: string) {
if (fired.has(event)) return;
fired.add(event);
// the game runs delayed actions once their delay is up, so they go in that
// order rather than the order they're stored in
for (const { owner, action } of sortBy(
actions,
({ action }) => action["act.delay"],
)) {
if (
(animate || action["act.delay"] === 0) &&
(event === LOAD_EVENTS[0]
? action["act.event"] === SCENE_LOADED_EVENT
: action["act.event"] === USER_EVENT &&
action["act.userEventId"] === event)
) {
runAction(owner, action);
}
}
for (const scenario of scenarios) runScenario(scenario, event);
}
for (const event of LOAD_EVENTS) fireEvent(event);
for (let run = pending.shift(); run; run = pending.shift()) run();
return {
states: new Map(
[...states].map(([entity, state]) => [
entity.hierarchy as Hierarchy,
state,
]),
),
motions: new Set(
[...looping]
.filter(isShown)
.map((entity) => entity.hierarchy as Hierarchy),
),
};
}
/**
* picks each state switcher's state; 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 states: Record<string, string | null> = {};
for (const [hierarchy, state] of replay(sc2, preset, attachments, false)
.states) {
states[hierarchy.name] = state;
}
return states;
}
/**
* where a customization part ends up: each state switcher's state and the
* motions left looping
*/
export function partGarage(
sc2: ReturnType<Sc2ReadStream["sc2"]>,
preset: string | undefined,
) {
return replay(sc2, preset, new Map(), true);
}
+3 -2
View File
@@ -1,3 +1,4 @@
import { createClientVFS } from "@blitzkit/core/src/blitzkit/vfs/client";
import { assertSecret } from "@blitzkit/core";
import { LocalVFS } from "@blitzkit/core/src/blitzkit/vfs/local";
export const vfs = await createClientVFS();
export const vfs = new LocalVFS(assertSecret(import.meta.env.CLIENT_DIR));
@@ -1,31 +0,0 @@
import { Matrix4, type Object3D } from "three";
export interface FlatNode {
object: Object3D;
// relative to the root's parent, like jsxTree renders it
matrix: Matrix4;
root: Object3D;
}
function allChildren(object: Object3D) {
return object.children;
}
// every object under the roots; children picks which ones to descend into
export function flattenNodes(roots: Object3D[], children = allChildren) {
const flat: FlatNode[] = [];
function walk(object: Object3D, parent: Matrix4, root: Object3D) {
object.updateMatrix();
const matrix = parent.clone().multiply(object.matrix);
flat.push({ object, matrix, root });
for (const child of children(object)) walk(child, matrix, root);
}
for (const root of roots) walk(root, new Matrix4(), root);
return flat;
}
@@ -1,4 +0,0 @@
import { Quicklime } from "quicklime";
// something that casts or receives shadows was added, removed or changed
export const sceneChangeEvent = new Quicklime();
@@ -1,65 +0,0 @@
import type { Armor } from "@blitzkit/core";
import { useMemo } from "react";
import type { Object3D } from "three";
import { nameToArmorId } from "../core/blitzkit/nameToArmorId";
import { resolveArmor } from "../core/blitzkit/resolveThickness";
import { Duel } from "../stores/duel";
import { useArmor } from "./useArmor";
import { useTankModelDefinition } from "./useTankModelDefinition";
export interface ArmorPlate {
node: Object3D;
thickness: number;
}
interface SectionPlates {
primary: ArmorPlate[];
spaced: ArmorPlate[];
}
// the protagonist's hull, turret and gun plates; nodes whose name contains
// hiddenState are dynamic armor in the other state
export function useArmorPlates(hiddenState: string) {
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 { gltf } = useArmor(tank.id);
const tankModelDefinition = useTankModelDefinition();
return useMemo(() => {
const turretModelDefinition = tankModelDefinition.turrets[turret.id];
const gunModelDefinition = turretModelDefinition.guns[gun.id];
const nodes = Object.values(gltf.nodes);
function platesOf(prefix: string, armor: Armor) {
const plates: SectionPlates = { primary: [], spaced: [] };
for (const node of nodes) {
if (!node.name.startsWith(prefix) || node.name.includes(hiddenState)) {
continue;
}
const { spaced, thickness } = resolveArmor(
armor,
nameToArmorId(node.name),
);
plates[spaced ? "spaced" : "primary"].push({ node, thickness });
}
return plates;
}
const hullPlates = platesOf("hull_", tankModelDefinition.armor!);
const turretPlates = platesOf(
`turret_${turretModelDefinition.model_id.toString().padStart(2, "0")}`,
turretModelDefinition.armor!,
);
const gunPlates = platesOf(
`gun_${gunModelDefinition.model_id.toString().padStart(2, "0")}`,
gunModelDefinition.armor!,
);
return { hull: hullPlates, turret: turretPlates, gun: gunPlates };
}, [gltf, tankModelDefinition, turret.id, gun.id, hiddenState]);
}
@@ -1,107 +0,0 @@
import { useEffect, useMemo } from "react";
import {
Mesh,
MeshStandardMaterial,
type Material,
type Matrix4,
type Object3D,
} from "three";
import type { BatchItem } from "../components/Batch";
import { prepareMaterial } from "../core/blitzkit/jsxTree";
import { nameOf } from "../core/blitzkit/skinTree";
import { flattenNodes } from "../core/three/flattenNodes";
import type { Skin } from "./useSkin";
interface BatchGroup {
material: MeshStandardMaterial;
items: BatchItem[];
}
interface SkinPart {
part: Object3D;
matrix: Matrix4;
}
/**
* Model nodes grouped into one batch per material. Skins are layered in order,
* so an attachment's states win over the camouflage's. Their parts aren't
* batched so their bones can animate.
*/
export function useBatchGroups(nodes: Object3D[], skins: Skin[]) {
const batchGroups = useMemo(() => {
const skinMaterials = new Map<string, Material>();
const states: Record<string, string | null> = {};
for (const skin of skins) {
for (const [name, material] of skin.materials) {
skinMaterials.set(name, material);
}
Object.assign(states, skin.scene.userData.states);
}
function stateChildren(object: Object3D) {
if (object.userData.state === undefined) return object.children;
const name = nameOf(object);
const state = name in states ? states[name] : object.userData.state;
return object.children.filter((child) => nameOf(child) === state);
}
const groups = new Map<Material, BatchGroup>();
const parts: SkinPart[] = [];
for (const { object, matrix } of flattenNodes(nodes, stateChildren)) {
for (const skin of skins) {
for (const part of skin.parts.get(object.name) ?? []) {
parts.push({ part, matrix });
}
}
if (!(object instanceof Mesh)) continue;
const source =
skinMaterials.get((object.material as Material).name) ??
object.material;
if (!(source instanceof MeshStandardMaterial)) continue;
let group = groups.get(source);
if (!group) {
const material = source.clone();
prepareMaterial(material);
group = { material, items: [] };
groups.set(source, group);
}
group.items.push({ mesh: object, matrix });
}
const materials = [...groups.values()].map(({ material }) => material);
for (const { part } of parts) {
part.traverse((object) => {
if (
object instanceof Mesh &&
object.material instanceof MeshStandardMaterial
) {
materials.push(object.material);
}
});
}
return { groups: [...groups.values()], parts, materials };
}, [nodes, skins]);
useEffect(
() => () => {
for (const { material } of batchGroups.groups) material.dispose();
},
[batchGroups],
);
return batchGroups;
}
@@ -1,71 +0,0 @@
import { useMemo } from "react";
import type { Object3D } from "three";
import { Duel } from "../stores/duel";
import { useModel } from "./useModel";
import { useTankModelDefinition } from "./useTankModelDefinition";
interface ModelNodes {
hull: Object3D[];
wheels: Object3D[];
tracks: Object3D[];
turret: Object3D[];
gun: Object3D[];
mask: Object3D[];
}
// the protagonist's visual model split into its parts
export function useModelNodes() {
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 { gltf } = useModel(tank.id);
const tankModelDefinition = useTankModelDefinition();
return useMemo(() => {
const turretModelDefinition = tankModelDefinition.turrets[turret.id];
const gunModelDefinition = turretModelDefinition.guns[gun.id];
const turretName = `turret_${turretModelDefinition.model_id
.toString()
.padStart(2, "0")}`;
const gunName = `gun_${gunModelDefinition.model_id
.toString()
.padStart(2, "0")}`;
const maskName = `${gunName}_mask`;
const nodes: ModelNodes = {
hull: [],
wheels: [],
tracks: [],
turret: [],
gun: [],
mask: [],
};
for (const node of Object.values(gltf.nodes)) {
switch (node.name) {
case "hull":
nodes.hull.push(node);
continue;
case turretName:
nodes.turret.push(node);
continue;
case gunName:
nodes.gun.push(node);
continue;
case maskName:
nodes.mask.push(node);
continue;
}
if (node.name.startsWith("chassis_wheel_")) {
nodes.wheels.push(node);
} else if (node.name.startsWith("chassis_track_")) {
nodes.tracks.push(node);
}
}
return nodes;
}, [gltf, tankModelDefinition, turret.id, gun.id]);
}
@@ -1,21 +0,0 @@
import { useEffect } from "react";
import { modelTransformEvent } from "../core/blitzkit/modelTransform";
import { sceneChangeEvent } from "../core/three/sceneChange";
/**
* Calls back on mount and whenever shadows may have changed: the tank moved or
* something dispatched sceneChangeEvent.
*/
export function useOnSceneChange(callback: () => void) {
useEffect(() => {
callback();
modelTransformEvent.on(callback);
sceneChangeEvent.on(callback);
return () => {
modelTransformEvent.off(callback);
sceneChangeEvent.off(callback);
};
}, [callback]);
}
@@ -1,27 +0,0 @@
import { useMemo } from "react";
import { Mesh } from "three";
import type { BatchItem } from "../components/Batch";
import { flattenNodes } from "../core/three/flattenNodes";
import type { ArmorPlate } from "./useArmorPlates";
// batch items for armor plates, each carrying its plate's thickness
export function usePlateItems(plates: ArmorPlate[]) {
return useMemo(() => {
const thicknesses = new Map(
plates.map(({ node, thickness }) => [node, thickness]),
);
return flattenNodes(plates.map(({ node }) => node)).flatMap(
({ object, matrix, root }) =>
object instanceof Mesh
? [
{
mesh: object,
matrix,
thickness: thicknesses.get(root)!,
} satisfies BatchItem,
]
: [],
);
}, [plates]);
}
@@ -1,21 +0,0 @@
import { invalidate, useThree } from "@react-three/fiber";
import { useEffect } from "react";
import { useOnSceneChange } from "./useOnSceneChange";
// shadow maps only re-render when the scene changes, not every frame
export function useShadowsOnDemand() {
const gl = useThree((state) => state.gl);
useEffect(() => {
gl.shadowMap.autoUpdate = false;
return () => {
gl.shadowMap.autoUpdate = true;
};
}, [gl]);
useOnSceneChange(() => {
gl.shadowMap.needsUpdate = true;
invalidate();
});
}
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff. Show more