diff --git a/.gitignore b/.gitignore index 07bda0a..4642f47 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,7 @@ __pycache__/ /out/ /scratch/ +bin/ +obj/ +.godot/ +.vs/ diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..047d29f --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,8 @@ + + + $(YMIR_ROOT) + $(MSBuildThisFileDirectory)..\Ymir + $(CULTLIB_ROOT) + $(MSBuildThisFileDirectory)..\CultLib + + diff --git a/README.md b/README.md index e28e9d8..658af05 100644 --- a/README.md +++ b/README.md @@ -8,21 +8,54 @@ The lore lives in Weksa: `settings/rust-to-dust/` in [GameCult/Weksa](https://github.com/GameCult/Weksa) (setting, story, battle royale, aliens, language design). This repo holds no lore. -## What is here today +## What is live today (`nibu/rtd-prototype`) -Nothing runnable yet. This repo is the home for the mech work now being -prototyped: +- **`RustToDust.Core`**: + - Aetheria 2D grid chassis (`Dorsal` vehicles/quadrupeds and `Coronal` bipeds), + conductive/radiative heat transfer, trapezoidal thermal plateau curves, + localized armor + core destruction, and live cargo-to-hardpoint swapping. + - 6 playable chassis (`buggy`, `technical`, `tank`, `manticore`, `raptor`, + `paladin`), 8 human salvage modules, and 5 Imperial Tourist modules. + - Shrinking `SpectatorRing` perimeter (`Tourist`, `Patron`, and `Exemplar` + tiers with `Neutral` / `Cleared` / `Provoked` stances and Weksa-voiced + `BroadcastFeed` commentary). + - `TerrainField`: deterministic `1536m x 1536m` desert terrain divided into an + `8x8` (`192m x 192m`) tile grid with procedural dunes, mesas, salvage pads, + dirt roads, and runtime crater / tire-track / thermal-scorch stamping. +- **`RustToDust.Ymir`**: + - `ArenaSession` bridging `MatchState` onto Ymir's `Box3DSoaWorld` with + 4-corner spring-damper terrain support, raycast weapons, terrain crater/scorch + impacts, and AI contenders + perimeter spectators. +- **`tests/RustToDust.Tests`**: + - Behavioral xUnit suite covering Aetheria grid heat, spectator ring clearance, + Ymir vehicle driving/combat/swapping, and procedural/dynamic terrain relief. +- **`client/` (Godot 4.7.2 Mono)**: + - 3D desert client with a top-down orthographic `SubViewport` brush-to-tile PBR + + height displacement baker, procedural 3D chassis/spectator silhouettes, + tactical radar, clickable Aetheria Hardpoint & Heat schematic, and Imperial + Broadcast chyron. -- mechs kitbashed from parts with [Brokkr](https://eureka.gamecult.org/forge/GameCult/Brokkr) - (armour shells, ribs, cuts, joints, hoses, frames); -- a mechanical rig with one bone per degree of freedom, driven rams and linkages; -- generic walk and combat animation retargeted onto each chassis. +## Build, test, and run -That work currently lives on `nibu/fable-*` experiment branches in -GameCult/Brokkr and moves here as it settles. +Requires a sibling `Ymir` checkout beside `RustToDust` (or `YMIR_ROOT` set), +CMake, a C compiler, .NET SDK 8/10, and Godot 4.7.2 Mono (`--path client`). -## Planned, not live +```bash +# Run the behavioral test suite +dotnet test tests/RustToDust.Tests/RustToDust.Tests.csproj -c Release -- Mech parts library and chassis definitions. -- Rig generator and goal-space retargeting solver. -- A playable walk-and-fight prototype. +# Build the Godot 4.7.2 Mono client assembly (also builds Ymir native Box3D) +dotnet build client/RustToDust.Client.csproj -c Debug + +# Run the playable 3D client +godot --path client + +# Run the headless Godot smoke test +godot --headless --path client res://tests/Smoke.tscn +``` + +## Planned, not live yet + +- Kitbashed Brokkr mechanical rigs and goal-space walk/combat retargeting + replacing the procedural box/cylinder silhouettes. +- Multiplayer networking and audio synthesis. diff --git a/RustToDust.slnx b/RustToDust.slnx new file mode 100644 index 0000000..5955da4 --- /dev/null +++ b/RustToDust.slnx @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/assets/decals/decal_atlas_albedo.png b/assets/decals/decal_atlas_albedo.png new file mode 100644 index 0000000..c87f3e1 Binary files /dev/null and b/assets/decals/decal_atlas_albedo.png differ diff --git a/assets/decals/decal_atlas_normal.png b/assets/decals/decal_atlas_normal.png new file mode 100644 index 0000000..6155e10 Binary files /dev/null and b/assets/decals/decal_atlas_normal.png differ diff --git a/assets/decals/decal_atlas_ormh.png b/assets/decals/decal_atlas_ormh.png new file mode 100644 index 0000000..89b9590 Binary files /dev/null and b/assets/decals/decal_atlas_ormh.png differ diff --git a/assets/gear/autocannon.glb b/assets/gear/autocannon.glb new file mode 100644 index 0000000..fa2c413 Binary files /dev/null and b/assets/gear/autocannon.glb differ diff --git a/assets/gear/copper_rad.glb b/assets/gear/copper_rad.glb new file mode 100644 index 0000000..e1c2692 Binary files /dev/null and b/assets/gear/copper_rad.glb differ diff --git a/assets/gear/gilded_lance.glb b/assets/gear/gilded_lance.glb new file mode 100644 index 0000000..1e0878b Binary files /dev/null and b/assets/gear/gilded_lance.glb differ diff --git a/assets/gear/gold_radiator.glb b/assets/gear/gold_radiator.glb new file mode 100644 index 0000000..b0952c8 Binary files /dev/null and b/assets/gear/gold_radiator.glb differ diff --git a/assets/gear/mg_762.glb b/assets/gear/mg_762.glb new file mode 100644 index 0000000..8c6658a Binary files /dev/null and b/assets/gear/mg_762.glb differ diff --git a/assets/gear/recoilless.glb b/assets/gear/recoilless.glb new file mode 100644 index 0000000..815f0cc Binary files /dev/null and b/assets/gear/recoilless.glb differ diff --git a/assets/vehicles/anvil/anvil.glb b/assets/vehicles/anvil/anvil.glb new file mode 100644 index 0000000..1468d2e Binary files /dev/null and b/assets/vehicles/anvil/anvil.glb differ diff --git a/assets/vehicles/anvil/manifest.json b/assets/vehicles/anvil/manifest.json new file mode 100644 index 0000000..ca8cff5 --- /dev/null +++ b/assets/vehicles/anvil/manifest.json @@ -0,0 +1,154 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "anvil", + "name": "Anvil", + "class": "Heavy Quad-Track Siege Tank", + "plane": "Dorsal", + "gridWidth": 5, + "gridHeight": 6, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.armor.front", + "kind": "armor", + "x": 0, + "y": 0, + "w": 5, + "h": 1, + "modelNodeId": "hp.armor.front" + }, + { + "id": "hp.weapon.sponson_l", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.sponson_l" + }, + { + "id": "hp.weapon.siege_l", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.siege_l" + }, + { + "id": "hp.armor.sides", + "kind": "armor", + "x": 2, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.armor.sides" + }, + { + "id": "hp.weapon.siege_r", + "kind": "weapon", + "x": 3, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.siege_r" + }, + { + "id": "hp.weapon.sponson_r", + "kind": "weapon", + "x": 4, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.sponson_r" + }, + { + "id": "hp.engine.rear", + "kind": "engine", + "x": 1, + "y": 3, + "w": 3, + "h": 2, + "modelNodeId": "hp.engine.rear" + }, + { + "id": "hp.radiator.l", + "kind": "radiator", + "x": 0, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.l" + }, + { + "id": "hp.radiator.r", + "kind": "radiator", + "x": 4, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.r" + } + ], + "joints": [ + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -1.93, + 0.0, + -2.8252 + ], + "max": [ + 1.93, + 3.0266, + 2.8252 + ], + "size": [ + 3.86, + 3.0266, + 5.6504 + ] + }, + "triCount": 18044 +} diff --git a/assets/vehicles/anvil/vehicle.cc b/assets/vehicles/anvil/vehicle.cc new file mode 100644 index 0000000..1e82918 Binary files /dev/null and b/assets/vehicles/anvil/vehicle.cc differ diff --git a/assets/vehicles/bastion/bastion.glb b/assets/vehicles/bastion/bastion.glb new file mode 100644 index 0000000..aada0cf Binary files /dev/null and b/assets/vehicles/bastion/bastion.glb differ diff --git a/assets/vehicles/bastion/manifest.json b/assets/vehicles/bastion/manifest.json new file mode 100644 index 0000000..43f8d8a --- /dev/null +++ b/assets/vehicles/bastion/manifest.json @@ -0,0 +1,151 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "bastion", + "name": "Bastion", + "class": "Heavy Siege Quadruped", + "plane": "Dorsal", + "gridWidth": 6, + "gridHeight": 6, + "mask": [ + false, + false, + true, + true, + false, + false, + false, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + false, + true, + false, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.armor.prow", + "kind": "armor", + "x": 2, + "y": 0, + "w": 2, + "h": 1, + "modelNodeId": "hp.armor.prow" + }, + { + "id": "hp.weapon.turret_pd", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.turret_pd" + }, + { + "id": "hp.weapon.turret_main", + "kind": "weapon", + "x": 2, + "y": 1, + "w": 2, + "h": 2, + "modelNodeId": "hp.weapon.turret_main" + }, + { + "id": "hp.weapon.flank_l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.flank_l" + }, + { + "id": "hp.weapon.flank_r", + "kind": "weapon", + "x": 5, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.flank_r" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 2, + "y": 3, + "w": 2, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.radiator.rear_l", + "kind": "radiator", + "x": 1, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.rear_l" + }, + { + "id": "hp.radiator.rear_r", + "kind": "radiator", + "x": 4, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.rear_r" + } + ], + "joints": [ + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -6.6043, + 0.0, + -8.043 + ], + "max": [ + 6.6094, + 9.625, + 6.7519 + ], + "size": [ + 13.2137, + 9.625, + 14.7949 + ] + }, + "triCount": 36656 +} diff --git a/assets/vehicles/bastion/vehicle.cc b/assets/vehicles/bastion/vehicle.cc new file mode 100644 index 0000000..db90253 Binary files /dev/null and b/assets/vehicles/bastion/vehicle.cc differ diff --git a/assets/vehicles/breaker/breaker.glb b/assets/vehicles/breaker/breaker.glb new file mode 100644 index 0000000..5a4cf61 Binary files /dev/null and b/assets/vehicles/breaker/breaker.glb differ diff --git a/assets/vehicles/breaker/manifest.json b/assets/vehicles/breaker/manifest.json new file mode 100644 index 0000000..0d7d940 --- /dev/null +++ b/assets/vehicles/breaker/manifest.json @@ -0,0 +1,1084 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "breaker", + "name": "Breaker", + "class": "Heavy Assault Biped", + "plane": "Coronal", + "gridWidth": 5, + "gridHeight": 6, + "mask": [ + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + false, + true, + false, + false, + true, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.arm_l", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_l" + }, + { + "id": "hp.weapon.arm_r", + "kind": "weapon", + "x": 4, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_r" + }, + { + "id": "hp.weapon.shoulder_l", + "kind": "weapon", + "x": 1, + "y": 0, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.shoulder_l" + }, + { + "id": "hp.armor.torso", + "kind": "armor", + "x": 2, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.armor.torso" + }, + { + "id": "hp.engine.chest", + "kind": "engine", + "x": 2, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.chest" + }, + { + "id": "hp.radiator.back_l", + "kind": "radiator", + "x": 1, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_l" + }, + { + "id": "hp.radiator.back_r", + "kind": "radiator", + "x": 3, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_r" + } + ], + "joints": [ + { + "id": "joint.torso_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -90.0, + "max": 90.0 + }, + { + "id": "joint.arm_l_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + }, + { + "id": "joint.arm_r_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + } + ], + "bounds": { + "min": [ + -2.3356, + -0.0, + -1.274 + ], + "max": [ + 2.3808, + 6.2911, + 1.8859 + ], + "size": [ + 4.7164, + 6.2911, + 3.1599 + ] + }, + "triCount": 35967, + "mechanisms": { + "frame": "gltf (+Y up, +Z forward, +X left, meters)", + "rootOrigin": [ + -0.0, + 3.362557, + 0.0 + ], + "dofs": [ + { + "name": "LegL.Hip", + "parent": -1, + "kind": "slew", + "mechanism": "hip", + "side": "L", + "origin": [ + 0.6209, + 3.362557, + 0.0 + ], + "axis": [ + 1.0, + -0.0, + 0.0 + ], + "lo": -1.0471975511965976, + "hi": 1.0471975511965976, + "depth": 0 + }, + { + "name": "LegL.Thigh", + "parent": 0, + "kind": "slew", + "mechanism": "hip yaw", + "side": "L", + "origin": [ + 1.0809, + 2.71148, + 0.173509 + ], + "axis": [ + -0.0, + -0.966276, + 0.257508 + ], + "lo": -0.6108652381980153, + "hi": 0.6108652381980153, + "depth": 1 + }, + { + "name": "LegL.Shin", + "parent": 1, + "kind": "hinge", + "mechanism": "knee", + "side": "L", + "origin": [ + 1.0809, + 2.086744, + 0.339999 + ], + "axis": [ + -0.0, + -0.970991, + -0.239116 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 2 + }, + { + "name": "LegL.Oleo", + "parent": 2, + "kind": "slide", + "mechanism": "oleo", + "side": "L", + "origin": [ + 1.0809, + 1.021033, + 0.077557 + ], + "axis": [ + -0.0, + -0.970991, + -0.239116 + ], + "lo": -0.2, + "hi": 0.0, + "depth": 3, + "compliance": { + "damping_ratio": 0.45, + "hertz": 1.6 + } + }, + { + "name": "LegL.Foot", + "parent": 3, + "kind": "hinge", + "mechanism": "ankle", + "side": "L", + "origin": [ + 1.0809, + 0.624869, + -0.020002 + ], + "axis": [ + -0.0, + -1.0, + 0.0 + ], + "lo": -0.6981317007977318, + "hi": 0.6981317007977318, + "depth": 4, + "stopped_by": "ram" + }, + { + "name": "LegL.Foot.Toe0.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 0.753334, + 0.252079, + 0.237904 + ], + "axis": [ + -0.08495, + -0.223571, + 0.970979 + ], + "lo": -0.1745329183221527, + "hi": 0.5235987824755791, + "depth": 5 + }, + { + "name": "LegL.Foot.Toe0.Seg1", + "parent": 5, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 0.719354, + 0.162651, + 0.626296 + ], + "axis": [ + -0.087156, + 0.0, + 0.996195 + ], + "lo": -0.2094395171165998, + "hi": 0.8377580340799979, + "depth": 6 + }, + { + "name": "LegL.Foot.Toe1.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 1.408466, + 0.252079, + 0.237904 + ], + "axis": [ + 0.08495, + -0.223571, + 0.970979 + ], + "lo": -0.1745329183221527, + "hi": 0.5235987824755791, + "depth": 5 + }, + { + "name": "LegL.Foot.Toe1.Seg1", + "parent": 7, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 1.442446, + 0.162651, + 0.626296 + ], + "axis": [ + 0.087156, + 0.0, + 0.996195 + ], + "lo": -0.2094395171165998, + "hi": 0.8377580340799979, + "depth": 6 + }, + { + "name": "LegL.Foot.Toe2.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 0.353393, + 0.252079, + 0.057444 + ], + "axis": [ + -0.58406, + -0.316267, + 0.747562 + ], + "lo": -0.17453293312755827, + "hi": 0.5235987676701735, + "depth": 5 + }, + { + "name": "LegL.Foot.Toe3.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 1.808407, + 0.252079, + 0.057444 + ], + "axis": [ + 0.58406, + -0.316267, + 0.747562 + ], + "lo": -0.17453293312755827, + "hi": 0.5235987676701735, + "depth": 5 + }, + { + "name": "LegL.Foot.Toe4.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 0.694624, + 0.252079, + -0.387362 + ], + "axis": [ + -0.225859, + -0.358307, + -0.905872 + ], + "lo": -0.20943950039479836, + "hi": 0.4188790303231602, + "depth": 5 + }, + { + "name": "LegL.Foot.Toe5.Seg0", + "parent": 4, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "L", + "origin": [ + 1.467176, + 0.252079, + -0.387362 + ], + "axis": [ + 0.225859, + -0.358307, + -0.905872 + ], + "lo": -0.20943950039479836, + "hi": 0.4188790303231602, + "depth": 5 + }, + { + "name": "LegR.Hip", + "parent": -1, + "kind": "slew", + "mechanism": "hip", + "side": "R", + "origin": [ + -0.6209, + 3.362557, + 0.0 + ], + "axis": [ + -1.0, + -0.0, + -0.0 + ], + "lo": -1.0471975511965976, + "hi": 1.0471975511965976, + "depth": 0 + }, + { + "name": "LegR.Thigh", + "parent": 13, + "kind": "slew", + "mechanism": "hip yaw", + "side": "R", + "origin": [ + -1.0809, + 2.690817, + 0.052652 + ], + "axis": [ + 0.0, + -0.996942, + 0.078142 + ], + "lo": -0.6108652381980153, + "hi": 0.6108652381980153, + "depth": 1 + }, + { + "name": "LegR.Shin", + "parent": 14, + "kind": "hinge", + "mechanism": "knee", + "side": "R", + "origin": [ + -1.0809, + 2.046254, + 0.103173 + ], + "axis": [ + 0.0, + -0.944097, + -0.329667 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 2 + }, + { + "name": "LegR.Oleo", + "parent": 15, + "kind": "slide", + "mechanism": "oleo", + "side": "R", + "origin": [ + -1.0809, + 1.01006, + -0.258652 + ], + "axis": [ + 0.0, + -0.944097, + -0.329667 + ], + "lo": -0.2, + "hi": 0.0, + "depth": 3, + "compliance": { + "damping_ratio": 0.45, + "hertz": 1.6 + } + }, + { + "name": "LegR.Foot", + "parent": 16, + "kind": "hinge", + "mechanism": "ankle", + "side": "R", + "origin": [ + -1.0809, + 0.624868, + -0.393156 + ], + "axis": [ + 0.0, + -1.0, + 0.0 + ], + "lo": -0.6981317007977318, + "hi": 0.6981317007977318, + "depth": 4, + "stopped_by": "ram" + }, + { + "name": "LegR.Foot.Toe0.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -1.408466, + 0.252079, + -0.13525 + ], + "axis": [ + -0.08495, + -0.223571, + 0.970979 + ], + "lo": -0.1745329183221527, + "hi": 0.5235987824755791, + "depth": 5 + }, + { + "name": "LegR.Foot.Toe0.Seg1", + "parent": 18, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -1.442446, + 0.16265, + 0.253141 + ], + "axis": [ + -0.087156, + 0.0, + 0.996195 + ], + "lo": -0.2094395171165998, + "hi": 0.8377580340799979, + "depth": 6 + }, + { + "name": "LegR.Foot.Toe1.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -0.753334, + 0.252079, + -0.135251 + ], + "axis": [ + 0.08495, + -0.223571, + 0.970979 + ], + "lo": -0.1745329183221527, + "hi": 0.5235987824755791, + "depth": 5 + }, + { + "name": "LegR.Foot.Toe1.Seg1", + "parent": 20, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -0.719354, + 0.16265, + 0.253141 + ], + "axis": [ + 0.087156, + 0.0, + 0.996195 + ], + "lo": -0.2094395171165998, + "hi": 0.8377580340799979, + "depth": 6 + }, + { + "name": "LegR.Foot.Toe2.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -1.808407, + 0.252079, + -0.315711 + ], + "axis": [ + -0.58406, + -0.316267, + 0.747562 + ], + "lo": -0.17453293312755827, + "hi": 0.5235987676701735, + "depth": 5 + }, + { + "name": "LegR.Foot.Toe3.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -0.353393, + 0.252079, + -0.315711 + ], + "axis": [ + 0.58406, + -0.316267, + 0.747562 + ], + "lo": -0.17453293312755827, + "hi": 0.5235987676701735, + "depth": 5 + }, + { + "name": "LegR.Foot.Toe4.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -1.467176, + 0.252079, + -0.760517 + ], + "axis": [ + -0.225859, + -0.358307, + -0.905872 + ], + "lo": -0.20943950039479836, + "hi": 0.4188790303231602, + "depth": 5 + }, + { + "name": "LegR.Foot.Toe5.Seg0", + "parent": 17, + "kind": "hinge", + "mechanism": "toe pitch", + "side": "R", + "origin": [ + -0.694624, + 0.252079, + -0.760517 + ], + "axis": [ + 0.225859, + -0.358307, + -0.905872 + ], + "lo": -0.20943950039479836, + "hi": 0.4188790303231602, + "depth": 5 + }, + { + "name": "Core", + "parent": -1, + "kind": "slew", + "mechanism": "waist", + "side": "", + "origin": [ + -0.0, + 3.721381, + 0.0 + ], + "axis": [ + -0.0, + 1.0, + 0.0 + ], + "lo": -1.9198621771937625, + "hi": 1.9198621771937625, + "depth": 0 + }, + { + "name": "ShoulderYokeL", + "parent": 26, + "kind": "slew", + "mechanism": "shoulder slew", + "side": "L", + "origin": [ + 0.819255, + 4.983909, + 0.0 + ], + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 1 + }, + { + "name": "UpperArmL", + "parent": 27, + "kind": "hinge", + "mechanism": "shoulder hinge", + "side": "L", + "origin": [ + 1.488455, + 4.983909, + 0.0 + ], + "axis": [ + 0.087165, + -0.991212, + 0.0995 + ], + "lo": -0.7853981633974483, + "hi": 0.7853981633974483, + "depth": 2 + }, + { + "name": "ElbowYokeL", + "parent": 28, + "kind": "slew", + "mechanism": "arm twist", + "side": "L", + "origin": [ + 1.556551, + 4.209545, + 0.077732 + ], + "axis": [ + 0.087165, + -0.991212, + 0.0995 + ], + "lo": -1.5707963267948966, + "hi": 1.5707963267948966, + "depth": 3 + }, + { + "name": "ForearmL", + "parent": 29, + "kind": "hinge", + "mechanism": "elbow", + "side": "L", + "origin": [ + 1.601947, + 3.693322, + 0.129552 + ], + "axis": [ + 0.1199, + -0.441691, + 0.889119 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 4 + }, + { + "name": "ShoulderYokeR", + "parent": 26, + "kind": "slew", + "mechanism": "shoulder slew", + "side": "R", + "origin": [ + -0.819255, + 4.983909, + 0.0 + ], + "axis": [ + -1.0, + -0.0, + -0.0 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 1 + }, + { + "name": "UpperArmR", + "parent": 31, + "kind": "hinge", + "mechanism": "shoulder hinge", + "side": "R", + "origin": [ + -1.488455, + 4.983909, + -0.0 + ], + "axis": [ + -0.061315, + -0.978592, + 0.196466 + ], + "lo": -0.7853981633974483, + "hi": 0.7853981633974483, + "depth": 2 + }, + { + "name": "ElbowYokeR", + "parent": 32, + "kind": "slew", + "mechanism": "arm twist", + "side": "R", + "origin": [ + -1.536356, + 4.219404, + 0.153485 + ], + "axis": [ + -0.061315, + -0.978592, + 0.196466 + ], + "lo": -1.5707963267948966, + "hi": 1.5707963267948966, + "depth": 3 + }, + { + "name": "ForearmR", + "parent": 33, + "kind": "hinge", + "mechanism": "elbow", + "side": "R", + "origin": [ + -1.56829, + 3.709754, + 0.255804 + ], + "axis": [ + 0.03822, + -0.374104, + 0.926599 + ], + "lo": -1.7453292519943295, + "hi": 1.7453292519943295, + "depth": 4 + } + ], + "rams": [ + { + "name": "LegL.RecessRam0", + "barrel_bone": "LegL.RecessRam0.barrel", + "rod_bone": "LegL.RecessRam0.rod", + "spans": [ + "LegL.Oleo", + "LegL.Foot" + ], + "bore": 0.09, + "body": 0.664775, + "inner": 0.8131586697281079, + "extension": 0.407443, + "rest": 1.3782174197281079, + "stroke": [ + -0.407443, + 0.514775 + ], + "a_parent_dof": 2, + "a_pos": [ + 0.9109, + 2.117333, + -0.202422 + ], + "b_parent_dof": 4, + "b_pos": [ + 0.9109, + 0.745732, + -0.337304 + ], + "pin_dir": [ + 1.0, + -0.0, + -0.0 + ] + }, + { + "name": "LegL.RecessRam1", + "barrel_bone": "LegL.RecessRam1.barrel", + "rod_bone": "LegL.RecessRam1.rod", + "spans": [ + "LegL.Oleo", + "LegL.Foot" + ], + "bore": 0.09, + "body": 0.664775, + "inner": 0.8131586697281079, + "extension": 0.407443, + "rest": 1.3782174197281079, + "stroke": [ + -0.407443, + 0.514775 + ], + "a_parent_dof": 2, + "a_pos": [ + 1.2509, + 2.117333, + -0.202422 + ], + "b_parent_dof": 4, + "b_pos": [ + 1.2509, + 0.745732, + -0.337304 + ], + "pin_dir": [ + 1.0, + -0.0, + -0.0 + ] + }, + { + "name": "LegR.RecessRam0", + "barrel_bone": "LegR.RecessRam0.barrel", + "rod_bone": "LegR.RecessRam0.rod", + "spans": [ + "LegR.Oleo", + "LegR.Foot" + ], + "bore": 0.09, + "body": 0.684197, + "inner": 0.8279768098379127, + "extension": 0.419347, + "rest": 1.4095442598379126, + "stroke": [ + -0.419347, + 0.534197 + ], + "a_parent_dof": 15, + "a_pos": [ + -1.2509, + 2.127887, + -0.433941 + ], + "b_parent_dof": 17, + "b_pos": [ + -1.2509, + 0.745731, + -0.710458 + ], + "pin_dir": [ + 1.0, + 0.0, + -0.0 + ] + }, + { + "name": "LegR.RecessRam1", + "barrel_bone": "LegR.RecessRam1.barrel", + "rod_bone": "LegR.RecessRam1.rod", + "spans": [ + "LegR.Oleo", + "LegR.Foot" + ], + "bore": 0.09, + "body": 0.684197, + "inner": 0.8279768098379127, + "extension": 0.419347, + "rest": 1.4095442598379126, + "stroke": [ + -0.419347, + 0.534197 + ], + "a_parent_dof": 15, + "a_pos": [ + -0.9109, + 2.127887, + -0.433941 + ], + "b_parent_dof": 17, + "b_pos": [ + -0.9109, + 0.745731, + -0.710458 + ], + "pin_dir": [ + 1.0, + 0.0, + -0.0 + ] + } + ], + "scissors": [ + { + "name": "LegL.Torque", + "upper_bone": "LegL.Torque.upper", + "lower_bone": "LegL.Torque.lower", + "arm": 0.3087611656677239, + "a_parent_dof": 2, + "a_pos": [ + 1.0809, + 1.240598, + 0.44059 + ], + "b_parent_dof": 3, + "b_pos": [ + 1.0809, + 0.757042, + 0.32151 + ], + "out_dir": [ + 0.0, + -0.239116, + 0.970991 + ] + }, + { + "name": "LegR.Torque", + "upper_bone": "LegR.Torque.upper", + "lower_bone": "LegR.Torque.lower", + "arm": 0.30876125639651403, + "a_parent_dof": 15, + "a_pos": [ + -1.0809, + 1.194391, + 0.123477 + ], + "b_parent_dof": 16, + "b_pos": [ + -1.0809, + 0.724229, + -0.040697 + ], + "out_dir": [ + 0.0, + -0.329667, + 0.944097 + ] + } + ], + "struts": [ + { + "name": "LegL.Oleo", + "side": "L", + "dof": "LegL.Oleo", + "travel": 0.2, + "hertz": 1.6, + "damping_ratio": 0.45 + }, + { + "name": "LegR.Oleo", + "side": "R", + "dof": "LegR.Oleo", + "travel": 0.2, + "hertz": 1.6, + "damping_ratio": 0.45 + } + ] + } +} diff --git a/assets/vehicles/breaker/vehicle.cc b/assets/vehicles/breaker/vehicle.cc new file mode 100644 index 0000000..e6e6c58 Binary files /dev/null and b/assets/vehicles/breaker/vehicle.cc differ diff --git a/assets/vehicles/condor/condor.glb b/assets/vehicles/condor/condor.glb new file mode 100644 index 0000000..692968b Binary files /dev/null and b/assets/vehicles/condor/condor.glb differ diff --git a/assets/vehicles/condor/manifest.json b/assets/vehicles/condor/manifest.json new file mode 100644 index 0000000..8b056e5 --- /dev/null +++ b/assets/vehicles/condor/manifest.json @@ -0,0 +1,225 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "condor", + "name": "Condor", + "class": "Heavy Quad-Thruster Assault VTOL", + "plane": "Dorsal", + "gridWidth": 5, + "gridHeight": 6, + "mask": [ + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + false, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.nose", + "kind": "weapon", + "x": 1, + "y": 0, + "w": 2, + "h": 1, + "modelNodeId": "hp.weapon.nose" + }, + { + "id": "hp.armor.hull", + "kind": "armor", + "x": 3, + "y": 0, + "w": 1, + "h": 1, + "modelNodeId": "hp.armor.hull" + }, + { + "id": "hp.weapon.sponson_l", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.sponson_l" + }, + { + "id": "hp.weapon.dorsal", + "kind": "weapon", + "x": 2, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.dorsal" + }, + { + "id": "hp.weapon.sponson_r", + "kind": "weapon", + "x": 4, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.sponson_r" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 1, + "y": 2, + "w": 3, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.radiator.spine_l", + "kind": "radiator", + "x": 0, + "y": 3, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.spine_l" + }, + { + "id": "hp.radiator.spine_r", + "kind": "radiator", + "x": 4, + "y": 3, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.spine_r" + } + ], + "joints": [ + { + "id": "joint.nacelle_fl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_fl", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.nacelle_fr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_fr", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.nacelle_rl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_rl", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.nacelle_rr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_rr", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -2.3586, + 0.0, + -3.1 + ], + "max": [ + 2.3586, + 2.2046, + 2.7758 + ], + "size": [ + 4.7172, + 2.2046, + 5.8758 + ] + }, + "triCount": 12960 +} diff --git a/assets/vehicles/condor/vehicle.cc b/assets/vehicles/condor/vehicle.cc new file mode 100644 index 0000000..ba2ef62 Binary files /dev/null and b/assets/vehicles/condor/vehicle.cc differ diff --git a/assets/vehicles/ferret/ferret.glb b/assets/vehicles/ferret/ferret.glb new file mode 100644 index 0000000..e2bd6ea Binary files /dev/null and b/assets/vehicles/ferret/ferret.glb differ diff --git a/assets/vehicles/ferret/manifest.json b/assets/vehicles/ferret/manifest.json new file mode 100644 index 0000000..77052ab --- /dev/null +++ b/assets/vehicles/ferret/manifest.json @@ -0,0 +1,100 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "ferret", + "name": "Ferret", + "class": "Light Tracked Scout Tankette", + "plane": "Dorsal", + "gridWidth": 3, + "gridHeight": 4, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.armor.glacis", + "kind": "armor", + "x": 0, + "y": 0, + "w": 3, + "h": 1, + "modelNodeId": "hp.armor.glacis" + }, + { + "id": "hp.weapon.pod", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.pod" + }, + { + "id": "hp.weapon.turret", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.turret" + }, + { + "id": "hp.engine.rear", + "kind": "engine", + "x": 2, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.rear" + }, + { + "id": "hp.radiator.deck", + "kind": "radiator", + "x": 1, + "y": 3, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.deck" + } + ], + "joints": [ + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -1.1075, + 0.0, + -1.8009 + ], + "max": [ + 1.1075, + 1.5523, + 1.869 + ], + "size": [ + 2.215, + 1.5523, + 3.6699 + ] + }, + "triCount": 7612 +} diff --git a/assets/vehicles/ferret/vehicle.cc b/assets/vehicles/ferret/vehicle.cc new file mode 100644 index 0000000..d2a9452 Binary files /dev/null and b/assets/vehicles/ferret/vehicle.cc differ diff --git a/assets/vehicles/hornet/hornet.glb b/assets/vehicles/hornet/hornet.glb new file mode 100644 index 0000000..abc6a71 Binary files /dev/null and b/assets/vehicles/hornet/hornet.glb differ diff --git a/assets/vehicles/hornet/manifest.json b/assets/vehicles/hornet/manifest.json new file mode 100644 index 0000000..bfe246a --- /dev/null +++ b/assets/vehicles/hornet/manifest.json @@ -0,0 +1,143 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "hornet", + "name": "Hornet", + "class": "Light Ducted-Fan VTOL Gunship", + "plane": "Dorsal", + "gridWidth": 4, + "gridHeight": 4, + "mask": [ + false, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.chin", + "kind": "weapon", + "x": 1, + "y": 0, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.chin" + }, + { + "id": "hp.radiator.nacelle_l", + "kind": "radiator", + "x": 0, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.nacelle_l" + }, + { + "id": "hp.radiator.nacelle_r", + "kind": "radiator", + "x": 3, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.nacelle_r" + }, + { + "id": "hp.weapon.wing_l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.wing_l" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 1, + "y": 2, + "w": 2, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.weapon.wing_r", + "kind": "weapon", + "x": 3, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.wing_r" + } + ], + "joints": [ + { + "id": "joint.nacelle_l", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_l", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.nacelle_r", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 75.0 + }, + { + "id": "joint.rotor_r", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + } + ], + "bounds": { + "min": [ + -1.65, + -0.0, + -2.6715 + ], + "max": [ + 1.65, + 1.8235, + 2.0 + ], + "size": [ + 3.3, + 1.8235, + 4.6715 + ] + }, + "triCount": 7252 +} diff --git a/assets/vehicles/hornet/vehicle.cc b/assets/vehicles/hornet/vehicle.cc new file mode 100644 index 0000000..e3321d1 Binary files /dev/null and b/assets/vehicles/hornet/vehicle.cc differ diff --git a/assets/vehicles/ironclad/ironclad.glb b/assets/vehicles/ironclad/ironclad.glb new file mode 100644 index 0000000..e7a9470 Binary files /dev/null and b/assets/vehicles/ironclad/ironclad.glb differ diff --git a/assets/vehicles/ironclad/manifest.json b/assets/vehicles/ironclad/manifest.json new file mode 100644 index 0000000..f3b5bfa --- /dev/null +++ b/assets/vehicles/ironclad/manifest.json @@ -0,0 +1,126 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "ironclad", + "name": "Ironclad", + "class": "Medium Tracked Battle Tank", + "plane": "Dorsal", + "gridWidth": 4, + "gridHeight": 5, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.armor.front", + "kind": "armor", + "x": 0, + "y": 0, + "w": 4, + "h": 1, + "modelNodeId": "hp.armor.front" + }, + { + "id": "hp.weapon.coax", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.coax" + }, + { + "id": "hp.weapon.main", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 2, + "h": 2, + "modelNodeId": "hp.weapon.main" + }, + { + "id": "hp.armor.skirts", + "kind": "armor", + "x": 3, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.armor.skirts" + }, + { + "id": "hp.radiator.l", + "kind": "radiator", + "x": 0, + "y": 3, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.l" + }, + { + "id": "hp.engine.rear", + "kind": "engine", + "x": 1, + "y": 3, + "w": 2, + "h": 2, + "modelNodeId": "hp.engine.rear" + }, + { + "id": "hp.radiator.r", + "kind": "radiator", + "x": 3, + "y": 3, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.r" + } + ], + "joints": [ + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -1.5272, + 0.0, + -2.4115 + ], + "max": [ + 1.4934, + 1.792, + 2.3554 + ], + "size": [ + 3.0206, + 1.792, + 4.7669 + ] + }, + "triCount": 16840 +} diff --git a/assets/vehicles/ironclad/vehicle.cc b/assets/vehicles/ironclad/vehicle.cc new file mode 100644 index 0000000..b121484 Binary files /dev/null and b/assets/vehicles/ironclad/vehicle.cc differ diff --git a/assets/vehicles/jackal/jackal.glb b/assets/vehicles/jackal/jackal.glb new file mode 100644 index 0000000..73444df Binary files /dev/null and b/assets/vehicles/jackal/jackal.glb differ diff --git a/assets/vehicles/jackal/manifest.json b/assets/vehicles/jackal/manifest.json new file mode 100644 index 0000000..fc9934c --- /dev/null +++ b/assets/vehicles/jackal/manifest.json @@ -0,0 +1,132 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "jackal", + "name": "Jackal", + "class": "Light Wheeled Dune Buggy", + "plane": "Dorsal", + "gridWidth": 3, + "gridHeight": 4, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.weapon.roof", + "kind": "weapon", + "x": 1, + "y": 0, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.roof" + }, + { + "id": "hp.engine.rear", + "kind": "engine", + "x": 1, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.rear" + }, + { + "id": "hp.radiator.rear", + "kind": "radiator", + "x": 2, + "y": 3, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.rear" + } + ], + "joints": [ + { + "id": "joint.steer_fl", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -32.0, + "max": 32.0 + }, + { + "id": "joint.wheel_fl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.steer_fr", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -32.0, + "max": 32.0 + }, + { + "id": "joint.wheel_fr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + } + ], + "bounds": { + "min": [ + -0.9778, + 0.0, + -1.5461 + ], + "max": [ + 0.9778, + 1.5457, + 1.705 + ], + "size": [ + 1.9556, + 1.5457, + 3.2511 + ] + }, + "triCount": 16068 +} diff --git a/assets/vehicles/jackal/vehicle.cc b/assets/vehicles/jackal/vehicle.cc new file mode 100644 index 0000000..86378ee Binary files /dev/null and b/assets/vehicles/jackal/vehicle.cc differ diff --git a/assets/vehicles/kestrel/kestrel.glb b/assets/vehicles/kestrel/kestrel.glb new file mode 100644 index 0000000..284a261 Binary files /dev/null and b/assets/vehicles/kestrel/kestrel.glb differ diff --git a/assets/vehicles/kestrel/manifest.json b/assets/vehicles/kestrel/manifest.json new file mode 100644 index 0000000..41c8428 --- /dev/null +++ b/assets/vehicles/kestrel/manifest.json @@ -0,0 +1,133 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "kestrel", + "name": "Kestrel", + "class": "Light Scout Biped", + "plane": "Coronal", + "gridWidth": 5, + "gridHeight": 5, + "mask": [ + false, + false, + true, + false, + false, + false, + true, + true, + true, + false, + false, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + true, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.dorsal", + "kind": "weapon", + "x": 2, + "y": 0, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.dorsal" + }, + { + "id": "hp.armor.chest", + "kind": "armor", + "x": 2, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.armor.chest" + }, + { + "id": "hp.radiator.back", + "kind": "radiator", + "x": 1, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 2, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.weapon.arm_r", + "kind": "weapon", + "x": 4, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_r" + } + ], + "joints": [ + { + "id": "joint.torso_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -90.0, + "max": 90.0 + }, + { + "id": "joint.arm_l_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + }, + { + "id": "joint.arm_r_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + } + ], + "bounds": { + "min": [ + -2.6628, + 0.0, + -2.0753 + ], + "max": [ + 2.6048, + 9.7815, + 2.378 + ], + "size": [ + 5.2676, + 9.7815, + 4.4533 + ] + }, + "triCount": 41374 +} diff --git a/assets/vehicles/kestrel/vehicle.cc b/assets/vehicles/kestrel/vehicle.cc new file mode 100644 index 0000000..f3734f4 Binary files /dev/null and b/assets/vehicles/kestrel/vehicle.cc differ diff --git a/assets/vehicles/mammoth/mammoth.glb b/assets/vehicles/mammoth/mammoth.glb new file mode 100644 index 0000000..32427a5 Binary files /dev/null and b/assets/vehicles/mammoth/mammoth.glb differ diff --git a/assets/vehicles/mammoth/manifest.json b/assets/vehicles/mammoth/manifest.json new file mode 100644 index 0000000..c57615a --- /dev/null +++ b/assets/vehicles/mammoth/manifest.json @@ -0,0 +1,259 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "mammoth", + "name": "Mammoth", + "class": "Heavy 8x8 Armored Fire Support Rig", + "plane": "Dorsal", + "gridWidth": 4, + "gridHeight": 6, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.armor.glacis", + "kind": "armor", + "x": 0, + "y": 0, + "w": 4, + "h": 1, + "modelNodeId": "hp.armor.glacis" + }, + { + "id": "hp.weapon.bow", + "kind": "weapon", + "x": 0, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.bow" + }, + { + "id": "hp.weapon.turret_l", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.turret_l" + }, + { + "id": "hp.weapon.turret_r", + "kind": "weapon", + "x": 2, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.turret_r" + }, + { + "id": "hp.armor.flanks", + "kind": "armor", + "x": 3, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.armor.flanks" + }, + { + "id": "hp.engine.rear", + "kind": "engine", + "x": 1, + "y": 3, + "w": 2, + "h": 2, + "modelNodeId": "hp.engine.rear" + }, + { + "id": "hp.radiator.l", + "kind": "radiator", + "x": 0, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.l" + }, + { + "id": "hp.radiator.r", + "kind": "radiator", + "x": 3, + "y": 4, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.r" + } + ], + "joints": [ + { + "id": "joint.steer_fl1", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -28.0, + "max": 28.0 + }, + { + "id": "joint.wheel_fl1", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.steer_fr1", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -28.0, + "max": 28.0 + }, + { + "id": "joint.wheel_fr1", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.steer_fl2", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -28.0, + "max": 28.0 + }, + { + "id": "joint.wheel_fl2", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.steer_fr2", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -28.0, + "max": 28.0 + }, + { + "id": "joint.wheel_fr2", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rl1", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rr1", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rl2", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rr2", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.turret_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -180.0, + "max": 180.0 + } + ], + "bounds": { + "min": [ + -1.46, + 0.0, + -2.64 + ], + "max": [ + 1.46, + 2.3467, + 3.2249 + ], + "size": [ + 2.92, + 2.3467, + 5.8649 + ] + }, + "triCount": 20512 +} diff --git a/assets/vehicles/mammoth/vehicle.cc b/assets/vehicles/mammoth/vehicle.cc new file mode 100644 index 0000000..00c244d Binary files /dev/null and b/assets/vehicles/mammoth/vehicle.cc differ diff --git a/assets/vehicles/manticore/manifest.json b/assets/vehicles/manticore/manifest.json new file mode 100644 index 0000000..d47831b --- /dev/null +++ b/assets/vehicles/manticore/manifest.json @@ -0,0 +1,171 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "manticore", + "name": "Manticore", + "class": "Heavy Quadruped Scorpion", + "plane": "Dorsal", + "gridWidth": 5, + "gridHeight": 5, + "mask": [ + true, + true, + true, + true, + true, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + true, + true, + true, + false, + true, + false, + true, + false, + true + ], + "hardpoints": [ + { + "id": "hp.weapon.chin", + "kind": "weapon", + "x": 2, + "y": 0, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.chin" + }, + { + "id": "hp.radiator.flank_l", + "kind": "radiator", + "x": 1, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.flank_l" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 2, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.radiator.flank_r", + "kind": "radiator", + "x": 3, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.flank_r" + }, + { + "id": "hp.weapon.l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.l" + }, + { + "id": "hp.weapon.r", + "kind": "weapon", + "x": 4, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.r" + }, + { + "id": "hp.armor.prow", + "kind": "armor", + "x": 2, + "y": 3, + "w": 1, + "h": 1, + "modelNodeId": "hp.armor.prow" + } + ], + "joints": [ + { + "id": "joint.tail_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -75.0, + "max": 75.0 + }, + { + "id": "joint.tail_s1", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -60.0, + "max": 60.0 + }, + { + "id": "joint.tail_s2", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -75.0, + "max": 15.0 + }, + { + "id": "joint.tail_s3", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -80.0, + "max": 10.0 + }, + { + "id": "joint.tail_elev", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -40.0, + "max": 30.0 + } + ], + "bounds": { + "min": [ + -3.4374, + 0.0, + -4.5621 + ], + "max": [ + 3.4358, + 6.5001, + 4.547 + ], + "size": [ + 6.8732, + 6.5001, + 9.1091 + ] + }, + "triCount": 33517 +} diff --git a/assets/vehicles/manticore/manticore.glb b/assets/vehicles/manticore/manticore.glb new file mode 100644 index 0000000..57c7313 Binary files /dev/null and b/assets/vehicles/manticore/manticore.glb differ diff --git a/assets/vehicles/manticore/vehicle.cc b/assets/vehicles/manticore/vehicle.cc new file mode 100644 index 0000000..d740b50 Binary files /dev/null and b/assets/vehicles/manticore/vehicle.cc differ diff --git a/assets/vehicles/mule/manifest.json b/assets/vehicles/mule/manifest.json new file mode 100644 index 0000000..a646428 --- /dev/null +++ b/assets/vehicles/mule/manifest.json @@ -0,0 +1,182 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "mule", + "name": "Mule", + "class": "Medium 6x6 Armored Gun Truck", + "plane": "Dorsal", + "gridWidth": 3, + "gridHeight": 5, + "mask": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "hardpoints": [ + { + "id": "hp.armor.front", + "kind": "armor", + "x": 0, + "y": 0, + "w": 3, + "h": 1, + "modelNodeId": "hp.armor.front" + }, + { + "id": "hp.radiator.left", + "kind": "radiator", + "x": 0, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.left" + }, + { + "id": "hp.engine.front", + "kind": "engine", + "x": 1, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.front" + }, + { + "id": "hp.radiator.right", + "kind": "radiator", + "x": 2, + "y": 1, + "w": 1, + "h": 2, + "modelNodeId": "hp.radiator.right" + }, + { + "id": "hp.weapon.cab", + "kind": "weapon", + "x": 0, + "y": 3, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.cab" + }, + { + "id": "hp.weapon.bed_main", + "kind": "weapon", + "x": 1, + "y": 3, + "w": 2, + "h": 2, + "modelNodeId": "hp.weapon.bed_main" + } + ], + "joints": [ + { + "id": "joint.steer_fl", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -30.0, + "max": 30.0 + }, + { + "id": "joint.wheel_fl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.steer_fr", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -30.0, + "max": 30.0 + }, + { + "id": "joint.wheel_fr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_ml", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_mr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rl", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + }, + { + "id": "joint.wheel_rr", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -360.0, + "max": 360.0 + } + ], + "bounds": { + "min": [ + -1.1938, + 0.0, + -2.4067 + ], + "max": [ + 1.1938, + 2.0889, + 2.46 + ], + "size": [ + 2.3876, + 2.0889, + 4.8667 + ] + }, + "triCount": 13772 +} diff --git a/assets/vehicles/mule/mule.glb b/assets/vehicles/mule/mule.glb new file mode 100644 index 0000000..8f82821 Binary files /dev/null and b/assets/vehicles/mule/mule.glb differ diff --git a/assets/vehicles/mule/vehicle.cc b/assets/vehicles/mule/vehicle.cc new file mode 100644 index 0000000..043b8f1 Binary files /dev/null and b/assets/vehicles/mule/vehicle.cc differ diff --git a/assets/vehicles/paladin/manifest.json b/assets/vehicles/paladin/manifest.json new file mode 100644 index 0000000..dd6df5f --- /dev/null +++ b/assets/vehicles/paladin/manifest.json @@ -0,0 +1,186 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "paladin", + "name": "Paladin", + "class": "Heavy Assault Biped", + "plane": "Coronal", + "gridWidth": 6, + "gridHeight": 7, + "mask": [ + false, + false, + true, + true, + false, + false, + false, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + false, + true, + false, + false, + true, + false, + false, + true, + false, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.sh_l", + "kind": "weapon", + "x": 1, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.sh_l" + }, + { + "id": "hp.armor.torso", + "kind": "armor", + "x": 2, + "y": 1, + "w": 2, + "h": 1, + "modelNodeId": "hp.armor.torso" + }, + { + "id": "hp.weapon.sh_r", + "kind": "weapon", + "x": 4, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.sh_r" + }, + { + "id": "hp.weapon.arm_l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_l" + }, + { + "id": "hp.engine.chest", + "kind": "engine", + "x": 2, + "y": 2, + "w": 2, + "h": 2, + "modelNodeId": "hp.engine.chest" + }, + { + "id": "hp.weapon.arm_r", + "kind": "weapon", + "x": 5, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_r" + }, + { + "id": "hp.radiator.back_l", + "kind": "radiator", + "x": 1, + "y": 4, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_l" + }, + { + "id": "hp.armor.legs", + "kind": "armor", + "x": 2, + "y": 4, + "w": 2, + "h": 1, + "modelNodeId": "hp.armor.legs" + }, + { + "id": "hp.radiator.back_r", + "kind": "radiator", + "x": 4, + "y": 4, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_r" + } + ], + "joints": [ + { + "id": "joint.torso_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -90.0, + "max": 90.0 + }, + { + "id": "joint.arm_l_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -40.0, + "max": 70.0 + }, + { + "id": "joint.arm_r_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -40.0, + "max": 70.0 + } + ], + "bounds": { + "min": [ + -4.4388, + -0.0, + -1.5109 + ], + "max": [ + 4.4387, + 11.3161, + 2.4514 + ], + "size": [ + 8.8775, + 11.3161, + 3.9623 + ] + }, + "triCount": 36463 +} diff --git a/assets/vehicles/paladin/paladin.glb b/assets/vehicles/paladin/paladin.glb new file mode 100644 index 0000000..5a0c2ab Binary files /dev/null and b/assets/vehicles/paladin/paladin.glb differ diff --git a/assets/vehicles/paladin/vehicle.cc b/assets/vehicles/paladin/vehicle.cc new file mode 100644 index 0000000..460cd19 Binary files /dev/null and b/assets/vehicles/paladin/vehicle.cc differ diff --git a/assets/vehicles/raptor/manifest.json b/assets/vehicles/raptor/manifest.json new file mode 100644 index 0000000..29f6590 --- /dev/null +++ b/assets/vehicles/raptor/manifest.json @@ -0,0 +1,128 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "raptor", + "name": "Raptor", + "class": "Medium Theropod Biped", + "plane": "Coronal", + "gridWidth": 5, + "gridHeight": 6, + "mask": [ + false, + false, + true, + false, + false, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + false, + true, + false, + true, + false, + true, + false, + true, + false, + false, + true, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.radiator.sh_l", + "kind": "radiator", + "x": 1, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.sh_l" + }, + { + "id": "hp.radiator.sh_r", + "kind": "radiator", + "x": 3, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.sh_r" + }, + { + "id": "hp.weapon.arm_l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_l" + }, + { + "id": "hp.engine.chest", + "kind": "engine", + "x": 2, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.chest" + }, + { + "id": "hp.weapon.arm_r", + "kind": "weapon", + "x": 4, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_r" + } + ], + "joints": [ + { + "id": "joint.arm_l_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 45.0 + }, + { + "id": "joint.arm_r_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 45.0 + } + ], + "bounds": { + "min": [ + -2.3822, + 0.0, + -4.422 + ], + "max": [ + 2.3822, + 6.9873, + 4.5553 + ], + "size": [ + 4.7644, + 6.9873, + 8.9773 + ] + }, + "triCount": 36156 +} diff --git a/assets/vehicles/raptor/raptor.glb b/assets/vehicles/raptor/raptor.glb new file mode 100644 index 0000000..36a4b9e Binary files /dev/null and b/assets/vehicles/raptor/raptor.glb differ diff --git a/assets/vehicles/raptor/vehicle.cc b/assets/vehicles/raptor/vehicle.cc new file mode 100644 index 0000000..faa2ec4 Binary files /dev/null and b/assets/vehicles/raptor/vehicle.cc differ diff --git a/assets/vehicles/spectre/manifest.json b/assets/vehicles/spectre/manifest.json new file mode 100644 index 0000000..83922ea --- /dev/null +++ b/assets/vehicles/spectre/manifest.json @@ -0,0 +1,156 @@ +{ + "schema": "rtd.vehicle.manifest.v1", + "id": "spectre", + "name": "Spectre", + "class": "Medium Recon/Skirmisher Biped", + "plane": "Coronal", + "gridWidth": 5, + "gridHeight": 6, + "mask": [ + false, + true, + false, + false, + false, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + false, + true, + false, + false, + true, + false, + true, + false + ], + "hardpoints": [ + { + "id": "hp.weapon.shoulder_l", + "kind": "weapon", + "x": 1, + "y": 0, + "w": 1, + "h": 1, + "modelNodeId": "hp.weapon.shoulder_l" + }, + { + "id": "hp.armor.torso", + "kind": "armor", + "x": 2, + "y": 1, + "w": 1, + "h": 1, + "modelNodeId": "hp.armor.torso" + }, + { + "id": "hp.weapon.arm_l", + "kind": "weapon", + "x": 0, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_l" + }, + { + "id": "hp.radiator.back_l", + "kind": "radiator", + "x": 1, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_l" + }, + { + "id": "hp.engine.core", + "kind": "engine", + "x": 2, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.engine.core" + }, + { + "id": "hp.radiator.back_r", + "kind": "radiator", + "x": 3, + "y": 2, + "w": 1, + "h": 1, + "modelNodeId": "hp.radiator.back_r" + }, + { + "id": "hp.weapon.arm_r", + "kind": "weapon", + "x": 4, + "y": 2, + "w": 1, + "h": 2, + "modelNodeId": "hp.weapon.arm_r" + } + ], + "joints": [ + { + "id": "joint.torso_yaw", + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "min": -90.0, + "max": 90.0 + }, + { + "id": "joint.arm_l_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + }, + { + "id": "joint.arm_r_pitch", + "axis": [ + 1.0, + 0.0, + 0.0 + ], + "min": -45.0, + "max": 60.0 + } + ], + "bounds": { + "min": [ + -3.4467, + -0.0, + -2.442 + ], + "max": [ + 3.8332, + 8.9891, + 3.6426 + ], + "size": [ + 7.2799, + 8.9891, + 6.0846 + ] + }, + "triCount": 40696 +} diff --git a/assets/vehicles/spectre/spectre.glb b/assets/vehicles/spectre/spectre.glb new file mode 100644 index 0000000..112cd17 Binary files /dev/null and b/assets/vehicles/spectre/spectre.glb differ diff --git a/assets/vehicles/spectre/vehicle.cc b/assets/vehicles/spectre/vehicle.cc new file mode 100644 index 0000000..831aaeb Binary files /dev/null and b/assets/vehicles/spectre/vehicle.cc differ diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs new file mode 100644 index 0000000..b92468e --- /dev/null +++ b/client/ArenaRenderer.cs @@ -0,0 +1,761 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +/// +/// Renders the 3D arena entities from : +/// cover ruins, shrinking Safe Circle ring, real Brokkr vehicle/mech GLBs with hardpoint snap-on gear, +/// live secondary mechanism animations, part-by-cell debris detachment, 3 alien spectator tiers + status halos/lock lasers, +/// real gear/chassis salvage drops, and weapon tracers. +/// +public partial class ArenaRenderer : Node3D +{ + private static readonly Color OlivePaint = Color.FromHtml("#9bb06a"); + private static readonly Color TouristGold = Color.FromHtml("#e6b838"); + private static readonly Color CyanSalvage = Color.FromHtml("#44d9e8"); + private static readonly Color CoverRust = Color.FromHtml("#4d433b"); + private static readonly Color BermDark = Color.FromHtml("#2c2723"); + + private sealed class ActorVisual + { + public required VehicleVisualInstance Visual; + public MeshInstance3D? HaloMesh; + public StandardMaterial3D? HaloMat; + public MeshInstance3D? LaserMesh; + public SpectatorStance? LastHaloStance; + public bool LastLaserVisible; + } + + private sealed class DropVisualEntry + { + public required Node3D Node; + public VehicleVisualInstance? ChassisVisual; + public float BaseY; + public int TileX; + public int TileZ; + public int TileVersion; + } + + private VehicleAssetCache _assetCache = null!; + private Node3D _staticGroup = null!; + private Node3D _actorsGroup = null!; + private Node3D _dropsGroup = null!; + private Node3D _tracersGroup = null!; + private DebrisSystem _debris = null!; + private MeshInstance3D _safeRingMesh = null!; + private ImmediateMesh _safeRingImm = null!; + + private readonly Dictionary _contenderVisuals = new(); + private readonly Dictionary _spectatorVisuals = new(); + private readonly Dictionary _dropVisuals = new(); + private readonly List _tracerPool = new(); + + private StandardMaterial3D _safeRingMat = null!; + private StandardMaterial3D _coverMat = null!; + private StandardMaterial3D _bermMat = null!; + private StandardMaterial3D _humanBeaconMat = null!; + private StandardMaterial3D _imperialBeaconMat = null!; + private StandardMaterial3D _cyanBeaconMat = null!; + private MatchState? _builtForState; + private float _lastSafeRingRadius = -1f; + + public VehicleAssetCache AssetCache => _assetCache; + public DebrisSystem Debris => _debris; + + public VehicleVisualInstance? GetContenderVisual(int contenderId) => + _contenderVisuals.TryGetValue(contenderId, out var vis) ? vis.Visual : null; + + public VehicleVisualInstance? GetSpectatorVisual(int spectatorId) => + _spectatorVisuals.TryGetValue(spectatorId, out var vis) ? vis.Visual : null; + + internal float? GetSpectatorHaloLocalY(int spectatorId) => + _spectatorVisuals.TryGetValue(spectatorId, out var vis) && vis.HaloMesh is not null + ? vis.HaloMesh.Position.Y + : null; + + internal int ActiveDropVisualCount => _dropVisuals.Count; + internal int DropGroupChildCount => _dropsGroup.GetChildCount(); + + public override void _Ready() + { + _assetCache = new VehicleAssetCache(); + + _staticGroup = new Node3D { Name = "StaticArena" }; + _actorsGroup = new Node3D { Name = "Actors" }; + _dropsGroup = new Node3D { Name = "GroundDrops" }; + _tracersGroup = new Node3D { Name = "Tracers" }; + _debris = new DebrisSystem { Name = "Debris" }; + AddChild(_staticGroup); + AddChild(_actorsGroup); + AddChild(_dropsGroup); + AddChild(_tracersGroup); + AddChild(_debris); + + _coverMat = new StandardMaterial3D { AlbedoColor = CoverRust, Roughness = 0.88f, Metallic = 0.25f }; + _bermMat = new StandardMaterial3D { AlbedoColor = BermDark, Roughness = 0.94f, Metallic = 0.1f }; + _humanBeaconMat = new StandardMaterial3D + { + AlbedoColor = new Color(OlivePaint.R, OlivePaint.G, OlivePaint.B, 0.72f), + Roughness = 0.55f, + Metallic = 0.35f, + EmissionEnabled = true, + Emission = OlivePaint, + EmissionEnergyMultiplier = 0.6f, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }; + _imperialBeaconMat = new StandardMaterial3D + { + AlbedoColor = new Color(TouristGold.R, TouristGold.G, TouristGold.B, 0.82f), + Roughness = 0.35f, + Metallic = 0.8f, + EmissionEnabled = true, + Emission = TouristGold, + EmissionEnergyMultiplier = 1.4f, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }; + _cyanBeaconMat = new StandardMaterial3D + { + AlbedoColor = new Color(CyanSalvage.R, CyanSalvage.G, CyanSalvage.B, 0.72f), + EmissionEnabled = true, + Emission = CyanSalvage, + EmissionEnergyMultiplier = 1.5f, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }; + + _safeRingImm = new ImmediateMesh(); + _safeRingMat = new StandardMaterial3D + { + AlbedoColor = new Color(1.0f, 0.38f, 0.14f, 0.78f), + EmissionEnabled = true, + Emission = new Color(1.0f, 0.32f, 0.08f), + EmissionEnergyMultiplier = 1.6f, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha, + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + CullMode = BaseMaterial3D.CullModeEnum.Disabled + }; + _safeRingMesh = new MeshInstance3D + { + Name = "SafeRing", + Mesh = _safeRingImm, + MaterialOverride = _safeRingMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + AddChild(_safeRingMesh); + } + + public override void _ExitTree() + { + _assetCache?.Dispose(); + } + + public void Sync(ArenaSession session, float elapsedSeconds, float dt = 1f / 60f) + { + var state = session.State; + if (!ReferenceEquals(_builtForState, state)) + { + RebuildStaticArena(state); + ClearDynamicVisuals(); + _builtForState = state; + } + + Camera3D? cam = GetViewport()?.GetCamera3D(); + bool hasCam = cam is not null && cam.IsInsideTree(); + Vector3 camPos = hasCam ? cam!.GlobalPosition : Vector3.Zero; + + UpdateSafeCircleRing(state.Terrain, state.Spectators.SafeRadius); + SyncContenders(session, dt, hasCam, camPos); + SyncSpectators(session, elapsedSeconds, dt, hasCam, camPos); + SyncGroundDrops(state, elapsedSeconds, hasCam, camPos); + SyncTracers(state.Tracers); + _debris.Step(dt, state.Terrain); + } + + private void RebuildStaticArena(MatchState state) + { + ClearChildren(_staticGroup); + + for (int i = 0; i < state.ArenaCoverBoxes.Count; i++) + { + var b = state.ArenaCoverBoxes[i]; + var mesh = new MeshInstance3D + { + Mesh = new BoxMesh { Size = new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f) }, + MaterialOverride = _coverMat, + Position = new Vector3(b.X, b.Y, b.Z) + }; + _staticGroup.AddChild(mesh); + } + + for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++) + { + var b = state.ArenaBoundaryBoxes[i]; + var mesh = new MeshInstance3D + { + Mesh = new BoxMesh { Size = new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f) }, + MaterialOverride = _bermMat, + Position = new Vector3(b.X, b.Y, b.Z), + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + _staticGroup.AddChild(mesh); + } + } + + private void ClearDynamicVisuals() + { + ClearChildren(_actorsGroup); + ClearChildren(_dropsGroup); + _debris.ClearAll(); + _contenderVisuals.Clear(); + _spectatorVisuals.Clear(); + _dropVisuals.Clear(); + _lastSafeRingRadius = -1f; + } + + private void UpdateSafeCircleRing(TerrainField terrain, float safeRadius) + { + if (_lastSafeRingRadius >= 0f && MathF.Abs(safeRadius - _lastSafeRingRadius) < 0.15f) + { + return; + } + _lastSafeRingRadius = safeRadius; + + _safeRingImm.ClearSurfaces(); + _safeRingImm.SurfaceBegin(Mesh.PrimitiveType.Triangles); + + const int segments = 160; + const float halfThick = 1.1f; + float rInner = MathF.Max(2f, safeRadius - halfThick); + float rOuter = safeRadius + halfThick; + + for (int i = 0; i < segments; i++) + { + float a0 = (i / (float)segments) * MathF.Tau; + float a1 = ((i + 1) / (float)segments) * MathF.Tau; + float c0 = MathF.Cos(a0), s0 = MathF.Sin(a0); + float c1 = MathF.Cos(a1), s1 = MathF.Sin(a1); + + float x0i = c0 * rInner, z0i = s0 * rInner; + float x0o = c0 * rOuter, z0o = s0 * rOuter; + float x1i = c1 * rInner, z1i = s1 * rInner; + float x1o = c1 * rOuter, z1o = s1 * rOuter; + + float y0 = terrain.SampleHeight(c0 * safeRadius, s0 * safeRadius) + 0.42f; + float y1 = terrain.SampleHeight(c1 * safeRadius, s1 * safeRadius) + 0.42f; + + var p0i = new Vector3(x0i, y0, z0i); + var p0o = new Vector3(x0o, y0, z0o); + var p1i = new Vector3(x1i, y1, z1i); + var p1o = new Vector3(x1o, y1, z1o); + + _safeRingImm.SurfaceAddVertex(p0i); + _safeRingImm.SurfaceAddVertex(p0o); + _safeRingImm.SurfaceAddVertex(p1o); + + _safeRingImm.SurfaceAddVertex(p0i); + _safeRingImm.SurfaceAddVertex(p1o); + _safeRingImm.SurfaceAddVertex(p1i); + } + + _safeRingImm.SurfaceEnd(); + } + + private void SyncContenders(ArenaSession session, float dt, bool hasCam, Vector3 camPos) + { + var view = session.World.View; + var contenders = session.State.Contenders; + + for (int i = 0; i < contenders.Count; i++) + { + var c = contenders[i]; + if (!c.Alive) + { + if (_contenderVisuals.TryGetValue(c.Id, out var deadVis)) + { + // Flush any final stripped plates/gear into debris before hiding wreck + deadVis.Visual.SyncDamageAndHeat(c.Grid, _debris, Vector3.Zero); + deadVis.Visual.Root.Visible = false; + } + continue; + } + + if (!_contenderVisuals.TryGetValue(c.Id, out var vis) || vis.Visual.ChassisId != c.Grid.Spec.Id) + { + if (vis is not null) + { + vis.Visual.Root.QueueFree(); + } + + var role = c.IsPlayer ? VehicleVisualRole.Player : VehicleVisualRole.Rival; + var instance = VehicleVisualInstance.Create(_assetCache, c.Grid.Spec.Id, role); + instance.SyncMountedGear(c.Grid); + _actorsGroup.AddChild(instance.Root); + vis = new ActorVisual { Visual = instance }; + _contenderVisuals[c.Id] = vis; + } + + vis.Visual.Root.Visible = true; + + Vector3 pos; + Vector3 vel; + var body = session.GetContenderBody(c.Id); + if (body is { } h) + { + int lane = h.Lane; + pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + vis.Visual.Root.Transform = new Transform3D(new Basis(q), pos); + } + else + { + pos = new Vector3(c.X, c.Y, c.Z); + vel = Vector3.Zero; + vis.Visual.Root.Position = pos; + vis.Visual.Root.Rotation = new Vector3(0f, c.Yaw, 0f); + } + + bool useStaticLod = false; + bool castShadows = true; + if (hasCam && !c.IsPlayer) + { + float distSq = pos.DistanceSquaredTo(camPos); + useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f; + castShadows = distSq <= 150f * 150f; + } + vis.Visual.SetLodState(useStaticLod, castShadows); + + if (!useStaticLod) + { + vis.Visual.SyncMountedGear(c.Grid); + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt); + vis.Visual.SyncDamageAndHeat(c.Grid, _debris, vel); + } + } + } + + private void SyncSpectators(ArenaSession session, float elapsedSeconds, float dt, bool hasCam, Vector3 camPos) + { + var view = session.World.View; + var specs = session.State.Spectators.Spectators; + + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive) + { + if (_spectatorVisuals.TryGetValue(s.Id, out var deadVis)) + { + deadVis.Visual.SyncDamageAndHeat(s.Grid, _debris, Vector3.Zero); + deadVis.Visual.Root.Visible = false; + if (deadVis.LaserMesh is not null) + { + deadVis.LaserMesh.Visible = false; + } + } + continue; + } + + if (!_spectatorVisuals.TryGetValue(s.Id, out var vis)) + { + var role = s.Tier switch + { + SpectatorTier.Tourist => VehicleVisualRole.SpectatorTourist, + SpectatorTier.Patron => VehicleVisualRole.SpectatorPatron, + _ => VehicleVisualRole.SpectatorExemplar + }; + var instance = VehicleVisualInstance.Create( + _assetCache, + s.Grid.Spec.Id, + role, + visualScale: 1f, + targetHalfHeight: s.Grid.Spec.HalfHeight); + instance.SyncMountedGear(s.Grid); + _actorsGroup.AddChild(instance.Root); + vis = CreateSpectatorVisualWrapper(instance); + _spectatorVisuals[s.Id] = vis; + } + + vis.Visual.Root.Visible = true; + var body = session.GetSpectatorBody(s.Id); + Vector3 specPos; + Vector3 vel; + if (body is { } h) + { + int lane = h.Lane; + specPos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + vis.Visual.Root.Transform = new Transform3D(new Basis(q), specPos); + } + else + { + specPos = new Vector3(s.X, s.Y, s.Z); + vel = Vector3.Zero; + vis.Visual.Root.Position = specPos; + vis.Visual.Root.Rotation = new Vector3(0f, s.Yaw, 0f); + } + + bool useStaticLod = false; + bool castShadows = true; + if (hasCam) + { + float distSq = specPos.DistanceSquaredTo(camPos); + useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f; + castShadows = distSq <= 150f * 150f; + } + vis.Visual.SetLodState(useStaticLod, castShadows); + + ContenderState? target = s.TargetContenderId.HasValue && + s.TargetContenderId.Value >= 0 && + s.TargetContenderId.Value < session.State.Contenders.Count + ? session.State.Contenders[s.TargetContenderId.Value] + : null; + + if (!useStaticLod) + { + float aimYawWorld = s.Yaw; + float aimPitchDeg = 0f; + if (s.Stance != SpectatorStance.Neutral && target is { Alive: true }) + { + float tdx = target.X - s.X; + float tdz = target.Z - s.Z; + if (tdx * tdx + tdz * tdz > 0.01f) + { + aimYawWorld = MathF.Atan2(tdx, tdz); + float horiz = MathF.Sqrt(tdx * tdx + tdz * tdz); + float eyeY = MatchRules.GetObserverEyeY(s.Y, s.Grid.Spec.HalfHeight); + float targetY = MatchRules.GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight); + aimPitchDeg = Mathf.RadToDeg(MathF.Atan2(targetY - eyeY, horiz)); + } + } + + var rigInput = new VehicleRigDriveInput( + Velocity: vel, + Yaw: s.Yaw, + AimYawWorld: aimYawWorld, + AimPitchDeg: aimPitchDeg, + SteerCmd: 0f, + ThrottleCmd: vel.Length() > 0.5f ? 0.6f : 0f, + VerticalThrottleCmd: 0f, + EngineThermalPerf: s.Grid.ComputeEngineThermalPerformance(), + DeltaTime: dt, + IsGrounded: !s.Grid.Spec.IsVtol); + + vis.Visual.SyncMountedGear(s.Grid); + VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis); + vis.Visual.SyncDamageAndHeat(s.Grid, _debris, vel); + } + + // Status halo + if (vis.HaloMat is not null && vis.HaloMesh is not null && + (vis.LastHaloStance != s.Stance || s.Stance == SpectatorStance.Provoked)) + { + vis.LastHaloStance = s.Stance; + if (s.Stance == SpectatorStance.Neutral) + { + vis.HaloMat.AlbedoColor = new Color(0.88f, 0.65f, 0.25f, 0.45f); + vis.HaloMat.Emission = new Color(0.88f, 0.65f, 0.25f); + vis.HaloMat.EmissionEnergyMultiplier = 0.6f; + } + else if (s.Stance == SpectatorStance.Cleared) + { + vis.HaloMat.AlbedoColor = new Color(1.0f, 0.22f, 0.18f, 0.9f); + vis.HaloMat.Emission = new Color(1.0f, 0.2f, 0.15f); + vis.HaloMat.EmissionEnergyMultiplier = 2.0f; + } + else + { + float pulse = 1.6f + 1.2f * MathF.Sin(elapsedSeconds * 10f); + vis.HaloMat.AlbedoColor = new Color(1.0f, 0.1f, 0.1f, 0.95f); + vis.HaloMat.Emission = new Color(1.0f, 0.08f, 0.08f); + vis.HaloMat.EmissionEnergyMultiplier = pulse; + } + } + + // Lock-on laser beam when Cleared or Provoked + if (vis.LaserMesh is not null) + { + if (s.Stance != SpectatorStance.Neutral && s.HasTargetLos && target is { Alive: true }) + { + Vector3 start = specPos + new Vector3(0f, s.Grid.Spec.HalfHeight * 0.7f, 0f); + Vector3 end = new Vector3(target.X, target.Y + target.Grid.Spec.HalfHeight * 0.3f, target.Z); + float dist = start.DistanceTo(end); + if (dist > 0.5f) + { + if (!vis.LastLaserVisible) + { + vis.LastLaserVisible = true; + vis.LaserMesh.Visible = true; + } + vis.LaserMesh.GlobalPosition = (start + end) * 0.5f; + Vector3 dir = (end - start).Normalized(); + Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.99f ? Vector3.Right : Vector3.Up; + vis.LaserMesh.LookAt(end, up); + vis.LaserMesh.Scale = new Vector3(1f, 1f, dist); + } + else if (vis.LastLaserVisible) + { + vis.LastLaserVisible = false; + vis.LaserMesh.Visible = false; + } + } + else if (vis.LastLaserVisible) + { + vis.LastLaserVisible = false; + vis.LaserMesh.Visible = false; + } + } + } + } + + private ActorVisual CreateSpectatorVisualWrapper(VehicleVisualInstance instance) + { + float haloY = MathF.Max(2.4f, instance.ComputeMountedMaxY() + 1.15f); + var haloMat = new StandardMaterial3D + { + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + EmissionEnabled = true, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }; + var halo = new MeshInstance3D + { + Mesh = new CylinderMesh { TopRadius = 2.4f, BottomRadius = 2.4f, Height = 0.1f, RadialSegments = 16 }, + MaterialOverride = haloMat, + Position = new Vector3(0f, haloY, 0f), + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + instance.Root.AddChild(halo); + + var laserMat = new StandardMaterial3D + { + AlbedoColor = new Color(1f, 0.15f, 0.15f, 0.85f), + EmissionEnabled = true, + Emission = new Color(1f, 0.12f, 0.1f), + EmissionEnergyMultiplier = 2.2f, + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }; + var laser = new MeshInstance3D + { + Mesh = new BoxMesh { Size = new Vector3(0.08f, 0.08f, 1.0f) }, + MaterialOverride = laserMat, + Visible = false, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + _actorsGroup.AddChild(laser); + + return new ActorVisual + { + Visual = instance, + HaloMesh = halo, + HaloMat = haloMat, + LaserMesh = laser + }; + } + + private void SyncGroundDrops(MatchState state, float elapsedSeconds, bool hasCam, Vector3 camPos) + { + for (int i = 0; i < state.GroundDrops.Count; i++) + { + var d = state.GroundDrops[i]; + if (d.PickedUp) + { + if (_dropVisuals.TryGetValue(d.Id, out var pickedEntry)) + { + if (GodotObject.IsInstanceValid(pickedEntry.Node)) + { + pickedEntry.Node.GetParent()?.RemoveChild(pickedEntry.Node); + pickedEntry.Node.QueueFree(); + } + _dropVisuals.Remove(d.Id); + } + continue; + } + + bool isNew = false; + if (!_dropVisuals.TryGetValue(d.Id, out var entry)) + { + Node3D node = BuildGroundDropVisual(d, out var chassisVis); + _dropsGroup.AddChild(node); + TerrainField.WorldToTile(d.X, d.Z, out int tx, out int tz); + entry = new DropVisualEntry + { + Node = node, + ChassisVisual = chassisVis, + BaseY = state.Terrain.SampleHeight(d.X, d.Z), + TileX = tx, + TileZ = tz, + TileVersion = state.Terrain.TileVersions[tx, tz] + }; + _dropVisuals[d.Id] = entry; + isNew = true; + } + else + { + int ver = state.Terrain.TileVersions[entry.TileX, entry.TileZ]; + if (ver != entry.TileVersion) + { + entry.TileVersion = ver; + entry.BaseY = state.Terrain.SampleHeight(d.X, d.Z); + isNew = true; + } + } + + if (isNew) + { + entry.Node.Visible = true; + } + if (d.Module is not null) + { + float bob = MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f; + entry.Node.Position = new Vector3(d.X, entry.BaseY + bob, d.Z); + entry.Node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f); + } + else + { + if (isNew) + { + entry.Node.Position = new Vector3(d.X, entry.BaseY, d.Z); + } + if (entry.ChassisVisual is { } cv) + { + bool useFarLod = false; + bool castShadows = true; + if (hasCam) + { + float d2 = new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos); + useFarLod = cv.IsStaticLod ? d2 > 126f * 126f : d2 > 130f * 130f; + castShadows = d2 <= 150f * 150f; + } + cv.SetLodState(useFarLod, castShadows); + } + } + } + } + + private void SyncTracers(IReadOnlyList tracers) + { + while (_tracerPool.Count < tracers.Count) + { + var mat = new StandardMaterial3D + { + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + EmissionEnabled = true + }; + var mesh = new MeshInstance3D + { + Mesh = new BoxMesh { Size = new Vector3(0.14f, 0.14f, 1.0f) }, + MaterialOverride = mat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + _tracersGroup.AddChild(mesh); + _tracerPool.Add(mesh); + } + + for (int i = 0; i < _tracerPool.Count; i++) + { + var m = _tracerPool[i]; + if (i >= tracers.Count) + { + m.Visible = false; + continue; + } + + var t = tracers[i]; + var start = new Vector3(t.StartX, t.StartY, t.StartZ); + var end = new Vector3(t.EndX, t.EndY, t.EndZ); + float dist = start.DistanceTo(end); + if (dist < 0.1f) + { + m.Visible = false; + continue; + } + + m.Visible = true; + m.Position = (start + end) * 0.5f; + Vector3 dir = (end - start).Normalized(); + Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; + m.LookAt(end, up); + m.Scale = new Vector3(1f, 1f, dist); + + var col = new Color( + ((t.ColorRgba >> 24) & 0xFF) / 255f, + ((t.ColorRgba >> 16) & 0xFF) / 255f, + ((t.ColorRgba >> 8) & 0xFF) / 255f, + 1f); + if (m.MaterialOverride is StandardMaterial3D sm) + { + sm.AlbedoColor = col; + sm.Emission = col; + sm.EmissionEnergyMultiplier = 2.5f; + } + } + } + + private Node3D BuildGroundDropVisual(GroundDrop drop, out VehicleVisualInstance? chassisVisual) + { + chassisVisual = null; + var root = new Node3D { Name = $"Drop_{drop.Id}" }; + if (drop.Module is { } mod) + { + var beaconMat = mod.IsImperial ? _imperialBeaconMat : _humanBeaconMat; + root.AddChild(new MeshInstance3D + { + Mesh = new CylinderMesh { TopRadius = 0.72f, BottomRadius = 0.85f, Height = 0.14f, RadialSegments = 14 }, + MaterialOverride = beaconMat, + Position = new Vector3(0f, 0.08f, 0f), + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }); + + // Real Brokkr gear GLB hovering cleanly above the salvage beacon disc + Node3D gear = VehicleVisualInstance.CreateStandaloneGearVisual(_assetCache, mod); + gear.Scale *= 1.45f; + gear.Position += new Vector3(0f, 0.35f, 0f); + root.AddChild(gear); + + if (mod.IsImperial) + { + root.AddChild(new MeshInstance3D + { + Mesh = new CylinderMesh { TopRadius = 0.06f, BottomRadius = 0.22f, Height = 5.5f, RadialSegments = 8 }, + MaterialOverride = _imperialBeaconMat, + Position = new Vector3(0f, 2.9f, 0f), + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }); + } + } + else if (drop.Chassis is { } ch) + { + const float dropScale = 0.85f; + var hull = VehicleVisualInstance.Create(_assetCache, ch.Id, VehicleVisualRole.SalvageDrop, dropScale); + chassisVisual = hull; + // ModelRoot sits at -HalfHeight*dropScale inside hull.Root, so lifting hull.Root by +HalfHeight*dropScale grounds minY=0 on terrain + hull.Root.Position = new Vector3(0f, ch.HalfHeight * dropScale, 0f); + root.AddChild(hull.Root); + + var ring = new MeshInstance3D + { + Mesh = new CylinderMesh { TopRadius = 2.6f, BottomRadius = 2.8f, Height = 0.14f, RadialSegments = 18 }, + MaterialOverride = _cyanBeaconMat, + Position = new Vector3(0f, 0.12f, 0f), + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + root.AddChild(ring); + } + return root; + } + + private static void ClearChildren(Node parent) + { + for (int i = parent.GetChildCount() - 1; i >= 0; i--) + { + var child = parent.GetChild(i); + parent.RemoveChild(child); + child.QueueFree(); + } + } +} diff --git a/client/DebrisSystem.cs b/client/DebrisSystem.cs new file mode 100644 index 0000000..3a7fed2 --- /dev/null +++ b/client/DebrisSystem.cs @@ -0,0 +1,287 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Manages physically detached armor plates and sheared hardpoint gear as tumbling, +/// terrain-bouncing debris pieces that settle and fade out cleanly after 8 seconds. +/// +public partial class DebrisSystem : Node3D +{ + private const float Gravity = -20f; + private const float DefaultLifetime = 8.0f; + private const float FadeDuration = 2.0f; + private const int MaxActiveDebris = 256; + + private sealed class DebrisPiece + { + public required Node3D Node; + public required Vector3 Velocity; + public required Vector3 AngularVelocity; + public required List FadeMaterials; + public required float[] BaseAlphas; + public float Age; + public float Lifetime; + public bool Settled; + } + + private readonly List _pieces = new(); + private uint _rngState = 0x9E3779B9u; + + public int ActiveCount => _pieces.Count; + + public void ClearAll() + { + for (int i = 0; i < _pieces.Count; i++) + { + if (GodotObject.IsInstanceValid(_pieces[i].Node)) + { + _pieces[i].Node.QueueFree(); + } + } + _pieces.Clear(); + + for (int i = GetChildCount() - 1; i >= 0; i--) + { + Node ch = GetChild(i); + RemoveChild(ch); + ch.QueueFree(); + } + } + + /// + /// Reparents from its vehicle hierarchy at its exact world transform + /// into and launches it with an outward blast impulse and tumble. + /// + public void SpawnDetachedPart( + Node3D part, + Vector3 blastOriginWorld, + Vector3 inheritedVelocity, + float impulseScale = 1.0f, + bool applyScorch = true) + { + if (!GodotObject.IsInstanceValid(part)) + { + return; + } + + // Evict oldest settled or oldest piece if we hit the cap so debris never leaks indefinitely + while (_pieces.Count >= MaxActiveDebris) + { + RemoveAt(0); + } + + Transform3D worldXform = part.IsInsideTree() ? part.GlobalTransform : part.Transform; + Node? oldParent = part.GetParent(); + oldParent?.RemoveChild(part); + AddChild(part); + + if (part.IsInsideTree() && IsInsideTree()) + { + part.GlobalTransform = worldXform; + } + else + { + part.Transform = worldXform; + } + + Vector3 outward = worldXform.Origin - blastOriginWorld; + outward.Y = 0f; + if (outward.LengthSquared() < 1e-4f) + { + float ang = NextFloat() * MathF.Tau; + outward = new Vector3(MathF.Cos(ang), 0f, MathF.Sin(ang)); + } + else + { + outward = outward.Normalized(); + } + + float horizSpeed = (4.2f + NextFloat() * 4.8f) * impulseScale; + float upSpeed = (4.0f + NextFloat() * 4.5f) * impulseScale; + Vector3 vel = inheritedVelocity * 0.45f + outward * horizSpeed + Vector3.Up * upSpeed; + + Vector3 angVel = new( + (NextFloat() * 2f - 1f) * 7.5f, + (NextFloat() * 2f - 1f) * 7.5f, + (NextFloat() * 2f - 1f) * 7.5f); + + var fadeMats = new List(); + PrepareInstanceMaterials(part, fadeMats, applyScorch); + var baseAlphas = new float[fadeMats.Count]; + for (int i = 0; i < fadeMats.Count; i++) + { + baseAlphas[i] = fadeMats[i].AlbedoColor.A; + } + + _pieces.Add(new DebrisPiece + { + Node = part, + Velocity = vel, + AngularVelocity = angVel, + FadeMaterials = fadeMats, + BaseAlphas = baseAlphas, + Age = 0f, + Lifetime = DefaultLifetime, + Settled = false + }); + } + + public void Step(float dt, TerrainField terrain) + { + if (dt <= 0f || !float.IsFinite(dt)) + { + return; + } + float stepDt = Math.Clamp(dt, 0f, 0.05f); + + for (int i = _pieces.Count - 1; i >= 0; i--) + { + DebrisPiece p = _pieces[i]; + if (!GodotObject.IsInstanceValid(p.Node)) + { + _pieces.RemoveAt(i); + continue; + } + + p.Age += stepDt; + if (p.Age >= p.Lifetime) + { + RemoveAt(i); + continue; + } + + if (!p.Settled) + { + p.Velocity += new Vector3(0f, Gravity * stepDt, 0f); + Vector3 pos = p.Node.Position + p.Velocity * stepDt; + + Basis basis = p.Node.Basis; + float spinLen = p.AngularVelocity.Length(); + if (spinLen > 1e-4f) + { + basis = new Basis(p.AngularVelocity / spinLen, spinLen * stepDt) * basis; + basis = basis.Orthonormalized(); + } + + float floorY = terrain.SampleHeight(pos.X, pos.Z) + 0.10f; + if (pos.Y <= floorY) + { + pos.Y = floorY; + if (p.Velocity.Y < -1.4f) + { + p.Velocity = new Vector3( + p.Velocity.X * 0.62f, + -p.Velocity.Y * 0.32f, + p.Velocity.Z * 0.62f); + p.AngularVelocity *= 0.55f; + } + else + { + p.Velocity = Vector3.Zero; + p.AngularVelocity = Vector3.Zero; + p.Settled = true; + } + } + + p.Node.Position = pos; + p.Node.Basis = basis; + } + + // Smooth alpha fade during final 2 seconds + float remaining = p.Lifetime - p.Age; + if (remaining < FadeDuration) + { + float alphaFrac = Math.Clamp(remaining / FadeDuration, 0f, 1f); + for (int m = 0; m < p.FadeMaterials.Count; m++) + { + StandardMaterial3D sm = p.FadeMaterials[m]; + if (sm.Transparency == BaseMaterial3D.TransparencyEnum.Disabled) + { + sm.Transparency = BaseMaterial3D.TransparencyEnum.Alpha; + } + Color col = sm.AlbedoColor; + col.A = p.BaseAlphas[m] * alphaFrac; + sm.AlbedoColor = col; + } + } + } + } + + private void RemoveAt(int index) + { + DebrisPiece p = _pieces[index]; + _pieces.RemoveAt(index); + if (GodotObject.IsInstanceValid(p.Node)) + { + if (p.Node.GetParent() == this) + { + RemoveChild(p.Node); + } + p.Node.QueueFree(); + } + } + + private static void PrepareInstanceMaterials(Node cur, List outMats, bool applyScorch) + { + if (cur is MeshInstance3D mi && mi.Mesh is not null) + { + if (mi.MaterialOverride is StandardMaterial3D ov) + { + var copy = (StandardMaterial3D)ov.Duplicate(); + if (applyScorch) + { + ApplyScorchTint(copy); + } + mi.MaterialOverride = copy; + outMats.Add(copy); + } + else + { + int surfCount = mi.Mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + Material? src = mi.GetActiveMaterial(s); + StandardMaterial3D copy = src is StandardMaterial3D sm + ? (StandardMaterial3D)sm.Duplicate() + : new StandardMaterial3D { AlbedoColor = new Color(0.28f, 0.25f, 0.23f), Roughness = 0.78f, Metallic = 0.45f }; + if (applyScorch) + { + ApplyScorchTint(copy); + } + mi.SetSurfaceOverrideMaterial(s, copy); + outMats.Add(copy); + } + } + } + + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + PrepareInstanceMaterials(cur.GetChild(i), outMats, applyScorch); + } + } + + private static void ApplyScorchTint(StandardMaterial3D mat) + { + Color c = mat.AlbedoColor; + mat.AlbedoColor = new Color(c.R * 0.42f + 0.04f, c.G * 0.36f + 0.03f, c.B * 0.34f + 0.02f, c.A); + mat.Roughness = MathF.Max(mat.Roughness, 0.78f); + mat.EmissionEnabled = true; + mat.Emission = new Color(0.95f, 0.32f, 0.06f); + mat.EmissionEnergyMultiplier = 0.35f; + } + + private float NextFloat() + { + uint x = _rngState; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + _rngState = x; + return (x & 0x00FFFFFFu) / 16777216f; + } +} diff --git a/client/Hud.cs b/client/Hud.cs new file mode 100644 index 0000000..de811bc --- /dev/null +++ b/client/Hud.cs @@ -0,0 +1,1040 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +/// +/// Rust to Dust industrial HUD: +/// - Top-Left: Chassis badge (DORSAL/CORONAL), Core HP, Speed, Contenders Alive, Safe Circle status, Pickup prompt. +/// - Top-Right: Tactical Radar (Safe Circle, RadarSignature-scaled Spectator Wall, lock lines, contenders, salvage). +/// - Bottom-Left: Live clickable Aetheria Hardpoint & Heat Schematic + Cargo Salvage Rack (Tab expands Garage details). +/// - Bottom-Center: Imperial Broadcast Chyron (Weksa commentary). +/// +public partial class Hud : CanvasLayer +{ + private static readonly Color BgDark = Color.FromHtml("#131613"); + private static readonly Color BgInner = Color.FromHtml("#1b1f1b"); + private static readonly Color BorderCol = Color.FromHtml("#3e4638"); + private static readonly Color OliveCol = Color.FromHtml("#9bb06a"); + private static readonly Color OrangeCol = Color.FromHtml("#e08a4a"); + private static readonly Color TextLight = Color.FromHtml("#e4dfd2"); + private static readonly Color TextMuted = Color.FromHtml("#989487"); + private static readonly Color CyanCol = Color.FromHtml("#44d9e8"); + private static readonly Color GoldCol = Color.FromHtml("#e6b838"); + private static readonly Color RedCol = Color.FromHtml("#d93829"); + + private readonly Func _getSession; + private readonly Action _onEquipCargo; + private readonly Func _getCameraYaw; + + private Label _chassisHeader = null!; + private Label _planeBadge = null!; + private ProgressBar _coreHpBar = null!; + private Label _coreHpLabel = null!; + private Label _statsLabel = null!; + private Label _safeLabel = null!; + private Label _detectionLabel = null!; + private Label _promptLabel = null!; + private Label _controlsHint = null!; + + private RadarWidget _radar = null!; + private CrosshairOverlay _crosshair = null!; + private InventoryGridControl _schematic = null!; + private Button _thermalButton = null!; + private Label _hoverLabel = null!; + private VBoxContainer _cargoList = null!; + private Label _cargoHeader = null!; + private Label _garageDetails = null!; + private ChromePanel _topLeftPanel = null!; + private ChromePanel _topRightPanel = null!; + private ChromePanel _bottomLeftPanel = null!; + private ChromePanel _chyronPanel = null!; + + private VBoxContainer _chyronBox = null!; + private readonly Label[] _chyronLabels = new Label[3]; + private BroadcastFeed? _lastBroadcastFeed; + private long _lastChyronVersion = -1; + private ChromePanel _outcomeBanner = null!; + private Label _outcomeLabel = null!; + + private int _selectedCargoIndex = -1; + private int _lastCargoHash = -1; + private bool _garageExpanded; + + public Hud(Func getSession, Action onEquipCargo, Func? getCameraYaw = null) + { + _getSession = getSession; + _onEquipCargo = onEquipCargo; + _getCameraYaw = getCameraYaw ?? (() => 0f); + Layer = 10; + } + + public bool GarageExpanded => _garageExpanded; + public bool ThermalMode => _schematic.ThermalEnabled; + public InventoryGridControl Schematic => _schematic; + internal Rect2 BottomLeftPanelRect => _bottomLeftPanel.GetGlobalRect(); + internal Rect2 ChyronPanelRect => _chyronPanel.GetGlobalRect(); + + public IEnumerable GetChromeMaterials() + { + yield return _topLeftPanel.ChromeMaterial; + yield return _topRightPanel.ChromeMaterial; + yield return _bottomLeftPanel.ChromeMaterial; + yield return _chyronPanel.ChromeMaterial; + yield return _outcomeBanner.ChromeMaterial; + } + + public void ToggleGarage() + { + _garageExpanded = !_garageExpanded; + _garageDetails.Visible = _garageExpanded; + _schematic.CustomMinimumSize = _garageExpanded ? new Vector2(198f, 208f) : new Vector2(180f, 188f); + _schematic.QueueRedraw(); + } + + public void ToggleThermal() => SetThermalMode(!_schematic.ThermalEnabled); + + public void SetThermalMode(bool enabled, bool instant = false) + { + if (instant) + { + _schematic.SetThermalInstant(enabled); + } + else + { + _schematic.ThermalEnabled = enabled; + } + _thermalButton.ButtonPressed = enabled; + _thermalButton.Modulate = enabled ? CyanCol : TextMuted; + _thermalButton.Text = enabled ? "[T] CONDUITS: ON" : "[T] CONDUITS"; + } + + public override void _Ready() + { + BuildCrosshair(); + BuildTopLeft(); + BuildTopRightRadar(); + BuildBottomLeftSchematic(); + BuildBottomCenterChyron(); + BuildOutcomeBanner(); + } + + public bool IsPointerOverInteractiveHud(Vector2 screenPos) + { + return (_topLeftPanel.Visible && _topLeftPanel.GetGlobalRect().HasPoint(screenPos)) + || (_topRightPanel.Visible && _topRightPanel.GetGlobalRect().HasPoint(screenPos)) + || (_bottomLeftPanel.Visible && _bottomLeftPanel.GetGlobalRect().HasPoint(screenPos)) + || (_chyronPanel.Visible && _chyronPanel.GetGlobalRect().HasPoint(screenPos)) + || (_chyronBox.Visible && _chyronBox.GetGlobalRect().HasPoint(screenPos)) + || (_outcomeBanner.Visible && _outcomeBanner.GetGlobalRect().HasPoint(screenPos)); + } + + public bool HasPanelOverlapOrClip(Vector2 viewportSize) + { + var panels = new[] { _topLeftPanel, _topRightPanel, _bottomLeftPanel, _chyronPanel }; + var bounds = new Rect2(Vector2.Zero, viewportSize + new Vector2(1f, 1f)); + for (int i = 0; i < panels.Length; i++) + { + if (!panels[i].Visible) continue; + var ri = panels[i].GetGlobalRect(); + if (!bounds.Encloses(ri)) + { + return true; + } + for (int j = i + 1; j < panels.Length; j++) + { + if (!panels[j].Visible) continue; + if (ri.Intersects(panels[j].GetGlobalRect())) + { + return true; + } + } + } + return false; + } + + public void Sync(ArenaSession session) + { + var state = session.State; + var player = state.Player; + + // Top-Left Status + _chassisHeader.Text = player.Grid.Spec.Name.ToUpperInvariant(); + bool isCoronal = player.Grid.Spec.Plane == GridPlane.Coronal; + _planeBadge.Text = isCoronal ? "CORONAL" : "DORSAL"; + _planeBadge.Modulate = isCoronal ? CyanCol : OliveCol; + + _coreHpBar.MaxValue = Math.Max(1f, player.Grid.MaxCoreHp); + _coreHpBar.Value = Math.Max(0f, player.Grid.CoreHp); + _coreHpLabel.Text = $"CORE {player.Grid.CoreHp:F0} / {player.Grid.MaxCoreHp:F0}"; + + int aliveCount = 0; + for (int i = 0; i < state.Contenders.Count; i++) + { + if (state.Contenders[i].Alive) aliveCount++; + } + if (player.Grid.Spec.IsVtol) + { + float agl = MathF.Max(0f, player.Y - player.Grid.Spec.HalfHeight - state.Terrain.SampleHeight(player.X, player.Z)); + _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALT {agl:F1}m | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; + _controlsHint.Text = "WASD Fly | Space/C Climb/Descend | Mouse Aim | LMB Fire | E Bolt/Swap | Tab Garage"; + } + else + { + _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; + _controlsHint.Text = "WASD Drive | Mouse Aim | LMB Fire | E Bolt/Swap | Tab Garage | T Conduits | Wheel Zoom"; + } + + float distCenter = MathF.Sqrt(player.X * player.X + player.Z * player.Z); + float outside = distCenter - state.Spectators.SafeRadius; + int cleared = state.Spectators.CountClearedFor(player.Id); + int provoked = state.Spectators.CountProvokedFor(player.Id); + + if (outside <= 0f) + { + _safeLabel.Text = $"RING SAFE ({-outside:F0}m margin)" + (provoked > 0 ? $" • {provoked} PROVOKED!" : ""); + _safeLabel.Modulate = provoked > 0 ? OrangeCol : OliveCol; + } + else + { + _safeLabel.Text = $"OUTSIDE +{outside:F0}m — {cleared} CLEARED" + (provoked > 0 ? $" / {provoked} PROVOKED!" : "!"); + _safeLabel.Modulate = RedCol; + } + + if (state.PlayerDetectedByCount > 0) + { + _detectionLabel.Text = $"DETECTED BY {state.PlayerDetectedByCount}"; + _detectionLabel.Modulate = RedCol; + } + else + { + _detectionLabel.Text = "CONCEALED (TERRAIN)"; + _detectionLabel.Modulate = OliveCol; + } + + _promptLabel.Text = BuildInteractionPrompt(state, player); + _promptLabel.Visible = !string.IsNullOrEmpty(_promptLabel.Text); + + // Crosshair + Heat Arc + _crosshair.SetState(player); + _crosshair.QueueRedraw(); + + // Radar (heading-up with camera yaw) + _radar.SetState(state, _getCameraYaw()); + _radar.QueueRedraw(); + + // Schematic + Cargo + _schematic.SetGrid(player.Grid, _selectedCargoIndex); + SyncCargoButtons(player.Grid); + + if (_garageExpanded) + { + _garageDetails.Text = BuildGarageDetails(player.Grid); + } + + // Broadcast Chyron + SyncBroadcastChyron(state.Broadcast); + + // Outcome + if (state.Phase == MatchPhase.Victory) + { + _outcomeBanner.Visible = true; + _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", OliveCol); + _outcomeLabel.Text = "VICTORY — LAST RIG STANDING\n[R] New Drop"; + _outcomeLabel.Modulate = OliveCol; + } + else if (state.Phase == MatchPhase.Defeat) + { + _outcomeBanner.Visible = true; + _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", RedCol); + _outcomeLabel.Text = "CHASSIS DESTROYED\n[R] Redeploy"; + _outcomeLabel.Modulate = RedCol; + } + else + { + _outcomeBanner.Visible = false; + } + } + + private void BuildCrosshair() + { + _crosshair = new CrosshairOverlay { Name = "Crosshair" }; + _crosshair.SetAnchorsPreset(Control.LayoutPreset.FullRect); + _crosshair.MouseFilter = Control.MouseFilterEnum.Ignore; + AddChild(_crosshair); + } + + private void BuildTopLeft() + { + var panel = CreateStyledPanel(OliveCol); + _topLeftPanel = panel; + panel.AnchorLeft = 0f; + panel.AnchorTop = 0f; + panel.OffsetLeft = 14f; + panel.OffsetTop = 14f; + panel.CustomMinimumSize = new Vector2(360f, 0f); + AddChild(panel); + + var vbox = new VBoxContainer { Theme = null }; + vbox.AddThemeConstantOverride("separation", 5); + panel.AddChild(vbox); + + var headRow = new HBoxContainer(); + headRow.AddThemeConstantOverride("separation", 10); + vbox.AddChild(headRow); + + _chassisHeader = new Label { Text = "DUNE BUGGY", SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; + _chassisHeader.AddThemeColorOverride("font_color", TextLight); + _chassisHeader.AddThemeFontSizeOverride("font_size", 17); + headRow.AddChild(_chassisHeader); + + _planeBadge = new Label { Text = "DORSAL" }; + _planeBadge.AddThemeFontSizeOverride("font_size", 13); + headRow.AddChild(_planeBadge); + + var hpRow = new HBoxContainer(); + hpRow.AddThemeConstantOverride("separation", 8); + vbox.AddChild(hpRow); + + _coreHpBar = new ProgressBar + { + ShowPercentage = false, + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + CustomMinimumSize = new Vector2(180f, 16f) + }; + var barBg = new StyleBoxFlat { BgColor = BgInner, BorderColor = BorderCol }; + barBg.SetBorderWidthAll(1); + var barFill = new StyleBoxFlat { BgColor = OliveCol }; + _coreHpBar.AddThemeStyleboxOverride("background", barBg); + _coreHpBar.AddThemeStyleboxOverride("fill", barFill); + hpRow.AddChild(_coreHpBar); + + _coreHpLabel = new Label { Text = "CORE 100 / 100" }; + _coreHpLabel.AddThemeColorOverride("font_color", TextLight); + _coreHpLabel.AddThemeFontSizeOverride("font_size", 13); + hpRow.AddChild(_coreHpLabel); + + _statsLabel = new Label { Text = "SPD 0.0 m/s" }; + _statsLabel.AddThemeColorOverride("font_color", TextMuted); + _statsLabel.AddThemeFontSizeOverride("font_size", 13); + vbox.AddChild(_statsLabel); + + _safeLabel = new Label { Text = "RING SAFE" }; + _safeLabel.AddThemeFontSizeOverride("font_size", 13); + vbox.AddChild(_safeLabel); + + _detectionLabel = new Label { Text = "CONCEALED (TERRAIN)" }; + _detectionLabel.AddThemeFontSizeOverride("font_size", 13); + vbox.AddChild(_detectionLabel); + + _promptLabel = new Label { Text = "", Visible = false }; + _promptLabel.AddThemeColorOverride("font_color", CyanCol); + _promptLabel.AddThemeFontSizeOverride("font_size", 14); + vbox.AddChild(_promptLabel); + + _controlsHint = new Label { Text = "WASD Drive | Mouse Aim | LMB Fire | E Loot/Swap | Tab Garage | T Conduits | Wheel Zoom" }; + _controlsHint.AddThemeColorOverride("font_color", TextMuted); + _controlsHint.AddThemeFontSizeOverride("font_size", 11); + vbox.AddChild(_controlsHint); + } + + private void BuildTopRightRadar() + { + var panel = CreateStyledPanel(OrangeCol); + _topRightPanel = panel; + panel.AnchorLeft = 1f; + panel.AnchorRight = 1f; + panel.AnchorTop = 0f; + panel.OffsetLeft = -246f; + panel.OffsetRight = -14f; + panel.OffsetTop = 14f; + AddChild(panel); + + var vbox = new VBoxContainer(); + vbox.AddThemeConstantOverride("separation", 4); + panel.AddChild(vbox); + + var title = new Label { Text = "GALLERY & ARENA RADAR", HorizontalAlignment = HorizontalAlignment.Center }; + title.AddThemeColorOverride("font_color", OrangeCol); + title.AddThemeFontSizeOverride("font_size", 12); + vbox.AddChild(title); + + _radar = new RadarWidget + { + CustomMinimumSize = new Vector2(214f, 214f) + }; + vbox.AddChild(_radar); + } + + private void BuildBottomLeftSchematic() + { + _bottomLeftPanel = CreateStyledPanel(OrangeCol); + _bottomLeftPanel.AnchorLeft = 0f; + _bottomLeftPanel.AnchorTop = 1f; + _bottomLeftPanel.AnchorBottom = 1f; + _bottomLeftPanel.GrowVertical = Control.GrowDirection.Begin; + _bottomLeftPanel.OffsetLeft = 14f; + _bottomLeftPanel.OffsetTop = -248f; + _bottomLeftPanel.OffsetBottom = -14f; + AddChild(_bottomLeftPanel); + + var hbox = new HBoxContainer(); + hbox.AddThemeConstantOverride("separation", 8); + _bottomLeftPanel.AddChild(hbox); + + var leftCol = new VBoxContainer(); + leftCol.AddThemeConstantOverride("separation", 4); + hbox.AddChild(leftCol); + + var headRow = new HBoxContainer(); + headRow.AddThemeConstantOverride("separation", 6); + leftCol.AddChild(headRow); + + var title = new Label + { + Text = "HARDPOINTS & HEAT", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + title.AddThemeColorOverride("font_color", OrangeCol); + title.AddThemeFontSizeOverride("font_size", 12); + headRow.AddChild(title); + + _thermalButton = new Button + { + Text = "[T] CONDUITS", + ToggleMode = true, + FocusMode = Control.FocusModeEnum.None, + Modulate = TextMuted + }; + _thermalButton.AddThemeFontSizeOverride("font_size", 10); + _thermalButton.Pressed += () => SetThermalMode(_thermalButton.ButtonPressed); + headRow.AddChild(_thermalButton); + + _schematic = new InventoryGridControl + { + CustomMinimumSize = new Vector2(180f, 188f) + }; + _schematic.HardpointClicked += OnHardpointClicked; + _schematic.HoverChanged += OnSchematicHoverChanged; + leftCol.AddChild(_schematic); + + _hoverLabel = new Label + { + Text = "HOVER CELL FOR TELEMETRY", + ClipText = true, + CustomMinimumSize = new Vector2(180f, 15f) + }; + _hoverLabel.AddThemeColorOverride("font_color", TextMuted); + _hoverLabel.AddThemeFontSizeOverride("font_size", 10); + leftCol.AddChild(_hoverLabel); + + var rightCol = new VBoxContainer { CustomMinimumSize = new Vector2(156f, 0f) }; + rightCol.AddThemeConstantOverride("separation", 3); + hbox.AddChild(rightCol); + + _cargoHeader = new Label { Text = "SALVAGE CARGO (0/4)" }; + _cargoHeader.AddThemeColorOverride("font_color", OliveCol); + _cargoHeader.AddThemeFontSizeOverride("font_size", 11); + rightCol.AddChild(_cargoHeader); + + _cargoList = new VBoxContainer(); + _cargoList.AddThemeConstantOverride("separation", 2); + rightCol.AddChild(_cargoList); + + _garageDetails = new Label { Visible = false, AutowrapMode = TextServer.AutowrapMode.Word }; + _garageDetails.AddThemeColorOverride("font_color", TextMuted); + _garageDetails.AddThemeFontSizeOverride("font_size", 10); + _garageDetails.CustomMinimumSize = new Vector2(178f, 0f); + hbox.AddChild(_garageDetails); + } + + private void BuildBottomCenterChyron() + { + _chyronPanel = CreateStyledPanel(GoldCol); + var panel = _chyronPanel; + panel.AnchorLeft = 1f; + panel.AnchorRight = 1f; + panel.AnchorTop = 1f; + panel.AnchorBottom = 1f; + panel.GrowHorizontal = Control.GrowDirection.Begin; + panel.GrowVertical = Control.GrowDirection.Begin; + panel.OffsetLeft = -584f; + panel.OffsetRight = -14f; + panel.OffsetTop = -104f; + panel.OffsetBottom = -14f; + AddChild(panel); + + var vbox = new VBoxContainer(); + vbox.AddThemeConstantOverride("separation", 3); + panel.AddChild(vbox); + + var header = new Label { Text = "IMPERIAL BROADCAST FEED" }; + header.AddThemeColorOverride("font_color", GoldCol); + header.AddThemeFontSizeOverride("font_size", 11); + vbox.AddChild(header); + + _chyronBox = new VBoxContainer(); + _chyronBox.AddThemeConstantOverride("separation", 2); + vbox.AddChild(_chyronBox); + + for (int i = 0; i < _chyronLabels.Length; i++) + { + var lbl = new Label + { + Visible = false, + AutowrapMode = TextServer.AutowrapMode.Word + }; + lbl.AddThemeFontSizeOverride("font_size", 11); + lbl.AddThemeColorOverride("font_color", TextMuted); + _chyronBox.AddChild(lbl); + _chyronLabels[i] = lbl; + } + } + + private void BuildOutcomeBanner() + { + _outcomeBanner = CreateStyledPanel(OliveCol, cornerLen: 16f, borderPx: 2f); + _outcomeBanner.AnchorLeft = 0.5f; + _outcomeBanner.AnchorRight = 0.5f; + _outcomeBanner.AnchorTop = 0.28f; + _outcomeBanner.AnchorBottom = 0.28f; + _outcomeBanner.OffsetLeft = -210f; + _outcomeBanner.OffsetRight = 210f; + _outcomeBanner.OffsetTop = -40f; + _outcomeBanner.OffsetBottom = 40f; + _outcomeBanner.Visible = false; + AddChild(_outcomeBanner); + + _outcomeLabel = new Label + { + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + _outcomeLabel.AddThemeFontSizeOverride("font_size", 22); + _outcomeBanner.AddChild(_outcomeLabel); + } + + private void OnHardpointClicked(string hardpointId) + { + var session = _getSession(); + if (session is null) return; + var cargo = session.State.Player.Grid.Cargo; + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < cargo.Count) + { + _onEquipCargo(_selectedCargoIndex, hardpointId); + _selectedCargoIndex = -1; + _lastCargoHash = -1; + } + } + + private void OnSchematicHoverChanged(Vector2I? cell, HardpointSpec? hp) + { + var grid = _schematic.Grid; + if (cell is null || grid is null) + { + _hoverLabel.Text = "HOVER CELL FOR TELEMETRY"; + _hoverLabel.AddThemeColorOverride("font_color", TextMuted); + return; + } + + var c = cell.Value; + float arm = grid.Armor[c.X, c.Y]; + float maxArm = grid.MaxArmor[c.X, c.Y]; + float temp = grid.Temperature[c.X, c.Y]; + if (hp is not null) + { + var mounted = grid.GetMountedOn(hp.Id); + bool strippedHp = !grid.IsHardpointOperational(hp); + string hpStatus = strippedHp ? " [STRIPPED]" : ""; + _hoverLabel.Text = mounted is not null + ? $"{hp.Kind.ToString().ToUpperInvariant()}: {mounted.Spec.Name} {mounted.CurrentTemp:F0}°C ({mounted.CurrentPerformance * 100f:F0}%){hpStatus}" + : $"{hp.Kind.ToString().ToUpperInvariant()} SLOT [{hp.Width}x{hp.Height}] EMPTY{hpStatus}"; + _hoverLabel.AddThemeColorOverride("font_color", (arm <= 0.01f || strippedHp) ? RedCol : TextLight); + } + else + { + _hoverLabel.Text = arm <= 0.01f + ? $"CELL ({c.X},{c.Y}) STRIPPED! {temp:F0}°C" + : $"HULL ({c.X},{c.Y}) ARM {arm:F0}/{maxArm:F0} {temp:F0}°C"; + _hoverLabel.AddThemeColorOverride("font_color", arm <= 0.01f ? RedCol : TextMuted); + } + } + + private void SyncCargoButtons(ChassisGrid grid) + { + int hash = HashCode.Combine(grid.Cargo.Count, grid.Spec.CargoCapacity, _selectedCargoIndex); + for (int i = 0; i < grid.Cargo.Count; i++) + { + hash = HashCode.Combine(hash, grid.Cargo[i].Id); + } + if (hash == _lastCargoHash) return; + _lastCargoHash = hash; + + _cargoHeader.Text = $"SALVAGE CARGO ({grid.Cargo.Count}/{grid.Spec.CargoCapacity})"; + for (int i = _cargoList.GetChildCount() - 1; i >= 0; i--) + { + var c = _cargoList.GetChild(i); + _cargoList.RemoveChild(c); + c.QueueFree(); + } + + if (grid.Cargo.Count == 0) + { + var empty = new Label { Text = "No modules in rack.\nPress [E] near crates." }; + empty.AddThemeColorOverride("font_color", TextMuted); + empty.AddThemeFontSizeOverride("font_size", 11); + _cargoList.AddChild(empty); + return; + } + + for (int i = 0; i < grid.Cargo.Count; i++) + { + int idx = i; + var mod = grid.Cargo[i]; + var row = new HBoxContainer(); + row.AddThemeConstantOverride("separation", 4); + + var selectBtn = new Button + { + Text = $"{(mod.IsImperial ? "★ " : "")}{mod.Name}", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + Alignment = HorizontalAlignment.Left, + FocusMode = Control.FocusModeEnum.None, + ClipText = true, + CustomMinimumSize = new Vector2(114f, 0f) + }; + selectBtn.AddThemeFontSizeOverride("font_size", 10); + if (_selectedCargoIndex == idx) + { + selectBtn.Modulate = OrangeCol; + } + else if (mod.IsImperial) + { + selectBtn.Modulate = GoldCol; + } + selectBtn.Pressed += () => + { + _selectedCargoIndex = (_selectedCargoIndex == idx) ? -1 : idx; + _lastCargoHash = -1; + }; + row.AddChild(selectBtn); + + var fitBtn = new Button { Text = "FIT", FocusMode = Control.FocusModeEnum.None }; + fitBtn.AddThemeFontSizeOverride("font_size", 10); + fitBtn.Pressed += () => AutoFitCargo(grid, idx); + row.AddChild(fitBtn); + + _cargoList.AddChild(row); + } + } + + private void AutoFitCargo(ChassisGrid grid, int cargoIndex) + { + if (cargoIndex < 0 || cargoIndex >= grid.Cargo.Count) return; + var mod = grid.Cargo[cargoIndex]; + for (int i = 0; i < grid.Spec.Hardpoints.Length; i++) + { + var hp = grid.Spec.Hardpoints[i]; + if (ChassisGrid.CanFit(hp, mod)) + { + _onEquipCargo(cargoIndex, hp.Id); + _selectedCargoIndex = -1; + _lastCargoHash = -1; + return; + } + } + } + + private void SyncBroadcastChyron(BroadcastFeed broadcast) + { + var lines = broadcast.Lines; + if (ReferenceEquals(_lastBroadcastFeed, broadcast) && broadcast.Version == _lastChyronVersion) + { + return; + } + + _lastBroadcastFeed = broadcast; + _lastChyronVersion = broadcast.Version; + + int start = Math.Max(0, lines.Count - _chyronLabels.Length); + int visibleCount = lines.Count - start; + for (int slot = 0; slot < _chyronLabels.Length; slot++) + { + var lbl = _chyronLabels[slot]; + if (slot < visibleCount) + { + int lineIdx = start + slot; + var line = lines[lineIdx]; + bool isLatest = lineIdx == lines.Count - 1; + lbl.Visible = true; + lbl.Text = $"[{line.Timestamp:00.0}s] {line.Text}"; + lbl.AddThemeFontSizeOverride("font_size", isLatest ? 12 : 11); + lbl.AddThemeColorOverride("font_color", isLatest ? TextLight : TextMuted); + } + else + { + lbl.Visible = false; + lbl.Text = ""; + } + } + } + + private static string BuildInteractionPrompt(MatchState state, ContenderState player) + { + GroundDrop? nearest = state.FindNearestInteractableDrop(player.Id); + if (nearest is null) return ""; + if (nearest.Module is { } mod) + { + var freeHp = player.Grid.FindFirstEmptyCompatibleHardpoint(mod); + return freeHp is not null + ? $"[E] Bolt {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name} -> {freeHp.Id}" + : $"[E] Loot {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name}"; + } + if (nearest.Chassis is { } ch) + { + return $"[E] Swap to {ch.Name} ({ch.Plane})"; + } + return ""; + } + + private static string BuildGarageDetails(ChassisGrid grid) + { + var lines = new List + { + $"COND {grid.Spec.HullConductivity:F1} | THRUST {grid.ComputeDriveThrust():F0} N", + "MOUNTED:" + }; + for (int i = 0; i < grid.Mounted.Count; i++) + { + var m = grid.Mounted[i]; + string stateTag = grid.IsHardpointOperational(m.HardpointId) ? "" : " [STRIPPED]"; + lines.Add($"• {m.HardpointId}: {m.Spec.Name} {m.CurrentTemp:F0}°C ({(m.CurrentPerformance * 100f):F0}%){stateTag}"); + } + return string.Join("\n", lines); + } + + private static ChromePanel CreateStyledPanel(Color accentColor, float cornerLen = 12f, float borderPx = 1.5f) + { + return new ChromePanel(accentColor, cornerLen, borderPx); + } + + private sealed partial class ChromePanel : PanelContainer + { + private static Shader? _sharedChromeShader; + private static ImageTexture? _sharedWhiteTex; + private readonly ShaderMaterial _material; + + public ChromePanel(Color accentColor, float cornerLen, float borderPx) + { + _sharedChromeShader ??= GD.Load("res://panel_chrome.gdshader"); + if (_sharedWhiteTex is null) + { + var img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + img.SetPixel(0, 0, Colors.White); + _sharedWhiteTex = ImageTexture.CreateFromImage(img); + } + + _material = new ShaderMaterial { Shader = _sharedChromeShader }; + _material.SetShaderParameter("bg_color", new Color(BgDark.R, BgDark.G, BgDark.B, 0.88f)); + _material.SetShaderParameter("border_color", BorderCol); + _material.SetShaderParameter("accent_color", accentColor); + _material.SetShaderParameter("corner_len", cornerLen); + _material.SetShaderParameter("border_px", borderPx); + Material = _material; + + var empty = new StyleBoxEmpty + { + ContentMarginLeft = 10, + ContentMarginRight = 10, + ContentMarginTop = 8, + ContentMarginBottom = 8 + }; + AddThemeStyleboxOverride("panel", empty); + } + + public ShaderMaterial ChromeMaterial => _material; + + public override void _Notification(int what) + { + if (what == NotificationResized) + { + _material.SetShaderParameter("rect_size", Size); + QueueRedraw(); + } + } + + public override void _Draw() + { + if (Size.X < 2f || Size.Y < 2f || _sharedWhiteTex is null) return; + _material.SetShaderParameter("rect_size", Size); + DrawTextureRect(_sharedWhiteTex, new Rect2(Vector2.Zero, Size), false, Colors.White); + } + } + + private sealed partial class CrosshairOverlay : Control + { + private ContenderState? _player; + + public void SetState(ContenderState player) => _player = player; + + public override void _Draw() + { + Vector2 center = Size * 0.5f; + float gap = 6f; + float tick = 10f; + bool allDisabled = _player is not null && _player.Alive && + _player.InArcWeaponCount == 0 && _player.OutOfArcWeaponCount == 0 && _player.DisabledWeaponCount > 0; + bool outOfArc = _player is not null && _player.Alive && _player.AllWeaponsOutOfArc; + Color retCol = (outOfArc || allDisabled) + ? new Color(RedCol.R, RedCol.G, RedCol.B, 0.95f) + : new Color(TextLight.R, TextLight.G, TextLight.B, 0.88f); + + // Clean 4-tick center crosshair + center pip + DrawCircle(center, 1.8f, retCol); + DrawLine(center + new Vector2(-gap - tick, 0f), center + new Vector2(-gap, 0f), retCol, 1.6f); + DrawLine(center + new Vector2(gap, 0f), center + new Vector2(gap + tick, 0f), retCol, 1.6f); + DrawLine(center + new Vector2(0f, -gap - tick), center + new Vector2(0f, -gap), retCol, 1.6f); + DrawLine(center + new Vector2(0f, gap), center + new Vector2(0f, gap + tick), retCol, 1.6f); + + if (allDisabled) + { + DrawString( + ThemeDB.FallbackFont, + center + new Vector2(-52f, 36f), + "WEAPONS STRIPPED", + HorizontalAlignment.Left, + -1, + 11, + RedCol); + } + else if (outOfArc) + { + DrawString( + ThemeDB.FallbackFont, + center + new Vector2(-34f, 36f), + "OUT OF ARC", + HorizontalAlignment.Left, + -1, + 11, + RedCol); + } + + if (_player is null || !_player.Alive) + { + return; + } + + // Thermal heat-arc indicator around crosshair + float heatRatio = 0f; + bool overPlateau = false; + var mounted = _player.Grid.Mounted; + for (int i = 0; i < mounted.Count; i++) + { + var m = mounted[i]; + if (m.Spec.Kind == HardpointKind.Weapon) + { + float r = Math.Clamp( + (m.CurrentTemp - ChassisGrid.AmbientTemp) / MathF.Max(1f, m.Spec.MaxTemp - ChassisGrid.AmbientTemp), + 0f, 1f); + if (r > heatRatio) heatRatio = r; + if (m.CurrentTemp > m.Spec.OptimalTemp + m.Spec.PlateauWidth * 0.5f) + { + overPlateau = true; + } + } + } + + float arcRadius = 21f; + float startAngle = -MathF.PI * 0.75f; + float maxSweep = MathF.PI * 1.5f; + DrawArc(center, arcRadius, startAngle, startAngle + maxSweep, 24, new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.4f), 2.0f); + + if (heatRatio > 0.01f) + { + Color heatCol = overPlateau + ? RedCol + : (heatRatio > 0.65f ? OrangeCol : OliveCol); + DrawArc(center, arcRadius, startAngle, startAngle + maxSweep * heatRatio, 24, heatCol, 2.4f); + } + } + } + + private sealed partial class RadarWidget : Control + { + private MatchState? _state; + private float _cameraYaw; + + public void SetState(MatchState state, float cameraYaw) + { + _state = state; + _cameraYaw = cameraYaw; + } + + private static Vector2 WorldToRadar(Vector2 center, float scale, float wx, float wz, float camYaw) + { + // Heading-up 3P radar: camera forward (sinY, cosY) is always UP (-screenY), camera right (-cosY, sinY) is RIGHT (+screenX). + float sinY = MathF.Sin(camYaw); + float cosY = MathF.Cos(camYaw); + float rx = -wx * cosY + wz * sinY; + float fy = wx * sinY + wz * cosY; + return center + new Vector2(rx, -fy) * scale; + } + + private static Vector2 ClampToRadarDisc(Vector2 center, float maxRadius, Vector2 pt) + { + Vector2 delta = pt - center; + float dist = delta.Length(); + if (dist > maxRadius && dist > 1e-4f) + { + return center + delta * (maxRadius / dist); + } + return pt; + } + + public override void _Draw() + { + Vector2 center = Size * 0.5f; + float radius = MathF.Min(Size.X, Size.Y) * 0.47f; + float maxBlipRadius = MathF.Max(4f, radius - 3f); + float scale = radius / MatchState.ArenaHalfExtent; + + DrawCircle(center, radius, BgInner); + DrawArc(center, radius, 0f, MathF.Tau, 48, BorderCol, 1.5f); + // Forward-up indicator tick at top of radar + DrawLine(center + new Vector2(0f, -radius), center + new Vector2(0f, -radius + 6f), CyanCol, 2.0f); + + if (_state is null) return; + + // Safe Circle + float safePx = MathF.Min(_state.Spectators.SafeRadius * scale, maxBlipRadius); + DrawArc(center, safePx, 0f, MathF.Tau, 64, OrangeCol, 1.6f); + + // Ground drops + for (int i = 0; i < _state.GroundDrops.Count; i++) + { + var d = _state.GroundDrops[i]; + if (d.PickedUp) continue; + var p = ClampToRadarDisc(center, MathF.Max(4f, radius - 4f), WorldToRadar(center, scale, d.X, d.Z, _cameraYaw)); + if (d.Chassis is not null) + { + DrawRect(new Rect2(p - new Vector2(2.5f, 2.5f), new Vector2(5f, 5f)), CyanCol); + } + else if (d.Module is { IsImperial: true }) + { + DrawCircle(p, 3.0f, GoldCol); + } + } + + // Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory; hidden Exemplars vanish!) + var specs = _state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive) continue; + + _state.SpectatorContacts.TryGetValue(s.Id, out var mem); + if (!MatchState.IsContactOnRadar(mem)) + { + continue; + } + + bool live = mem!.VisibleToPlayer; + float drawX = live || mem.FaintHorizonPing ? s.X : mem.LastSeenX; + float drawZ = live || mem.FaintHorizonPing ? s.Z : mem.LastSeenZ; + float blipR = 1.6f + s.RadarSignature * 3.1f; + float specClampR = MathF.Max(4f, radius - blipR - 1f); + var p = ClampToRadarDisc(center, specClampR, WorldToRadar(center, scale, drawX, drawZ, _cameraYaw)); + + Color col = s.Tier switch + { + SpectatorTier.Tourist => GoldCol, + SpectatorTier.Patron => PatronColor, + _ => RedCol + }; + + if (live && s.Stance != SpectatorStance.Neutral && s.HasTargetLos && s.TargetContenderId.HasValue) + { + int tid = s.TargetContenderId.Value; + if (tid >= 0 && tid < _state.Contenders.Count && _state.Contenders[tid].Alive) + { + var tgt = _state.Contenders[tid]; + bool targetVisible = tgt.IsPlayer || + (_state.ContenderContacts.TryGetValue(tgt.Id, out var tgtMem) && tgtMem.VisibleToPlayer); + if (targetVisible) + { + float tgtClampR = MathF.Max(4f, radius - (tgt.IsPlayer ? 7.5f : 4.3f)); + var tp = ClampToRadarDisc(center, tgtClampR, WorldToRadar(center, scale, tgt.X, tgt.Z, _cameraYaw)); + DrawLine(p, tp, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f), 1.3f); + } + } + col = RedCol; + } + + if (!live) + { + float alpha = mem.FaintHorizonPing + ? 0.42f + : Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); + Color ghostCol = mem.FaintHorizonPing ? GoldCol : col; + DrawCircle(p, blipR, new Color(ghostCol.R, ghostCol.G, ghostCol.B, alpha)); + } + else + { + DrawCircle(p, blipR, col); + } + } + + // Contenders (player always live; rivals obey LOS + 5s ghost memory) + float sinY = MathF.Sin(_cameraYaw); + float cosY = MathF.Cos(_cameraYaw); + for (int i = 0; i < _state.Contenders.Count; i++) + { + var c = _state.Contenders[i]; + if (!c.Alive) continue; + + if (c.IsPlayer) + { + float playerClampR = MathF.Max(4f, radius - 6.5f - 1f); + var p = ClampToRadarDisc(center, playerClampR, WorldToRadar(center, scale, c.X, c.Z, _cameraYaw)); + var dir = new Vector2( + -MathF.Sin(c.Yaw) * cosY + MathF.Cos(c.Yaw) * sinY, + -(MathF.Sin(c.Yaw) * sinY + MathF.Cos(c.Yaw) * cosY)); + var perp = new Vector2(-dir.Y, dir.X); + var pts = new[] + { + p + dir * 6.5f, + p - dir * 4.5f + perp * 4.2f, + p - dir * 4.5f - perp * 4.2f + }; + DrawColoredPolygon(pts, OliveCol); + continue; + } + + _state.ContenderContacts.TryGetValue(c.Id, out var mem); + if (!MatchState.IsContactOnRadar(mem)) + { + continue; + } + + if (mem!.VisibleToPlayer) + { + float rivalClampR = MathF.Max(4f, radius - 3.3f - 1f); + var p = ClampToRadarDisc(center, rivalClampR, WorldToRadar(center, scale, c.X, c.Z, _cameraYaw)); + DrawCircle(p, 3.3f, OrangeCol); + } + else + { + float ghostClampR = MathF.Max(4f, radius - 2.8f - 1f); + var p = ClampToRadarDisc(center, ghostClampR, WorldToRadar(center, scale, mem.LastSeenX, mem.LastSeenZ, _cameraYaw)); + float alpha = Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); + DrawCircle(p, 2.8f, new Color(OrangeCol.R, OrangeCol.G, OrangeCol.B, alpha)); + } + } + } + + private static readonly Color PatronColor = Color.FromHtml("#4ba8a5"); + } +} diff --git a/client/InventoryGridControl.cs b/client/InventoryGridControl.cs new file mode 100644 index 0000000..15a3456 --- /dev/null +++ b/client/InventoryGridControl.cs @@ -0,0 +1,783 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Godot Control owning inventory_grid.gdshader: +/// packs a into a 3W x H RGBA8 nearest-filter data texture +/// and a W x H RGBA8 bilinear temperature texture, tracks hover and hit-pulse decay, +/// and provides accurate mouse-to-cell hit-testing for HUD and Garage schematics. +/// +public partial class InventoryGridControl : Control +{ + private static readonly Color ColBgIntact = Color.FromHtml("#263022"); + private static readonly Color ColBgArmorFull = Color.FromHtml("#4b6136"); + private static readonly Color ColBgDamaged = Color.FromHtml("#8a3c22"); + private static readonly Color ColBgStripped = Color.FromHtml("#2b1210"); + + private static readonly Color ColBorderHull = Color.FromHtml("#7a856e"); + private static readonly Color ColBorderRadiatorCell = Color.FromHtml("#44d9e8"); + private static readonly Color ColBorderWeapon = Color.FromHtml("#e08a4a"); + private static readonly Color ColBorderEngine = Color.FromHtml("#e6b838"); + private static readonly Color ColBorderRadiator = Color.FromHtml("#44d9e8"); + private static readonly Color ColBorderArmor = Color.FromHtml("#9bb06a"); + private static readonly Color ColBorderUtility = Color.FromHtml("#4ba8a5"); + private static readonly Color ColGold = Color.FromHtml("#e6b838"); + private static readonly Color ColTextLight = Color.FromHtml("#e4dfd2"); + + // 8-neighbor offsets in Aetheria mask order: N, E, S, W, NE, SE, SW, NW (screen Y-down) + private static readonly (int Dx, int Dy)[] Offsets8 = + { + (0, -1), (1, 0), (0, 1), (-1, 0), + (1, -1), (1, 1), (-1, 1), (-1, -1) + }; + + private static Shader? _sharedShader; + + private readonly TextureRect _gridSurface; + private readonly LabelsOverlay _labelsOverlay; + private readonly ShaderMaterial _material; + + private Image? _dataImage; + private ImageTexture? _dataTex; + private Image? _tempImage; + private ImageTexture? _tempTex; + + private int _gridWidth; + private int _gridHeight; + private ChassisGrid? _grid; + private ChassisSpec? _spec; + private int _selectedCargoIndex = -1; + private int _lastHitSequence = -1; + + private HardpointSpec?[,] _hardpointLookup = new HardpointSpec?[0, 0]; + private float[,] _prevArmor = new float[0, 0]; + private float[,] _prevTemp = new float[0, 0]; + private float[,] _hitPulse = new float[0, 0]; + + private int _lastSelectedCargoIndex = int.MinValue; + private int _lastMountedSig = int.MinValue; + private Vector2I? _hoveredCell; + private bool _thermalEnabled; + private float _thermalBlend; + private bool _dataDirty; + private bool _tempDirty; + + public InventoryGridControl() + { + MouseFilter = MouseFilterEnum.Stop; + + _sharedShader ??= GD.Load("res://inventory_grid.gdshader"); + _material = new ShaderMaterial { Shader = _sharedShader }; + + _gridSurface = new TextureRect + { + Name = "GridShaderSurface", + MouseFilter = MouseFilterEnum.Ignore, + ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize, + StretchMode = TextureRect.StretchModeEnum.Scale, + Material = _material + }; + _gridSurface.SetAnchorsPreset(LayoutPreset.FullRect); + AddChild(_gridSurface); + + _labelsOverlay = new LabelsOverlay(this) + { + Name = "GridLabelsOverlay", + MouseFilter = MouseFilterEnum.Ignore + }; + _labelsOverlay.SetAnchorsPreset(LayoutPreset.FullRect); + AddChild(_labelsOverlay); + + MouseExited += OnMouseExited; + } + + public ShaderMaterial ShaderMaterial => _material; + public Control ShaderSurface => _gridSurface; + public ChassisGrid? Grid => _grid; + public Vector2I? HoveredCell => _hoveredCell; + public HardpointSpec? HoveredHardpoint => + _hoveredCell is { } c && _grid is not null && c.X >= 0 && c.Y >= 0 && c.X < _gridWidth && c.Y < _gridHeight + ? _hardpointLookup[c.X, c.Y] + : null; + + public bool ThermalEnabled + { + get => _thermalEnabled; + set + { + if (_thermalEnabled == value) return; + _thermalEnabled = value; + } + } + + public float ThermalBlend => _thermalBlend; + + public void SetThermalInstant(bool enabled) + { + _thermalEnabled = enabled; + _thermalBlend = enabled ? 1f : 0f; + _material.SetShaderParameter("thermal_mode", _thermalBlend); + _labelsOverlay.QueueRedraw(); + } + + public event Action? CellClicked; + public event Action? HardpointClicked; + public event Action? HoverChanged; + + public override void _Notification(int what) + { + if (what == NotificationResized) + { + SyncRectUniform(); + _labelsOverlay.QueueRedraw(); + } + } + + public override void _Process(double delta) + { + float dt = (float)delta; + bool needUniform = false; + + float targetThermal = _thermalEnabled ? 1f : 0f; + if (MathF.Abs(_thermalBlend - targetThermal) > 0.001f) + { + float t = dt >= 0.25f ? 1f : 1f - MathF.Exp(-dt * 14f); + _thermalBlend = Mathf.Lerp(_thermalBlend, targetThermal, t); + if (MathF.Abs(_thermalBlend - targetThermal) < 0.005f) + { + _thermalBlend = targetThermal; + } + needUniform = true; + _labelsOverlay.QueueRedraw(); + } + + if (needUniform) + { + _material.SetShaderParameter("thermal_mode", _thermalBlend); + } + + bool anyPulse = false; + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (_hitPulse[x, y] > 0f) + { + _hitPulse[x, y] = MathF.Max(0f, _hitPulse[x, y] - dt * 2.8f); + anyPulse = true; + } + } + } + + if (anyPulse && _grid is not null) + { + PackDataTexture(_grid); + FlushTextures(); + } + } + + public override void _GuiInput(InputEvent @event) + { + if (@event is InputEventMouseMotion mm) + { + UpdateHover(mm.Position); + return; + } + + if (@event is InputEventMouseButton mb && mb.Pressed && mb.ButtonIndex == MouseButton.Left) + { + UpdateHover(mb.Position); + if (TryGetCellAt(mb.Position, out var cell) && _grid is not null && _grid.Spec.IsActive(cell.X, cell.Y)) + { + CellClicked?.Invoke(cell.X, cell.Y); + var hp = _hardpointLookup[cell.X, cell.Y]; + if (hp is not null) + { + HardpointClicked?.Invoke(hp.Id); + } + AcceptEvent(); + } + } + } + + public void SetGrid(ChassisGrid grid, int selectedCargoIndex = -1) + { + if (grid is null) throw new ArgumentNullException(nameof(grid)); + + bool gridIdentityChanged = !ReferenceEquals(_grid, grid) + || !ReferenceEquals(_spec, grid.Spec) + || _gridWidth != grid.Spec.Width + || _gridHeight != grid.Spec.Height; + + _grid = grid; + _spec = grid.Spec; + _selectedCargoIndex = selectedCargoIndex; + + if (gridIdentityChanged) + { + EnsureBackingBuffers(grid); + _lastSelectedCargoIndex = selectedCargoIndex; + _lastMountedSig = ComputeMountedSignature(grid); + SnapshotTemperatures(grid); + PackDataTexture(grid); + PackTempTexture(grid); + FlushTextures(); + SyncRectUniform(); + _labelsOverlay.QueueRedraw(); + return; + } + + bool dataChanged = DetectHits(grid); + int mountedSig = ComputeMountedSignature(grid); + if (_lastSelectedCargoIndex != selectedCargoIndex || _lastMountedSig != mountedSig) + { + _lastSelectedCargoIndex = selectedCargoIndex; + _lastMountedSig = mountedSig; + dataChanged = true; + } + + bool tempChanged = HasTemperatureChanged(grid); + + if (dataChanged) + { + PackDataTexture(grid); + _labelsOverlay.QueueRedraw(); + } + if (tempChanged) + { + SnapshotTemperatures(grid); + PackTempTexture(grid); + } + if (dataChanged || tempChanged) + { + FlushTextures(); + } + } + + public void TriggerHitPulse(int x, int y, float intensity = 1f) + { + if (_grid is null || x < 0 || y < 0 || x >= _gridWidth || y >= _gridHeight) return; + if (!_grid.Spec.IsActive(x, y)) return; + _hitPulse[x, y] = Math.Clamp(intensity, 0f, 1f); + PackDataTexture(_grid); + FlushTextures(); + } + + public bool TryGetCellAt(Vector2 localPos, out Vector2I cell) + { + cell = default; + if (_grid is null || _gridWidth <= 0 || _gridHeight <= 0) return false; + ComputeCellLayout(out float cellSize, out Vector2 origin); + if (cellSize <= 0.5f) return false; + + Vector2 rel = (localPos - origin) / cellSize; + int cx = Mathf.FloorToInt(rel.X); + int cy = Mathf.FloorToInt(rel.Y); + if (cx < 0 || cy < 0 || cx >= _gridWidth || cy >= _gridHeight) return false; + cell = new Vector2I(cx, cy); + return true; + } + + public HardpointSpec? GetHardpointAt(int x, int y) + { + if (x < 0 || y < 0 || x >= _gridWidth || y >= _gridHeight) return null; + return _hardpointLookup[x, y]; + } + + public void ComputeCellLayout(out float cellSize, out Vector2 origin) + { + int w = Math.Max(1, _gridWidth); + int h = Math.Max(1, _gridHeight); + Vector2 size = Size; + if (size.X < 2f || size.Y < 2f) + { + size = CustomMinimumSize; + } + cellSize = MathF.Min(size.X / w, size.Y / h); + origin = (size - new Vector2(w * cellSize, h * cellSize)) * 0.5f; + } + + private void OnMouseExited() + { + if (_hoveredCell.HasValue) + { + _hoveredCell = null; + HoverChanged?.Invoke(null, null); + if (_grid is not null) + { + PackDataTexture(_grid); + FlushTextures(); + } + } + } + + private void UpdateHover(Vector2 localPos) + { + Vector2I? next = null; + if (TryGetCellAt(localPos, out var c) && _grid is not null && _grid.Spec.IsActive(c.X, c.Y)) + { + next = c; + } + + if (_hoveredCell == next) return; + _hoveredCell = next; + HoverChanged?.Invoke(next, HoveredHardpoint); + if (_grid is not null) + { + PackDataTexture(_grid); + FlushTextures(); + } + } + + private void EnsureBackingBuffers(ChassisGrid grid) + { + int w = grid.Spec.Width; + int h = grid.Spec.Height; + bool dimsChanged = w != _gridWidth || h != _gridHeight || _dataTex is null || _tempTex is null; + + _gridWidth = w; + _gridHeight = h; + _hardpointLookup = new HardpointSpec?[w, h]; + for (int i = 0; i < grid.Spec.Hardpoints.Length; i++) + { + var hp = grid.Spec.Hardpoints[i]; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int hx = hp.X + dx; + int hy = hp.Y + dy; + if (hx >= 0 && hy >= 0 && hx < w && hy < h && grid.Spec.IsActive(hx, hy)) + { + _hardpointLookup[hx, hy] = hp; + } + } + } + } + + _prevArmor = new float[w, h]; + _prevTemp = new float[w, h]; + _hitPulse = new float[w, h]; + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + _prevArmor[x, y] = grid.Armor[x, y]; + _prevTemp[x, y] = grid.Temperature[x, y]; + } + } + _lastHitSequence = grid.HitSequence; + bool hadHover = _hoveredCell.HasValue; + _hoveredCell = null; + + if (dimsChanged) + { + _dataImage = Image.CreateEmpty(Math.Max(1, w * 3), Math.Max(1, h), false, Image.Format.Rgba8); + _dataTex = ImageTexture.CreateFromImage(_dataImage); + _tempImage = Image.CreateEmpty(Math.Max(1, w), Math.Max(1, h), false, Image.Format.Rgba8); + _tempTex = ImageTexture.CreateFromImage(_tempImage); + + _gridSurface.Texture = _dataTex; + _material.SetShaderParameter("data_tex", _dataTex); + _material.SetShaderParameter("temp_tex", _tempTex); + } + + _material.SetShaderParameter("grid_size", new Vector2(w, h)); + _material.SetShaderParameter("thermal_mode", _thermalBlend); + + if (hadHover) + { + HoverChanged?.Invoke(null, null); + } + } + + private bool DetectHits(ChassisGrid grid) + { + bool changed = false; + if (grid.HitSequence != _lastHitSequence) + { + _lastHitSequence = grid.HitSequence; + if (grid.LastHitX >= 0 && grid.LastHitY >= 0 && grid.LastHitX < _gridWidth && grid.LastHitY < _gridHeight) + { + _hitPulse[grid.LastHitX, grid.LastHitY] = 1f; + } + changed = true; + } + + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + float arm = grid.Armor[x, y]; + if (arm < _prevArmor[x, y] - 0.05f) + { + _hitPulse[x, y] = 1f; + _prevArmor[x, y] = arm; + changed = true; + } + else if (MathF.Abs(arm - _prevArmor[x, y]) > 0.01f) + { + _prevArmor[x, y] = arm; + changed = true; + } + } + } + return changed; + } + + private static int ComputeMountedSignature(ChassisGrid grid) + { + var hc = new HashCode(); + hc.Add(grid.Mounted.Count); + for (int i = 0; i < grid.Mounted.Count; i++) + { + var m = grid.Mounted[i]; + hc.Add(m.HardpointId); + hc.Add(m.Spec.Id); + hc.Add(m.CurrentPerformance > 0.05f); + } + return hc.ToHashCode(); + } + + private bool HasTemperatureChanged(ChassisGrid grid) + { + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (MathF.Abs(grid.Temperature[x, y] - _prevTemp[x, y]) >= 0.25f) + { + return true; + } + } + } + return false; + } + + private void SnapshotTemperatures(ChassisGrid grid) + { + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + _prevTemp[x, y] = grid.Temperature[x, y]; + } + } + } + + private void PackDataTexture(ChassisGrid grid) + { + if (_dataImage is null) return; + var spec = grid.Spec; + + ModuleSpec? selectedCargo = _selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count + ? grid.Cargo[_selectedCargoIndex] + : null; + + HardpointSpec? hoveredHp = HoveredHardpoint; + + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (!spec.IsActive(x, y)) + { + var zero = new Color(0f, 0f, 0f, 0f); + _dataImage.SetPixel(x * 3 + 0, y, zero); + _dataImage.SetPixel(x * 3 + 1, y, zero); + _dataImage.SetPixel(x * 3 + 2, y, zero); + continue; + } + + var hp = _hardpointLookup[x, y]; + var mounted = hp is not null ? grid.GetMountedOn(hp.Id) : null; + float maxArm = MathF.Max(1f, grid.MaxArmor[x, y]); + float arm = grid.Armor[x, y]; + float armRatio = Math.Clamp(arm / maxArm, 0f, 1f); + bool stripped = arm <= 0.01f; + bool isBorder = grid.BorderCells[x, y]; + bool isCompatible = hp is not null && selectedCargo is not null && ChassisGrid.CanFit(hp, selectedCargo); + bool isHovered = (_hoveredCell is { } hc && hc.X == x && hc.Y == y) + || (hoveredHp is not null && ReferenceEquals(hp, hoveredHp)); + + // 3x+0: Cell / item fill & armor tint + Color fill; + if (stripped) + { + fill = ColBgStripped; + } + else + { + Color armorCol = armRatio > 0.5f + ? ColBgIntact.Lerp(ColBgArmorFull, (armRatio - 0.5f) * 2f) + : ColBgDamaged.Lerp(ColBgIntact, armRatio * 2f); + + if (mounted is not null) + { + Color modTint = mounted.Spec.IsImperial ? ColGold : KindColor(hp!.Kind); + fill = armorCol.Lerp(modTint, 0.28f); + } + else + { + fill = armorCol; + } + } + fill.A = stripped ? 0.92f : 0.86f; + + // 3x+1: Border / L-bracket / pipe accent color + Color accent; + if (hp is not null) + { + if (isCompatible) + { + accent = ColGold; + } + else if (mounted is { Spec.IsImperial: true }) + { + accent = ColGold; + } + else + { + accent = KindColor(hp.Kind); + if (mounted is null) + { + accent = accent.Lerp(ColBorderHull, 0.45f); + } + } + accent.A = 0.96f; + } + else if (isBorder) + { + accent = ColBorderHull.Lerp(ColBorderRadiatorCell, 0.28f); + accent.A = 0.72f; + } + else + { + accent = ColBorderHull; + accent.A = 0.62f; + } + + // 3x+2.R: 8-bit neighbor mismatch mask (Aetheria rule) + byte mask = 0; + for (int i = 0; i < Offsets8.Length; i++) + { + int nx = x + Offsets8[i].Dx; + int ny = y + Offsets8[i].Dy; + bool match; + if (!spec.IsActive(nx, ny)) + { + match = false; + } + else if (hp is not null) + { + match = ReferenceEquals(_hardpointLookup[nx, ny], hp); + } + else + { + match = _hardpointLookup[nx, ny] is null; + } + + if (!match) + { + mask |= (byte)(1 << i); + } + } + + // 3x+2.G: flags byte + int flags = 1; // bit 0: present + if (mounted is not null) flags |= 2; // bit 1: mounted module / item + if (isHovered) flags |= 4; // bit 2: hovered + if (stripped) flags |= 8; // bit 3: stripped / Armor == 0 + if (isCompatible) flags |= 16; // bit 4: compatible cargo drop target + if (isBorder) flags |= 32; // bit 5: border radiator cell + + // 3x+2.B: 4-bit N/E/S/W thermal conductivity pipe mask + byte cond = 0; + for (int i = 0; i < 4; i++) + { + int nx = x + Offsets8[i].Dx; + int ny = y + Offsets8[i].Dy; + if (spec.IsActive(nx, ny)) + { + cond |= (byte)(1 << i); + } + } + + float pulse = Math.Clamp(_hitPulse[x, y], 0f, 1f); + var meta = new Color(mask / 255f, flags / 255f, cond / 255f, pulse); + + _dataImage.SetPixel(x * 3 + 0, y, fill); + _dataImage.SetPixel(x * 3 + 1, y, accent); + _dataImage.SetPixel(x * 3 + 2, y, meta); + } + } + + _dataDirty = true; + } + + private void PackTempTexture(ChassisGrid grid) + { + if (_tempImage is null) return; + var spec = grid.Spec; + + // First pass: active cells + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (!spec.IsActive(x, y)) continue; + + float t = grid.Temperature[x, y]; + float normTemp = Math.Clamp((t - ChassisGrid.AmbientTemp) / 180f, 0f, 1f); + + float stress = normTemp * 0.25f; + var hp = _hardpointLookup[x, y]; + var mounted = hp is not null ? grid.GetMountedOn(hp.Id) : null; + if (mounted is not null) + { + float highPlateau = mounted.Spec.OptimalTemp + mounted.Spec.PlateauWidth * 0.5f; + if (t > highPlateau) + { + float overSpan = MathF.Max(1f, mounted.Spec.MaxTemp - highPlateau); + stress = 0.5f + 0.5f * Math.Clamp((t - highPlateau) / overSpan, 0f, 1f); + } + else + { + stress = 0.5f * Math.Clamp(mounted.CurrentPerformance, 0f, 1f); + } + } + + _tempImage.SetPixel(x, y, new Color(normTemp, stress, 1f, 1f)); + } + } + + // Second pass: extrapolate boundary temperature into inactive neighbor cells + // so bilinear filter_linear sampling stays smooth without cold zero bleed at hull edges. + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) + { + if (spec.IsActive(x, y)) continue; + + float sumR = 0f; + float sumG = 0f; + int count = 0; + for (int i = 0; i < Offsets8.Length; i++) + { + int nx = x + Offsets8[i].Dx; + int ny = y + Offsets8[i].Dy; + if (spec.IsActive(nx, ny)) + { + var c = _tempImage.GetPixel(nx, ny); + sumR += c.R; + sumG += c.G; + count++; + } + } + + if (count > 0) + { + _tempImage.SetPixel(x, y, new Color(sumR / count, sumG / count, 0f, 1f)); + } + else + { + _tempImage.SetPixel(x, y, new Color(0f, 0f, 0f, 1f)); + } + } + } + + _tempDirty = true; + } + + private void FlushTextures() + { + if (_dataDirty && _dataTex is not null && _dataImage is not null) + { + _dataTex.Update(_dataImage); + _dataDirty = false; + } + if (_tempDirty && _tempTex is not null && _tempImage is not null) + { + _tempTex.Update(_tempImage); + _tempDirty = false; + } + } + + private void SyncRectUniform() + { + Vector2 size = Size; + if (size.X < 2f || size.Y < 2f) + { + size = CustomMinimumSize; + } + _material.SetShaderParameter("rect_size", size); + } + + private static Color KindColor(HardpointKind kind) => kind switch + { + HardpointKind.Weapon => ColBorderWeapon, + HardpointKind.Engine => ColBorderEngine, + HardpointKind.Radiator => ColBorderRadiator, + HardpointKind.Armor => ColBorderArmor, + HardpointKind.Utility => ColBorderUtility, + _ => ColTextLight + }; + + private sealed partial class LabelsOverlay : Control + { + private readonly InventoryGridControl _owner; + + public LabelsOverlay(InventoryGridControl owner) => _owner = owner; + + public override void _Draw() + { + var grid = _owner._grid; + if (grid is null) return; + + _owner.ComputeCellLayout(out float cellSize, out Vector2 origin); + if (cellSize < 14f) return; + + var spec = grid.Spec; + int fontSize = cellSize >= 38f ? 10 : 9; + float alpha = Mathf.Lerp(0.95f, 0.55f, _owner._thermalBlend); + + for (int i = 0; i < spec.Hardpoints.Length; i++) + { + var hp = spec.Hardpoints[i]; + var mounted = grid.GetMountedOn(hp.Id); + var pos = origin + new Vector2(hp.X * cellSize, hp.Y * cellSize); + float maxW = MathF.Max(12f, hp.Width * cellSize - 6f); + + string tag = mounted is not null + ? $"{mounted.Spec.Kind.ToString()[..1]}:{mounted.CurrentTemp:F0}°" + : hp.Kind.ToString()[..3].ToUpperInvariant(); + + Color col = mounted is { Spec.IsImperial: true } ? ColGold : ColTextLight; + col.A = alpha; + + // Dark shadow for crisp legibility over bright thermal glow + DrawString( + ThemeDB.FallbackFont, + pos + new Vector2(7f, fontSize + 6f), + tag, + HorizontalAlignment.Left, + maxW - 2f, + fontSize, + new Color(0.04f, 0.05f, 0.04f, alpha * 0.9f)); + + DrawString( + ThemeDB.FallbackFont, + pos + new Vector2(6f, fontSize + 5f), + tag, + HorizontalAlignment.Left, + maxW - 2f, + fontSize, + col); + } + } + } +} diff --git a/client/Main.cs b/client/Main.cs new file mode 100644 index 0000000..079399d --- /dev/null +++ b/client/Main.cs @@ -0,0 +1,592 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using Godot; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +/// +/// Root Godot node for Rust to Dust. +/// Godot physics is Dummy; owns 100% of vehicle, thermal, spectator, and terrain physics at 60 Hz. +/// +public partial class Main : Node3D +{ + private TerrainRenderer _terrain = null!; + private ArenaRenderer _arena = null!; + private Camera3D _camera = null!; + private Hud _hud = null!; + private ArenaSession? _session; + + private PlayerInput? _scriptedInput; + private float _cameraYaw; + private float _cameraPitch = Mathf.DegToRad(12f); + private float _cameraZoom = 1.0f; + private Vector3 _cameraSmoothedAnchor = Vector3.Zero; + private float _elapsedSeconds; + private bool _interactQueued; + private int _seed = 42; + + // Temporary Step 1/Step 3 perf probe (enabled only when RTD_PERF_FRAMES is set) + private int _perfTargetFrames; + private int _perfFrameCount; + private int _perfPhysicsTicks; + private long _perfLastFrameTick; + private int _perfLastDirtyRebakes; + private readonly List _perfFrameMs = new(); + private readonly List _perfPhysicsStepMs = new(); + private readonly List _perfTerrainSyncMs = new(); + private readonly List _perfArenaSyncMs = new(); + private readonly List _perfHudMs = new(); + private readonly List _perfDirtyRebakeDelta = new(); + private readonly List _perfDrawCalls = new(); + private readonly List _perfPrimitives = new(); + private readonly List _perfObjects = new(); + private readonly List _perfNodeCount = new(); + private readonly List _perfTimeProcess = new(); + private readonly List _perfTimePhysicsProcess = new(); + private double _perfPendingStepMs; + private double _perfPendingTerrainMs; + private double _perfPendingArenaMs; + private double _perfCamMsSum; + + public ArenaSession Session => _session ?? throw new InvalidOperationException($"No active ArenaSession ({Failure ?? "uninitialized"})"); + public TerrainRenderer Terrain => _terrain; + public ArenaRenderer Arena => _arena; + public Hud Hud => _hud; + public string? Failure { get; private set; } + public int Seed => _seed; + public float CameraYaw => _cameraYaw; + + public override void _Ready() + { + SetupLightingAndSky(); + + _terrain = new TerrainRenderer { Name = "Terrain" }; + AddChild(_terrain); + + _arena = new ArenaRenderer { Name = "Arena" }; + AddChild(_arena); + + _camera = new Camera3D + { + Name = "ShoulderCamera", + Current = true, + Fov = 58f, + Far = 1800f + }; + AddChild(_camera); + + _hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw) { Name = "Hud" }; + AddChild(_hud); + + if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0) + { + _perfTargetFrames = perfFrames; + ArenaSession.PerfEnabled = true; + } + + Reset(_seed); + _perfLastFrameTick = Stopwatch.GetTimestamp(); + _perfLastDirtyRebakes = _terrain.DirtyRebakes; + } + + public override void _ExitTree() + { + _session?.Dispose(); + _session = null; + } + + public void Reset(int seed) + { + _seed = seed; + _session?.Dispose(); + _session = null; + Failure = null; + + try + { + _session = new ArenaSession(seed); + var p = _session.State.Player; + _cameraYaw = p.Yaw; + _cameraPitch = Mathf.DegToRad(12f); + _cameraZoom = 1.0f; + _cameraSmoothedAnchor = ComputeTargetAnchor(p); + + _terrain.InvalidateAll(); + _terrain.Sync(_session.State.Terrain); + _arena.Sync(_session, _elapsedSeconds, 0f); + UpdateCamera(1f); + _hud.Sync(_session); + + if (DisplayServer.GetName() != "headless" && !_hud.GarageExpanded && _perfTargetFrames == 0) + { + Input.MouseMode = Input.MouseModeEnum.Captured; + } + } + catch (Exception ex) + { + Failure = ex.Message; + GD.PushError("ArenaSession startup failed: " + ex); + } + } + + public void SetScriptedInput(PlayerInput? input) => _scriptedInput = input; + + public override void _UnhandledInput(InputEvent @event) + { + if (@event is InputEventMouseMotion mm && Input.MouseMode == Input.MouseModeEnum.Captured) + { + _cameraYaw -= mm.Relative.X * 0.0028f; + _cameraPitch = Math.Clamp( + _cameraPitch + mm.Relative.Y * 0.0024f, + Mathf.DegToRad(-78f), + Mathf.DegToRad(62f)); + return; + } + + if (@event is InputEventKey key && key.Pressed && !key.Echo) + { + switch (key.Keycode) + { + case Key.E: + _interactQueued = true; + break; + case Key.Tab: + _hud.ToggleGarage(); + if (DisplayServer.GetName() != "headless") + { + Input.MouseMode = _hud.GarageExpanded + ? Input.MouseModeEnum.Visible + : Input.MouseModeEnum.Captured; + } + break; + case Key.T: + _hud.ToggleThermal(); + break; + case Key.R: + Reset(_seed + 1); + break; + case Key.Escape: + if (_hud.GarageExpanded) + { + _hud.ToggleGarage(); + if (DisplayServer.GetName() != "headless") + { + Input.MouseMode = Input.MouseModeEnum.Visible; + } + } + else if (DisplayServer.GetName() != "headless") + { + Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Captured + ? Input.MouseModeEnum.Visible + : Input.MouseModeEnum.Captured; + } + break; + } + } + else if (@event is InputEventMouseButton mb && mb.Pressed) + { + if (mb.ButtonIndex == MouseButton.WheelUp) + { + _cameraZoom = Math.Clamp(_cameraZoom - 0.08f, 0.75f, 1.6f); + } + else if (mb.ButtonIndex == MouseButton.WheelDown) + { + _cameraZoom = Math.Clamp(_cameraZoom + 0.08f, 0.75f, 1.6f); + } + else if (mb.ButtonIndex == MouseButton.Left && + Input.MouseMode == Input.MouseModeEnum.Visible && + !_hud.GarageExpanded && + !_hud.IsPointerOverInteractiveHud(mb.Position) && + DisplayServer.GetName() != "headless") + { + Input.MouseMode = Input.MouseModeEnum.Captured; + } + } + } + + public override void _PhysicsProcess(double delta) + { + if (_session is null) + { + return; + } + + _elapsedSeconds += (float)delta; + var input = _scriptedInput ?? GatherPlayerInput(); + _interactQueued = false; + + if (_perfTargetFrames > 0) + { + long t0 = Stopwatch.GetTimestamp(); + _session.Step(input); + long t1 = Stopwatch.GetTimestamp(); + _terrain.Sync(_session.State.Terrain); + long t2 = Stopwatch.GetTimestamp(); + _arena.Sync(_session, _elapsedSeconds, (float)delta); + long t3 = Stopwatch.GetTimestamp(); + double toMs = 1000.0 / Stopwatch.Frequency; + _perfPendingStepMs += (t1 - t0) * toMs; + _perfPendingTerrainMs += (t2 - t1) * toMs; + _perfPendingArenaMs += (t3 - t2) * toMs; + _perfPhysicsTicks++; + } + else + { + _session.Step(input); + _terrain.Sync(_session.State.Terrain); + _arena.Sync(_session, _elapsedSeconds, (float)delta); + } + } + + public override void _Process(double delta) + { + if (_session is null) + { + return; + } + + if (_perfTargetFrames > 0) + { + long tc0 = Stopwatch.GetTimestamp(); + UpdateCamera((float)delta); + _terrain.UpdateTileLod(_camera.GlobalPosition); + long th0 = Stopwatch.GetTimestamp(); + _hud.Sync(_session); + long th1 = Stopwatch.GetTimestamp(); + _perfCamMsSum += (th0 - tc0) * 1000.0 / Stopwatch.Frequency; + double hudMs = (th1 - th0) * 1000.0 / Stopwatch.Frequency; + + long now = Stopwatch.GetTimestamp(); + double frameMs = (now - _perfLastFrameTick) * 1000.0 / Stopwatch.Frequency; + _perfLastFrameTick = now; + + _perfFrameMs.Add(frameMs); + _perfPhysicsStepMs.Add(_perfPendingStepMs); + _perfTerrainSyncMs.Add(_perfPendingTerrainMs); + _perfArenaSyncMs.Add(_perfPendingArenaMs); + _perfHudMs.Add(hudMs); + _perfPendingStepMs = 0; + _perfPendingTerrainMs = 0; + _perfPendingArenaMs = 0; + + int rebakesNow = _terrain.DirtyRebakes; + _perfDirtyRebakeDelta.Add(rebakesNow - _perfLastDirtyRebakes); + _perfLastDirtyRebakes = rebakesNow; + + _perfDrawCalls.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalDrawCallsInFrame)); + _perfPrimitives.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalPrimitivesInFrame)); + _perfObjects.Add(Performance.GetMonitor(Performance.Monitor.RenderTotalObjectsInFrame)); + _perfNodeCount.Add(Performance.GetMonitor(Performance.Monitor.ObjectNodeCount)); + _perfTimeProcess.Add(Performance.GetMonitor(Performance.Monitor.TimeProcess) * 1000.0); + _perfTimePhysicsProcess.Add(Performance.GetMonitor(Performance.Monitor.TimePhysicsProcess) * 1000.0); + + _perfFrameCount++; + if (_perfFrameCount >= _perfTargetFrames) + { + PrintPerfSummaryAndQuit(); + } + } + else + { + UpdateCamera((float)delta); + _terrain.UpdateTileLod(_camera.GlobalPosition); + _hud.Sync(_session); + } + } + + private void PrintPerfSummaryAndQuit() + { + static double Avg(List v) + { + if (v.Count == 0) return 0; + double s = 0; + foreach (double x in v) s += x; + return s / v.Count; + } + static double P95(List v) + { + if (v.Count == 0) return 0; + var sorted = new List(v); + sorted.Sort(); + int idx = Math.Clamp((int)Math.Ceiling(sorted.Count * 0.95) - 1, 0, sorted.Count - 1); + return sorted[idx]; + } + double totalMs = 0; + foreach (double x in _perfFrameMs) totalMs += x; + double fps = totalMs > 0 ? (_perfFrameMs.Count * 1000.0 / totalMs) : 0; + double rebakeAvg = 0; + int rebakeTotal = 0; + foreach (int r in _perfDirtyRebakeDelta) rebakeTotal += r; + rebakeAvg = _perfDirtyRebakeDelta.Count > 0 ? (double)rebakeTotal / _perfDirtyRebakeDelta.Count : 0; + + double steadyMs = 0; + int steadyCount = Math.Max(0, _perfFrameMs.Count - 10); + for (int i = 10; i < _perfFrameMs.Count; i++) steadyMs += _perfFrameMs[i]; + double steadyAvgMs = steadyCount > 0 ? steadyMs / steadyCount : 0; + double steadyFps = steadyAvgMs > 0 ? 1000.0 / steadyAvgMs : 0; + + GD.Print("=== PERF BENCHMARK SUMMARY ==="); + GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..59)={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}"); + GD.Print($"frameMs: avg={Avg(_perfFrameMs):F2} steadyAvg={steadyAvgMs:F2} p95={P95(_perfFrameMs):F2}"); + GD.Print($"physicsStepMs/frame: avg={Avg(_perfPhysicsStepMs):F2} p95={P95(_perfPhysicsStepMs):F2}"); + GD.Print($"terrainSyncMs/frame: avg={Avg(_perfTerrainSyncMs):F2} p95={P95(_perfTerrainSyncMs):F2} dirtyRebakesTotal={rebakeTotal} dirtyRebakesAvg={rebakeAvg:F2}"); + GD.Print($"arenaSyncMs/frame: avg={Avg(_perfArenaSyncMs):F2} p95={P95(_perfArenaSyncMs):F2}"); + GD.Print($"hudMs/frame: avg={Avg(_perfHudMs):F2} p95={P95(_perfHudMs):F2}"); + GD.Print($"RenderTotalDrawCallsInFrame: avg={Avg(_perfDrawCalls):F0} max={P95(_perfDrawCalls):F0}"); + GD.Print($"RenderTotalPrimitivesInFrame: avg={Avg(_perfPrimitives):F0}"); + GD.Print($"RenderTotalObjectsInFrame: avg={Avg(_perfObjects):F0}"); + GD.Print($"ObjectNodeCount: avg={Avg(_perfNodeCount):F0}"); + GD.Print($"TimeProcessMs: avg={Avg(_perfTimeProcess):F2}"); + GD.Print($"TimePhysicsProcessMs: avg={Avg(_perfTimePhysicsProcess):F2}"); + GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}"); + GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / _perfPhysicsTicks:F2} ai={ArenaSession.PerfAiMs / _perfPhysicsTicks:F2} drive={ArenaSession.PerfDriveMs / _perfPhysicsTicks:F2} world={ArenaSession.PerfWorldMs / _perfPhysicsTicks:F2} sync={ArenaSession.PerfBodySyncMs / _perfPhysicsTicks:F2} detect={ArenaSession.PerfDetectMs / _perfPhysicsTicks:F2} weapons={ArenaSession.PerfWeaponsMs / _perfPhysicsTicks:F2}"); + foreach (var kv in _arena.AssetCache.Vehicles) + { + int tris = 0; + var bm = kv.Value.BakedStaticMesh; + for (int s = 0; s < bm.GetSurfaceCount(); s++) + { + var arr = bm.SurfaceGetArrays(s); + if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array) + tris += arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length / 3; + } + int farTris = 0; + var fm = kv.Value.BakedLodFarMesh; + for (int s = 0; s < fm.GetSurfaceCount(); s++) + { + var arr = fm.SurfaceGetArrays(s); + if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array) + farTris += arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length / 3; + } + int nodes = CountSubtreeNodes(kv.Value.SceneTemplate); + GD.Print($" Vehicle '{kv.Key}': nodes={nodes} bakedTris={tris} farTris={farTris} surfs={bm.GetSurfaceCount()} farSurfs={fm.GetSurfaceCount()} detachChunks={kv.Value.DetachableParts.Count}"); + } + if (_arena.AssetCache.Vehicles.TryGetValue("paladin", out var palTpl)) + { + var names = new List(); + CollectNodeNames(palTpl.SceneTemplate, names, 40); + GD.Print($" Paladin sample nodes: {string.Join(", ", names)}"); + } + GD.Print("=== END PERF BENCHMARK ==="); + GetTree().Quit(0); + } + + private static void CollectNodeNames(Node cur, List outNames, int limit) + { + if (outNames.Count >= limit) return; + outNames.Add($"{cur.Name}({cur.GetType().Name})"); + for (int i = 0; i < cur.GetChildCount(); i++) CollectNodeNames(cur.GetChild(i), outNames, limit); + } + + private static int CountSubtreeNodes(Node cur) + { + int n = 1; + for (int i = 0; i < cur.GetChildCount(); i++) n += CountSubtreeNodes(cur.GetChild(i)); + return n; + } + + private PlayerInput GatherPlayerInput() + { + float throttle = 0f; + if (Input.IsKeyPressed(Key.W) || Input.IsKeyPressed(Key.Up)) throttle += 1f; + if (Input.IsKeyPressed(Key.S) || Input.IsKeyPressed(Key.Down)) throttle -= 1f; + + float steer = 0f; + if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) steer += 1f; + if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) steer -= 1f; + + bool isVtol = Session.State.Player.Grid.Spec.IsVtol; + float verticalThrottle = 0f; + if (Input.IsKeyPressed(Key.Space)) verticalThrottle += 1f; + if (Input.IsKeyPressed(Key.C) || Input.IsKeyPressed(Key.Ctrl)) verticalThrottle -= 1f; + + bool brake = isVtol ? Input.IsKeyPressed(Key.Shift) : Input.IsKeyPressed(Key.Space); + bool pointerOnHud = Input.MouseMode != Input.MouseModeEnum.Captured && + _hud.IsPointerOverInteractiveHud(GetViewport().GetMousePosition()); + bool fire = !pointerOnHud && Input.IsMouseButtonPressed(MouseButton.Left); + + var (aimX, aimY, aimZ) = ComputeCenterScreenAim(); + return new PlayerInput( + Throttle: throttle, + Steer: steer, + AimWorldX: aimX, + AimWorldZ: aimZ, + Fire: fire, + InteractPickup: _interactQueued, + Brake: brake, + AimWorldY: aimY, + VerticalThrottle: verticalThrottle); + } + + private (float AimX, float AimY, float AimZ) ComputeCenterScreenAim() + { + var player = Session.State.Player; + Vector2 screenSize = GetViewport().GetVisibleRect().Size; + if (screenSize.X < 2f || screenSize.Y < 2f) + { + return ( + player.X + MathF.Sin(_cameraYaw) * 40f, + player.Y, + player.Z + MathF.Cos(_cameraYaw) * 40f); + } + + Vector2 center = screenSize * 0.5f; + Vector3 rayOrigin = _camera.ProjectRayOrigin(center); + Vector3 rayDir = _camera.ProjectRayNormal(center); + + const float maxAimDist = 450f; + ulong playerStableId = ArenaSession.ContenderStableIdBase + (ulong)player.Id; + + Vector3 castOrigin = rayOrigin; + float remainingDist = maxAimDist; + float boxDist = maxAimDist; + Vector3 boxHitPt = Vector3.Zero; + bool hasBoxHit = false; + + // Cast against Ymir world, skipping the player's own chassis if hit along the shoulder ray. + for (int attempt = 0; attempt < 2; attempt++) + { + var hit = Session.World.CastRayClosest( + (castOrigin.X, castOrigin.Y, castOrigin.Z), + (rayDir.X * remainingDist, rayDir.Y * remainingDist, rayDir.Z * remainingDist)); + if (!hit.Hit) + { + break; + } + + var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z); + if (hit.StableId == playerStableId) + { + float skip = rayOrigin.DistanceTo(pt) + 0.4f; + castOrigin = rayOrigin + rayDir * skip; + remainingDist = MathF.Max(1f, maxAimDist - skip); + continue; + } + + boxHitPt = pt; + boxDist = rayOrigin.DistanceTo(pt); + hasBoxHit = true; + break; + } + + bool hasTerrainHit = Session.State.Terrain.Raycast( + rayOrigin.X, rayOrigin.Y, rayOrigin.Z, + rayDir.X, rayDir.Y, rayDir.Z, + maxDistance: boxDist, + out float tx, out float ty, out float tz, out float terrainDist); + + if (hasTerrainHit && terrainDist <= boxDist) + { + return (tx, ty, tz); + } + + if (hasBoxHit) + { + return (boxHitPt.X, boxHitPt.Y, boxHitPt.Z); + } + + Vector3 farPt = rayOrigin + rayDir * 320f; + return (farPt.X, farPt.Y, farPt.Z); + } + + private Vector3 ComputeTargetAnchor(ContenderState p) + { + var spec = p.Grid.Spec; + float heightT = Math.Clamp((spec.HalfHeight - 0.75f) / (2.35f - 0.75f), 0f, 1.2f); + float upOffset = Mathf.Lerp(3.2f, 6.5f, heightT); + float rightOffset = Mathf.Lerp(1.6f, 2.8f, heightT); + + var camRight = new Vector3(-MathF.Cos(_cameraYaw), 0f, MathF.Sin(_cameraYaw)); + return new Vector3(p.X, p.Y + (upOffset - spec.HalfHeight), p.Z) + camRight * rightOffset; + } + + private void UpdateCamera(float dt) + { + var p = Session.State.Player; + var spec = p.Grid.Spec; + float heightT = Math.Clamp((spec.HalfHeight - 0.75f) / (2.35f - 0.75f), 0f, 1.2f); + float backDist = Mathf.Lerp(7.5f, 12.5f, heightT) * _cameraZoom; + + Vector3 targetAnchor = ComputeTargetAnchor(p); + float blend = dt >= 1f ? 1f : 1f - MathF.Exp(-dt * 16f); + _cameraSmoothedAnchor = _cameraSmoothedAnchor.Lerp(targetAnchor, blend); + + var camFwdHoriz = new Vector3(MathF.Sin(_cameraYaw), 0f, MathF.Cos(_cameraYaw)); + var lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized(); + + // Pull camera forward along arm if terrain or static cover blocks the shoulder-to-camera ray + float effectiveBack = backDist; + if (Session.State.Terrain.Raycast( + _cameraSmoothedAnchor.X, _cameraSmoothedAnchor.Y, _cameraSmoothedAnchor.Z, + -lookDir.X, -lookDir.Y, -lookDir.Z, + backDist, + out _, out _, out _, out float terrainDist)) + { + effectiveBack = MathF.Min(effectiveBack, MathF.Max(1.6f, terrainDist - 0.6f)); + } + + var boxHit = Session.World.CastRayClosest( + (_cameraSmoothedAnchor.X, _cameraSmoothedAnchor.Y, _cameraSmoothedAnchor.Z), + (-lookDir.X * effectiveBack, -lookDir.Y * effectiveBack, -lookDir.Z * effectiveBack)); + if (boxHit.Hit && boxHit.StableId < ArenaSession.ContenderStableIdBase) + { + var pt = new Vector3(boxHit.Point.X, boxHit.Point.Y, boxHit.Point.Z); + effectiveBack = MathF.Min(effectiveBack, MathF.Max(1.6f, _cameraSmoothedAnchor.DistanceTo(pt) - 0.5f)); + } + + Vector3 camPos = _cameraSmoothedAnchor - lookDir * effectiveBack; + float minTerrainY = Session.State.Terrain.SampleHeight(camPos.X, camPos.Z) + 1.2f; + if (camPos.Y < minTerrainY) + { + camPos.Y = minTerrainY; + } + + _camera.GlobalPosition = camPos; + _camera.LookAt(camPos + lookDir * 60f, Vector3.Up); + } + + private void OnEquipCargo(int cargoIndex, string hardpointId) + { + _session?.TryEquipCargo(cargoIndex, hardpointId); + } + + private void SetupLightingAndSky() + { + var sun = new DirectionalLight3D + { + Name = "DesertSun", + LightColor = new Color(1.0f, 0.92f, 0.78f), + LightEnergy = 1.45f, + ShadowEnabled = true, + DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel2Splits, + DirectionalShadowMaxDistance = 145f, + RotationDegrees = new Vector3(-48f, 32f, 0f) + }; + AddChild(sun); + + var skyMat = new ProceduralSkyMaterial + { + SkyTopColor = new Color(0.24f, 0.34f, 0.44f), + SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f), + GroundBottomColor = new Color(0.32f, 0.22f, 0.14f), + GroundHorizonColor = new Color(0.70f, 0.50f, 0.33f) + }; + var env = new Godot.Environment + { + BackgroundMode = Godot.Environment.BGMode.Sky, + Sky = new Sky { SkyMaterial = skyMat }, + AmbientLightSource = Godot.Environment.AmbientSource.Sky, + AmbientLightEnergy = 0.55f, + FogEnabled = true, + FogMode = Godot.Environment.FogModeEnum.Depth, + FogLightColor = new Color(0.76f, 0.57f, 0.39f), + FogDensity = 0.72f, + FogDepthBegin = 380f, + FogDepthEnd = 1100f + }; + AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env }); + } +} diff --git a/client/Main.tscn b/client/Main.tscn new file mode 100644 index 0000000..4285746 --- /dev/null +++ b/client/Main.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://Main.cs" id="1"] + +[node name="Main" type="Node3D"] +script = ExtResource("1") diff --git a/client/NativeLibraries.cs b/client/NativeLibraries.cs new file mode 100644 index 0000000..e5bafde --- /dev/null +++ b/client/NativeLibraries.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Godot; +using Ymir.Box3D; + +namespace RustToDust.Client; + +/// +/// Finds ymir_box3d for Ymir.Box3D's DllImports. Godot loads game assemblies into its own load context, so the +/// default probing does not look beside them. A run from the editor or --path loads the library from the +/// project's build directory; an exported run from the data folder Godot puts beside the executable. +/// +internal static class NativeLibraries +{ + private const string Library = "ymir_box3d"; + +#pragma warning disable CA2255 // application code: the resolver must exist before the first DllImport + [ModuleInitializer] + internal static void Register() => + NativeLibrary.SetDllImportResolver(typeof(Box3DSoaWorld).Assembly, Resolve); + + private static IntPtr Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath) + { + if (name != Library) return IntPtr.Zero; + string fileName = FileName(); + + if (OS.HasFeature("template")) + { + string exportPath = Path.Combine( + Path.GetDirectoryName(OS.GetExecutablePath())!, + $"data_RustToDust.Client_{Platform()}_{Arch()}", + fileName); + return File.Exists(exportPath) && NativeLibrary.TryLoad(exportPath, out var exportHandle) + ? exportHandle + : IntPtr.Zero; + } + + string debugPath = Path.Combine(ProjectSettings.GlobalizePath("res://.godot/mono/temp/bin/Debug"), fileName); + if (File.Exists(debugPath) && NativeLibrary.TryLoad(debugPath, out var debugHandle)) + { + return debugHandle; + } + + string releasePath = Path.Combine(ProjectSettings.GlobalizePath("res://.godot/mono/temp/bin/Release"), fileName); + return File.Exists(releasePath) && NativeLibrary.TryLoad(releasePath, out var releaseHandle) + ? releaseHandle + : IntPtr.Zero; + } + + private static string FileName() => + OperatingSystem.IsWindows() ? "ymir_box3d.dll" : OperatingSystem.IsMacOS() ? "libymir_box3d.dylib" : "libymir_box3d.so"; + + private static string Platform() => + OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linuxbsd"; + + private static string Arch() => + RuntimeInformation.ProcessArchitecture == System.Runtime.InteropServices.Architecture.Arm64 ? "arm64" : "x86_64"; +} diff --git a/client/RustToDust.Client.csproj b/client/RustToDust.Client.csproj new file mode 100644 index 0000000..aa56926 --- /dev/null +++ b/client/RustToDust.Client.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + true + enable + RustToDust.Client + RustToDust.Client + + + + + diff --git a/client/TerrainRenderer.cs b/client/TerrainRenderer.cs new file mode 100644 index 0000000..ca03e2f --- /dev/null +++ b/client/TerrainRenderer.cs @@ -0,0 +1,466 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Top-down orthographic SubViewport brush-to-tile PBR + displacement terrain baker. +/// Maintains an 8x8 grid of 192m x 192m terrain tiles covering [-768, +768] in X and Z. +/// Only tiles whose changed are re-baked. +/// +public partial class TerrainRenderer : Node3D +{ + private const int ViewportSize = 256; + private const float InnerTexelSpan = 253.0f; // texel 1 center (1.5) .. texel 254 center (254.5) + private const float GutterCenterOffset = 1.5f; + private const float PixelsPerMeter = InnerTexelSpan / TerrainField.TileSize; + private const float HeightSpan = TerrainField.MaxWorldHeight - TerrainField.MinWorldHeight; + private const float BaseHeightNorm = (0f - TerrainField.MinWorldHeight) / HeightSpan; + + private static readonly Color HeightClearColor = new(BaseHeightNorm, 0.88f, 0.0f, 1.0f); + private static readonly Color AlbedoClearColor = new(0.69f, 0.50f, 0.31f, 1.0f); + private static readonly Vector2[] BrushUv = + { + new(0f, 0f), + new(1f, 0f), + new(1f, 1f), + new(0f, 1f) + }; + + private sealed class TileNode + { + public SubViewport HeightViewport = null!; + public Node2D HeightCanvas = null!; + public SubViewport AlbedoViewport = null!; + public Node2D AlbedoCanvas = null!; + public MeshInstance3D SurfaceMesh = null!; + public int BakedVersion = -1; + } + + private readonly TileNode[,] _tiles = new TileNode[TerrainField.TileGridCount, TerrainField.TileGridCount]; + private PlaneMesh _nearPlaneMesh = null!; + private PlaneMesh _farPlaneMesh = null!; + private ImageTexture _white1x1 = null!; + private Shader _clearShader = null!; + private Shader _brushAddShader = null!; + private Shader _brushSubShader = null!; + private Shader _brushAlbedoShader = null!; + private Shader _surfaceShader = null!; + private const int MaxDirtyRebakesPerSync = 2; + private TerrainField? _lastTerrain; + private int _rebakeCursor; + + public int BakedTileCount { get; private set; } + public int DirtyRebakes { get; private set; } + + public override void _Ready() + { + var whiteImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + whiteImg.SetPixel(0, 0, Colors.White); + _white1x1 = ImageTexture.CreateFromImage(whiteImg); + + _nearPlaneMesh = new PlaneMesh + { + Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize), + SubdivideWidth = 64, + SubdivideDepth = 64 + }; + _farPlaneMesh = new PlaneMesh + { + Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize), + SubdivideWidth = 16, + SubdivideDepth = 16 + }; + + _clearShader = new Shader + { + Code = """ + shader_type canvas_item; + render_mode blend_disabled; + uniform vec4 clear_color = vec4(0.0, 0.0, 0.0, 1.0); + void fragment() { + COLOR = clear_color; + } + """ + }; + _brushAddShader = GD.Load("res://terrain_brush.gdshader"); + _brushSubShader = GD.Load("res://terrain_brush_sub.gdshader"); + _brushAlbedoShader = GD.Load("res://terrain_brush_albedo.gdshader"); + _surfaceShader = GD.Load("res://terrain_surface.gdshader"); + + BuildTileGrid(); + } + + public void InvalidateAll() + { + for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + { + for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + { + _tiles[tx, tz].BakedVersion = -1; + } + } + BakedTileCount = 0; + DirtyRebakes = 0; + _lastTerrain = null; + } + + public void Sync(TerrainField terrain) + { + if (!ReferenceEquals(_lastTerrain, terrain)) + { + InvalidateAll(); + _lastTerrain = terrain; + } + + const int totalTiles = TerrainField.TileGridCount * TerrainField.TileGridCount; + + // 1. Always bake uninitialized tiles immediately + for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + { + for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + { + var tile = _tiles[tx, tz]; + int version = terrain.TileVersions[tx, tz]; + if (tile.BakedVersion < 0 && tile.BakedVersion != version) + { + BakeTile(tx, tz, tile, terrain); + BakedTileCount++; + tile.BakedVersion = version; + } + } + } + + // 2. Budget dynamic tile rebakes (tracks/craters) to <= 2 per Sync in round-robin order + int rebakedThisSync = 0; + bool anyRemainingDirty = false; + for (int step = 0; step < totalTiles; step++) + { + int idx = (_rebakeCursor + step) % totalTiles; + int tx = idx % TerrainField.TileGridCount; + int tz = idx / TerrainField.TileGridCount; + var tile = _tiles[tx, tz]; + int version = terrain.TileVersions[tx, tz]; + if (tile.BakedVersion != version) + { + if (rebakedThisSync < MaxDirtyRebakesPerSync) + { + BakeTile(tx, tz, tile, terrain); + DirtyRebakes++; + tile.BakedVersion = version; + rebakedThisSync++; + _rebakeCursor = (idx + 1) % totalTiles; + } + else + { + anyRemainingDirty = true; + } + } + } + + if (!anyRemainingDirty) + { + terrain.ClearDirtyMask(); + } + } + + public void UpdateTileLod(Vector3 camPos) + { + const float nearRadiusSq = 240f * 240f; + const float shadowRadiusSq = 220f * 220f; + for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + { + for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + { + var tile = _tiles[tx, tz]; + if (tile?.SurfaceMesh is null) + { + continue; + } + Vector3 pos = tile.SurfaceMesh.Position; + float dx = pos.X - camPos.X; + float dz = pos.Z - camPos.Z; + float d2 = dx * dx + dz * dz; + PlaneMesh desired = d2 <= nearRadiusSq ? _nearPlaneMesh : _farPlaneMesh; + if (!ReferenceEquals(tile.SurfaceMesh.Mesh, desired)) + { + tile.SurfaceMesh.Mesh = desired; + } + var desiredShadow = d2 <= shadowRadiusSq + ? GeometryInstance3D.ShadowCastingSetting.On + : GeometryInstance3D.ShadowCastingSetting.Off; + if (tile.SurfaceMesh.CastShadow != desiredShadow) + { + tile.SurfaceMesh.CastShadow = desiredShadow; + } + } + } + } + + public bool TryGetHeightImageFormat(out Image.Format format) + { + format = Image.Format.Max; + var img = _tiles[0, 0]?.HeightViewport?.GetTexture()?.GetImage(); + if (img is null || img.IsEmpty()) + { + return false; + } + format = img.GetFormat(); + return true; + } + + public bool TrySampleBakedHeight(float wx, float wz, out float bakedHeight) + { + bakedHeight = 0f; + float cx = Math.Clamp(wx, -TerrainField.HalfExtent, TerrainField.HalfExtent); + float cz = Math.Clamp(wz, -TerrainField.HalfExtent, TerrainField.HalfExtent); + TerrainField.WorldToTile(cx, cz, out int tx, out int tz); + + var tile = _tiles[tx, tz]; + var tex = tile?.HeightViewport?.GetTexture(); + var img = tex?.GetImage(); + if (img is null || img.IsEmpty() || img.GetWidth() < ViewportSize || img.GetHeight() < ViewportSize) + { + return false; + } + + float tileMinX = -TerrainField.HalfExtent + tx * TerrainField.TileSize; + float tileMinZ = -TerrainField.HalfExtent + tz * TerrainField.TileSize; + float px = GutterCenterOffset + (cx - tileMinX) * PixelsPerMeter; + float py = GutterCenterOffset + (cz - tileMinZ) * PixelsPerMeter; + + float fx = Math.Clamp(px - 0.5f, 0f, ViewportSize - 1.0001f); + float fy = Math.Clamp(py - 0.5f, 0f, ViewportSize - 1.0001f); + int x0 = (int)MathF.Floor(fx); + int y0 = (int)MathF.Floor(fy); + int x1 = Math.Min(x0 + 1, ViewportSize - 1); + int y1 = Math.Min(y0 + 1, ViewportSize - 1); + float txFrac = fx - x0; + float tyFrac = fy - y0; + + var c00 = img.GetPixel(x0, y0); + if (c00.A < 0.5f) + { + return false; + } + + var c10 = img.GetPixel(x1, y0); + var c01 = img.GetPixel(x0, y1); + var c11 = img.GetPixel(x1, y1); + + float r = (c00.R * (1f - txFrac) + c10.R * txFrac) * (1f - tyFrac) + + (c01.R * (1f - txFrac) + c11.R * txFrac) * tyFrac; + bakedHeight = TerrainField.MinWorldHeight + Math.Clamp(r, 0f, 1f) * HeightSpan; + return true; + } + + private void BuildTileGrid() + { + for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + { + for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + { + var tile = new TileNode(); + + tile.HeightViewport = CreateOrthoViewport($"Tile_{tx}_{tz}_Height", useHdr: true, out var heightCanvas); + tile.HeightCanvas = heightCanvas; + AddChild(tile.HeightViewport); + + tile.AlbedoViewport = CreateOrthoViewport($"Tile_{tx}_{tz}_Albedo", useHdr: false, out var albedoCanvas); + tile.AlbedoCanvas = albedoCanvas; + AddChild(tile.AlbedoViewport); + + var mat = new ShaderMaterial { Shader = _surfaceShader }; + mat.SetShaderParameter("height_tex", tile.HeightViewport.GetTexture()); + mat.SetShaderParameter("albedo_tex", tile.AlbedoViewport.GetTexture()); + mat.SetShaderParameter("height_min", TerrainField.MinWorldHeight); + mat.SetShaderParameter("height_max", TerrainField.MaxWorldHeight); + mat.SetShaderParameter("tile_size", TerrainField.TileSize); + mat.SetShaderParameter("inner_span", InnerTexelSpan); + mat.SetShaderParameter("tex_size", (float)ViewportSize); + mat.SetShaderParameter("gutter_offset", GutterCenterOffset); + + float centerX = -TerrainField.HalfExtent + (tx + 0.5f) * TerrainField.TileSize; + float centerZ = -TerrainField.HalfExtent + (tz + 0.5f) * TerrainField.TileSize; + + tile.SurfaceMesh = new MeshInstance3D + { + Name = $"Tile_{tx}_{tz}_Mesh", + Mesh = _nearPlaneMesh, + MaterialOverride = mat, + Position = new Vector3(centerX, 0f, centerZ), + CustomAabb = new Aabb( + new Vector3(-TerrainField.TileSize * 0.5f, TerrainField.MinWorldHeight - 2f, -TerrainField.TileSize * 0.5f), + new Vector3(TerrainField.TileSize, HeightSpan + 4f, TerrainField.TileSize)) + }; + AddChild(tile.SurfaceMesh); + + _tiles[tx, tz] = tile; + } + } + } + + private static SubViewport CreateOrthoViewport(string name, bool useHdr, out Node2D canvas) + { + var vp = new SubViewport + { + Name = name, + Size = new Vector2I(ViewportSize, ViewportSize), + Disable3D = true, + UseHdr2D = useHdr, + TransparentBg = false, + Snap2DTransformsToPixel = false, + Snap2DVerticesToPixel = false, + RenderTargetClearMode = SubViewport.ClearMode.Always, + RenderTargetUpdateMode = SubViewport.UpdateMode.Disabled + }; + + var cam = new Camera2D + { + AnchorMode = Camera2D.AnchorModeEnum.FixedTopLeft, + Position = Vector2.Zero, + Enabled = true, + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + ProcessCallback = Camera2D.Camera2DProcessCallback.Physics + }; + vp.AddChild(cam); + + canvas = new Node2D { Name = "Canvas" }; + vp.AddChild(canvas); + return vp; + } + + private void BakeTile(int tx, int tz, TileNode tile, TerrainField terrain) + { + ClearCanvasChildren(tile.HeightCanvas); + ClearCanvasChildren(tile.AlbedoCanvas); + + // Full-tile base clear quads (Polygon2D avoids GUI pixel snapping) + tile.HeightCanvas.AddChild(CreateClearQuad(HeightClearColor, _clearShader, _white1x1)); + tile.AlbedoCanvas.AddChild(CreateClearQuad(AlbedoClearColor, _clearShader, _white1x1)); + + float tileMinX = -TerrainField.HalfExtent + tx * TerrainField.TileSize; + float tileMinZ = -TerrainField.HalfExtent + tz * TerrainField.TileSize; + IReadOnlyList indices = terrain.GetTileBrushIndices(tx, tz); + var brushes = terrain.Brushes; + + for (int i = 0; i < indices.Count; i++) + { + var b = brushes[indices[i]]; + if (b.RadiusX <= 0.05f || b.RadiusZ <= 0.05f) + { + continue; + } + + float px = GutterCenterOffset + (b.X - tileMinX) * PixelsPerMeter; + float py = GutterCenterOffset + (b.Z - tileMinZ) * PixelsPerMeter; + float rxPx = b.RadiusX * PixelsPerMeter; + float rzPx = b.RadiusZ * PixelsPerMeter; + int kindInt = (int)b.Kind; + + // 1. Height+Material brush pass(es) + if (b.Kind == TerrainBrushKind.Crater) + { + // Crater uses subtractive pit + additive ejecta rim/scorch + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta, _white1x1)); + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta, _white1x1)); + } + else if (b.Kind == TerrainBrushKind.Track) + { + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta, _white1x1)); + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta, _white1x1)); + } + else if (b.Kind == TerrainBrushKind.Road || b.HeightDelta < 0f) + { + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta, _white1x1)); + } + else + { + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta, _white1x1)); + } + + // 2. Albedo brush pass + var albedoQuad = CreateOrientedQuad(px, py, rxPx, rzPx, b.RotationRad, _white1x1); + var albedoMat = new ShaderMaterial { Shader = _brushAlbedoShader }; + albedoMat.SetShaderParameter("brush_kind", kindInt); + albedoMat.SetShaderParameter("brush_albedo", new Vector3(b.AlbedoR, b.AlbedoG, b.AlbedoB)); + albedoMat.SetShaderParameter("height_delta", b.HeightDelta); + albedoQuad.Material = albedoMat; + tile.AlbedoCanvas.AddChild(albedoQuad); + } + + tile.HeightViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; + tile.AlbedoViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; + } + + private static Polygon2D CreateClearQuad(Color color, Shader clearShader, ImageTexture whiteTex) + { + var mat = new ShaderMaterial { Shader = clearShader }; + mat.SetShaderParameter("clear_color", color); + return new Polygon2D + { + Polygon = new[] + { + new Vector2(0f, 0f), + new Vector2(ViewportSize, 0f), + new Vector2(ViewportSize, ViewportSize), + new Vector2(0f, ViewportSize) + }, + UV = BrushUv, + Texture = whiteTex, + Material = mat + }; + } + + private static Polygon2D CreateOrientedQuad( + float px, float py, + float rxPx, float rzPx, + float rotationRad, + ImageTexture whiteTex) + { + return new Polygon2D + { + Position = new Vector2(px, py), + Rotation = rotationRad, + Polygon = new[] + { + new Vector2(-rxPx, -rzPx), + new Vector2(rxPx, -rzPx), + new Vector2(rxPx, rzPx), + new Vector2(-rxPx, rzPx) + }, + UV = BrushUv, + Texture = whiteTex + }; + } + + private static Polygon2D CreateBrushQuad( + float px, float py, + float rxPx, float rzPx, + float rotationRad, + Shader shader, + int kindInt, + float heightDelta, + ImageTexture whiteTex) + { + var quad = CreateOrientedQuad(px, py, rxPx, rzPx, rotationRad, whiteTex); + var mat = new ShaderMaterial { Shader = shader }; + mat.SetShaderParameter("brush_kind", kindInt); + mat.SetShaderParameter("height_delta", heightDelta); + mat.SetShaderParameter("height_span", HeightSpan); + quad.Material = mat; + return quad; + } + + private static void ClearCanvasChildren(Node2D canvas) + { + for (int i = canvas.GetChildCount() - 1; i >= 0; i--) + { + var child = canvas.GetChild(i); + canvas.RemoveChild(child); + child.QueueFree(); + } + } +} diff --git a/client/VehicleAssetCache.cs b/client/VehicleAssetCache.cs new file mode 100644 index 0000000..4b8fcbb --- /dev/null +++ b/client/VehicleAssetCache.cs @@ -0,0 +1,1552 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Runtime GLB asset loader & template cache for all 15 Brokkr vehicles (resolved via +/// + ) +/// and all 6 modular gear GLBs in assets/gear/. +/// Parses the glTF JSON chunk to map rtd.id, rtd.kind, rtd.size, and rtd.joint +/// deterministically to exact s inside the Godot scene tree generated by +/// + . +/// +public sealed class VehicleAssetCache : IDisposable +{ + public sealed record GlbAnchorInfo( + string Id, + string Kind, + Vector3 Size, + NodePath RelativePath, + Transform3D ModelSpaceTransform); + + public sealed record GlbJointInfo( + string JointId, + string NodeName, + Vector3 Axis, + float MinVal, + float MaxVal, + NodePath RelativePath); + + public sealed record GlbPartNodeInfo( + string NodeName, + int CellX, + int CellY, + string Kind, + NodePath RelativePath, + bool HasProtectedDescendant); + + public sealed class VehicleTemplate + { + public required VehiclePackage Package { get; init; } + public required string GlbPath { get; init; } + public required Node3D SceneTemplate { get; init; } + public required ArrayMesh BakedStaticMesh { get; init; } + public required ArrayMesh BakedLodFarMesh { get; init; } + public required float MinY { get; init; } + public required float MaxY { get; init; } + public required IReadOnlyDictionary Anchors { get; init; } + public required IReadOnlyDictionary Joints { get; init; } + public required IReadOnlyDictionary NodesByOriginalName { get; init; } + public required IReadOnlyList DetachableParts { get; init; } + public required IReadOnlyList MobilityNodePaths { get; init; } + } + + public sealed class GearTemplate + { + public required string Id { get; init; } + public required string GlbPath { get; init; } + public required Node3D SceneTemplate { get; init; } + public required Vector3 Size { get; init; } + public required float MinY { get; init; } + public required Vector3 LocalModelForward { get; init; } + } + + public static readonly string[] ExpectedGearIds = + { + "mg_762", "autocannon", "recoilless", "copper_rad", "gilded_lance", "gold_radiator" + }; + + private readonly Dictionary _vehicles = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _gear = new(StringComparer.OrdinalIgnoreCase); + private readonly string _vehiclesDir; + private readonly string _gearDir; + private bool _disposed; + + public VehicleAssetCache() + { + _vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); + string assetsDir = Directory.GetParent(_vehiclesDir)?.FullName + ?? throw new DirectoryNotFoundException($"Could not locate assets parent directory of '{_vehiclesDir}'."); + _gearDir = Path.Combine(assetsDir, "gear"); + if (!Directory.Exists(_gearDir)) + { + throw new DirectoryNotFoundException($"Could not locate gear directory '{_gearDir}'."); + } + } + + public IReadOnlyDictionary Vehicles => _vehicles; + public IReadOnlyDictionary Gear => _gear; + + public void PreloadAll() + { + foreach (var pkg in Catalog.PackagesById.Values) + { + GetOrLoadVehicle(pkg.Id); + } + foreach (string gearId in ExpectedGearIds) + { + GetOrLoadGear(gearId); + } + } + + public VehicleTemplate GetOrLoadVehicle(string vehicleId) + { + ObjectDisposedException.ThrowIf(_disposed, this); + string resolvedId = ResolveModelId(vehicleId); + if (_vehicles.TryGetValue(resolvedId, out var cached)) + { + return cached; + } + + var pkg = Catalog.TryGetPackage(resolvedId) + ?? throw new KeyNotFoundException($"Unknown vehicle '{vehicleId}' in Catalog.PackagesById."); + + string glbPath = Path.Combine(_vehiclesDir, pkg.Id, pkg.ModelAsset); + if (!File.Exists(glbPath)) + { + throw new FileNotFoundException($"Missing vehicle GLB for '{pkg.Id}': {glbPath}", glbPath); + } + + var template = LoadVehicleTemplate(pkg, glbPath); + _vehicles[pkg.Id] = template; + return template; + } + + public static string ResolveModelId(string chassisId) => + string.Equals(chassisId, "exemplar_frame", StringComparison.OrdinalIgnoreCase) + ? "raptor" + : chassisId; + + public GearTemplate GetOrLoadGear(string gearId) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_gear.TryGetValue(gearId, out var cached)) + { + return cached; + } + + string glbPath = Path.Combine(_gearDir, $"{gearId}.glb"); + if (!File.Exists(glbPath)) + { + throw new FileNotFoundException($"Missing gear GLB '{gearId}': {glbPath}", glbPath); + } + + var template = LoadGearTemplate(gearId, glbPath); + _gear[gearId] = template; + return template; + } + + private static VehicleTemplate LoadVehicleTemplate(VehiclePackage pkg, string glbPath) + { + byte[] jsonBytes = ReadGlbJsonChunk(glbPath); + using var gltfJson = JsonDocument.Parse(jsonBytes); + JsonElement jsonRoot = gltfJson.RootElement; + + var doc = new GltfDocument(); + var state = new GltfState(); + Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty); + if (err != Error.Ok) + { + throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for '{glbPath}': {err}"); + } + + Node? generated = doc.GenerateScene(state); + if (generated is not Node3D sceneRoot) + { + generated?.QueueFree(); + throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for '{glbPath}'."); + } + ClearOwnerRecursive(sceneRoot); + + var gltfNodes = state.GetNodes(); + var jsonNodes = jsonRoot.GetProperty("nodes"); + int nodeCount = Math.Min(gltfNodes.Count, jsonNodes.GetArrayLength()); + + var pathByGltfIndex = new NodePath[nodeCount]; + var nodeByGltfIndex = new Node3D?[nodeCount]; + var origNameByIndex = new string[nodeCount]; + var nodesByOriginalName = new Dictionary(StringComparer.Ordinal); + var anchors = new Dictionary(StringComparer.Ordinal); + var joints = new Dictionary(StringComparer.Ordinal); + var protectedIndices = new HashSet(); + var parentByIndex = new Dictionary(); + + for (int i = 0; i < nodeCount; i++) + { + JsonElement jn = jsonNodes[i]; + if (jn.TryGetProperty("children", out var childrenEl) && childrenEl.ValueKind == JsonValueKind.Array) + { + foreach (var ch in childrenEl.EnumerateArray()) + { + parentByIndex[ch.GetInt32()] = i; + } + } + } + + // Resolve every glTF node deterministically to its exact Godot Node3D via GltfNode.GetSceneNodePath(state) + for (int i = 0; i < nodeCount; i++) + { + GltfNode gn = gltfNodes[i]; + JsonElement jn = jsonNodes[i]; + string origName = !string.IsNullOrEmpty(gn.OriginalName) + ? gn.OriginalName + : (jn.TryGetProperty("name", out var nm) ? nm.GetString() ?? $"node_{i}" : $"node_{i}"); + origNameByIndex[i] = origName; + + Node? resolved = ResolveSceneNode(sceneRoot, gn.GetSceneNodePath(state), origName); + if (resolved is Node3D n3d) + { + NodePath relPath = BuildRelativeNodePath(sceneRoot, n3d); + pathByGltfIndex[i] = relPath; + nodeByGltfIndex[i] = n3d; + nodesByOriginalName.TryAdd(origName, relPath); + } + else + { + pathByGltfIndex[i] = new NodePath(); + } + } + + // Compute model-space transforms once from sceneRoot + var modelTransforms = new Dictionary(); + CollectModelTransforms(sceneRoot, Transform3D.Identity, modelTransforms); + + // Extract rtd.* extras from glTF JSON chunk & mark protected structural/joint/hardpoint nodes + for (int i = 0; i < nodeCount; i++) + { + JsonElement jn = jsonNodes[i]; + Node3D? node = nodeByGltfIndex[i]; + if (node is null) + { + continue; + } + + NodePath relPath = pathByGltfIndex[i]; + if (!jn.TryGetProperty("extras", out JsonElement extras) || extras.ValueKind != JsonValueKind.Object) + { + continue; + } + + if (extras.TryGetProperty("rtd.id", out var rtdIdEl) && rtdIdEl.ValueKind == JsonValueKind.String) + { + string hpId = rtdIdEl.GetString()!; + string hpKind = extras.TryGetProperty("rtd.kind", out var kEl) && kEl.ValueKind == JsonValueKind.String + ? kEl.GetString()! + : "weapon"; + Vector3 hpSize = ReadVec3(extras, "rtd.size", new Vector3(0.5f, 0.5f, 0.1f)); + Transform3D modelXform = modelTransforms.TryGetValue(node, out var xf) ? xf : Transform3D.Identity; + anchors[hpId] = new GlbAnchorInfo(hpId, hpKind, hpSize, relPath, modelXform); + MarkAncestorsProtected(i, parentByIndex, protectedIndices); + } + + if (extras.TryGetProperty("rtd.joint", out var rtdJointEl) && rtdJointEl.ValueKind == JsonValueKind.String) + { + string jId = rtdJointEl.GetString()!; + Vector3 axis = ReadVec3(extras, "rtd.axis", Vector3.Up); + if (axis.LengthSquared() < 1e-6f) axis = Vector3.Up; + axis = axis.Normalized(); + float minVal = extras.TryGetProperty("rtd.min", out var mnEl) ? mnEl.GetSingle() : -180f; + float maxVal = extras.TryGetProperty("rtd.max", out var mxEl) ? mxEl.GetSingle() : 180f; + joints[jId] = new GlbJointInfo(jId, origNameByIndex[i], axis, minVal, maxVal, relPath); + MarkAncestorsProtected(i, parentByIndex, protectedIndices); + } + } + + // Also mark structural mechanism/skeleton/mobility nodes and their ancestors protected + var mobilityPaths = new List(); + var mechNames = new HashSet(StringComparer.Ordinal); + if (pkg.Mechanisms is not null) + { + foreach (var d in pkg.Mechanisms.Dofs) mechNames.Add(d.Name); + foreach (var r in pkg.Mechanisms.Rams) + { + mechNames.Add(r.Name); + mechNames.Add(r.BarrelBone); + mechNames.Add(r.RodBone); + } + foreach (var sc in pkg.Mechanisms.Scissors) + { + mechNames.Add(sc.Name); + mechNames.Add(sc.UpperBone); + mechNames.Add(sc.LowerBone); + } + } + + for (int i = 0; i < nodeCount; i++) + { + string nm = origNameByIndex[i]; + if (mechNames.Contains(nm) || IsStructuralNodeName(nm)) + { + MarkAncestorsProtected(i, parentByIndex, protectedIndices); + } + } + + foreach (var pc in pkg.PartCells) + { + if (string.Equals(pc.Kind, "mobility", StringComparison.OrdinalIgnoreCase)) + { + if (nodesByOriginalName.TryGetValue(pc.NodeName, out var mobPath)) + { + mobilityPaths.Add(mobPath); + } + for (int i = 0; i < nodeCount; i++) + { + if (string.Equals(origNameByIndex[i], pc.NodeName, StringComparison.Ordinal)) + { + MarkAncestorsProtected(i, parentByIndex, protectedIndices); + } + } + } + } + + // Compute protected-descendant flag for each glTF node index + var hasProtectedDesc = new bool[nodeCount]; + for (int i = 0; i < nodeCount; i++) + { + if (protectedIndices.Contains(i)) + { + int cur = i; + while (parentByIndex.TryGetValue(cur, out int p)) + { + hasProtectedDesc[p] = true; + cur = p; + } + } + } + + // Index detachable exterior armor/shroud (and safe leaf cladding) parts mapped to cells + var indexByName = new Dictionary(StringComparer.Ordinal); + for (int i = 0; i < nodeCount; i++) + { + indexByName.TryAdd(origNameByIndex[i], i); + } + + var detachableParts = new List(); + foreach (var pc in pkg.PartCells) + { + if (!indexByName.TryGetValue(pc.NodeName, out int idx)) + { + continue; + } + Node3D? node = nodeByGltfIndex[idx]; + if (node is not MeshInstance3D) + { + continue; + } + if (protectedIndices.Contains(idx) || hasProtectedDesc[idx]) + { + continue; + } + if (!IsDetachablePartKind(pc.Kind, pc.NodeName, node.GetChildCount())) + { + continue; + } + detachableParts.Add(new GlbPartNodeInfo( + pc.NodeName, + pc.CellX, + pc.CellY, + pc.Kind, + pathByGltfIndex[idx], + hasProtectedDesc[idx])); + } + + // Verify all VehiclePackage hardpoint AnchorIds & Joints resolved + foreach (var hp in pkg.Hardpoints) + { + if (!anchors.ContainsKey(hp.AnchorId)) + { + sceneRoot.QueueFree(); + throw new InvalidOperationException($"{pkg.Id}: failed to resolve hardpoint AnchorId '{hp.AnchorId}' in '{glbPath}'."); + } + } + foreach (var j in pkg.Joints) + { + if (!joints.ContainsKey(j.Id)) + { + sceneRoot.QueueFree(); + throw new InvalidOperationException($"{pkg.Id}: failed to resolve joint '{j.Id}' in '{glbPath}'."); + } + } + + ComputeSceneMeshBoundsY(sceneRoot, out float minY, out float maxY); + + // Build full set of protected structural/rig/joint/anchor/mobility Godot nodes + var protectedNodes = new HashSet { sceneRoot }; + for (int i = 0; i < nodeCount; i++) + { + if ((protectedIndices.Contains(i) || hasProtectedDesc[i]) && nodeByGltfIndex[i] is { } pn) + { + MarkNodeAndAncestorsProtected(pn, sceneRoot, protectedNodes); + } + } + foreach (var a in anchors.Values) + { + if (sceneRoot.GetNodeOrNull(a.RelativePath) is { } an) + { + MarkNodeAndAncestorsProtected(an, sceneRoot, protectedNodes); + } + } + foreach (var j in joints.Values) + { + if (sceneRoot.GetNodeOrNull(j.RelativePath) is { } jn) + { + MarkNodeAndAncestorsProtected(jn, sceneRoot, protectedNodes); + } + } + foreach (var mp in mobilityPaths) + { + if (sceneRoot.GetNodeOrNull(mp) is { } mn) + { + MarkNodeAndAncestorsProtected(mn, sceneRoot, protectedNodes); + } + } + + // Map original detachable MeshInstance3Ds so we can merge them per (rigidParent, CellX, CellY) + var detachableByNode = new Dictionary(); + foreach (var dp in detachableParts) + { + if (sceneRoot.GetNodeOrNull(dp.RelativePath) is MeshInstance3D mi && !protectedNodes.Contains(mi)) + { + detachableByNode.TryAdd(mi, (dp.CellX, dp.CellY, dp.Kind)); + } + } + + // A & B: Merge detachable armor per (rigidParent, CellX, CellY) and static meshes per rigidParent + var mergedDetachableInfos = MergeVehicleSubMeshes(sceneRoot, protectedNodes, detachableByNode); + + // Prune stale nodesByOriginalName entries that were collapsed into merged meshes + var survivingNames = new Dictionary(StringComparer.Ordinal); + foreach (var (origName, relPath) in nodesByOriginalName) + { + Node? resolved = relPath.ToString() == "." ? sceneRoot : sceneRoot.GetNodeOrNull(relPath); + if (resolved is not null) + { + survivingNames[origName] = relPath; + } + } + + // C: Build single-node BakedStaticMesh + decimated BakedLodFarMesh (>130m) per template + ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false); + ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true); + ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f); + + return new VehicleTemplate + { + Package = pkg, + GlbPath = glbPath, + SceneTemplate = sceneRoot, + BakedStaticMesh = bakedStaticMesh, + BakedLodFarMesh = bakedLodFarMesh, + MinY = minY, + MaxY = maxY, + Anchors = anchors, + Joints = joints, + NodesByOriginalName = survivingNames, + DetachableParts = mergedDetachableInfos, + MobilityNodePaths = mobilityPaths + }; + } + + private static readonly HashSet PreservedGearPartNames = new(StringComparer.OrdinalIgnoreCase) + { + "barrel_inner", "receiver", "muzzle_brake_L", "gun_housing", + "sight_tube", "breech_band", "condenser_ring_2", "ivory_cowl" + }; + + private static GearTemplate LoadGearTemplate(string gearId, string glbPath) + { + var doc = new GltfDocument(); + var state = new GltfState(); + Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty); + if (err != Error.Ok) + { + throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for gear '{glbPath}': {err}"); + } + + Node? generated = doc.GenerateScene(state); + if (generated is not Node3D sceneRoot) + { + generated?.QueueFree(); + throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for gear '{glbPath}'."); + } + ClearOwnerRecursive(sceneRoot); + + ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax); + MergeGearSubMeshes(sceneRoot, gearId); + Vector3 localFwd = new Vector3(0f, 0f, 1f); + + return new GearTemplate + { + Id = gearId, + GlbPath = glbPath, + SceneTemplate = sceneRoot, + Size = bMax - bMin, + MinY = bMin.Y, + LocalModelForward = localFwd + }; + } + + private static readonly HashSet ExactStructuralNodeNames = new(StringComparer.OrdinalIgnoreCase) + { + "chassis", "hull", "pelvis", "core", "trunk", "waist", "torso.pose", "aim.turret", "hull.pose", + "legl.hip", "legr.hip", "legl.shin", "legr.shin", "legl.foot", "legr.foot", + "legl.upper", "legr.upper", "legl.lower", "legr.lower", "legl.ankle", "legr.ankle", + "legl.thigh", "legr.thigh", "legl.cannon", "legr.cannon", + "legl.oleo", "legr.oleo", "legl.oleofork", "legr.oleofork", + "legl.torqueup", "legr.torqueup", "legl.torquelow", "legr.torquelow", + "legl.lug", "legr.lug", "legl.ramluga0", "legl.ramluga1", "legr.ramluga0", "legr.ramluga1", + "legl.recessram0", "legl.recessram1", "legr.recessram0", "legr.recessram1", + "legfl.s1", "legfr.s1", "legbl.s1", "legbr.s1", + "legfl.s2", "legfr.s2", "legbl.s2", "legbr.s2", + "footfl", "footfr", "footbl", "footbr", + "thigh.fl", "thigh.fr", "thigh.rl", "thigh.rr", + "shin.fl", "shin.fr", "shin.rl", "shin.rr", + "ankle.fl", "ankle.fr", "ankle.rl", "ankle.rr" + }; + + private static bool IsStructuralNodeName(string name) => + ExactStructuralNodeNames.Contains(name); + + private static void ClearOwnerRecursive(Node cur) + { + cur.Owner = null; + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + ClearOwnerRecursive(cur.GetChild(i)); + } + } + + private static bool IsDetachablePartKind(string kind, string nodeName, int childCount) + { + if (string.Equals(kind, "armor", StringComparison.OrdinalIgnoreCase) || + string.Equals(kind, "shroud", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + if (!string.Equals(kind, "hull", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + string low = nodeName.ToLowerInvariant(); + // Safe exterior cladding panels (e.g., buggy hood/side panels, skirt/tasset/cod plates, mech dress panels) + if (low.Contains("hood") || low.Contains("side.") || low.Contains("roof") || + low.Contains("tasset") || low.Contains("cod") || low.Contains("cuisse") || + low.Contains(".panels") || low.Contains(".dress.") || low.Contains("brow") || + low.Contains("pauldron") || low.Contains("wing") && !low.Contains("stub_wing")) + { + return true; + } + return childCount == 0 && (low.Contains("canopy") || low.Contains("hatch") || low.Contains("visor")); + } + + private static void MarkNodeAndAncestorsProtected(Node node, Node root, HashSet protectedNodes) + { + Node? cur = node; + while (cur is not null) + { + protectedNodes.Add(cur); + if (ReferenceEquals(cur, root)) + { + break; + } + cur = cur.GetParent(); + } + } + + private static Node3D FindNearestProtectedParent(Node node, Node3D sceneRoot, HashSet protectedNodes) + { + Node? cur = node.GetParent(); + while (cur is not null) + { + if (cur is Node3D n3d && protectedNodes.Contains(cur)) + { + return n3d; + } + if (ReferenceEquals(cur, sceneRoot)) + { + break; + } + cur = cur.GetParent(); + } + return sceneRoot; + } + + private static Transform3D ComputeRelativeTransform(Node3D ancestor, Node descendant) + { + Transform3D xf = Transform3D.Identity; + Node? cur = descendant; + while (cur is not null && !ReferenceEquals(cur, ancestor)) + { + if (cur is Node3D n3d) + { + xf = n3d.Transform * xf; + } + cur = cur.GetParent(); + } + return xf; + } + + private static bool CanMergeMeshInstance(MeshInstance3D mi) + { + if (mi.Mesh is null || mi.Mesh.GetSurfaceCount() == 0) + { + return false; + } + if (mi.Mesh is ArrayMesh am) + { + int surfCount = am.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + if (am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles) + { + return false; + } + } + } + return true; + } + + private static void CollectAllMeshInstances(Node cur, List outList) + { + if (cur is MeshInstance3D mi) + { + outList.Add(mi); + } + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + CollectAllMeshInstances(cur.GetChild(i), outList); + } + } + + private static void ReparentChildrenAndRemove(MeshInstance3D mi) + { + Node? parent = mi.GetParent(); + if (parent is not null) + { + for (int i = mi.GetChildCount() - 1; i >= 0; i--) + { + Node ch = mi.GetChild(i); + mi.RemoveChild(ch); + if (ch is Node3D ch3d) + { + ch3d.Transform = mi.Transform * ch3d.Transform; + } + parent.AddChild(ch); + } + parent.RemoveChild(mi); + } + mi.QueueFree(); + } + + private static List MergeVehicleSubMeshes( + Node3D sceneRoot, + HashSet protectedNodes, + Dictionary detachableByNode) + { + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + + var detachableGroups = new Dictionary<(Node3D RigidParent, int CellX, int CellY), (string Kind, List<(MeshInstance3D Mi, Transform3D RelXf)> Items)>(); + var staticGroups = new Dictionary>(); + var detachResultNodes = new List<(MeshInstance3D Node, int CellX, int CellY, string Kind)>(); + + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (!CanMergeMeshInstance(mi)) + { + continue; + } + + if (detachableByNode.TryGetValue(mi, out var detInfo)) + { + Node3D rigidParent = FindNearestProtectedParent(mi, sceneRoot, protectedNodes); + Transform3D relXf = ComputeRelativeTransform(rigidParent, mi); + var key = (rigidParent, detInfo.CellX, detInfo.CellY); + if (!detachableGroups.TryGetValue(key, out var group)) + { + group = (detInfo.Kind, new List<(MeshInstance3D, Transform3D)>()); + detachableGroups[key] = group; + } + group.Items.Add((mi, relXf)); + } + else if (!protectedNodes.Contains(mi)) + { + Node3D rigidParent = FindNearestProtectedParent(mi, sceneRoot, protectedNodes); + Transform3D relXf = ComputeRelativeTransform(rigidParent, mi); + if (!staticGroups.TryGetValue(rigidParent, out var list)) + { + list = new List<(MeshInstance3D, Transform3D)>(); + staticGroups[rigidParent] = list; + } + list.Add((mi, relXf)); + } + } + + // B. Merge detachable armor parts per (rigidParent, CellX, CellY) + int detSeq = 0; + foreach (var ((rigidParent, cellX, cellY), (kind, items)) in detachableGroups) + { + if (items.Count == 1 && ReferenceEquals(items[0].Mi.GetParent(), rigidParent)) + { + // Already a single child directly under rigidParent — keep as-is + detachResultNodes.Add((items[0].Mi, cellX, cellY, kind)); + continue; + } + + ArrayMesh? merged = BuildMergedArrayMesh(items); + if (merged is null) + { + continue; + } + + var chunkNode = new MeshInstance3D + { + Name = $"ArmorCell_{cellX}_{cellY}_{detSeq++}", + Mesh = merged + }; + rigidParent.AddChild(chunkNode); + detachResultNodes.Add((chunkNode, cellX, cellY, kind)); + + for (int i = 0; i < items.Count; i++) + { + ReparentChildrenAndRemove(items[i].Mi); + } + } + + // A. Merge static non-detachable sub-meshes per rigid articulated parent + foreach (var (rigidParent, items) in staticGroups) + { + if (rigidParent is MeshInstance3D parentMi && CanMergeMeshInstance(parentMi)) + { + var combined = new List<(MeshInstance3D, Transform3D)>(items.Count + 1) + { + (parentMi, Transform3D.Identity) + }; + combined.AddRange(items); + ArrayMesh? merged = BuildMergedArrayMesh(combined); + if (merged is not null) + { + parentMi.MaterialOverride = null; + parentMi.Mesh = merged; + for (int i = 0; i < items.Count; i++) + { + ReparentChildrenAndRemove(items[i].Mi); + } + } + } + else if (items.Count > 1 || (items.Count == 1 && !ReferenceEquals(items[0].Mi.GetParent(), rigidParent))) + { + ArrayMesh? merged = BuildMergedArrayMesh(items); + if (merged is not null) + { + var staticNode = new MeshInstance3D + { + Name = $"{rigidParent.Name}_StaticMerged", + Mesh = merged + }; + rigidParent.AddChild(staticNode); + for (int i = 0; i < items.Count; i++) + { + ReparentChildrenAndRemove(items[i].Mi); + } + } + } + } + + // Prune empty non-protected grouping nodes left behind + PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, protectedNodes); + + var result = new List(detachResultNodes.Count); + for (int i = 0; i < detachResultNodes.Count; i++) + { + var (node, cellX, cellY, kind) = detachResultNodes[i]; + if (!GodotObject.IsInstanceValid(node) || !sceneRoot.IsAncestorOf(node)) + { + continue; + } + result.Add(new GlbPartNodeInfo( + node.Name, + cellX, + cellY, + kind, + BuildRelativeNodePath(sceneRoot, node), + HasProtectedDescendant: false)); + } + return result; + } + + private static void MergeGearSubMeshes(Node3D sceneRoot, string gearId) + { + var keptNodes = new HashSet { sceneRoot }; + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (PreservedGearPartNames.Contains(mi.Name)) + { + MarkNodeAndAncestorsProtected(mi, sceneRoot, keptNodes); + } + } + + var mergeList = new List<(MeshInstance3D Mi, Transform3D RelXf)>(); + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (!keptNodes.Contains(mi) && CanMergeMeshInstance(mi)) + { + mergeList.Add((mi, ComputeRelativeTransform(sceneRoot, mi))); + } + } + + if (mergeList.Count <= 1) + { + return; + } + + ArrayMesh? merged = BuildMergedArrayMesh(mergeList); + if (merged is null) + { + return; + } + + var mergedNode = new MeshInstance3D + { + Name = $"{gearId}_StaticMerged", + Mesh = merged + }; + sceneRoot.AddChild(mergedNode); + for (int i = 0; i < mergeList.Count; i++) + { + ReparentChildrenAndRemove(mergeList[i].Mi); + } + PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, keptNodes); + } + + private static ArrayMesh BuildBakedStaticMesh(Node3D sceneRoot, bool coarseMaterials = false) + { + var allMeshes = new List(); + CollectAllMeshInstances(sceneRoot, allMeshes); + + var items = new List<(MeshInstance3D Mi, Transform3D RelXf)>(allMeshes.Count); + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (CanMergeMeshInstance(mi)) + { + items.Add((mi, ComputeRelativeTransform(sceneRoot, mi))); + } + } + + return BuildMergedArrayMesh(items, coarseMaterials) ?? new ArrayMesh(); + } + + private static void PruneEmptyNonProtectedNodes(Node cur, Node sceneRoot, HashSet protectedNodes) + { + for (int i = cur.GetChildCount() - 1; i >= 0; i--) + { + Node ch = cur.GetChild(i); + PruneEmptyNonProtectedNodes(ch, sceneRoot, protectedNodes); + if (!ReferenceEquals(ch, sceneRoot) && + !protectedNodes.Contains(ch) && + ch is not MeshInstance3D && + ch.GetChildCount() == 0) + { + cur.RemoveChild(ch); + ch.QueueFree(); + } + } + } + + private readonly record struct StandardMatKey( + int PaintTag, + int R, + int G, + int B, + int A, + int Metallic, + int Roughness, + bool EmissionEnabled, + int EmR, + int EmG, + int EmB, + int EmEnergy, + int Transparency, + int CullMode); + + private static bool TryGetMaterialValueKey(Material mat, bool coarse, out StandardMatKey key) + { + if (mat is StandardMaterial3D sm && + sm.AlbedoTexture is null && + sm.NormalTexture is null && + sm.RoughnessTexture is null && + sm.MetallicTexture is null && + sm.EmissionTexture is null) + { + string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant(); + int paintTag = (mName.Contains("olive") || mName.Contains("khaki")) ? 1 + : (mName.Contains("signal") || mName.Contains("orange")) ? 2 + : 0; + float colorScale = coarse ? 6f : 255f; + float pbrScale = coarse ? 2f : 100f; + key = new StandardMatKey( + paintTag, + (int)MathF.Round(sm.AlbedoColor.R * colorScale), + (int)MathF.Round(sm.AlbedoColor.G * colorScale), + (int)MathF.Round(sm.AlbedoColor.B * colorScale), + (int)MathF.Round(sm.AlbedoColor.A * 10f), + (int)MathF.Round(sm.Metallic * pbrScale), + (int)MathF.Round(sm.Roughness * pbrScale), + sm.EmissionEnabled, + (int)MathF.Round(sm.Emission.R * colorScale), + (int)MathF.Round(sm.Emission.G * colorScale), + (int)MathF.Round(sm.Emission.B * colorScale), + (int)MathF.Round(sm.EmissionEnergyMultiplier * pbrScale), + (int)sm.Transparency, + (int)sm.CullMode); + return true; + } + key = default; + return false; + } + + private sealed class MaterialSurfaceBucket + { + public required Material? Material; + public readonly List<(Mesh Mesh, int SurfaceIdx, Transform3D RelXf)> Sources = new(); + } + + private static ArrayMesh? BuildMergedArrayMesh(List<(MeshInstance3D Mi, Transform3D RelXf)> items, bool coarseMaterials = false) + { + if (items.Count == 0) + { + return null; + } + + var buckets = new List(); + var bucketByMatId = new Dictionary(); + var bucketByMatVal = new Dictionary(); + MaterialSurfaceBucket? nullMatBucket = null; + + for (int i = 0; i < items.Count; i++) + { + var (mi, relXf) = items[i]; + if (mi.Mesh is not { } mesh) + { + continue; + } + int surfCount = mesh.GetSurfaceCount(); + var am = mesh as ArrayMesh; + for (int s = 0; s < surfCount; s++) + { + if (am is not null && am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles) + { + continue; + } + Material? mat = mi.MaterialOverride ?? mi.GetActiveMaterial(s); + MaterialSurfaceBucket bucket; + if (mat is null) + { + nullMatBucket ??= new MaterialSurfaceBucket { Material = null }; + if (!buckets.Contains(nullMatBucket)) + { + buckets.Add(nullMatBucket); + } + bucket = nullMatBucket; + } + else if (TryGetMaterialValueKey(mat, coarseMaterials, out var matKey)) + { + if (!bucketByMatVal.TryGetValue(matKey, out bucket!)) + { + bucket = new MaterialSurfaceBucket { Material = mat }; + bucketByMatVal[matKey] = bucket; + buckets.Add(bucket); + } + } + else + { + ulong id = mat.GetInstanceId(); + if (!bucketByMatId.TryGetValue(id, out bucket!)) + { + bucket = new MaterialSurfaceBucket { Material = mat }; + bucketByMatId[id] = bucket; + buckets.Add(bucket); + } + } + bucket.Sources.Add((mesh, s, relXf)); + } + } + + if (buckets.Count == 0) + { + return null; + } + + var outMesh = new ArrayMesh(); + for (int b = 0; b < buckets.Count; b++) + { + var bucket = buckets[b]; + bool anyNormal = false; + bool anyTangent = false; + bool anyUv = false; + bool anyUv2 = false; + bool anyColor = false; + int totalVerts = 0; + int totalIndices = 0; + + var cachedArrays = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, int VertCount, int IndexCount)>(bucket.Sources.Count); + for (int s = 0; s < bucket.Sources.Count; s++) + { + var (mesh, surfIdx, relXf) = bucket.Sources[s]; + var arr = mesh.SurfaceGetArrays(surfIdx); + if (arr.Count <= (int)Mesh.ArrayType.Vertex || + arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + if (verts.Length == 0) + { + continue; + } + + if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array) anyNormal = true; + if (arr.Count > (int)Mesh.ArrayType.Tangent && arr[(int)Mesh.ArrayType.Tangent].VariantType == Variant.Type.PackedFloat32Array) anyTangent = true; + if (arr.Count > (int)Mesh.ArrayType.TexUV && arr[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.PackedVector2Array) anyUv = true; + if (arr.Count > (int)Mesh.ArrayType.TexUV2 && arr[(int)Mesh.ArrayType.TexUV2].VariantType == Variant.Type.PackedVector2Array) anyUv2 = true; + if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) anyColor = true; + + int idxCount = verts.Length; + if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array) + { + idxCount = arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length; + } + + totalVerts += verts.Length; + totalIndices += idxCount; + cachedArrays.Add((arr, relXf, verts.Length, idxCount)); + } + + if (totalVerts == 0 || totalIndices == 0) + { + continue; + } + + var outVerts = new Vector3[totalVerts]; + Vector3[]? outNormals = anyNormal ? new Vector3[totalVerts] : null; + float[]? outTangents = anyTangent ? new float[totalVerts * 4] : null; + Vector2[]? outUvs = anyUv ? new Vector2[totalVerts] : null; + Vector2[]? outUv2s = anyUv2 ? new Vector2[totalVerts] : null; + Color[]? outColors = anyColor ? new Color[totalVerts] : null; + var outIndices = new int[totalIndices]; + + int vOffset = 0; + int iOffset = 0; + for (int c = 0; c < cachedArrays.Count; c++) + { + var (arr, relXf, vCount, idxCount) = cachedArrays[c]; + Vector3[] srcVerts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + bool flipWinding = relXf.Basis.Determinant() < 0f; + Basis normBasis = relXf.Basis.Inverse().Transposed(); + + for (int v = 0; v < vCount; v++) + { + outVerts[vOffset + v] = relXf * srcVerts[v]; + } + + if (outNormals is not null) + { + if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array) + { + Vector3[] srcN = arr[(int)Mesh.ArrayType.Normal].AsVector3Array(); + for (int v = 0; v < vCount; v++) + { + Vector3 n = normBasis * srcN[v]; + outNormals[vOffset + v] = n.LengthSquared() > 1e-10f ? n.Normalized() : Vector3.Up; + } + } + else + { + for (int v = 0; v < vCount; v++) outNormals[vOffset + v] = Vector3.Up; + } + } + + if (outTangents is not null) + { + if (arr.Count > (int)Mesh.ArrayType.Tangent && arr[(int)Mesh.ArrayType.Tangent].VariantType == Variant.Type.PackedFloat32Array) + { + float[] srcT = arr[(int)Mesh.ArrayType.Tangent].AsFloat32Array(); + for (int v = 0; v < vCount; v++) + { + int sBase = v * 4; + int dBase = (vOffset + v) * 4; + Vector3 t = relXf.Basis * new Vector3(srcT[sBase], srcT[sBase + 1], srcT[sBase + 2]); + t = t.LengthSquared() > 1e-10f ? t.Normalized() : Vector3.Right; + outTangents[dBase] = t.X; + outTangents[dBase + 1] = t.Y; + outTangents[dBase + 2] = t.Z; + outTangents[dBase + 3] = flipWinding ? -srcT[sBase + 3] : srcT[sBase + 3]; + } + } + else + { + for (int v = 0; v < vCount; v++) + { + int dBase = (vOffset + v) * 4; + outTangents[dBase] = 1f; + outTangents[dBase + 3] = 1f; + } + } + } + + if (outUvs is not null) + { + if (arr.Count > (int)Mesh.ArrayType.TexUV && arr[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.PackedVector2Array) + { + Array.Copy(arr[(int)Mesh.ArrayType.TexUV].AsVector2Array(), 0, outUvs, vOffset, vCount); + } + } + + if (outUv2s is not null) + { + if (arr.Count > (int)Mesh.ArrayType.TexUV2 && arr[(int)Mesh.ArrayType.TexUV2].VariantType == Variant.Type.PackedVector2Array) + { + Array.Copy(arr[(int)Mesh.ArrayType.TexUV2].AsVector2Array(), 0, outUv2s, vOffset, vCount); + } + } + + if (outColors is not null) + { + if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) + { + Array.Copy(arr[(int)Mesh.ArrayType.Color].AsColorArray(), 0, outColors, vOffset, vCount); + } + else + { + for (int v = 0; v < vCount; v++) outColors[vOffset + v] = Colors.White; + } + } + + bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array; + int[]? srcIdx = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null; + if (!flipWinding) + { + if (srcIdx is not null) + { + for (int k = 0; k < idxCount; k++) outIndices[iOffset + k] = srcIdx[k] + vOffset; + } + else + { + for (int k = 0; k < idxCount; k++) outIndices[iOffset + k] = k + vOffset; + } + } + else + { + for (int k = 0; k + 2 < idxCount; k += 3) + { + int a = srcIdx is not null ? srcIdx[k] : k; + int bIdx = srcIdx is not null ? srcIdx[k + 1] : k + 1; + int cIdx = srcIdx is not null ? srcIdx[k + 2] : k + 2; + outIndices[iOffset + k] = a + vOffset; + outIndices[iOffset + k + 1] = cIdx + vOffset; + outIndices[iOffset + k + 2] = bIdx + vOffset; + } + } + + vOffset += vCount; + iOffset += idxCount; + } + + var surfArrays = new Godot.Collections.Array(); + surfArrays.Resize((int)Mesh.ArrayType.Max); + surfArrays[(int)Mesh.ArrayType.Vertex] = outVerts; + if (outNormals is not null) surfArrays[(int)Mesh.ArrayType.Normal] = outNormals; + if (outTangents is not null) surfArrays[(int)Mesh.ArrayType.Tangent] = outTangents; + if (outUvs is not null) surfArrays[(int)Mesh.ArrayType.TexUV] = outUvs; + if (outUv2s is not null) surfArrays[(int)Mesh.ArrayType.TexUV2] = outUv2s; + if (outColors is not null) surfArrays[(int)Mesh.ArrayType.Color] = outColors; + surfArrays[(int)Mesh.ArrayType.Index] = outIndices; + + int newSurf = outMesh.GetSurfaceCount(); + outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfArrays); + if (bucket.Material is not null) + { + outMesh.SurfaceSetMaterial(newSurf, bucket.Material); + } + } + + return outMesh.GetSurfaceCount() > 0 ? outMesh : null; + } + + private static ArrayMesh DecimateMeshGrid(ArrayMesh src, float cellSize) + { + var outMesh = new ArrayMesh(); + float invCell = 1f / MathF.Max(0.02f, cellSize); + int surfCount = src.GetSurfaceCount(); + + for (int s = 0; s < surfCount; s++) + { + var arr = src.SurfaceGetArrays(s); + if (arr.Count <= (int)Mesh.ArrayType.Vertex || + arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + if (verts.Length == 0) + { + continue; + } + + bool hasNorm = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array; + Vector3[]? norms = hasNorm ? arr[(int)Mesh.ArrayType.Normal].AsVector3Array() : null; + + bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array; + int[]? indices = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null; + int triVertCount = indices is not null ? indices.Length : verts.Length; + + var cellToNewIdx = new Dictionary<(int, int, int), int>(verts.Length / 2 + 16); + var vertToCellIdx = new int[verts.Length]; + var accumPos = new List(verts.Length / 2 + 16); + var accumNorm = norms is not null ? new List(verts.Length / 2 + 16) : null; + var counts = new List(verts.Length / 2 + 16); + + for (int v = 0; v < verts.Length; v++) + { + Vector3 p = verts[v]; + var key = ( + (int)MathF.Floor(p.X * invCell), + (int)MathF.Floor(p.Y * invCell), + (int)MathF.Floor(p.Z * invCell)); + + if (!cellToNewIdx.TryGetValue(key, out int ci)) + { + ci = accumPos.Count; + cellToNewIdx[key] = ci; + accumPos.Add(p); + if (accumNorm is not null) accumNorm.Add(norms![v]); + counts.Add(1); + } + else + { + accumPos[ci] += p; + if (accumNorm is not null) accumNorm[ci] += norms![v]; + counts[ci]++; + } + vertToCellIdx[v] = ci; + } + + var outIndices = new List(triVertCount / 2 + 12); + for (int k = 0; k + 2 < triVertCount; k += 3) + { + int i0 = indices is not null ? indices[k] : k; + int i1 = indices is not null ? indices[k + 1] : k + 1; + int i2 = indices is not null ? indices[k + 2] : k + 2; + int c0 = vertToCellIdx[i0]; + int c1 = vertToCellIdx[i1]; + int c2 = vertToCellIdx[i2]; + if (c0 != c1 && c1 != c2 && c0 != c2) + { + outIndices.Add(c0); + outIndices.Add(c1); + outIndices.Add(c2); + } + } + + if (outIndices.Count == 0) + { + // Keep original tiny surface intact if grid collapsed all triangles + int fallbackSurf = outMesh.GetSurfaceCount(); + outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arr); + Material? fMat = src.SurfaceGetMaterial(s); + if (fMat is not null) outMesh.SurfaceSetMaterial(fallbackSurf, fMat); + continue; + } + + var outVerts = new Vector3[accumPos.Count]; + Vector3[]? outNorms = accumNorm is not null ? new Vector3[accumPos.Count] : null; + for (int i = 0; i < accumPos.Count; i++) + { + outVerts[i] = accumPos[i] / counts[i]; + if (outNorms is not null) + { + Vector3 n = accumNorm![i]; + outNorms[i] = n.LengthSquared() > 1e-8f ? n.Normalized() : Vector3.Up; + } + } + + var newArr = new Godot.Collections.Array(); + newArr.Resize((int)Mesh.ArrayType.Max); + newArr[(int)Mesh.ArrayType.Vertex] = outVerts; + if (outNorms is not null) newArr[(int)Mesh.ArrayType.Normal] = outNorms; + newArr[(int)Mesh.ArrayType.Index] = outIndices.ToArray(); + + int newSurf = outMesh.GetSurfaceCount(); + outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, newArr); + Material? mat = src.SurfaceGetMaterial(s); + if (mat is not null) + { + outMesh.SurfaceSetMaterial(newSurf, mat); + } + } + + return outMesh.GetSurfaceCount() > 0 ? outMesh : src; + } + + private static void MarkAncestorsProtected(int idx, Dictionary parentByIndex, HashSet protectedSet) + { + int cur = idx; + while (true) + { + if (!protectedSet.Add(cur)) + { + // Still continue up in case a parent wasn't marked yet, or break if parent already marked + } + if (!parentByIndex.TryGetValue(cur, out int parent)) + { + break; + } + cur = parent; + } + } + + private static Node? ResolveSceneNode(Node3D sceneRoot, NodePath scenePath, string originalName) + { + if (!scenePath.IsEmpty) + { + Node? direct = sceneRoot.GetNodeOrNull(scenePath); + if (direct is not null) + { + return direct; + } + + string raw = scenePath.ToString(); + if (raw == "." || raw == sceneRoot.Name) + { + return sceneRoot; + } + + int slash = raw.IndexOf('/'); + if (slash >= 0) + { + string sub = raw[(slash + 1)..]; + Node? trimmed = sceneRoot.GetNodeOrNull(sub); + if (trimmed is not null) + { + return trimmed; + } + } + } + + // Fallback: sanitized name match + string sanitized = originalName.Replace('.', '_').Replace(':', '_').Replace('@', '_').Replace('/', '_'); + return FindNodeRecursive(sceneRoot, originalName, sanitized); + } + + private static Node? FindNodeRecursive(Node cur, string exactName, string sanitized) + { + string nm = cur.Name; + if (string.Equals(nm, exactName, StringComparison.Ordinal) || + string.Equals(nm, sanitized, StringComparison.Ordinal)) + { + return cur; + } + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + Node? found = FindNodeRecursive(cur.GetChild(i), exactName, sanitized); + if (found is not null) + { + return found; + } + } + return null; + } + + private static NodePath BuildRelativeNodePath(Node root, Node target) + { + if (ReferenceEquals(root, target)) + { + return new NodePath("."); + } + + var segments = new List(); + Node? cur = target; + while (cur is not null && !ReferenceEquals(cur, root)) + { + segments.Add(cur.Name); + cur = cur.GetParent(); + } + if (!ReferenceEquals(cur, root)) + { + return new NodePath("."); + } + segments.Reverse(); + return new NodePath(string.Join("/", segments)); + } + + private static void CollectModelTransforms(Node cur, Transform3D parentTransform, Dictionary map) + { + Transform3D world = cur is Node3D n3d ? parentTransform * n3d.Transform : parentTransform; + map[cur] = world; + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + CollectModelTransforms(cur.GetChild(i), world, map); + } + } + + private static void ComputeSceneMeshBoundsY(Node3D root, out float minY, out float maxY) + { + ComputeSceneMeshBounds(root, out Vector3 mn, out Vector3 mx); + minY = mn.Y; + maxY = mx.Y; + } + + private static void ComputeSceneMeshBounds(Node3D root, out Vector3 boundsMin, out Vector3 boundsMax) + { + Vector3 mn = new(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + Vector3 mx = new(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); + AccumulateBounds(root, Transform3D.Identity, ref mn, ref mx); + + if (!float.IsFinite(mn.X)) + { + mn = Vector3.Zero; + mx = Vector3.One; + } + boundsMin = mn; + boundsMax = mx; + } + + private static void AccumulateBounds(Node cur, Transform3D parentXf, ref Vector3 mn, ref Vector3 mx) + { + Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf; + if (cur is MeshInstance3D mi && mi.Mesh is not null) + { + bool usedVertices = false; + int surfCount = mi.Mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arrays = mi.Mesh.SurfaceGetArrays(s); + if (arrays.Count > (int)Mesh.ArrayType.Vertex) + { + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + if (verts.Length > 0) + { + usedVertices = true; + for (int v = 0; v < verts.Length; v++) + { + Vector3 w = xf * verts[v]; + mn = new Vector3(MathF.Min(mn.X, w.X), MathF.Min(mn.Y, w.Y), MathF.Min(mn.Z, w.Z)); + mx = new Vector3(MathF.Max(mx.X, w.X), MathF.Max(mx.Y, w.Y), MathF.Max(mx.Z, w.Z)); + } + } + } + } + + if (!usedVertices) + { + Aabb aabb = mi.Mesh.GetAabb(); + Vector3 p = aabb.Position; + Vector3 sz = aabb.Size; + for (int ix = 0; ix < 2; ix++) + { + for (int iy = 0; iy < 2; iy++) + { + for (int iz = 0; iz < 2; iz++) + { + Vector3 corner = new(p.X + ix * sz.X, p.Y + iy * sz.Y, p.Z + iz * sz.Z); + Vector3 w = xf * corner; + mn = new Vector3(MathF.Min(mn.X, w.X), MathF.Min(mn.Y, w.Y), MathF.Min(mn.Z, w.Z)); + mx = new Vector3(MathF.Max(mx.X, w.X), MathF.Max(mx.Y, w.Y), MathF.Max(mx.Z, w.Z)); + } + } + } + } + } + + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + AccumulateBounds(cur.GetChild(i), xf, ref mn, ref mx); + } + } + + private static byte[] ReadGlbJsonChunk(string glbPath) + { + byte[] data = File.ReadAllBytes(glbPath); + if (data.Length < 20) + { + throw new InvalidDataException($"{glbPath}: GLB smaller than 20-byte header."); + } + + uint magic = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(0, 4)); + uint version = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4, 4)); + if (magic != 0x46546C67 || version != 2) + { + throw new InvalidDataException($"{glbPath}: invalid GLB header magic=0x{magic:X8} version={version}."); + } + + uint jsonLen = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12, 4)); + uint jsonType = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16, 4)); + if (jsonType != 0x4E4F534A) + { + throw new InvalidDataException($"{glbPath}: first GLB chunk is not JSON (0x{jsonType:X8})."); + } + + return data.AsSpan(20, (int)jsonLen).ToArray(); + } + + private static Vector3 ReadVec3(JsonElement obj, string propName, Vector3 fallback) + { + if (!obj.TryGetProperty(propName, out JsonElement arr) || arr.ValueKind != JsonValueKind.Array || arr.GetArrayLength() < 3) + { + return fallback; + } + return new Vector3(arr[0].GetSingle(), arr[1].GetSingle(), arr[2].GetSingle()); + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + foreach (var v in _vehicles.Values) + { + if (GodotObject.IsInstanceValid(v.SceneTemplate)) + { + v.SceneTemplate.QueueFree(); + } + } + foreach (var g in _gear.Values) + { + if (GodotObject.IsInstanceValid(g.SceneTemplate)) + { + g.SceneTemplate.QueueFree(); + } + } + _vehicles.Clear(); + _gear.Clear(); + } +} diff --git a/client/VehicleRigAnimator.cs b/client/VehicleRigAnimator.cs new file mode 100644 index 0000000..aa35ba8 --- /dev/null +++ b/client/VehicleRigAnimator.cs @@ -0,0 +1,1077 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +public readonly record struct VehicleRigDriveInput( + Vector3 Velocity, + float Yaw, + float AimYawWorld, + float AimPitchDeg, + float SteerCmd, + float ThrottleCmd, + float VerticalThrottleCmd, + float EngineThermalPerf, + float DeltaTime, + bool IsGrounded = true); + +/// +/// Drives real-time secondary mechanism animations on +/// from live physics state with strict NaN/Inf guards: +/// - Wheeled: wheel spin (v / r), front-axle steering, subtle chassis suspension roll/pitch. +/// - Turrets/Torsos/Arms: yaw tracking (joint.turret_yaw, joint.torso_yaw) & arm pitch. +/// - VTOL: rotor spin scaled by EngineThermalPerf + lift demand, nacelle tilt with acceleration. +/// - Walkers/Mechs: procedural leg stride returning to neutral rest when stopped, Manticore tail aiming, +/// and Breaker's damped oleo strut + 2-link scissor torque links + telescoping recess rams. +/// +public static class VehicleRigAnimator +{ + public sealed class StrutState + { + public float Compression; + public float Velocity; + } + + public sealed class ScissorBinding + { + public required Node3D UpperNode; + public required Node3D LowerNode; + public required Node3D ShinNode; + public required Node3D OleoNode; + public required Node3D OleoForkNode; + public required Transform3D RestLocalUp; + public required Transform3D RestLocalLow; + public required Vector3 AInShin; + public required Vector3 BInOleoFork; + public required Vector3 OutInShin; + public required float Arm; + public required Vector3 DirUp0InShin; + public required Vector3 DirLow0InOleoFork; + } + + public sealed class RamBinding + { + public required Node3D RamNode; + public required Node3D LugNode; + public required Node3D OleoNode; + public required Node3D OleoForkNode; + public required Node3D FootNode; + public required Transform3D RestLocalRam; + public required Vector3 APosInLug; + public required Vector3 BPosInFoot; + public required Vector3 WantDir0InLug; + } + + public sealed class BreakerMechRig + { + public bool Initialized; + public readonly Dictionary Struts = new(StringComparer.Ordinal); + public readonly Dictionary OleoNodes = new(StringComparer.Ordinal); + public readonly List Scissors = new(); + public readonly List Rams = new(); + } + + public sealed class WalkerFootSample + { + public required Node3D[] ChainFromModelRoot; + public required Vector3[] LocalPoints; + } + + public sealed class RigState + { + public float WheelSpinRad; + public float SteerRad; + public float TurretYawRad; + public float ArmPitchRad; + public float RotorSpinRad; + public float NacelleTiltRad; + public float StridePhaseRad; + public float StrideAmp; + public float PrevForwardSpeed; + public float PrevVelY; + public float ChassisPitchRad; + public float ChassisRollRad; + public float ElapsedSeconds; + public BreakerMechRig? BreakerRig; + public List? FootSamples; + } + + public static void Update( + VehicleVisualInstance visual, + ContenderState c, + Vector3 velocity, + Basis worldBasis, + float dt, + bool snap = false) + { + float aimYawWorld = c.Yaw; + float dx = c.AimX - c.X; + float dz = c.AimZ - c.Z; + if (float.IsFinite(dx) && float.IsFinite(dz) && (dx * dx + dz * dz) > 0.01f) + { + aimYawWorld = MathF.Atan2(dx, dz); + } + + float aimPitchDeg = 0f; + if (float.IsFinite(c.AimY)) + { + float aimOriginY = MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight); + float horiz = MathF.Sqrt(dx * dx + dz * dz); + if (horiz > 0.1f) + { + aimPitchDeg = Mathf.RadToDeg(MathF.Atan2(c.AimY - aimOriginY, horiz)); + } + } + + var input = new VehicleRigDriveInput( + Velocity: velocity, + Yaw: c.Yaw, + AimYawWorld: aimYawWorld, + AimPitchDeg: aimPitchDeg, + SteerCmd: c.SteerCmd, + ThrottleCmd: c.ThrottleCmd, + VerticalThrottleCmd: c.VerticalThrottleCmd, + EngineThermalPerf: c.Grid.ComputeEngineThermalPerformance(), + DeltaTime: dt, + IsGrounded: !c.Grid.Spec.IsVtol); + + Update(visual, in input, worldBasis, snap); + } + + public static void Update( + VehicleVisualInstance visual, + in VehicleRigDriveInput input, + Basis worldBasis, + bool snap = false) + { + float dt = Sanitize(input.DeltaTime, 0f, 0f, 0.1f); + if (!snap && dt <= 0f) + { + return; + } + Vector3 vel = SanitizeVec(input.Velocity); + float yaw = Sanitize(input.Yaw, 0f, -MathF.Tau * 4f, MathF.Tau * 4f); + float aimYawWorld = Sanitize(input.AimYawWorld, yaw, -MathF.Tau * 4f, MathF.Tau * 4f); + float aimPitchDeg = Sanitize(input.AimPitchDeg, 0f, -85f, 85f); + float steerCmd = Sanitize(input.SteerCmd, 0f, -1f, 1f); + float throttleCmd = Sanitize(input.ThrottleCmd, 0f, -1f, 1f); + float vertCmd = Sanitize(input.VerticalThrottleCmd, 0f, -1f, 1f); + float enginePerf = Sanitize(input.EngineThermalPerf, 1f, 0f, 1f); + + RigState st = visual.RigState; + st.ElapsedSeconds += dt; + + Vector3 fwd = worldBasis.Z; + fwd.Y = 0f; + fwd = fwd.LengthSquared() > 1e-5f ? fwd.Normalized() : new Vector3(MathF.Sin(yaw), 0f, MathF.Cos(yaw)); + Vector3 right = new(-fwd.Z, 0f, fwd.X); + + float forwardSpeed = vel.Dot(fwd); + float lateralSpeed = vel.Dot(right); + float horizSpeed = MathF.Sqrt(forwardSpeed * forwardSpeed + lateralSpeed * lateralSpeed); + + float relYaw = MatchRules.NormalizeAngle(aimYawWorld - yaw); + float aimPitchRad = Mathf.DegToRad(aimPitchDeg); + + float blendFast = dt > 0f ? 1f - MathF.Exp(-dt * 10f) : 1f; + float blendMed = dt > 0f ? 1f - MathF.Exp(-dt * 7f) : 1f; + + // 1. Turrets & torsos + UpdateTurretAndTorso(visual, st, relYaw, aimPitchRad, blendFast); + + // 2. Mobility-specific drives + var mobility = visual.Package.Mobility; + switch (mobility) + { + case MobilityKind.Wheeled: + UpdateWheeled(visual, st, forwardSpeed, lateralSpeed, steerCmd, dt, blendFast); + break; + + case MobilityKind.Vtol: + UpdateVtol(visual, st, forwardSpeed, throttleCmd, vertCmd, enginePerf, dt, blendMed); + break; + + case MobilityKind.Walker: + UpdateWalker(visual, st, horizSpeed, forwardSpeed, vel.Y, steerCmd, relYaw, aimPitchRad, dt, blendMed); + break; + + case MobilityKind.Tracked: + UpdateTrackedSuspension(visual, st, forwardSpeed, lateralSpeed, dt, blendMed); + break; + } + + st.PrevForwardSpeed = forwardSpeed; + st.PrevVelY = vel.Y; + } + + private static void UpdateTurretAndTorso( + VehicleVisualInstance visual, + RigState st, + float relYaw, + float aimPitchRad, + float blend) + { + if (visual.Joints.TryGetValue("joint.turret_yaw", out var turretJoint) || + visual.Joints.TryGetValue("joint.torso_yaw", out turretJoint)) + { + bool fullSpin = turretJoint.MinRad <= -MathF.PI * 0.99f && turretJoint.MaxRad >= MathF.PI * 0.99f; + float targetYaw = fullSpin + ? relYaw + : Math.Clamp(relYaw, turretJoint.MinRad, turretJoint.MaxRad); + + if (fullSpin) + { + float diff = MatchRules.NormalizeAngle(targetYaw - st.TurretYawRad); + st.TurretYawRad = MatchRules.NormalizeAngle(st.TurretYawRad + diff * blend); + } + else + { + st.TurretYawRad += (targetYaw - st.TurretYawRad) * blend; + } + + SetJointAngle(turretJoint, st.TurretYawRad); + } + + st.ArmPitchRad += (aimPitchRad - st.ArmPitchRad) * blend; + // Positive elevation (+aimPitchRad) rotates negatively around vehicle +X (raises +Z barrels toward +Y) + if (visual.Joints.TryGetValue("joint.arm_l_pitch", out var armL)) + { + float clampedL = Math.Clamp(-st.ArmPitchRad, armL.MinRad, armL.MaxRad); + SetJointAngle(armL, clampedL); + } + if (visual.Joints.TryGetValue("joint.arm_r_pitch", out var armR)) + { + float clampedR = Math.Clamp(-st.ArmPitchRad, armR.MinRad, armR.MaxRad); + SetJointAngle(armR, clampedR); + } + } + + private static void UpdateWheeled( + VehicleVisualInstance visual, + RigState st, + float forwardSpeed, + float lateralSpeed, + float steerCmd, + float dt, + float blend) + { + // Determine average wheel radius from wheel joint Y height in grounded GLB + float radiusSum = 0f; + int radiusCount = 0; + foreach (var (jid, j) in visual.Joints) + { + if (jid.StartsWith("joint.wheel_", StringComparison.Ordinal)) + { + float y = j.RestLocal.Origin.Y; + if (y <= 0.05f && j.Node.GetParent() is Node3D p3) + { + y = p3.Transform.Origin.Y; + } + if (y > 0.1f) + { + radiusSum += y; + radiusCount++; + } + } + } + float wheelRadius = radiusCount > 0 ? radiusSum / radiusCount : 0.45f; + + st.WheelSpinRad = MathF.IEEERemainder(st.WheelSpinRad + (forwardSpeed / MathF.Max(0.25f, wheelRadius)) * dt, MathF.Tau); + + float targetSteer = -steerCmd * Mathf.DegToRad(28f); + st.SteerRad += (targetSteer - st.SteerRad) * blend; + + foreach (var (jid, j) in visual.Joints) + { + if (jid.StartsWith("joint.wheel_", StringComparison.Ordinal)) + { + SetJointAngle(j, st.WheelSpinRad); + } + else if (jid.StartsWith("joint.steer_", StringComparison.Ordinal)) + { + float clampedSteer = Math.Clamp(st.SteerRad, j.MinRad, j.MaxRad); + SetJointAngle(j, clampedSteer); + } + } + + // Subtle chassis suspension pitch & roll + float accel = dt > 1e-4f ? (forwardSpeed - st.PrevForwardSpeed) / dt : 0f; + float targetPitch = Math.Clamp(-accel * 0.0022f, -0.05f, 0.05f); + float targetRoll = Math.Clamp(lateralSpeed * 0.0045f + steerCmd * MathF.Min(1f, MathF.Abs(forwardSpeed) / 14f) * 0.035f, -0.06f, 0.06f); + st.ChassisPitchRad += (targetPitch - st.ChassisPitchRad) * blend; + st.ChassisRollRad += (targetRoll - st.ChassisRollRad) * blend; + + if (visual.GetNamedNode("Chassis") is { } chassis && visual.TryGetRestLocal("Chassis", out var restChassis)) + { + Basis tilt = new Basis(Vector3.Right, st.ChassisPitchRad) * new Basis(Vector3.Back, st.ChassisRollRad); + chassis.Transform = new Transform3D(tilt * restChassis.Basis, restChassis.Origin); + } + } + + private static void UpdateTrackedSuspension( + VehicleVisualInstance visual, + RigState st, + float forwardSpeed, + float lateralSpeed, + float dt, + float blend) + { + float accel = dt > 1e-4f ? (forwardSpeed - st.PrevForwardSpeed) / dt : 0f; + float targetPitch = Math.Clamp(-accel * 0.0018f, -0.045f, 0.045f); + float targetRoll = Math.Clamp(lateralSpeed * 0.003f, -0.045f, 0.045f); + st.ChassisPitchRad += (targetPitch - st.ChassisPitchRad) * blend; + st.ChassisRollRad += (targetRoll - st.ChassisRollRad) * blend; + + if (visual.GetNamedNode("Chassis") is { } chassis && visual.TryGetRestLocal("Chassis", out var restChassis)) + { + Basis tilt = new Basis(Vector3.Right, st.ChassisPitchRad) * new Basis(Vector3.Back, st.ChassisRollRad); + chassis.Transform = new Transform3D(tilt * restChassis.Basis, restChassis.Origin); + } + } + + private static void UpdateVtol( + VehicleVisualInstance visual, + RigState st, + float forwardSpeed, + float throttleCmd, + float vertCmd, + float enginePerf, + float dt, + float blend) + { + float rotorSpeed = (5.5f + 18.0f * enginePerf) * + (1f + 0.35f * MathF.Max(0f, vertCmd) + 0.16f * MathF.Abs(throttleCmd)); + st.RotorSpinRad = MathF.IEEERemainder(st.RotorSpinRad + rotorSpeed * dt, MathF.Tau); + + float targetTilt = throttleCmd * 0.42f + (forwardSpeed / 42f) * 0.28f; + st.NacelleTiltRad += (targetTilt - st.NacelleTiltRad) * blend; + + foreach (var (jid, j) in visual.Joints) + { + if (jid.StartsWith("joint.rotor_", StringComparison.Ordinal)) + { + float dir = (jid.Contains("_r", StringComparison.Ordinal) && !jid.Contains("_rl", StringComparison.Ordinal)) || + jid.EndsWith("_rl", StringComparison.Ordinal) + ? -1f + : 1f; + SetJointAngle(j, st.RotorSpinRad * dir); + } + else if (jid.StartsWith("joint.nacelle_", StringComparison.Ordinal)) + { + float clampedTilt = Math.Clamp(st.NacelleTiltRad, j.MinRad, j.MaxRad); + SetJointAngle(j, clampedTilt); + } + } + } + + private static void UpdateWalker( + VehicleVisualInstance visual, + RigState st, + float horizSpeed, + float forwardSpeed, + float velY, + float steerCmd, + float relYaw, + float aimPitchRad, + float dt, + float blend) + { + EnsureWalkerFootSamples(visual, st); + + float targetAmp = Math.Clamp(horizSpeed / 6.5f + MathF.Abs(steerCmd) * 0.32f, 0f, 1f); + st.StrideAmp += (targetAmp - st.StrideAmp) * blend; + + float strideDir = forwardSpeed >= -0.35f ? 1f : -1f; + float phaseRate = (2.8f + horizSpeed * 0.48f + MathF.Abs(steerCmd) * 1.4f) * strideDir; + st.StridePhaseRad = MathF.IEEERemainder(st.StridePhaseRad + phaseRate * dt, MathF.Tau); + + float phiL = st.StridePhaseRad; + float phiR = st.StridePhaseRad + MathF.PI; + string id = visual.ModelId.ToLowerInvariant(); + + switch (id) + { + case "breaker": + AnimateBipedLeg(visual, "LegL.Hip", "LegL.Shin", "LegL.Foot", phiL, st.StrideAmp, signX: -1f); + AnimateBipedLeg(visual, "LegR.Hip", "LegR.Shin", "LegR.Foot", phiR, st.StrideAmp, signX: -1f); + ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.06f, rollScale: 0.024f); + StepBreakerMechanisms(visual, st, phiL, phiR, velY, dt); + ApplyWalkerFloorClearance(visual, st, "Pelvis"); + break; + + case "paladin": + AnimateBipedVehicleX(visual, "LegL.Upper", "LegL.Lower", "LegL.Ankle", phiL, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.28f, kneeForwardFlexAmp: 0.08f); + AnimateBipedVehicleX(visual, "LegR.Upper", "LegR.Lower", "LegR.Ankle", phiR, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.28f, kneeForwardFlexAmp: 0.08f); + ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.07f, rollScale: 0.020f); + ApplyWalkerFloorClearance(visual, st, "Pelvis"); + break; + + case "raptor": + AnimateBipedVehicleX(visual, "LegL.Thigh", "LegL.Shin", "LegL.Cannon", phiL, st.StrideAmp, hipAmp: 0.20f, kneeLiftAmp: 0.34f, kneeForwardFlexAmp: 0.22f); + AnimateBipedVehicleX(visual, "LegR.Thigh", "LegR.Shin", "LegR.Cannon", phiR, st.StrideAmp, hipAmp: 0.20f, kneeLiftAmp: 0.34f, kneeForwardFlexAmp: 0.22f); + ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.06f, rollScale: 0.020f); + ApplyWalkerFloorClearance(visual, st, "Pelvis"); + break; + + case "spectre": + AnimateBipedVehicleX(visual, "LegL.Thigh", "LegL.Shin", "LegL.Cannon", phiL, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.32f, kneeForwardFlexAmp: 0f); + AnimateBipedVehicleX(visual, "LegR.Thigh", "LegR.Shin", "LegR.Cannon", phiR, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.32f, kneeForwardFlexAmp: 0f); + ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.06f, rollScale: 0.020f); + ApplyWalkerFloorClearance(visual, st, "Pelvis"); + break; + + case "kestrel": + // Kestrel leg meshes are baked under Pelvis; animate Pelvis stride bob/sway with floor clearance + ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.07f, rollScale: 0.024f); + ApplyWalkerFloorClearance(visual, st, "Pelvis"); + break; + + case "manticore": + AnimateManticoreLeg(visual, "LegFL.S1", "LegFL.S2", "FootFL", phiL, st.StrideAmp, isFront: true); + AnimateManticoreLeg(visual, "LegBR.S1", "LegBR.S2", "FootBR", phiL, st.StrideAmp, isFront: false); + AnimateManticoreLeg(visual, "LegFR.S1", "LegFR.S2", "FootFR", phiR, st.StrideAmp, isFront: true); + AnimateManticoreLeg(visual, "LegBL.S1", "LegBL.S2", "FootBL", phiR, st.StrideAmp, isFront: false); + ApplyPelvisBob(visual, "Hull", st.StridePhaseRad, st.StrideAmp, bobScale: 0.04f, rollScale: 0.018f); + ApplyWalkerFloorClearance(visual, st, "Hull"); + AnimateManticoreTail(visual, st, relYaw, aimPitchRad, blend); + break; + + case "bastion": + AnimateBastionLeg(visual, "Thigh.fl", "Shin.fl", "Ankle.fl", phiL, st.StrideAmp, isFront: true); + AnimateBastionLeg(visual, "Thigh.rr", "Shin.rr", "Ankle.rr", phiL, st.StrideAmp, isFront: false); + AnimateBastionLeg(visual, "Thigh.fr", "Shin.fr", "Ankle.fr", phiR, st.StrideAmp, isFront: true); + AnimateBastionLeg(visual, "Thigh.rl", "Shin.rl", "Ankle.rl", phiR, st.StrideAmp, isFront: false); + ApplyPelvisBob(visual, "Trunk", st.StridePhaseRad, st.StrideAmp, bobScale: 0.05f, rollScale: 0.012f); + ApplyWalkerFloorClearance(visual, st, "Trunk"); + break; + } + } + + private static float SwingLift(float phase) => MathF.Max(0f, MathF.Cos(phase)); + + private static void AnimateBipedLeg( + VehicleVisualInstance visual, + string hipName, + string shinName, + string footName, + float phase, + float amp, + float signX) + { + float hipAng = MathF.Sin(phase) * 0.30f * amp; + float kneeAng = MathF.Max(0f, -MathF.Cos(phase)) * 0.38f * amp; + float footAng = -(hipAng * 0.55f + kneeAng * 0.45f); + + RotateVehicleAxis(visual, hipName, Vector3.Right, hipAng * signX); + RotateVehicleAxis(visual, shinName, Vector3.Right, kneeAng * signX); + RotateVehicleAxis(visual, footName, Vector3.Right, footAng * signX); + } + + private static void AnimateBipedVehicleX( + VehicleVisualInstance visual, + string thighName, + string shinName, + string footName, + float phase, + float amp, + float hipAmp, + float kneeLiftAmp, + float kneeForwardFlexAmp) + { + float hipAng = -MathF.Sin(phase) * hipAmp * amp; + float kneeAng = (SwingLift(phase) * kneeLiftAmp + MathF.Max(0f, MathF.Sin(phase)) * kneeForwardFlexAmp) * amp; + float footAng = -(hipAng + kneeAng); + + RotateVehicleAxis(visual, thighName, Vector3.Right, hipAng); + RotateVehicleAxis(visual, shinName, Vector3.Right, kneeAng); + RotateVehicleAxis(visual, footName, Vector3.Right, footAng); + } + + private static void AnimateManticoreLeg( + VehicleVisualInstance visual, + string s1Name, + string s2Name, + string footName, + float phase, + float amp, + bool isFront) + { + float s2Ang = -MathF.Sin(phase) * 0.22f * amp; + float liftSign = isFront ? -1f : 1f; + float s1Ang = SwingLift(phase) * 0.26f * amp * liftSign; + float footAng = -(s1Ang + s2Ang); + + RotateVehicleAxis(visual, s1Name, Vector3.Right, s1Ang); + RotateVehicleAxis(visual, s2Name, Vector3.Right, s2Ang); + RotateVehicleAxis(visual, footName, Vector3.Right, footAng); + } + + private static void AnimateBastionLeg( + VehicleVisualInstance visual, + string thighName, + string shinName, + string ankleName, + float phase, + float amp, + bool isFront) + { + float thAng; + float shAng; + if (isFront) + { + thAng = -MathF.Sin(phase) * 0.16f * amp; + shAng = SwingLift(phase) * 0.14f * amp; + } + else + { + thAng = (MathF.Max(0f, -MathF.Sin(phase)) * 0.14f + SwingLift(phase) * 0.10f) * amp; + shAng = (-MathF.Sin(phase) * 0.16f - SwingLift(phase) * 0.16f) * amp; + } + float anAng = -(thAng + shAng); + + RotateVehicleAxis(visual, thighName, Vector3.Right, thAng); + RotateVehicleAxis(visual, shinName, Vector3.Right, shAng); + RotateVehicleAxis(visual, ankleName, Vector3.Right, anAng); + } + + private static void ApplyPelvisBob( + VehicleVisualInstance visual, + string rootNodeName, + float phase, + float amp, + float bobScale, + float rollScale = 0.024f) + { + if (visual.GetNamedNode(rootNodeName) is not { } node || + !visual.TryGetRestLocal(rootNodeName, out var rest)) + { + return; + } + + float bobY = MathF.Abs(MathF.Sin(phase)) * bobScale * amp; + float swayRoll = MathF.Cos(phase) * rollScale * amp; + Basis roll = new Basis(Vector3.Back, swayRoll); + node.Transform = new Transform3D(roll * rest.Basis, rest.Origin + new Vector3(0f, bobY, 0f)); + } + + private static void AnimateManticoreTail( + VehicleVisualInstance visual, + RigState st, + float relYaw, + float aimPitchRad, + float blend) + { + if (visual.Joints.TryGetValue("joint.tail_yaw", out var tailYaw)) + { + float targetTailYaw = Math.Clamp(relYaw, tailYaw.MinRad, tailYaw.MaxRad); + st.TurretYawRad += (targetTailYaw - st.TurretYawRad) * blend; + SetJointAngle(tailYaw, st.TurretYawRad); + } + + float idleSway = MathF.Sin(st.ElapsedSeconds * 2.1f) * 0.05f; + float pitchDrive = aimPitchRad * 0.5f + idleSway; + + if (visual.Joints.TryGetValue("joint.tail_s1", out var s1)) + { + SetJointAngle(s1, Math.Clamp(pitchDrive * 0.45f, s1.MinRad, s1.MaxRad)); + } + if (visual.Joints.TryGetValue("joint.tail_s2", out var s2)) + { + SetJointAngle(s2, Math.Clamp(-pitchDrive * 0.65f, s2.MinRad, s2.MaxRad)); + } + if (visual.Joints.TryGetValue("joint.tail_s3", out var s3)) + { + SetJointAngle(s3, Math.Clamp(-pitchDrive * 0.55f, s3.MinRad, s3.MaxRad)); + } + if (visual.Joints.TryGetValue("joint.tail_elev", out var elev)) + { + SetJointAngle(elev, Math.Clamp(-aimPitchRad * 0.85f, elev.MinRad, elev.MaxRad)); + } + } + + private static void StepBreakerMechanisms( + VehicleVisualInstance visual, + RigState st, + float phiL, + float phiR, + float velY, + float dt) + { + VehicleMechanismsRecord? mech = visual.Package.Mechanisms; + if (mech is null || mech.Struts.Count == 0) + { + return; + } + + BreakerMechRig rig = st.BreakerRig ??= InitBreakerRig(visual, mech); + if (!rig.Initialized) + { + return; + } + + float accelY = dt > 1e-4f ? Math.Clamp((velY - st.PrevVelY) / dt, -25f, 25f) : 0f; + float strideLoadL = 1.0f + 0.42f * MathF.Sin(phiL) * st.StrideAmp + MathF.Max(-0.6f, accelY * 0.05f); + float strideLoadR = 1.0f + 0.42f * MathF.Sin(phiR) * st.StrideAmp + MathF.Max(-0.6f, accelY * 0.05f); + + // 1. Oleo gas-spring + asymmetric orifice damping (Brokkr mechrig.Model.strut_step) + if (dt > 0f) + { + float stepDt = Math.Clamp(dt, 0.001f, 0.05f); + for (int i = 0; i < mech.Struts.Count; i++) + { + var sr = mech.Struts[i]; + if (!rig.Struts.TryGetValue(sr.Name, out var ss)) + { + continue; + } + + float load = string.Equals(sr.Side, "R", StringComparison.OrdinalIgnoreCase) ? strideLoadR : strideLoadL; + float w = MathF.Tau * MathF.Max(0.1f, sr.Hertz); + float column = 1.15f * MathF.Max(0.02f, sr.Travel); + float h = stepDt / 16f; + + for (int sub = 0; sub < 16; sub++) + { + float ratio = Math.Clamp(1f - ss.Compression / column, 0.08f, 2f); + float spring = w * w * column * (MathF.Pow(ratio, -1.3f) - 1f) / 1.3f; + float c = 2f * sr.DampingRatio * w * (ss.Velocity < 0f ? 1.3f : 1f); + ss.Velocity += h * (9.81f * load - spring - c * ss.Velocity); + ss.Compression += h * ss.Velocity; + if (ss.Compression < 0f || ss.Compression > sr.Travel) + { + ss.Compression = Math.Clamp(ss.Compression, 0f, sr.Travel); + ss.Velocity = 0f; + } + } + + if (rig.OleoNodes.TryGetValue(sr.Dof, out var oleo)) + { + // LegL/R.Oleo local +Y points down toward the foot; compression slides up (-Y) + oleo.Node.Transform = new Transform3D( + oleo.RestLocal.Basis, + oleo.RestLocal.Origin + new Vector3(0f, -ss.Compression, 0f)); + } + } + } + + // 2. Scissor 2-link torque knees (LegL/R.TorqueUp, LegL/R.TorqueLow) + for (int i = 0; i < rig.Scissors.Count; i++) + { + var sb = rig.Scissors[i]; + Transform3D forkInShin = sb.OleoNode.Transform * sb.OleoForkNode.Transform; + Vector3 bInShin = forkInShin * sb.BInOleoFork; + Vector3 apexInShin = SolveScissorApex(sb.AInShin, bInShin, sb.OutInShin, sb.Arm); + + Vector3 dirUp = (apexInShin - sb.AInShin); + if (dirUp.LengthSquared() > 1e-8f) + { + Quaternion qUp = ShortestArcQuat(sb.DirUp0InShin, dirUp.Normalized()); + Basis rotUp = new Basis(qUp); + sb.UpperNode.Transform = new Transform3D(rotUp, sb.AInShin - rotUp * sb.AInShin) * sb.RestLocalUp; + } + + Vector3 apexInFork = forkInShin.Inverse() * apexInShin; + Vector3 dirLow = (apexInFork - sb.BInOleoFork); + if (dirLow.LengthSquared() > 1e-8f) + { + Quaternion qLow = ShortestArcQuat(sb.DirLow0InOleoFork, dirLow.Normalized()); + Basis rotLow = new Basis(qLow); + sb.LowerNode.Transform = new Transform3D(rotLow, sb.BInOleoFork - rotLow * sb.BInOleoFork) * sb.RestLocalLow; + } + } + + // 3. Telescoping recess hydraulic rams (LegL/R.RecessRam0/1) + for (int i = 0; i < rig.Rams.Count; i++) + { + var rb = rig.Rams[i]; + Transform3D forkInShin = rb.OleoNode.Transform * rb.OleoForkNode.Transform; + Transform3D footInLug = rb.LugNode.Transform.Inverse() * forkInShin * rb.FootNode.Transform; + Vector3 bInLug = footInLug * rb.BPosInFoot; + Vector3 span = bInLug - rb.APosInLug; + if (span.LengthSquared() > 1e-8f) + { + Quaternion qRam = ShortestArcQuat(rb.WantDir0InLug, span.Normalized()); + rb.RamNode.Transform = new Transform3D(new Basis(qRam) * rb.RestLocalRam.Basis, rb.RestLocalRam.Origin); + } + } + } + + private static BreakerMechRig InitBreakerRig(VehicleVisualInstance visual, VehicleMechanismsRecord mech) + { + var rig = new BreakerMechRig(); + + foreach (var sr in mech.Struts) + { + float w = MathF.Tau * MathF.Max(0.1f, sr.Hertz); + float col = 1.15f * MathF.Max(0.02f, sr.Travel); + float xRest = col * (1f - MathF.Pow(1f + 1.3f * 9.81f * 1.0f / (w * w * col), -1f / 1.3f)); + rig.Struts[sr.Name] = new StrutState + { + Compression = Math.Clamp(xRest, 0f, sr.Travel), + Velocity = 0f + }; + + if (visual.GetNamedNode(sr.Dof) is { } oNode && visual.TryGetRestLocal(sr.Dof, out var oRest)) + { + rig.OleoNodes[sr.Dof] = (oNode, oRest); + } + } + + foreach (var sc in mech.Scissors) + { + string side = sc.Name.StartsWith("LegR", StringComparison.Ordinal) ? "R" : "L"; + string upName = $"Leg{side}.TorqueUp"; + string lowName = $"Leg{side}.TorqueLow"; + string shinName = $"Leg{side}.Shin"; + string oleoName = $"Leg{side}.Oleo"; + string forkName = $"Leg{side}.OleoFork"; + + if (visual.GetNamedNode(upName) is not { } upNode || + visual.GetNamedNode(lowName) is not { } lowNode || + visual.GetNamedNode(shinName) is not { } shinNode || + visual.GetNamedNode(oleoName) is not { } oleoNode || + visual.GetNamedNode(forkName) is not { } forkNode || + !visual.TryGetRestLocal(upName, out var restUp) || + !visual.TryGetRestLocal(lowName, out var restLow) || + !visual.TryGetRestModel(shinName, out var shinRestModel) || + !visual.TryGetRestModel(forkName, out var forkRestModel) || + sc.APos is null || sc.BPos is null || sc.OutDir is null) + { + continue; + } + + Vector3 aModel = new(sc.APos[0], sc.APos[1], sc.APos[2]); + Vector3 bModel = new(sc.BPos[0], sc.BPos[1], sc.BPos[2]); + Vector3 outModel = new(sc.OutDir[0], sc.OutDir[1], sc.OutDir[2]); + + Transform3D shinInv = shinRestModel.Inverse(); + Transform3D forkInv = forkRestModel.Inverse(); + + Vector3 aInShin = shinInv * aModel; + Vector3 bRestInShin = shinInv * bModel; + Vector3 bInFork = forkInv * bModel; + Vector3 outInShin = (shinInv.Basis * outModel).Normalized(); + + Vector3 apex0InShin = SolveScissorApex(aInShin, bRestInShin, outInShin, sc.Arm); + Vector3 apex0InFork = (forkRestModel.Inverse() * shinRestModel) * apex0InShin; + + Vector3 dirUp0 = (apex0InShin - aInShin).Normalized(); + Vector3 dirLow0 = (apex0InFork - bInFork).Normalized(); + + rig.Scissors.Add(new ScissorBinding + { + UpperNode = upNode, + LowerNode = lowNode, + ShinNode = shinNode, + OleoNode = oleoNode, + OleoForkNode = forkNode, + RestLocalUp = restUp, + RestLocalLow = restLow, + AInShin = aInShin, + BInOleoFork = bInFork, + OutInShin = outInShin, + Arm = sc.Arm, + DirUp0InShin = dirUp0, + DirLow0InOleoFork = dirLow0 + }); + } + + foreach (var r in mech.Rams) + { + // Name: "LegL.RecessRam0" -> lug "LegL.RamLugA0", oleo "LegL.Oleo", foot "LegL.Foot" + string side = r.Name.StartsWith("LegR", StringComparison.Ordinal) ? "R" : "L"; + char idxChar = r.Name[^1]; + string lugName = $"Leg{side}.RamLugA{idxChar}"; + string oleoName = $"Leg{side}.Oleo"; + string forkName = $"Leg{side}.OleoFork"; + string footName = $"Leg{side}.Foot"; + + if (visual.GetNamedNode(r.Name) is not { } ramNode || + visual.GetNamedNode(lugName) is not { } lugNode || + visual.GetNamedNode(oleoName) is not { } oleoNode || + visual.GetNamedNode(forkName) is not { } forkNode || + visual.GetNamedNode(footName) is not { } footNode || + !visual.TryGetRestLocal(r.Name, out var restRam) || + !visual.TryGetRestModel(lugName, out var lugRestModel) || + !visual.TryGetRestModel(footName, out var footRestModel) || + r.BPos is null) + { + continue; + } + + Vector3 bModel = new(r.BPos[0], r.BPos[1], r.BPos[2]); + Vector3 aInLug = restRam.Origin; + Vector3 bInLug0 = lugRestModel.Inverse() * bModel; + Vector3 bInFoot = footRestModel.Inverse() * bModel; + Vector3 want0 = (bInLug0 - aInLug).Normalized(); + + rig.Rams.Add(new RamBinding + { + RamNode = ramNode, + LugNode = lugNode, + OleoNode = oleoNode, + OleoForkNode = forkNode, + FootNode = footNode, + RestLocalRam = restRam, + APosInLug = aInLug, + BPosInFoot = bInFoot, + WantDir0InLug = want0 + }); + } + + rig.Initialized = rig.Struts.Count > 0; + return rig; + } + + private static Vector3 SolveScissorApex(Vector3 a, Vector3 b, Vector3 outDir, float arm) + { + Vector3 u = b - a; + float d = u.Length(); + if (d < 1e-5f) + { + return (a + b) * 0.5f + outDir * arm; + } + u /= d; + Vector3 oFlat = outDir - u * outDir.Dot(u); + oFlat = oFlat.LengthSquared() > 1e-6f ? oFlat.Normalized() : Vector3.Back; + float h = MathF.Sqrt(MathF.Max(arm * arm - (d * 0.5f) * (d * 0.5f), 0f)); + return (a + b) * 0.5f + oFlat * h; + } + + private static void SetJointAngle(VehicleVisualInstance.BoundJoint j, float angleRad) + { + if (!GodotObject.IsInstanceValid(j.Node) || !float.IsFinite(angleRad)) + { + return; + } + Basis delta = new Basis(j.AxisInParent, angleRad); + j.Node.Transform = new Transform3D(delta * j.RestLocal.Basis, j.RestLocal.Origin); + } + + private static void RotateVehicleAxis(VehicleVisualInstance visual, string nodeName, Vector3 vehicleAxis, float angleRad) + { + if (visual.GetNamedNode(nodeName) is not { } node || + !visual.TryGetRestLocal(nodeName, out var rest)) + { + return; + } + + Vector3 axisInParent = vehicleAxis; + if (node.GetParent() is Node3D p3 && visual.TryGetRestModel(p3, out var pModel)) + { + axisInParent = (pModel.Basis.Orthonormalized().Inverse() * vehicleAxis).Normalized(); + } + Basis delta = new Basis(axisInParent, angleRad); + node.Transform = new Transform3D(delta * rest.Basis, rest.Origin); + } + + private static void EnsureWalkerFootSamples(VehicleVisualInstance visual, RigState st) + { + if (st.FootSamples is not null) + { + return; + } + + var list = new List(); + var stack = new List(); + float cutoffY = visual.Template.MinY + 0.75f; + int count = visual.ModelRoot.GetChildCount(); + for (int i = 0; i < count; i++) + { + CollectFootSamplesRecursive(visual.ModelRoot.GetChild(i), Transform3D.Identity, cutoffY, stack, list); + } + st.FootSamples = list; + } + + private static readonly Vector3[] FootSupportDirs = + { + new(0f, -1f, 0f), + new(0.45f, -1f, 0f), + new(-0.45f, -1f, 0f), + new(0f, -1f, 0.45f), + new(0f, -1f, -0.45f), + new(0.45f, -1f, 0.45f), + new(0.45f, -1f, -0.45f), + new(-0.45f, -1f, 0.45f), + new(-0.45f, -1f, -0.45f), + }; + + private static void CollectFootSamplesRecursive( + Node cur, + Transform3D parentToModel, + float cutoffY, + List stack, + List list) + { + Transform3D toModel = parentToModel; + bool pushed = false; + if (cur is Node3D n3d) + { + toModel = parentToModel * n3d.Transform; + stack.Add(n3d); + pushed = true; + } + + if (cur is MeshInstance3D mi && mi.Mesh is { } mesh) + { + Aabb aabb = mesh.GetAabb(); + float aabbMinY = float.PositiveInfinity; + for (int c = 0; c < 8; c++) + { + Vector3 corner = aabb.Position + new Vector3( + (c & 1) != 0 ? aabb.Size.X : 0f, + (c & 2) != 0 ? aabb.Size.Y : 0f, + (c & 4) != 0 ? aabb.Size.Z : 0f); + float wy = (toModel * corner).Y; + if (wy < aabbMinY) + { + aabbMinY = wy; + } + } + + if (aabbMinY < cutoffY) + { + var bestPts = new Vector3[FootSupportDirs.Length]; + var bestDots = new float[FootSupportDirs.Length]; + for (int d = 0; d < FootSupportDirs.Length; d++) + { + bestDots[d] = float.NegativeInfinity; + } + + bool anyVert = false; + int surfCount = mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arrays = mesh.SurfaceGetArrays(s); + if (arrays.Count <= (int)Mesh.ArrayType.Vertex || + arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + Vector3 localPt = verts[v]; + Vector3 mPt = toModel * localPt; + for (int d = 0; d < FootSupportDirs.Length; d++) + { + float score = mPt.Dot(FootSupportDirs[d]); + if (score > bestDots[d]) + { + bestDots[d] = score; + bestPts[d] = localPt; + } + } + anyVert = true; + } + } + + if (anyVert) + { + var unique = new List(FootSupportDirs.Length); + for (int d = 0; d < bestPts.Length; d++) + { + bool dup = false; + for (int u = 0; u < unique.Count; u++) + { + if ((unique[u] - bestPts[d]).LengthSquared() < 1e-6f) + { + dup = true; + break; + } + } + if (!dup) + { + unique.Add(bestPts[d]); + } + } + + list.Add(new WalkerFootSample + { + ChainFromModelRoot = stack.ToArray(), + LocalPoints = unique.ToArray() + }); + } + } + } + + int childCount = cur.GetChildCount(); + for (int i = 0; i < childCount; i++) + { + CollectFootSamplesRecursive(cur.GetChild(i), toModel, cutoffY, stack, list); + } + + if (pushed) + { + stack.RemoveAt(stack.Count - 1); + } + } + + private static void ApplyWalkerFloorClearance(VehicleVisualInstance visual, RigState st, string rootNodeName) + { + var samples = st.FootSamples; + if (samples is null || samples.Count == 0 || visual.GetNamedNode(rootNodeName) is not { } rootNode) + { + return; + } + + float minModelY = float.PositiveInfinity; + for (int i = 0; i < samples.Count; i++) + { + var s = samples[i]; + Transform3D toModel = Transform3D.Identity; + for (int k = 0; k < s.ChainFromModelRoot.Length; k++) + { + toModel *= s.ChainFromModelRoot[k].Transform; + } + for (int p = 0; p < s.LocalPoints.Length; p++) + { + float y = (toModel * s.LocalPoints[p]).Y; + if (y < minModelY) + { + minModelY = y; + } + } + } + + float restMinY = visual.Template.MinY; + if (float.IsFinite(minModelY) && minModelY < restMinY) + { + Vector3 liftInModel = new Vector3(0f, restMinY - minModelY, 0f); + Vector3 liftInParent = liftInModel; + if (rootNode.GetParent() is Node3D p3 && visual.TryGetRestModel(p3, out var pModel)) + { + liftInParent = pModel.Basis.Orthonormalized().Inverse() * liftInModel; + } + rootNode.Transform = new Transform3D(rootNode.Transform.Basis, rootNode.Transform.Origin + liftInParent); + } + } + + private static Quaternion ShortestArcQuat(Vector3 from, Vector3 to) + { + float dot = Math.Clamp(from.Dot(to), -1f, 1f); + if (dot > 0.99999f) + { + return Quaternion.Identity; + } + if (dot < -0.99999f) + { + Vector3 ortho = MathF.Abs(from.X) < 0.8f ? Vector3.Right : Vector3.Up; + Vector3 axis = from.Cross(ortho).Normalized(); + return new Quaternion(axis, MathF.PI); + } + Vector3 cross = from.Cross(to); + return new Quaternion(cross.X, cross.Y, cross.Z, 1f + dot).Normalized(); + } + + private static float Sanitize(float v, float fallback, float min, float max) => + float.IsFinite(v) ? Math.Clamp(v, min, max) : fallback; + + private static Vector3 SanitizeVec(Vector3 v) => + new( + float.IsFinite(v.X) ? v.X : 0f, + float.IsFinite(v.Y) ? v.Y : 0f, + float.IsFinite(v.Z) ? v.Z : 0f); +} diff --git a/client/VehicleVisualInstance.cs b/client/VehicleVisualInstance.cs new file mode 100644 index 0000000..24caff7 --- /dev/null +++ b/client/VehicleVisualInstance.cs @@ -0,0 +1,906 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +public enum VehicleVisualRole +{ + Player, + Rival, + SpectatorTourist, + SpectatorPatron, + SpectatorExemplar, + SalvageDrop +} + +/// +/// Live Godot 3D instance of a Brokkr vehicle/mech GLB, managing: +/// - grounded model alignment (minY = 0 at physics chassis bottom -HalfHeight), +/// - exterior hardpoint anchor bindings and snap-on modular gear GLBs, +/// - joint pivot bindings with rest transforms and vehicle-space axes, +/// - part-by-cell armor/shroud detachment and hardpoint gear shearing into , +/// - per-cell scorch/damage darkening and thermal heat glow. +/// +public sealed class VehicleVisualInstance +{ + public sealed class BoundJoint + { + public required string JointId; + public required Node3D Node; + public required Transform3D RestLocal; + public required Vector3 AxisInParent; + public required float MinRad; + public required float MaxRad; + } + + private sealed class BoundHardpoint + { + public required HardpointSpec Spec; + public required VehicleAssetCache.GlbAnchorInfo AnchorInfo; + public required Node3D AnchorNode; + public string? MountedModuleId; + public Node3D? GearNode; + public readonly List GearHeatMaterials = new(); + } + + private sealed class CellPartBinding + { + public required MeshInstance3D Node; + public readonly List<(StandardMaterial3D Mat, Color BaseColor, float BaseRoughness)> Materials = new(); + public bool Detached; + public float LastTintScore = -1f; + } + + private readonly record struct GearVisualRecipe( + string GearGlbId, + Vector3 VariantScale, + Color? PaintTint, + Color? AccentTint); + + private static readonly Color RivalArmorColor = Color.FromHtml("#5d4d42"); + private static readonly Color RivalAccentColor = Color.FromHtml("#b64a32"); + private static readonly Color TouristGold = Color.FromHtml("#e6b838"); + private static readonly Color TouristIvory = Color.FromHtml("#f2ead8"); + private static readonly Color PatronTeal = Color.FromHtml("#2d7a78"); + private static readonly Color PatronBronze = Color.FromHtml("#a86c36"); + private static readonly Color ExemplarObsidian = Color.FromHtml("#1b1b22"); + private static readonly Color ExemplarCrimson = Color.FromHtml("#c92a2a"); + private static readonly Color SalvageSteel = Color.FromHtml("#545b5c"); + private static readonly Color SalvageCyan = Color.FromHtml("#44d9e8"); + + private readonly VehicleAssetCache _cache; + private readonly VehicleAssetCache.VehicleTemplate _template; + private readonly Dictionary _hardpoints = new(StringComparer.Ordinal); + private readonly Dictionary _joints = new(StringComparer.Ordinal); + private readonly Dictionary _namedNodes = new(StringComparer.Ordinal); + private readonly Dictionary _restLocalByName = new(StringComparer.Ordinal); + private readonly Dictionary _restModelByName = new(StringComparer.Ordinal); + private readonly Dictionary _restModelByNode = new(); + private readonly List[,] _cellParts; + private readonly bool[,] _strippedCells; + private readonly HashSet _shearedHardpoints = new(StringComparer.Ordinal); + private readonly VehicleRigAnimator.RigState _rigState = new(); + + private readonly string _chassisId; + private MeshInstance3D? _lodStaticMesh; + private bool _isStaticLod; + private bool _castShadows = true; + + private VehicleVisualInstance( + VehicleAssetCache cache, + VehicleAssetCache.VehicleTemplate template, + Node3D root, + Node3D modelRoot, + string chassisId) + { + _cache = cache; + _template = template; + Root = root; + ModelRoot = modelRoot; + _chassisId = chassisId; + + int w = template.Package.GridWidth; + int h = template.Package.GridHeight; + _cellParts = new List[w, h]; + _strippedCells = new bool[w, h]; + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + _cellParts[x, y] = new List(); + } + } + } + + public Node3D Root { get; } + public Node3D ModelRoot { get; } + public VehicleAssetCache.VehicleTemplate Template => _template; + public VehiclePackage Package => _template.Package; + public string ChassisId => _chassisId; + public string ModelId => _template.Package.Id; + public VehicleRigAnimator.RigState RigState => _rigState; + public IReadOnlyDictionary Joints => _joints; + public int BoundHardpointCount => _hardpoints.Count; + public bool IsStaticLod => _isStaticLod; + + public void SetLodState(bool useStaticLod, bool castShadows) + { + if (_lodStaticMesh is null) + { + if (ModelRoot is MeshInstance3D dropMi) + { + if (_isStaticLod != useStaticLod) + { + _isStaticLod = useStaticLod; + dropMi.Mesh = useStaticLod ? _template.BakedLodFarMesh : _template.BakedStaticMesh; + } + if (_castShadows != castShadows) + { + _castShadows = castShadows; + dropMi.CastShadow = castShadows + ? GeometryInstance3D.ShadowCastingSetting.On + : GeometryInstance3D.ShadowCastingSetting.Off; + } + } + return; + } + if (_isStaticLod != useStaticLod) + { + _isStaticLod = useStaticLod; + ModelRoot.Visible = !useStaticLod; + ModelRoot.PhysicsInterpolationMode = useStaticLod + ? Node.PhysicsInterpolationModeEnum.Off + : Node.PhysicsInterpolationModeEnum.Inherit; + ModelRoot.ProcessMode = useStaticLod + ? Node.ProcessModeEnum.Disabled + : Node.ProcessModeEnum.Inherit; + _lodStaticMesh.Visible = useStaticLod; + } + if (_castShadows != castShadows) + { + _castShadows = castShadows; + _lodStaticMesh.CastShadow = castShadows + ? GeometryInstance3D.ShadowCastingSetting.On + : GeometryInstance3D.ShadowCastingSetting.Off; + } + } + + public static VehicleVisualInstance Create( + VehicleAssetCache cache, + string chassisId, + VehicleVisualRole role, + float visualScale = 1.0f, + float? targetHalfHeight = null) + { + var template = cache.GetOrLoadVehicle(chassisId); + var pkg = template.Package; + float halfHeight = targetHalfHeight ?? (pkg.HalfHeight * visualScale); + float effectiveScale = targetHalfHeight.HasValue && pkg.HalfHeight > 1e-4f + ? visualScale * (targetHalfHeight.Value / pkg.HalfHeight) + : visualScale; + + var root = new Node3D { Name = $"Actor_{chassisId}" }; + Vector3 modelScale = new(effectiveScale, effectiveScale, effectiveScale); + // Align glTF grounded minY=0 to physics chassis bottom (-halfHeight) + Vector3 modelPos = new(0f, -halfHeight - template.MinY * effectiveScale, 0f); + + if (role == VehicleVisualRole.SalvageDrop) + { + var dropMesh = new MeshInstance3D + { + Name = $"Model_{pkg.Id}", + Mesh = template.BakedStaticMesh, + Scale = modelScale, + Position = modelPos + }; + ApplyRoleTint(dropMesh, role); + root.AddChild(dropMesh); + return new VehicleVisualInstance(cache, template, root, dropMesh, chassisId); + } + + if (template.SceneTemplate.Duplicate() is not Node3D modelRoot) + { + throw new InvalidOperationException($"Failed to duplicate GLB scene template for '{pkg.Id}'."); + } + modelRoot.Name = $"Model_{pkg.Id}"; + modelRoot.Scale = modelScale; + modelRoot.Position = modelPos; + root.AddChild(modelRoot); + + var lodMesh = new MeshInstance3D + { + Name = $"LodStatic_{pkg.Id}", + Mesh = template.BakedLodFarMesh, + Scale = modelScale, + Position = modelPos, + Visible = false + }; + if (role != VehicleVisualRole.Player) + { + ApplyRoleTint(lodMesh, role); + } + root.AddChild(lodMesh); + + var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId) + { + _lodStaticMesh = lodMesh + }; + instance.BindAll(role); + return instance; + } + + private void BindAll(VehicleVisualRole role) + { + var pkg = _template.Package; + + // Collect cumulative pure glTF model-space transforms (minY=0, unscaled) starting at ModelRoot = Identity + var modelXforms = new Dictionary + { + [ModelRoot] = Transform3D.Identity + }; + int modelChildCount = ModelRoot.GetChildCount(); + for (int i = 0; i < modelChildCount; i++) + { + CollectNodeTransforms(ModelRoot.GetChild(i), Transform3D.Identity, modelXforms); + } + + // Bind named nodes for procedural/mechanism rigs + foreach (var (origName, relPath) in _template.NodesByOriginalName) + { + Node3D? node = ResolveRelative(ModelRoot, relPath); + if (node is not null) + { + _namedNodes[origName] = node; + _restLocalByName[origName] = node.Transform; + if (modelXforms.TryGetValue(node, out var mxf)) + { + _restModelByName[origName] = mxf; + _restModelByNode[node] = mxf; + } + } + } + + // Bind all joints from rtd.joint metadata + foreach (var (jointId, jInfo) in _template.Joints) + { + Node3D? jNode = ResolveRelative(ModelRoot, jInfo.RelativePath); + if (jNode is null) + { + throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing joint node '{jInfo.NodeName}' ({jointId})."); + } + + Basis parentModelBasis = Basis.Identity; + Node? parent = jNode.GetParent(); + if (parent is not null && modelXforms.TryGetValue(parent, out var pxf)) + { + parentModelBasis = pxf.Basis.Orthonormalized(); + } + + Vector3 axisInParent = parentModelBasis.Inverse() * jInfo.Axis; + axisInParent = axisInParent.LengthSquared() > 1e-6f ? axisInParent.Normalized() : Vector3.Up; + + _joints[jointId] = new BoundJoint + { + JointId = jointId, + Node = jNode, + RestLocal = jNode.Transform, + AxisInParent = axisInParent, + MinRad = Mathf.DegToRad(jInfo.MinVal), + MaxRad = Mathf.DegToRad(jInfo.MaxVal) + }; + } + + // Bind every ChassisSpec hardpoint to its exact exterior anchor Node3D + ChassisSpec spec = pkg.ToChassisSpec(); + var pkgHpById = new Dictionary(StringComparer.Ordinal); + foreach (var rec in pkg.Hardpoints) + { + pkgHpById[rec.Id] = rec; + } + + for (int i = 0; i < spec.Hardpoints.Length; i++) + { + HardpointSpec hp = spec.Hardpoints[i]; + if (!pkgHpById.TryGetValue(hp.Id, out var rec) || + !_template.Anchors.TryGetValue(rec.AnchorId, out var anchorInfo)) + { + throw new InvalidOperationException($"{pkg.Id}: missing AnchorId for hardpoint '{hp.Id}'."); + } + + Node3D? anchorNode = ResolveRelative(ModelRoot, anchorInfo.RelativePath); + if (anchorNode is null) + { + throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing anchor node '{rec.AnchorId}'."); + } + + _hardpoints[hp.Id] = new BoundHardpoint + { + Spec = hp, + AnchorInfo = anchorInfo, + AnchorNode = anchorNode + }; + } + + // Apply role palette tinting to painted hull meshes before binding per-cell damage clones + if (role != VehicleVisualRole.Player) + { + ApplyRoleTint(ModelRoot, role); + } + + // Bind detachable exterior armor/shroud parts to their (CellX, CellY) + int w = pkg.GridWidth; + int h = pkg.GridHeight; + foreach (var dp in _template.DetachableParts) + { + if (dp.CellX < 0 || dp.CellX >= w || dp.CellY < 0 || dp.CellY >= h) + { + continue; + } + if (ResolveRelative(ModelRoot, dp.RelativePath) is MeshInstance3D mi) + { + _cellParts[dp.CellX, dp.CellY].Add(new CellPartBinding { Node = mi }); + } + } + } + + public Node3D? GetNamedNode(string name) => + _namedNodes.TryGetValue(name, out var n) && GodotObject.IsInstanceValid(n) ? n : null; + + public bool TryGetRestLocal(string name, out Transform3D xform) => + _restLocalByName.TryGetValue(name, out xform); + + public bool TryGetRestModel(string name, out Transform3D xform) => + _restModelByName.TryGetValue(name, out xform); + + public bool TryGetRestModel(Node3D node, out Transform3D xform) => + _restModelByNode.TryGetValue(node, out xform); + + public Node3D? GetHardpointAnchorNode(string hardpointId) => + _hardpoints.TryGetValue(hardpointId, out var bh) ? bh.AnchorNode : null; + + public Node3D? GetMountedGearNode(string hardpointId) => + _hardpoints.TryGetValue(hardpointId, out var bh) && GodotObject.IsInstanceValid(bh.GearNode) ? bh.GearNode : null; + + public int CountDetachablePartsForCell(int x, int y) => + x >= 0 && x < _template.Package.GridWidth && y >= 0 && y < _template.Package.GridHeight + ? _cellParts[x, y].Count + : 0; + + /// + /// Synchronizes visible exterior gear GLBs on all hardpoint anchors with . + /// + public void SyncMountedGear(ChassisGrid grid) + { + foreach (var bh in _hardpoints.Values) + { + if (_shearedHardpoints.Contains(bh.Spec.Id) || !grid.IsHardpointOperational(bh.Spec)) + { + continue; + } + + MountedModule? mounted = grid.GetMountedOn(bh.Spec.Id); + string? desiredId = mounted?.Spec.Id; + + if (string.Equals(bh.MountedModuleId, desiredId, StringComparison.Ordinal)) + { + continue; + } + + // Clear old gear visual if unmounted or swapped + if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) + { + bh.GearNode.GetParent()?.RemoveChild(bh.GearNode); + bh.GearNode.QueueFree(); + } + bh.GearNode = null; + bh.GearHeatMaterials.Clear(); + bh.MountedModuleId = desiredId; + + if (mounted is null) + { + continue; + } + + Node3D gearNode = InstantiateGearForHardpoint(mounted.Spec, bh.Spec, bh.AnchorInfo, bh.GearHeatMaterials); + bh.AnchorNode.AddChild(gearNode); + bh.GearNode = gearNode; + } + } + + /// + /// Detaches exterior armor/shroud plates when Armor[x, y] <= 0.01f, + /// shears mounted gear off non-operational hardpoints, and applies scorch/heat glow. + /// + public void SyncDamageAndHeat(ChassisGrid grid, DebrisSystem debris, Vector3 vehicleVelocity) + { + int w = Math.Min(grid.Spec.Width, _template.Package.GridWidth); + int h = Math.Min(grid.Spec.Height, _template.Package.GridHeight); + Vector3 blastOrigin = Root.IsInsideTree() ? Root.GlobalPosition : Root.Position; + + // 1. Part-by-cell detachment & cell scorch/heat tinting + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!grid.Spec.IsActive(x, y)) + { + continue; + } + + float armor = grid.Armor[x, y]; + var parts = _cellParts[x, y]; + if (!_strippedCells[x, y] && armor <= 0.01f) + { + _strippedCells[x, y] = true; + for (int i = 0; i < parts.Count; i++) + { + var pb = parts[i]; + if (!pb.Detached && GodotObject.IsInstanceValid(pb.Node)) + { + pb.Detached = true; + debris.SpawnDetachedPart(pb.Node, blastOrigin, vehicleVelocity, impulseScale: 1.0f, applyScorch: true); + } + } + continue; + } + + if (parts.Count == 0) + { + continue; + } + + float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]); + float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f); + float heatGlow = Math.Clamp((grid.Temperature[x, y] - 65f) / 110f, 0f, 1f); + float tintScore = MathF.Round(dmgFrac * 20f) + MathF.Round(heatGlow * 20f) * 32f; + + if (dmgFrac < 0.25f && heatGlow < 0.05f) + { + continue; + } + + for (int i = 0; i < parts.Count; i++) + { + var pb = parts[i]; + if (pb.Detached || !GodotObject.IsInstanceValid(pb.Node)) + { + continue; + } + if (MathF.Abs(pb.LastTintScore - tintScore) < 0.5f) + { + continue; + } + pb.LastTintScore = tintScore; + ApplyCellDamageAndHeat(pb, dmgFrac, heatGlow); + } + } + } + + // 2. Hardpoint shear & mounted gear heat glow + foreach (var bh in _hardpoints.Values) + { + if (!_shearedHardpoints.Contains(bh.Spec.Id) && !grid.IsHardpointOperational(bh.Spec)) + { + _shearedHardpoints.Add(bh.Spec.Id); + if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) + { + Node3D sheared = bh.GearNode; + bh.GearNode = null; + bh.MountedModuleId = null; + bh.GearHeatMaterials.Clear(); + debris.SpawnDetachedPart(sheared, blastOrigin, vehicleVelocity, impulseScale: 1.15f, applyScorch: true); + } + continue; + } + + if (bh.GearNode is null || bh.GearHeatMaterials.Count == 0) + { + continue; + } + + MountedModule? mounted = grid.GetMountedOn(bh.Spec.Id); + if (mounted is null) + { + continue; + } + + float heatFrac = Math.Clamp((mounted.CurrentTemp - 65f) / 115f, 0f, 1f); + for (int m = 0; m < bh.GearHeatMaterials.Count; m++) + { + StandardMaterial3D gm = bh.GearHeatMaterials[m]; + gm.EmissionEnabled = heatFrac > 0.02f; + gm.Emission = new Color(1.0f, 0.34f, 0.08f); + gm.EmissionEnergyMultiplier = heatFrac * 2.2f; + } + } + } + + public static Node3D CreateStandaloneGearVisual(VehicleAssetCache cache, ModuleSpec mod) + { + var list = new List(); + GearVisualRecipe recipe = ResolveGearRecipe(mod); + var template = cache.GetOrLoadGear(recipe.GearGlbId); + if (template.SceneTemplate.Duplicate() is not Node3D node) + { + return new Node3D { Name = $"Gear_{mod.Id}" }; + } + node.Name = $"GearDrop_{mod.Id}"; + node.Scale = recipe.VariantScale; + node.Position = new Vector3(0f, -template.MinY * recipe.VariantScale.Y, 0f); + if (recipe.PaintTint.HasValue || recipe.AccentTint.HasValue) + { + ApplyGearVariantTint(node, recipe.PaintTint, recipe.AccentTint, list); + } + return node; + } + + private Node3D InstantiateGearForHardpoint( + ModuleSpec mod, + HardpointSpec hp, + VehicleAssetCache.GlbAnchorInfo anchorInfo, + List heatMaterialsOut) + { + GearVisualRecipe recipe = ResolveGearRecipe(mod); + VehicleAssetCache.GearTemplate gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId); + if (gearTemplate.SceneTemplate.Duplicate() is not Node3D gearNode) + { + throw new InvalidOperationException($"Failed to duplicate gear GLB '{recipe.GearGlbId}'."); + } + gearNode.Name = $"Mounted_{mod.Id}_{hp.Id}"; + + // Compute outward socket normal & desired gear forward direction in vehicle/model space + Basis anchorModelBasis = anchorInfo.ModelSpaceTransform.Basis.Orthonormalized(); + Vector3 upOut = anchorModelBasis.Y.Normalized(); + if (upOut.LengthSquared() < 1e-6f) upOut = Vector3.Up; + + Vector3 vehForward = new(0f, 0f, 1f); + Vector3 desiredGearFwd; + + if (hp.Kind == HardpointKind.Weapon) + { + // Special guard for forward-facing chin mounts (e.g. manticore hp.weapon.chin): + // drop the turret base under the chin (-Y) so the barrel points straight forward (+Z) instead of up into the nose. + if (upOut.Z > 0.72f) + { + upOut = upOut.Y <= 0.1f ? new Vector3(0f, -1f, 0f) : new Vector3(0f, 1f, 0f); + desiredGearFwd = vehForward; + } + else + { + Vector3 proj = vehForward - upOut * vehForward.Dot(upOut); + desiredGearFwd = proj.LengthSquared() > 1e-4f + ? proj.Normalized() + : anchorModelBasis.Z.Normalized(); + } + } + else + { + // Non-weapon modules (radiator / engine / armor): align neatly to hull tangent plane + if (MathF.Abs(upOut.Z) > 0.78f) + { + Vector3 upProj = Vector3.Up - upOut * Vector3.Up.Dot(upOut); + desiredGearFwd = upProj.LengthSquared() > 1e-4f ? upProj.Normalized() : Vector3.Up; + } + else + { + Vector3 proj = vehForward - upOut * vehForward.Dot(upOut); + desiredGearFwd = proj.LengthSquared() > 1e-4f ? proj.Normalized() : Vector3.Up; + } + } + + // Right-handed basis: Y = upOut, Z = desiredGearFwd, X = Y x Z + Vector3 rightX = upOut.Cross(desiredGearFwd); + if (rightX.LengthSquared() < 1e-5f) + { + rightX = Vector3.Right; + } + else + { + rightX = rightX.Normalized(); + } + desiredGearFwd = rightX.Cross(upOut).Normalized(); + var desiredModelBasis = new Basis(rightX, upOut, desiredGearFwd); + + // If the gear GLB's own forward points along -Z, rotate 180 deg around Y + if (gearTemplate.LocalModelForward.Z < 0f) + { + desiredModelBasis *= new Basis(Vector3.Up, MathF.PI); + } + + Basis localBasis = anchorModelBasis.Inverse() * desiredModelBasis; + + // Fit cleanly to the socket's physical rtd.size + float sx = MathF.Max(0.25f, anchorInfo.Size.X); + float sy = MathF.Max(0.25f, anchorInfo.Size.Y); + Vector3 fitScale; + if (hp.Kind == HardpointKind.Weapon) + { + float baseScale = Math.Clamp(MathF.Min(sx, sy) / 0.56f, 0.72f, 1.75f); + fitScale = recipe.VariantScale * baseScale; + } + else + { + float scaleX = Math.Clamp(sx / 0.48f, 0.72f, 2.15f); + float scaleZ = Math.Clamp(sy / 0.45f, 0.72f, 2.15f); + float scaleY = Math.Clamp(0.5f * (scaleX + scaleZ), 0.72f, 1.85f); + fitScale = new Vector3( + recipe.VariantScale.X * scaleX, + recipe.VariantScale.Y * scaleY, + recipe.VariantScale.Z * scaleZ); + } + + gearNode.Basis = localBasis * Basis.FromScale(fitScale); + // Seat gear minY right on the anchor collar origin (with slight downward offset if chin flipped) + float ySeat = -gearTemplate.MinY * fitScale.Y; + gearNode.Position = (anchorModelBasis.Inverse() * upOut) * ySeat; + + ApplyGearVariantTint(gearNode, recipe.PaintTint, recipe.AccentTint, heatMaterialsOut); + return gearNode; + } + + private static GearVisualRecipe ResolveGearRecipe(ModuleSpec mod) + { + return mod.Id switch + { + "mg_762" => new("mg_762", Vector3.One, null, null), + "autocannon" => new("autocannon", Vector3.One, null, null), + "recoilless" => new("recoilless", Vector3.One, null, null), + "copper_rad" => new("copper_rad", Vector3.One, null, null), + "gilded_lance" => new("gilded_lance", Vector3.One, null, null), + "gold_radiator" => new("gold_radiator", Vector3.One, null, null), + + // Clean tint/scale variants from the 6 real gear GLBs + "flak" => new("autocannon", new Vector3(1.12f, 0.92f, 0.68f), Color.FromHtml("#5a4a3f"), Color.FromHtml("#d96c27")), + "pd_flak" => new("mg_762", new Vector3(1.22f, 1.10f, 0.85f), Color.FromHtml("#3d4440"), Color.FromHtml("#e08a4a")), + "touring_plasma" => new("gilded_lance", new Vector3(1.05f, 0.96f, 0.72f), TouristIvory, Color.FromHtml("#38c9d8")), + "aegis_pd" => new("gilded_lance", new Vector3(0.95f, 0.92f, 0.56f), TouristGold, Color.FromHtml("#38c9d8")), + "diesel_core" => new("copper_rad", new Vector3(0.92f, 1.15f, 1.05f), Color.FromHtml("#363a38"), Color.FromHtml("#b35a2b")), + "turbo_core" => new("copper_rad", new Vector3(1.12f, 1.28f, 1.38f), Color.FromHtml("#2a2f32"), Color.FromHtml("#e07024")), + "noble_core" => new("gold_radiator", new Vector3(1.10f, 1.32f, 1.38f), TouristGold, Color.FromHtml("#38c9d8")), + "welded_plate" => new("copper_rad", new Vector3(1.30f, 0.34f, 0.95f), Color.FromHtml("#4e5740"), Color.FromHtml("#6a6f66")), + "gilded_plate" => new("gold_radiator", new Vector3(1.30f, 0.34f, 0.95f), TouristIvory, TouristGold), + _ => new(mod.IsImperial ? "gilded_lance" : "mg_762", Vector3.One, null, null) + }; + } + + private static void ApplyGearVariantTint( + Node cur, + Color? paintTint, + Color? accentTint, + List trackMaterials) + { + if (cur is MeshInstance3D mi && mi.Mesh is not null) + { + int surfCount = mi.Mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + Material? src = mi.GetActiveMaterial(s); + if (src is not StandardMaterial3D sm) + { + continue; + } + + var copy = (StandardMaterial3D)sm.Duplicate(); + string matName = (sm.ResourceName ?? string.Empty).ToLowerInvariant(); + if (accentTint.HasValue && (matName.Contains("copper") || matName.Contains("signal") || matName.Contains("cyan") || matName.Contains("gold"))) + { + copy.AlbedoColor = accentTint.Value; + } + else if (paintTint.HasValue && (matName.Contains("olive") || matName.Contains("ivory") || matName.Contains("armor"))) + { + copy.AlbedoColor = paintTint.Value; + } + + mi.SetSurfaceOverrideMaterial(s, copy); + if (!matName.Contains("rubber") && !matName.Contains("glass")) + { + trackMaterials.Add(copy); + } + } + } + + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + ApplyGearVariantTint(cur.GetChild(i), paintTint, accentTint, trackMaterials); + } + } + + private static void ApplyRoleTint(Node root, VehicleVisualRole role) + { + var (armorColor, accentColor) = role switch + { + VehicleVisualRole.Rival => (RivalArmorColor, RivalAccentColor), + VehicleVisualRole.SpectatorTourist => (TouristGold, TouristIvory), + VehicleVisualRole.SpectatorPatron => (PatronTeal, PatronBronze), + VehicleVisualRole.SpectatorExemplar => (ExemplarObsidian, ExemplarCrimson), + VehicleVisualRole.SalvageDrop => (SalvageSteel, SalvageCyan), + _ => (RivalArmorColor, RivalAccentColor) + }; + + var clonedCache = new Dictionary(); + TintSubtreeRecursive(root, armorColor, accentColor, role, clonedCache); + } + + private static void TintSubtreeRecursive( + Node cur, + Color armorColor, + Color accentColor, + VehicleVisualRole role, + Dictionary clonedCache) + { + if (cur is MeshInstance3D mi && mi.Mesh is not null) + { + int surfCount = mi.Mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + if (mi.GetActiveMaterial(s) is not StandardMaterial3D sm) + { + continue; + } + + string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant(); + bool isPrimaryPaint = mName.Contains("olive") || mName.Contains("khaki"); + bool isAccentPaint = mName.Contains("signal") || mName.Contains("orange"); + if (!isPrimaryPaint && !isAccentPaint) + { + continue; + } + + if (!clonedCache.TryGetValue(sm, out var copy)) + { + copy = (StandardMaterial3D)sm.Duplicate(); + copy.AlbedoColor = isPrimaryPaint ? armorColor : accentColor; + if (role == VehicleVisualRole.SpectatorTourist && isPrimaryPaint) + { + copy.Metallic = 0.72f; + copy.Roughness = 0.30f; + } + else if (role == VehicleVisualRole.SpectatorExemplar && isAccentPaint) + { + copy.EmissionEnabled = true; + copy.Emission = ExemplarCrimson; + copy.EmissionEnergyMultiplier = 0.65f; + } + clonedCache[sm] = copy; + } + + mi.SetSurfaceOverrideMaterial(s, copy); + } + } + + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + TintSubtreeRecursive(cur.GetChild(i), armorColor, accentColor, role, clonedCache); + } + } + + private static void ApplyCellDamageAndHeat(CellPartBinding binding, float dmgFrac, float heatGlow) + { + if (binding.Materials.Count == 0 && binding.Node.Mesh is not null) + { + int surfCount = binding.Node.Mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + Material? src = binding.Node.GetActiveMaterial(s); + StandardMaterial3D copy = src is StandardMaterial3D sm + ? (StandardMaterial3D)sm.Duplicate() + : new StandardMaterial3D { AlbedoColor = new Color(0.32f, 0.34f, 0.30f), Roughness = 0.6f, Metallic = 0.35f }; + binding.Node.SetSurfaceOverrideMaterial(s, copy); + binding.Materials.Add((copy, copy.AlbedoColor, copy.Roughness)); + } + } + + float scorch = Math.Clamp((dmgFrac - 0.25f) / 0.75f, 0f, 1f) * 0.65f; + for (int i = 0; i < binding.Materials.Count; i++) + { + var (mat, baseCol, baseRough) = binding.Materials[i]; + mat.AlbedoColor = new Color( + baseCol.R * (1f - scorch) + 0.05f * scorch, + baseCol.G * (1f - scorch) + 0.035f * scorch, + baseCol.B * (1f - scorch) + 0.03f * scorch, + baseCol.A); + mat.Roughness = MathF.Min(0.95f, baseRough + scorch * 0.35f); + mat.EmissionEnabled = heatGlow > 0.05f; + mat.Emission = new Color(1.0f, 0.32f, 0.08f); + mat.EmissionEnergyMultiplier = heatGlow * 1.4f; + } + } + + private static Node3D? ResolveRelative(Node3D root, NodePath relPath) + { + if (relPath.IsEmpty) + { + return null; + } + return relPath.ToString() == "." ? root : root.GetNodeOrNull(relPath); + } + + private static void CollectNodeTransforms(Node cur, Transform3D parentXf, Dictionary map) + { + Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf; + map[cur] = xf; + int count = cur.GetChildCount(); + for (int i = 0; i < count; i++) + { + CollectNodeTransforms(cur.GetChild(i), xf, map); + } + } + + /// + /// Computes the highest rendered vertex Y in local space across the hull + /// and all currently mounted gear meshes. + /// + public float ComputeMountedMaxY() + { + float maxY = float.NegativeInfinity; + AccumulateMaxYRecursive(ModelRoot, Transform3D.Identity, ref maxY, isRoot: true); + if (!float.IsFinite(maxY)) + { + return ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y; + } + return maxY; + } + + private static void AccumulateMaxYRecursive(Node cur, Transform3D parentToRoot, ref float maxY, bool isRoot = false) + { + Transform3D toRoot = parentToRoot; + if (cur is Node3D n3d) + { + if (!isRoot && !n3d.Visible) + { + return; + } + toRoot = parentToRoot * n3d.Transform; + } + + if (cur is MeshInstance3D mi && mi.Mesh is { } mesh) + { + int surfCount = mesh.GetSurfaceCount(); + bool foundVerts = false; + for (int s = 0; s < surfCount; s++) + { + var arrays = mesh.SurfaceGetArrays(s); + if (arrays.Count > (int)Mesh.ArrayType.Vertex && + arrays[(int)Mesh.ArrayType.Vertex].VariantType == Variant.Type.PackedVector3Array) + { + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + float wy = (toRoot * verts[v]).Y; + if (wy > maxY) + { + maxY = wy; + } + } + foundVerts = true; + } + } + if (!foundVerts) + { + Aabb aabb = mesh.GetAabb(); + for (int c = 0; c < 8; c++) + { + Vector3 corner = aabb.Position + new Vector3( + (c & 1) != 0 ? aabb.Size.X : 0f, + (c & 2) != 0 ? aabb.Size.Y : 0f, + (c & 4) != 0 ? aabb.Size.Z : 0f); + float wy = (toRoot * corner).Y; + if (wy > maxY) + { + maxY = wy; + } + } + } + } + + int childCount = cur.GetChildCount(); + for (int i = 0; i < childCount; i++) + { + AccumulateMaxYRecursive(cur.GetChild(i), toRoot, ref maxY); + } + } +} diff --git a/client/decal_pom.gdshader b/client/decal_pom.gdshader new file mode 100644 index 0000000..7b9a1fc --- /dev/null +++ b/client/decal_pom.gdshader @@ -0,0 +1,140 @@ +shader_type spatial; +render_mode blend_mix, depth_draw_never, cull_back; + +// OpenGL 3.3 (gl_compatibility) Parallax Occlusion Mapping (POM) decal shader for MultiMeshInstance3D. +// Renders hundreds of hard-surface vents, hatches, stencils, and live combat hits in 1 draw call. +// +// INSTANCE_CUSTOM layout: +// x = tile_index (0..15 in 4x4 trim-sheet atlas) +// y = heat_glow (0..1, incandescent glow on rolled rim & core of fresh combat hits) +// z = opacity (0..1) +// w = depth_scale (default ~0.06 when 0) +// +// Atlas textures (assets/decals/): +// albedo_tex : RGBA albedo + alpha mask +// normal_tex : tangent-space normal map (+X right, +Y down, +Z out) +// ormh_tex : R=AO, G=Roughness, B=Metallic, A=Height (1.0=flush surface, 0.0=deep recess) + +uniform sampler2D albedo_tex : source_color, filter_linear_mipmap, repeat_disable; +uniform sampler2D normal_tex : hint_normal, filter_linear_mipmap, repeat_disable; +uniform sampler2D ormh_tex : filter_linear_mipmap, repeat_disable; + +uniform bool use_instance_custom = true; +uniform float fallback_tile_index : hint_range(0.0, 15.0) = 0.0; +uniform float fallback_heat_glow : hint_range(0.0, 1.0) = 0.0; +uniform float fallback_opacity : hint_range(0.0, 1.0) = 1.0; +uniform float default_depth_scale : hint_range(0.0, 0.25) = 0.06; +uniform float normal_offset : hint_range(0.0, 0.02) = 0.004; +uniform float normal_depth : hint_range(0.0, 3.0) = 1.15; +uniform float heat_emission_energy : hint_range(0.0, 10.0) = 2.6; + +varying vec4 v_custom; + +void vertex() { + VERTEX += NORMAL * normal_offset; + if (use_instance_custom) { + v_custom = INSTANCE_CUSTOM; + } else { + v_custom = vec4(fallback_tile_index, fallback_heat_glow, fallback_opacity, default_depth_scale); + } +} + +void fragment() { + const int POM_STEPS = 10; + const float CELL_SIZE = 0.25; + + float tile_idx = floor(clamp(v_custom.x + 0.5, 0.0, 15.0)); + float heat_glow = clamp(v_custom.y, 0.0, 1.0); + float opacity = clamp(v_custom.z, 0.0, 1.0); + float depth_scale = v_custom.w > 0.0001 ? v_custom.w : default_depth_scale; + + float col_idx = mod(tile_idx, 4.0); + float row_idx = floor(tile_idx * 0.25); + vec2 cell_origin = vec2(col_idx, row_idx) * CELL_SIZE; + + // Hoist screen-space derivatives above any non-uniform control flow / discard (GLSL 330 safety) + vec2 d_uv_dx = dFdx(UV * CELL_SIZE); + vec2 d_uv_dy = dFdy(UV * CELL_SIZE); + + // Soft outer edge fade on local quad UV + float edge_fade = smoothstep(0.0, 0.04, UV.x) + * smoothstep(1.0, 0.96, UV.x) + * smoothstep(0.0, 0.04, UV.y) + * smoothstep(1.0, 0.96, UV.y); + + // Tangent-space view ray (Godot fragment VIEW, TANGENT, BINORMAL, NORMAL are all in view space) + vec3 t_dir = normalize(TANGENT); + vec3 b_dir = normalize(BINORMAL); + vec3 n_dir = normalize(NORMAL); + vec3 view_ts = normalize(vec3(dot(VIEW, t_dir), dot(VIEW, b_dir), dot(VIEW, n_dir))); + + // Clamp grazing Z so oblique rays stay well-behaved without sliding out of the tile + float vz = max(view_ts.z, 0.22); + vec2 p_dir = -(view_ts.xy / vz) * depth_scale; + + // 10 linear POM steps from surface (layer_depth=0, height=1) into recess (layer_depth=1, height=0) + float step_size = 1.0 / float(POM_STEPS); + vec2 delta_uv = p_dir * step_size; + + vec2 cur_uv = UV; + float cur_layer_depth = 0.0; + float cur_tex_depth = 1.0 - textureLod(ormh_tex, cell_origin + clamp(cur_uv, 0.002, 0.998) * CELL_SIZE, 0.0).a; + + vec2 prev_uv = cur_uv; + float prev_layer_depth = cur_layer_depth; + float prev_tex_depth = cur_tex_depth; + + for (int i = 0; i < POM_STEPS; i++) { + if (cur_layer_depth >= cur_tex_depth) { + break; + } + prev_uv = cur_uv; + prev_layer_depth = cur_layer_depth; + prev_tex_depth = cur_tex_depth; + + cur_uv += delta_uv; + cur_layer_depth += step_size; + cur_tex_depth = 1.0 - textureLod(ormh_tex, cell_origin + clamp(cur_uv, 0.002, 0.998) * CELL_SIZE, 0.0).a; + } + + // 1 secant interpolation step + float after_d = cur_tex_depth - cur_layer_depth; + float before_d = prev_tex_depth - prev_layer_depth; + float denom = after_d - before_d; + float weight = abs(denom) > 1e-5 ? clamp(after_d / denom, 0.0, 1.0) : 0.0; + vec2 final_uv = mix(cur_uv, prev_uv, weight); + + // Discard cleanly outside tile bounds so adjacent atlas cells never bleed + if (final_uv.x < 0.002 || final_uv.x > 0.998 || final_uv.y < 0.002 || final_uv.y > 0.998) { + discard; + } + + vec2 atlas_uv = cell_origin + final_uv * CELL_SIZE; + vec4 alb = textureGrad(albedo_tex, atlas_uv, d_uv_dx, d_uv_dy); + vec3 nrm_sample = textureGrad(normal_tex, atlas_uv, d_uv_dx, d_uv_dy).rgb; + vec4 ormh = textureGrad(ormh_tex, atlas_uv, d_uv_dx, d_uv_dy); + + float out_alpha = alb.a * edge_fade * opacity; + if (out_alpha < 0.015) { + discard; + } + + // Emissive rim & molten crater mask for combat hits (Row 3: tiles 12..15) + float is_combat = step(11.5, tile_idx); + // Rolled metallic lip & crater wall glow hot while keeping pitch-black bore contrast + float rim_band = smoothstep(0.94, 0.50, ormh.a) * smoothstep(0.08, 0.55, ormh.b); + float bore_inner_ring = smoothstep(0.35, 0.10, ormh.a) * smoothstep(0.01, 0.16, ormh.a); + float hot_mask = clamp((rim_band * 1.15 + bore_inner_ring * 0.45) * is_combat, 0.0, 1.0); + float hot_intensity = heat_glow * hot_mask; + vec3 hot_col = mix(vec3(0.95, 0.18, 0.02), vec3(1.0, 0.58, 0.14), smoothstep(0.25, 0.90, hot_intensity)); + + ALBEDO = alb.rgb; + ALPHA = out_alpha; + NORMAL_MAP = nrm_sample; + NORMAL_MAP_DEPTH = normal_depth; + AO = ormh.r; + AO_LIGHT_AFFECT = 0.85; + ROUGHNESS = clamp(ormh.g, 0.12, 0.98); + METALLIC = clamp(ormh.b, 0.0, 1.0); + EMISSION = hot_col * (hot_intensity * heat_emission_energy); +} diff --git a/client/inventory_grid.gdshader b/client/inventory_grid.gdshader new file mode 100644 index 0000000..10aaa68 --- /dev/null +++ b/client/inventory_grid.gdshader @@ -0,0 +1,251 @@ +shader_type canvas_item; +render_mode blend_premul_alpha; + +// Port of Aetheria's UI/Inventory Grid shader to Godot 4 gl_compatibility (OpenGL 3.3). +// Evaluates analytical corner-folded texel boxes for hull/hardpoint silhouettes, L-brackets, +// hairline rules, and 2D Euclidean SDF thermal conduits with RoundUnion fillets. +// +// data_tex (3W x H, filter_nearest): +// 3x + 0 : cell/item fill & armor tint (RGBA) +// 3x + 1 : border/bracket/pipe accent color (RGBA) +// 3x + 2 : R = 8-bit neighbor mismatch mask (N,E,S,W,NE,SE,SW,NW) +// G = flags (bit0=present, bit1=item, bit2=hover, bit3=damaged/stripped, bit4=compatible, bit5=border_radiator) +// B = 4-bit N/E/S/W thermal conductivity pipe mask +// A = hit-pulse flash intensity (0..1) +// temp_tex (W x H, filter_linear): +// R = normalized temperature [20C..200C -> 0..1] +// G = thermal plateau / overheat stress [0..0.5 optimal, 0.5..1.0 overheating] +// B = active cell mask + +uniform sampler2D data_tex : filter_nearest, repeat_disable; +uniform sampler2D temp_tex : filter_linear, repeat_disable; + +uniform vec2 grid_size = vec2(4.0, 5.0); +uniform vec2 rect_size = vec2(180.0, 225.0); +uniform float thermal_mode : hint_range(0.0, 1.0) = 0.0; + +// Look parameters in Aetheria texel units +uniform float icon_texel = 1.51515; +uniform float bg_texel = 1.0; +uniform float rule_inset = 1.5; +uniform float rule_width = 1.0; +uniform float arm_texels = 1.25; +uniform float fill_inset = 2.6; +uniform float softness = 1.0; +uniform float rule_alpha = 0.34; +uniform float bracket_alpha = 1.0; +uniform float fill_alpha = 0.14; + +// Thermal pipe SDF parameters (in cell fractions, edge ramp in pixels) +uniform float blob_radius = 0.1272; +uniform float pipe_half_width = 0.1261; +uniform float fillet = 0.1172; +uniform float pipe_soft = 1.212; + +const float FAR = 1000.0; + +float box_profile(float x, float lo, float hi, float soft) { + if (hi < lo) { + return 0.0; + } + float outside = max(max(lo - x, x - hi), 0.0); + return clamp(1.0 - outside / soft, 0.0, 1.0); +} + +float eval_layer(vec2 p, float cell_px, float texel, uint mask, bool is_item, bool is_icon, float aa_px) { + float t = min(texel, cell_px / 8.0); + bool left = p.x < cell_px * 0.5; + bool top = p.y >= cell_px * 0.5; + float max_t = max(cell_px * 0.5 / t, 4.0); + float x = clamp((left ? p.x : cell_px - p.x) / t, 0.5, max_t); + float y = clamp((top ? cell_px - p.y : p.y) / t, 0.5, max_t); + + uint v_shift = top ? 0u : 2u; + uint h_shift = left ? 3u : 1u; + uint d_shift = top ? (left ? 7u : 4u) : (left ? 6u : 5u); + bool v = ((mask >> v_shift) & 1u) != 0u; + bool h = ((mask >> h_shift) & 1u) != 0u; + bool d = ((mask >> d_shift) & 1u) != 0u; + bool concave = !v && !h && d; + + float soft = clamp(softness * aa_px / max(t, 0.25), 0.15, 2.0); + float fill_lo = fill_inset + 0.5; + float fx = h ? box_profile(x, fill_lo, FAR, soft) : 1.0; + float fy = v ? box_profile(y, fill_lo, FAR, soft) : 1.0; + float f = fx * fy; + if (concave) { + f -= box_profile(x, -FAR, fill_inset - 0.5, soft) * box_profile(y, -FAR, fill_inset - 0.5, soft); + } + f = clamp(f, 0.0, 1.0); + if (!is_icon) { + return f; + } + + float a = is_item ? fill_alpha * f : 0.0; + float ri = rule_inset; + float rlo = ri - (rule_width - 1.0) * 0.5; + float rhi = ri + (rule_width - 1.0) * 0.5; + float rx = box_profile(x, rlo, rhi, soft); + float ry = box_profile(y, rlo, rhi, soft); + float arms = arm_texels >= 1.0 ? 1.0 : 0.0; + + if (v) { + a += rule_alpha * ry * (h ? box_profile(x, ri, FAR, soft) : 1.0); + } + if (h) { + a += rule_alpha * rx * (v ? box_profile(y, ri + 1.0, FAR, soft) : 1.0); + } + if (v && h) { + a += (bracket_alpha - rule_alpha) * (ry * box_profile(x, ri, ri + arm_texels, soft) + arms * rx * box_profile(y, ri + 1.0, ri + arm_texels, soft)); + } else if (concave) { + a += bracket_alpha * (ry * box_profile(x, ri - arm_texels, ri, soft) + arms * rx * box_profile(y, ri - arm_texels, ri - 1.0, soft)); + } else if (!v && !h) { + // Faint cell subdivision hairline across matched internal cell boundaries + float sub_x = box_profile(x, 0.0, 0.65, soft); + float sub_y = box_profile(y, 0.0, 0.65, soft); + a += 0.14 * max(sub_x, sub_y); + } + return clamp(a, 0.0, 1.0); +} + +float round_union(float a, float b, float r) { + vec2 u = max(vec2(r - a, r - b), vec2(0.0)); + return max(r, min(a, b)) - length(u); +} + +float eval_pipes(vec2 p, float cell_px, uint cond, float aa_px) { + vec2 q = p / cell_px - 0.5; + float d = length(q) - blob_radius; + vec2 dirs[4]; + dirs[0] = vec2(0.0, 1.0); + dirs[1] = vec2(1.0, 0.0); + dirs[2] = vec2(0.0, -1.0); + dirs[3] = vec2(-1.0, 0.0); + + float bars[4]; + for (int b = 0; b < 4; b++) { + float along = dot(q, dirs[b]); + float perp = abs(dot(q, vec2(dirs[b].y, -dirs[b].x))); + bool connected = ((cond >> uint(b)) & 1u) != 0u; + bars[b] = !connected + ? FAR + : (along >= 0.0 ? perp - pipe_half_width : length(vec2(perp, along)) - pipe_half_width); + d = min(d, bars[b]); + } + for (int c = 0; c < 4; c++) { + int n = (c + 1) % 4; + if (bars[c] < FAR && bars[n] < FAR && dot(q, dirs[c] + dirs[n]) > 0.0) { + d = min(d, round_union(bars[c], bars[n], fillet)); + } + } + return clamp(0.5 - d * cell_px / max(pipe_soft * aa_px, 0.25), 0.0, 1.0); +} + +vec3 thermal_ramp(float t) { + vec3 c0 = vec3(0.11, 0.18, 0.24); // ambient cool slate + vec3 c1 = vec3(0.24, 0.48, 0.34); // warm olive + vec3 c2 = vec3(0.86, 0.64, 0.18); // optimal plateau amber-gold + vec3 c3 = vec3(0.92, 0.28, 0.14); // hot crimson-orange + vec3 c4 = vec3(1.00, 0.85, 0.58); // critical incandescent + if (t < 0.25) return mix(c0, c1, t / 0.25); + if (t < 0.55) return mix(c1, c2, (t - 0.25) / 0.30); + if (t < 0.85) return mix(c2, c3, (t - 0.55) / 0.30); + return mix(c3, c4, (t - 0.85) / 0.15); +} + +void fragment() { + vec2 safe_grid = max(grid_size, vec2(1.0)); + vec2 cell_wh = rect_size / safe_grid; + float S = min(cell_wh.x, cell_wh.y); + vec2 grid_px = safe_grid * S; + vec2 origin = (rect_size - grid_px) * 0.5; + vec2 local_px = UV * rect_size - origin; + + // Hoist derivatives and implicit-LOD texture lookup above non-uniform branches (GLSL 330 helper quads) + float aa_px = clamp(max(fwidth(UV.x) * rect_size.x, fwidth(UV.y) * rect_size.y), 0.2, 2.0); + vec4 temp_sample = texture(temp_tex, clamp(local_px / max(grid_px, vec2(1.0)), vec2(0.0), vec2(1.0))); + + vec2 cellf = floor(local_px / S); + if (cellf.x < 0.0 || cellf.y < 0.0 || cellf.x >= safe_grid.x || cellf.y >= safe_grid.y) { + COLOR = vec4(0.0); + } else { + vec2 p_godot = local_px - cellf * S; + // Flip Y inside cell to match Aetheria's y-up Layer / Pipes convention + vec2 p = vec2(p_godot.x, S - p_godot.y); + + float tex_w = safe_grid.x * 3.0; + float ty = (cellf.y + 0.5) / safe_grid.y; + vec4 cell_fill = textureLod(data_tex, vec2((cellf.x * 3.0 + 0.5) / tex_w, ty), 0.0); + vec4 border_accent = textureLod(data_tex, vec2((cellf.x * 3.0 + 1.5) / tex_w, ty), 0.0); + vec4 meta = textureLod(data_tex, vec2((cellf.x * 3.0 + 2.5) / tex_w, ty), 0.0); + + uint mask = uint(round(meta.r * 255.0)); + uint flags = uint(round(meta.g * 255.0)); + uint cond = uint(round(meta.b * 255.0)); + float hit_pulse = meta.a; + + if ((flags & 1u) == 0u) { + COLOR = vec4(0.0); + } else { + bool is_item = (flags & 2u) != 0u; + bool is_hover = (flags & 4u) != 0u; + bool is_damaged = (flags & 8u) != 0u; + bool is_compatible = (flags & 16u) != 0u; + + float norm_temp = temp_sample.r; + float plateau_stress = temp_sample.g; + vec3 heat_col = thermal_ramp(norm_temp); + + float a_bg = eval_layer(p, S, bg_texel, mask, false, false, aa_px) * cell_fill.a; + float a_rules = eval_layer(p, S, icon_texel, mask, is_item, true, aa_px); + float a_pipes = eval_pipes(p, S, cond, aa_px); + + // Intact vs stripped (Armor == 0) interior fill + vec3 base_rgb = mix(cell_fill.rgb, heat_col, mix(0.24, 0.84, thermal_mode)); + if (is_damaged) { + // Diagonal fracture/exposed-core hatching at 45 deg + float hatch_coord = (p_godot.x + p_godot.y) / max(S * 0.22, 4.0); + float hatch_dist = abs(fract(hatch_coord) - 0.5); + float hatch = 1.0 - smoothstep(0.10, 0.22, hatch_dist); + base_rgb = mix(base_rgb * 0.55, vec3(0.82, 0.20, 0.14), hatch * 0.65); + } + + // Thermal plateau glow over hot cells + float overheat_glow = max(plateau_stress - 0.5, 0.0) * 2.0; + base_rgb += heat_col * (0.12 * norm_temp + 0.22 * overheat_glow); + base_rgb = clamp(base_rgb, vec3(0.0), vec3(1.0)); + + if (is_hover) { + base_rgb = mix(base_rgb, vec3(0.95, 0.94, 0.88), 0.16); + } + + // Active hit-pulse impact flash + vec3 flash_col = vec3(1.0, 0.76, 0.38); + base_rgb = clamp(mix(base_rgb, flash_col, hit_pulse * 0.85), vec3(0.0), vec3(1.0)); + + vec3 accent_rgb = border_accent.rgb; + if (is_damaged) { + accent_rgb = mix(accent_rgb, vec3(0.92, 0.26, 0.18), 0.70); + } + if (is_compatible) { + float pulse = 0.72 + 0.28 * sin(TIME * 6.5); + accent_rgb = mix(accent_rgb, vec3(0.96, 0.82, 0.30), pulse); + a_rules = clamp(a_rules * 1.35, 0.0, 1.0); + } + if (is_hover) { + accent_rgb = mix(accent_rgb, vec3(1.0), 0.35); + a_rules = clamp(a_rules * 1.25, 0.0, 1.0); + } + accent_rgb = clamp(mix(accent_rgb, flash_col, hit_pulse * 0.90), vec3(0.0), vec3(1.0)); + + float icon_alpha = clamp(mix(a_rules * border_accent.a, max(a_rules * 0.26, a_pipes), thermal_mode), 0.0, 1.0); + vec3 pipe_rgb = clamp(mix(accent_rgb, heat_col * 1.2 + vec3(0.14), 0.72), vec3(0.0), vec3(1.0)); + vec3 icon_rgb = clamp(mix(accent_rgb, pipe_rgb, thermal_mode * clamp(a_pipes * 1.2, 0.0, 1.0)), vec3(0.0), vec3(1.0)); + + float out_a = clamp(icon_alpha + a_bg * (1.0 - icon_alpha), 0.0, 1.0); + vec3 out_rgb = min(icon_rgb * icon_alpha + base_rgb * a_bg * (1.0 - icon_alpha), vec3(out_a)); + out_rgb = max(out_rgb, vec3(0.0)); + COLOR = vec4(out_rgb, out_a); + } + } +} diff --git a/client/mech_paint.gdshader b/client/mech_paint.gdshader new file mode 100644 index 0000000..9fdd554 --- /dev/null +++ b/client/mech_paint.gdshader @@ -0,0 +1,225 @@ +shader_type spatial; +render_mode cull_back, depth_draw_opaque; + +// Real-time GLSL 330 (gl_compatibility) port of Brokkr's 6-layer MechPaint. +// Samples 3D procedural noise in rest-pose object space (v_local_pos, v_local_nrm) +// so weathering never swims during skeletal/joint animation or chassis motion. +// +// Expects baked vertex COLOR_0: +// R = geometric cavity AO (0 = deep crevice, 1 = open exposed face) +// G = convex dihedral edge curvature (0 = flat, 1 = sharp exposed edge) +// B = per-island connected-component hash (0..1) +// A = rest-pose height above ground (meters / 6.0, clamped 0..1) +// +// Live combat channels (via INSTANCE_CUSTOM or uniform fallback for non-MultiMesh): +// INSTANCE_CUSTOM.x / scorch (0..1) -> char/soot darkening + matte roughness +// INSTANCE_CUSTOM.y / heat_glow (0..1) -> incandescent orange-red emission without cloning materials + +uniform vec4 base_color : source_color = vec4(0.306, 0.341, 0.251, 1.0); +uniform float roughness : hint_range(0.0, 1.0) = 0.58; +uniform float metallic : hint_range(0.0, 1.0) = 0.28; +uniform float tone_variation : hint_range(0.0, 1.0) = 0.30; +uniform float mottle : hint_range(0.0, 2.0) = 1.0; +uniform float noise_scale : hint_range(0.1, 10.0) = 1.0; + +uniform float grime : hint_range(0.0, 2.0) = 0.90; +uniform vec4 grime_color : source_color = vec4(0.145, 0.133, 0.114, 1.0); + +uniform float streaks : hint_range(0.0, 2.0) = 0.95; +uniform float dust : hint_range(0.0, 2.0) = 0.55; +uniform vec4 dust_color : source_color = vec4(0.451, 0.431, 0.388, 1.0); + +uniform float wear : hint_range(0.0, 2.5) = 0.95; +uniform vec4 chip_color : source_color = vec4(0.460, 0.470, 0.465, 1.0); +uniform float chip_metallic : hint_range(0.0, 1.0) = 0.85; +uniform float chip_roughness : hint_range(0.0, 1.0) = 0.28; +uniform vec4 primer_color : source_color = vec4(0.345, 0.325, 0.286, 1.0); + +uniform float mud : hint_range(0.0, 2.0) = 1.0; +uniform float mud_top : hint_range(0.1, 5.0) = 1.45; +uniform vec4 mud_color : source_color = vec4(0.180, 0.148, 0.118, 1.0); +uniform float wet : hint_range(0.0, 2.0) = 0.60; +uniform float wet_top : hint_range(0.1, 6.0) = 2.80; + +uniform float scorch : hint_range(0.0, 1.0) = 0.0; +uniform float heat_glow : hint_range(0.0, 1.0) = 0.0; +uniform float heat_emission_energy : hint_range(0.0, 8.0) = 2.6; + +varying vec3 v_local_pos; +varying vec3 v_local_nrm; +varying vec4 v_color; +varying float v_scorch; +varying float v_heat; + +// Safe remapping helper supporting inverted bounds (lo > hi) without GLSL smoothstep UB. +float map_range(float v, float lo, float hi, float out_lo, float out_hi) { + float denom = hi - lo; + float t = abs(denom) > 1e-6 ? clamp((v - lo) / denom, 0.0, 1.0) : 0.0; + t = t * t * (3.0 - 2.0 * t); + return mix(out_lo, out_hi, t); +} + +float hash31(vec3 p) { + p = fract(p * vec3(0.1031, 0.1030, 0.0973)); + p += dot(p, p.yxz + 33.33); + return fract((p.x + p.y) * p.z); +} + +float noise3d(vec3 p) { + vec3 i = floor(p); + vec3 f = fract(p); + vec3 u = f * f * (3.0 - 2.0 * f); + + float n000 = hash31(i + vec3(0.0, 0.0, 0.0)); + float n100 = hash31(i + vec3(1.0, 0.0, 0.0)); + float n010 = hash31(i + vec3(0.0, 1.0, 0.0)); + float n110 = hash31(i + vec3(1.0, 1.0, 0.0)); + float n001 = hash31(i + vec3(0.0, 0.0, 1.0)); + float n101 = hash31(i + vec3(1.0, 0.0, 1.0)); + float n011 = hash31(i + vec3(0.0, 1.0, 1.0)); + float n111 = hash31(i + vec3(1.0, 1.0, 1.0)); + + float nx00 = mix(n000, n100, u.x); + float nx10 = mix(n010, n110, u.x); + float nx01 = mix(n001, n101, u.x); + float nx11 = mix(n011, n111, u.x); + float nxy0 = mix(nx00, nx10, u.y); + float nxy1 = mix(nx01, nx11, u.y); + return mix(nxy0, nxy1, u.z); +} + +float fbm2(vec3 p) { + // Rotate second octave to eliminate cubic lattice grid alignment + const mat3 rot = mat3( + vec3(0.80, -0.48, 0.36), + vec3(0.60, 0.64, -0.48), + vec3(0.00, 0.60, 0.80) + ); + float a = noise3d(p); + float b = noise3d((rot * p) * 2.17 + vec3(17.3, 9.1, 23.7)); + float c = noise3d((rot * p) * 4.61 + vec3(5.7, 31.4, 11.2)); + return a * 0.55 + b * 0.30 + c * 0.15; +} + +vec3 rgb_to_hsv(vec3 c) { + vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); + vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); + float d = q.x - min(q.w, q.y); + float e = 1.0e-6; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} + +vec3 hsv_to_rgb(vec3 c) { + vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); +} + +void vertex() { + v_local_pos = VERTEX; + v_local_nrm = NORMAL; + v_color = COLOR; + v_scorch = clamp(max(INSTANCE_CUSTOM.x, scorch), 0.0, 1.0); + v_heat = clamp(max(INSTANCE_CUSTOM.y, heat_glow), 0.0, 1.0); +} + +void fragment() { + vec3 pos = v_local_pos * noise_scale; + vec3 nrm = normalize(v_local_nrm); + float up = nrm.y; + + float occ = clamp(v_color.r, 0.0, 1.0); + float edge = clamp(v_color.g, 0.0, 1.0); + float island_rand = clamp(v_color.b, 0.0, 1.0); + float height_m = clamp(v_color.a, 0.0, 1.0) * 6.0; + + // Layer 1: Base paint + per-island tone variation + 2-octave 3D object-space mottle + float rand2 = fract(island_rand * 7.31 + 0.37); + vec3 hsv = rgb_to_hsv(base_color.rgb); + hsv.x = fract(hsv.x + (rand2 - 0.5) * tone_variation * 0.14); + hsv.y = clamp(hsv.y * (1.0 + (rand2 - 0.5) * tone_variation * 0.75), 0.0, 1.0); + hsv.z = clamp(hsv.z * (1.0 + (island_rand * 2.0 - 1.0) * tone_variation * 0.65), 0.01, 2.0); + vec3 col = hsv_to_rgb(hsv); + + float blotch = fbm2(pos * 0.75); + float speck = fbm2(pos * 26.0); + float mid_n = fbm2(pos * 4.5); + float shade = map_range(blotch, 0.25, 0.75, -0.14, 0.14) + + map_range(speck, 0.25, 0.75, -0.07, 0.07) + + map_range(mid_n, 0.25, 0.75, -0.09, 0.09); + col *= clamp(1.0 + shade * mottle, 0.55, 1.35); + + // Layer 2: Cavity grime darkening + roughness boost from (1 - AO) + float cavity = clamp(map_range(occ, 0.90, 0.42, 0.0, 1.0) * map_range(fbm2(pos * 5.0), 0.30, 0.65, 0.45, 1.0) * grime, 0.0, 1.0); + float film = clamp(map_range(fbm2(pos * 2.1), 0.54, 0.72, 0.0, 1.0) * 0.30 * grime, 0.0, 1.0); + float grime_amt = max(cavity, film); + col = mix(col, grime_color.rgb, min(grime_amt, 0.85)); + + // Layer 3: Vertical rain/oil streaks on upright surfaces boosted by cavity + vec3 stretch = pos * vec3(13.0, 0.5, 13.0); + float upright = map_range(abs(up), 0.80, 0.35, 0.0, 1.0); + float under = map_range(occ, 0.96, 0.65, 0.40, 1.0); + float broken = map_range(noise3d(pos * 1.4), 0.35, 0.55, 0.15, 1.0); + float dark_run = clamp(map_range(fbm2(stretch), 0.52, 0.68, 0.0, 1.0) * upright * under * broken * streaks, 0.0, 1.0); + float pale_run = clamp(map_range(fbm2(stretch + vec3(31.0, 5.0, 17.0)), 0.62, 0.76, 0.0, 1.0) * upright * 0.28 * streaks, 0.0, 1.0); + col = mix(col, dust_color.rgb, pale_run); + col = mix(col, grime_color.rgb, dark_run * 0.85); + + // Layer 4: Pale dust on upward-facing normals (v_local_nrm.y) + float dust_amt = clamp(map_range(up, 0.45, 0.95, 0.0, 1.0) * map_range(fbm2(pos * 3.0), 0.25, 0.70, 0.25, 1.0) * dust * 0.55, 0.0, 1.0); + col = mix(col, dust_color.rgb, dust_amt); + + // Layer 5: Metallic edge chipping + thin primer_color halo from edge_curvature * noise + float exposed = map_range(occ, 0.42, 0.88, 0.0, 1.0); + float edge_sharp = pow(edge, 1.85); + float chip_n = map_range(fbm2(pos * 6.5), 0.30, 0.72, 0.0, 0.44) + + map_range(noise3d(pos * 46.0), 0.30, 0.70, -0.06, 0.06); + float wear_level = chip_n + edge_sharp * exposed * wear * 0.56; + float scuff = map_range(fbm2(pos * 4.5), 0.68, 0.72, 0.0, 1.0) * clamp(wear / 1.8, 0.0, 1.0) * 0.55; + float chip_metal_mask = clamp(max(map_range(wear_level, 0.76, 0.80, 0.0, 1.0), scuff * 0.85), 0.0, 1.0); + float primer_mask = clamp(max(map_range(wear_level, 0.71, 0.75, 0.0, 1.0), scuff), 0.0, 1.0); + col = mix(col, primer_color.rgb, primer_mask * 0.75); + col = mix(col, chip_color.rgb, chip_metal_mask); + + // Layer 6: Lower-hull/foot mud & wet gloss driven by rest_height (COLOR.a) + float wet_amt = clamp(map_range(height_m, wet_top, 0.0, 0.0, 1.0) * wet, 0.0, 1.0); + col *= (1.0 - 0.50 * wet_amt); + float mud_n = fbm2(pos * 3.2); + float thick = map_range(height_m, mud_top, 0.0, 0.0, 1.0) + * map_range(mud_n, 0.35, 0.62, 0.1, 1.5) + * map_range(occ, 0.95, 0.50, 0.7, 1.6) * mud; + float splash = map_range(fbm2(pos * 11.0), 0.62, 0.66, 0.0, 1.0) + * map_range(height_m, mud_top * 2.2, mud_top * 0.4, 0.0, 1.0) * mud * 0.85; + float mud_amt = clamp(max(map_range(thick, 0.20, 0.50, 0.0, 1.0), splash), 0.0, 1.0); + col = mix(col, mud_color.rgb * map_range(mud_n, 0.30, 0.70, 0.70, 1.30), mud_amt); + + // PBR metallic & roughness synthesis + float out_metallic = mix(metallic, chip_metallic, chip_metal_mask); + out_metallic *= (1.0 - mud_amt) * (1.0 - grime_amt * 0.70); + + float out_rough = roughness + grime_amt * 0.22 + (1.0 - occ) * 0.12 * clamp(grime, 0.0, 1.0); + out_rough = mix(out_rough, chip_roughness, chip_metal_mask); + out_rough -= wet_amt * 0.18; + out_rough += mud_amt * 0.18; + out_rough = clamp(out_rough, 0.12, 0.98); + + // Live combat channel 1: scorch (char/soot darkening + matte roughness) + float soot_pat = mix(0.65, 1.0, fbm2(pos * 4.5)); + float scorch_mask = clamp(v_scorch * soot_pat, 0.0, 1.0); + col = mix(col, vec3(0.022, 0.018, 0.016), scorch_mask * 0.88); + out_metallic *= (1.0 - scorch_mask * 0.75); + out_rough = mix(out_rough, 0.94, scorch_mask); + + // Live combat channel 2: heat_glow (incandescent orange-red emission without cloning material) + float heat_mod = mix(0.25, 1.15, pow(edge, 1.4) * 0.6 + fbm2(pos * 3.8) * 0.4); + float h_val = clamp(v_heat * heat_mod, 0.0, 1.0); + vec3 heat_col = mix(vec3(0.85, 0.12, 0.01), vec3(1.0, 0.52, 0.10), smoothstep(0.25, 0.95, h_val)); + + ALBEDO = col; + METALLIC = clamp(out_metallic, 0.0, 1.0); + ROUGHNESS = out_rough; + AO = mix(1.0, occ, 0.65); + AO_LIGHT_AFFECT = 0.65; + EMISSION = heat_col * (pow(v_heat, 1.35) * heat_mod * heat_emission_energy); +} diff --git a/client/panel_chrome.gdshader b/client/panel_chrome.gdshader new file mode 100644 index 0000000..2aa8a0f --- /dev/null +++ b/client/panel_chrome.gdshader @@ -0,0 +1,80 @@ +shader_type canvas_item; +render_mode blend_premul_alpha; + +// Resolution-independent industrial panel chrome using the same analytical corner-folded +// Box / L-bracket + hairline border + inset fill math as inventory_grid.gdshader (1x1 cell). +// Stays razor-sharp at 720p, 1080p, 1440p, and 4K. + +uniform vec2 rect_size = vec2(320.0, 160.0); +uniform float corner_len = 12.0; +uniform float border_px = 1.5; +uniform float fill_inset = 2.0; +uniform float rule_inset = 1.5; +uniform float rule_alpha = 0.55; +uniform float bracket_alpha = 1.0; +uniform float top_bar_px = 2.0; +uniform float scanline_strength = 0.045; + +uniform vec4 bg_color : source_color = vec4(0.075, 0.086, 0.075, 0.88); +uniform vec4 border_color : source_color = vec4(0.243, 0.275, 0.220, 1.0); +uniform vec4 accent_color : source_color = vec4(0.878, 0.541, 0.290, 1.0); + +const float FAR = 10000.0; + +float box_profile(float x, float lo, float hi, float soft) { + if (hi < lo) { + return 0.0; + } + float outside = max(max(lo - x, x - hi), 0.0); + return clamp(1.0 - outside / max(soft, 0.05), 0.0, 1.0); +} + +void fragment() { + vec2 size = max(rect_size, vec2(4.0)); + vec2 p = UV * size; + float aa = clamp(max(fwidth(UV.x) * size.x, fwidth(UV.y) * size.y), 0.2, 2.0); + + // Fold into nearest corner quadrant (1x1 cell, all 4 cardinal edges active) + bool left = p.x < size.x * 0.5; + bool top = p.y < size.y * 0.5; + float x = max(left ? p.x : size.x - p.x, 0.5 * aa); + float y = max(top ? p.y : size.y - p.y, 0.5 * aa); + + // Inset background fill + float fx = box_profile(x, fill_inset, FAR, aa); + float fy = box_profile(y, fill_inset, FAR, aa); + float fill_mask = fx * fy; + + // Hairline border and corner L-brackets (logical thickness stays fixed in rect_size units) + float ri = rule_inset; + float half_w = max(border_px - 1.0, 0.0) * 0.5; + float rlo = ri - half_w; + float rhi = ri + half_w; + float rx = box_profile(x, rlo, rhi, aa); + float ry = box_profile(y, rlo, rhi, aa); + + float rule_mask = max(ry * box_profile(x, rlo, FAR, aa), rx * box_profile(y, rlo, FAR, aa)); + float clen = min(corner_len, min(size.x, size.y) * 0.35); + float bracket_mask = max(ry * box_profile(x, rlo, ri + clen, aa), rx * box_profile(y, rlo, ri + clen, aa)); + + // Subtle top-bar & micro-scanline accent inside the fill + float top_bar = box_profile(p.y, fill_inset + 0.5, fill_inset + 0.5 + top_bar_px, aa) * fx; + float scan = 1.0 - scanline_strength * (0.5 + 0.5 * sin(p.y * 2.0943951)); + + vec3 fill_rgb = mix(bg_color.rgb * scan, accent_color.rgb, top_bar * 0.24); + float fill_a = fill_mask * bg_color.a; + + float edge_rule = clamp(rule_mask - bracket_mask, 0.0, 1.0) * rule_alpha * border_color.a; + float edge_bracket = bracket_mask * bracket_alpha * accent_color.a; + + vec3 rgb = fill_rgb * fill_a; + float alpha = fill_a; + + rgb = border_color.rgb * edge_rule + rgb * (1.0 - edge_rule); + alpha = edge_rule + alpha * (1.0 - edge_rule); + + rgb = accent_color.rgb * edge_bracket + rgb * (1.0 - edge_bracket); + alpha = edge_bracket + alpha * (1.0 - edge_bracket); + + COLOR = vec4(rgb, clamp(alpha, 0.0, 1.0)); +} diff --git a/client/project.godot b/client/project.godot new file mode 100644 index 0000000..d214e57 --- /dev/null +++ b/client/project.godot @@ -0,0 +1,33 @@ +; Engine configuration file. +; It's best edited using the editor UI and not directly, +; since the parameters that go here are not all obvious. + +config_version=5 + +[application] + +config/name="Rust to Dust" +run/main_scene="res://Main.tscn" +config/features=PackedStringArray("4.7", "C#") + +[display] + +window/size/viewport_width=1280 +window/size/viewport_height=720 +window/stretch/mode="canvas_items" + +[dotnet] + +project/assembly_name="RustToDust.Client" + +[physics] + +; Godot's physics is switched off: Ymir is the only physics world. ArenaSession ticks at 60 Hz. +3d/physics_engine="Dummy" +common/physics_ticks_per_second=60 +common/physics_interpolation=true + +[rendering] + +renderer/rendering_method="gl_compatibility" +renderer/rendering_method.mobile="gl_compatibility" diff --git a/client/terrain_brush.gdshader b/client/terrain_brush.gdshader new file mode 100644 index 0000000..eb66b71 --- /dev/null +++ b/client/terrain_brush.gdshader @@ -0,0 +1,67 @@ +shader_type canvas_item; +render_mode blend_add; + +// Encodes positive height deltas into R ([-18m, +52m] => span 70m), +// roughness delta into G, scorch/track wear into B, and ALWAYS A = 1.0 +// (required for gl_compatibility TransparentBg=false blend equations). +uniform int brush_kind = 0; +uniform float height_delta = 0.0; +uniform float height_span = 70.0; + +void fragment() { + vec2 uv_local = UV * 2.0 - 1.0; + float u = uv_local.x; + float v = uv_local.y; + float r2 = u * u + v * v; + if (r2 >= 1.0) { + discard; + } + + float pos_dh = 0.0; + float pos_dg = 0.0; + float d_scorch = 0.0; + + if (brush_kind == 0) { + // DuneRidge (positive) + float env = 1.0 - r2; + env *= env; + float ridge = max(0.0, 1.0 - u * u); + float asym = 1.0 + 0.32 * u; + pos_dh = max(0.0, height_delta) * env * (0.35 + 0.65 * ridge) * asym; + pos_dg = 0.02 * env; + } else if (brush_kind == 1) { + // Mesa + float r = sqrt(r2); + float t = clamp((1.0 - r) / 0.45, 0.0, 1.0); + float plateau = t * t * (3.0 - 2.0 * t); + pos_dh = max(0.0, height_delta) * plateau; + } else if (brush_kind == 2) { + // SalvagePad (positive part) + float env = 1.0 - r2; + env *= env; + pos_dh = max(0.0, height_delta) * env; + pos_dg = 0.03 * env; + } else if (brush_kind == 4) { + // Crater ejecta rim + slag/scorch + float r = sqrt(r2); + float depth = abs(height_delta); + float rim_t = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0)); + pos_dh = 0.32 * depth * rim_t * rim_t; + pos_dg = 0.04 * (1.0 - r); + d_scorch = 0.78 * clamp(1.0 - r * 0.9, 0.0, 1.0); + } else if (brush_kind == 5) { + // Track wear + float env = 1.0 - r2; + env *= env; + d_scorch = 0.32 * env; + } else if (brush_kind == 6) { + // Scorch + float r = sqrt(r2); + float mask = clamp(1.0 - r, 0.0, 1.0); + mask = mask * mask; + pos_dg = 0.02 * mask; + d_scorch = 0.85 * mask; + } + + COLOR = vec4(pos_dh / height_span, pos_dg, d_scorch, 1.0); +} diff --git a/client/terrain_brush_albedo.gdshader b/client/terrain_brush_albedo.gdshader new file mode 100644 index 0000000..3b1cdf8 --- /dev/null +++ b/client/terrain_brush_albedo.gdshader @@ -0,0 +1,73 @@ +shader_type canvas_item; +render_mode blend_mix; + +uniform int brush_kind = 0; +uniform vec3 brush_albedo = vec3(0.72, 0.53, 0.33); +uniform float height_delta = 0.0; + +void fragment() { + vec2 uv_local = UV * 2.0 - 1.0; + float u = uv_local.x; + float v = uv_local.y; + float r2 = u * u + v * v; + if (r2 >= 1.0) { + discard; + } + + vec3 col = brush_albedo; + float alpha = 0.0; + + if (brush_kind == 0) { + // DuneRidge: windward sunlit crest vs dry wash + float env = 1.0 - r2; + env *= env; + float ridge = max(0.0, 1.0 - u * u); + col = mix(brush_albedo * 0.90, brush_albedo * 1.12, ridge); + alpha = env * 0.72; + } else if (brush_kind == 1) { + // Mesa: rust-basalt plateau + stratified skirt + float r = sqrt(r2); + float t = clamp((1.0 - r) / 0.45, 0.0, 1.0); + float plateau = t * t * (3.0 - 2.0 * t); + float cliff_band = clamp(1.0 - abs(r - 0.74) * 5.0, 0.0, 1.0); + col = mix(brush_albedo, brush_albedo * 0.68, cliff_band); + alpha = clamp(plateau + cliff_band * 0.5, 0.0, 0.94); + } else if (brush_kind == 2) { + // SalvagePad: compacted gravel & weathered concrete slab + float env = 1.0 - r2; + env *= env; + float border = smoothstep(0.75, 0.92, sqrt(r2)); + col = mix(brush_albedo, vec3(0.32, 0.28, 0.24), border * 0.45); + alpha = clamp(env * 1.15, 0.0, 0.88); + } else if (brush_kind == 3) { + // Road: twin packed dirt ruts running longitudinally along u (cross-track offset abs(v)) + float env = 1.0 - r2; + env *= env; + float rut = smoothstep(0.15, 0.45, abs(v)) * (1.0 - smoothstep(0.60, 0.92, abs(v))); + col = mix(brush_albedo, brush_albedo * 0.76, rut); + alpha = env * (0.45 + 0.35 * rut); + } else if (brush_kind == 4) { + // Crater: charred pit center + bright rust ejecta rim + float r = sqrt(r2); + float pit = clamp(1.0 - r / 0.62, 0.0, 1.0); + float rim = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0)); + vec3 ejecta = vec3(0.62, 0.38, 0.22); + col = mix(ejecta, brush_albedo, clamp(pit * 1.3, 0.0, 1.0)); + alpha = clamp(max(pit * 0.94, rim * rim * 0.72), 0.0, 0.95); + } else if (brush_kind == 5) { + // Track: twin tire ruts along local X + float env = 1.0 - r2; + env *= env; + float treads = smoothstep(0.18, 0.45, abs(v)) * (1.0 - smoothstep(0.62, 0.92, abs(v))); + col = brush_albedo; + alpha = env * treads * 0.62; + } else if (brush_kind == 6) { + // Scorch + float r = sqrt(r2); + float mask = clamp(1.0 - r, 0.0, 1.0); + col = brush_albedo; + alpha = mask * mask * 0.88; + } + + COLOR = vec4(col, alpha); +} diff --git a/client/terrain_brush_sub.gdshader b/client/terrain_brush_sub.gdshader new file mode 100644 index 0000000..660e195 --- /dev/null +++ b/client/terrain_brush_sub.gdshader @@ -0,0 +1,41 @@ +shader_type canvas_item; +render_mode blend_sub; + +// Encodes negative height deltas (crater pits, dry washes, road ruts, tire ruts) into R. +uniform int brush_kind = 0; +uniform float height_delta = 0.0; +uniform float height_span = 70.0; + +void fragment() { + vec2 uv_local = UV * 2.0 - 1.0; + float u = uv_local.x; + float v = uv_local.y; + float r2 = u * u + v * v; + if (r2 >= 1.0) { + discard; + } + + float neg_dh = 0.0; + float neg_dg = 0.0; + if (brush_kind == 0) { + // Dry wash (negative DuneRidge) + float env = 1.0 - r2; + env *= env; + float ridge = max(0.0, 1.0 - u * u); + float asym = 1.0 + 0.32 * u; + neg_dh = max(0.0, -height_delta) * env * (0.35 + 0.65 * ridge) * asym; + } else if (brush_kind == 2 || brush_kind == 3 || brush_kind == 5) { + // SalvagePad (<0), Road, Track rut + float env = 1.0 - r2; + env *= env; + neg_dh = max(0.0, -height_delta) * env; + } else if (brush_kind == 4) { + // Crater pit + float r = sqrt(r2); + float depth = abs(height_delta); + float pit_t = clamp(1.0 - r / 0.62, 0.0, 1.0); + neg_dh = depth * pit_t * pit_t * (3.0 - 2.0 * pit_t); + } + + COLOR = vec4(neg_dh / height_span, neg_dg, 0.0, 1.0); +} diff --git a/client/terrain_surface.gdshader b/client/terrain_surface.gdshader new file mode 100644 index 0000000..eaf2609 --- /dev/null +++ b/client/terrain_surface.gdshader @@ -0,0 +1,56 @@ +shader_type spatial; +render_mode cull_back, depth_draw_opaque; + +uniform sampler2D height_tex : filter_linear, repeat_disable; +uniform sampler2D albedo_tex : filter_linear, repeat_disable; +uniform float height_min = -18.0; +uniform float height_max = 52.0; +uniform float tile_size = 192.0; +uniform float inner_span = 253.0; +uniform float tex_size = 256.0; +uniform float gutter_offset = 1.5; + +float decode_height(float h_norm) { + return mix(height_min, height_max, clamp(h_norm, 0.0, 1.0)); +} + +float hash21(vec2 p) { + p = fract(p * vec2(123.34, 456.21)); + p += dot(p, p + 45.32); + return fract(p.x * p.y); +} + +vec2 to_baked_uv(vec2 mesh_uv) { + return (mesh_uv * inner_span + gutter_offset) / tex_size; +} + +void vertex() { + float h_norm = textureLod(height_tex, to_baked_uv(UV), 0.0).r; + VERTEX.y += decode_height(h_norm); +} + +void fragment() { + vec2 uv_baked = to_baked_uv(UV); + float texel_step = 1.0 / tex_size; + float world_step = tile_size / inner_span; + + float hL = decode_height(texture(height_tex, uv_baked - vec2(texel_step, 0.0)).r); + float hR = decode_height(texture(height_tex, uv_baked + vec2(texel_step, 0.0)).r); + float hD = decode_height(texture(height_tex, uv_baked - vec2(0.0, texel_step)).r); + float hU = decode_height(texture(height_tex, uv_baked + vec2(0.0, texel_step)).r); + + vec3 world_normal = normalize(vec3(hL - hR, 2.0 * world_step, hD - hU)); + NORMAL = normalize((VIEW_MATRIX * vec4(world_normal, 0.0)).xyz); + + vec4 mat = texture(height_tex, uv_baked); + vec3 alb = texture(albedo_tex, uv_baked).rgb; + + // Subtle desert sand grain so dunes read crisply under sunlight + float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045; + float scorch = clamp(mat.b, 0.0, 1.0); + alb = clamp(alb + vec3(grain), 0.0, 1.0) * (1.0 - 0.30 * scorch); + + ALBEDO = alb; + ROUGHNESS = clamp(mat.g, 0.25, 1.0); + METALLIC = 0.05; +} diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs new file mode 100644 index 0000000..681fda2 --- /dev/null +++ b/client/tests/Smoke.cs @@ -0,0 +1,1205 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client.Tests; + +/// +/// Headless Godot smoke test: instantiates Main, drives 60 frames with throttle + fire + crater stamp, +/// verifies terrain tile baking and Ymir physics integration, and exits with code 0 on pass. +/// godot --headless --path client res://tests/Smoke.tscn +/// +public partial class Smoke : Node +{ + private const double WatchdogSeconds = 60.0; + + private readonly List _failures = new(); + private Main _main = null!; + private bool _done; + + public override void _Ready() => _ = RunAsync(); + + public override void _Process(double delta) + { + if (!_done && Time.GetTicksMsec() > WatchdogSeconds * 1000.0) + { + Check(false, $"Smoke watchdog timed out after {WatchdogSeconds}s"); + Finish(); + } + } + + private async Task RunAsync() + { + try + { + _main = GD.Load("res://Main.tscn").Instantiate
(); + AddChild(_main); + + if (_main.Failure is { } failure) + { + Check(false, "Main failed to initialize ArenaSession: " + failure); + } + else + { + await RunScenarioAsync(); + } + } + catch (Exception ex) + { + Check(false, ex.ToString()); + } + + Finish(); + } + + private async Task RunScenarioAsync() + { + Check(Engine.PhysicsTicksPerSecond == 60, $"Expected 60 physics ticks/sec, got {Engine.PhysicsTicksPerSecond}"); + Check((string)ProjectSettings.GetSetting("physics/3d/physics_engine") == "Dummy", "Godot 3D physics_engine is not Dummy"); + Check(!_main.GetWorld3D().Space.IsValid, "Godot should have no active 3D physics space"); + Check(_main.Terrain.BakedTileCount == 64, $"Expected 64 baked terrain tiles, got {_main.Terrain.BakedTileCount}"); + + var player = _main.Session.State.Player; + float startX = player.X; + float startZ = player.Z; + + _main.SetScriptedInput(new PlayerInput( + Throttle: 1f, + Steer: 0.25f, + AimWorldX: startX + 35f, + AimWorldZ: startZ + 10f, + Fire: true, + InteractPickup: false, + Brake: false)); + + for (int i = 0; i < 60; i++) + { + await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame); + if (_main.Failure is { } f) + { + Check(false, "Session failure during physics loop: " + f); + return; + } + } + + float dx = player.X - startX; + float dz = player.Z - startZ; + float displacement = MathF.Sqrt(dx * dx + dz * dz); + Check(displacement > 3f, $"Expected player displacement > 3m after 60 frames, got {displacement:F2}m"); + Check(!float.IsNaN(player.X) && !float.IsNaN(player.Y) && !float.IsNaN(player.Z), "Player position became NaN"); + + // Pause physics during the isolated crater check so AI contender track stamps in other tiles do not race it. + _main.SetScriptedInput(null); + _main.SetPhysicsProcess(false); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + bool isHeadless = DisplayServer.GetName() == "headless"; + int rebakesBefore = _main.Terrain.DirtyRebakes; + float cpuBefore = _main.Session.State.Terrain.SampleHeight(-96f, -96f); + float gpuBefore = 0f; + if (!isHeadless) + { + if (_main.Terrain.TryGetHeightImageFormat(out var imgFormat)) + { + GD.Print($"SMOKE INFO: HeightViewport format={imgFormat}"); + } + + bool hasGpuBefore = _main.Terrain.TrySampleBakedHeight(-96f, -96f, out gpuBefore); + Check(hasGpuBefore, "Expected GPU HeightViewport readback to succeed before crater"); + if (hasGpuBefore) + { + float beforeErr = MathF.Abs(gpuBefore - cpuBefore); + GD.Print($"SMOKE INFO: Crater-site pre-stamp cpu={cpuBefore:F4}m gpu={gpuBefore:F4}m err={beforeErr:F4}m"); + Check(beforeErr <= 0.20f, + $"Expected baked GPU height ({gpuBefore:F4}m) to match CPU height ({cpuBefore:F4}m) before crater within 0.20m"); + } + + // Verify brushed terrain relief (tallest Mesa/DuneRidge center) so a flat-map bug can never pass + TerrainBrush? reliefBrush = null; + float bestHillCpu = 0f; + foreach (var b in _main.Session.State.Terrain.Brushes) + { + if (b.Kind == TerrainBrushKind.Mesa || (b.Kind == TerrainBrushKind.DuneRidge && b.HeightDelta > 0f)) + { + float h = _main.Session.State.Terrain.SampleHeight(b.X, b.Z); + if (h > bestHillCpu) + { + bestHillCpu = h; + reliefBrush = b; + } + } + } + + Check(reliefBrush.HasValue && bestHillCpu > 10f, "Expected brushed terrain relief > 10m in generated arena"); + if (reliefBrush.HasValue) + { + var rb = reliefBrush.Value; + bool hasGpuHill = _main.Terrain.TrySampleBakedHeight(rb.X, rb.Z, out float gpuHill); + Check(hasGpuHill, "Expected GPU HeightViewport readback to succeed on brushed relief hill/mesa"); + if (hasGpuHill) + { + float hillErr = MathF.Abs(gpuHill - bestHillCpu); + GD.Print($"SMOKE INFO: Relief {rb.Kind} at ({rb.X:F1},{rb.Z:F1}) cpu={bestHillCpu:F4}m gpu={gpuHill:F4}m err={hillErr:F4}m"); + Check(gpuHill > 10f, $"Expected GPU baked hill height > 10m, got {gpuHill:F4}m"); + Check(hillErr <= 0.20f, + $"Expected GPU hill height ({gpuHill:F4}m) to match CPU ({bestHillCpu:F4}m) within 0.20m"); + } + } + + // Verify tile seam continuity across interior tile boundaries (< 0.01m) + float maxSeamErr = 0f; + float[] boundaries = { -192f, 0f, 192f }; + float[] offsets = { -280f, -96f, 96f, 280f }; + foreach (float bCoord in boundaries) + { + foreach (float ortho in offsets) + { + if (_main.Terrain.TrySampleBakedHeight(bCoord - 0.0001f, ortho, out float hL) && + _main.Terrain.TrySampleBakedHeight(bCoord + 0.0001f, ortho, out float hR)) + { + maxSeamErr = MathF.Max(maxSeamErr, MathF.Abs(hL - hR)); + } + if (_main.Terrain.TrySampleBakedHeight(ortho, bCoord - 0.0001f, out float hD) && + _main.Terrain.TrySampleBakedHeight(ortho, bCoord + 0.0001f, out float hU)) + { + maxSeamErr = MathF.Max(maxSeamErr, MathF.Abs(hD - hU)); + } + } + } + GD.Print($"SMOKE INFO: Max tile seam error={maxSeamErr:F5}m"); + Check(maxSeamErr < 0.01f, $"Expected tile seam error < 0.01m, got {maxSeamErr:F5}m"); + } + + _main.Session.State.Terrain.StampCrater(-96f, -96f, radius: 5f, depth: 1.4f); + _main.Terrain.Sync(_main.Session.State.Terrain); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + float cpuAfter = _main.Session.State.Terrain.SampleHeight(-96f, -96f); + Check(cpuAfter < cpuBefore - 0.8f, + $"Expected CPU terrain height to drop after crater stamp (before {cpuBefore:F2}m, after {cpuAfter:F2}m)"); + Check(_main.Terrain.DirtyRebakes == rebakesBefore + 1, + $"Expected 1 dirty tile rebake from isolated crater stamp, got {_main.Terrain.DirtyRebakes - rebakesBefore}"); + + if (!isHeadless) + { + bool hasGpuAfter = _main.Terrain.TrySampleBakedHeight(-96f, -96f, out float gpuAfter); + Check(hasGpuAfter, "Expected GPU HeightViewport readback to succeed after crater"); + if (hasGpuAfter) + { + float afterErr = MathF.Abs(gpuAfter - cpuAfter); + GD.Print($"SMOKE INFO: Crater-site post-stamp cpu={cpuAfter:F4}m gpu={gpuAfter:F4}m err={afterErr:F4}m"); + Check(afterErr <= 0.20f, + $"Expected baked GPU height ({gpuAfter:F4}m) to match CPU height ({cpuAfter:F4}m) after crater within 0.20m"); + Check(gpuAfter < gpuBefore - 0.8f, + $"Expected baked GPU height to drop after crater (before {gpuBefore:F4}m, after {gpuAfter:F4}m)"); + } + } + + _main.SetPhysicsProcess(true); + + await VerifyHudAndShadersAsync(isHeadless); + await VerifyCut3bVehiclesAndMechanismsAsync(); + await MaybeCapturePreviewAsync(isHeadless); + await VerifyMaxLoadPaladinGarageAsync(); + } + + private async Task VerifyHudAndShadersAsync(bool isHeadless) + { + var invShader = _main.Hud.Schematic.ShaderMaterial.Shader; + Check(invShader is not null && !string.IsNullOrWhiteSpace(invShader.Code), + "inventory_grid.gdshader failed to load"); + + int chromeCount = 0; + foreach (var mat in _main.Hud.GetChromeMaterials()) + { + chromeCount++; + Check(mat.Shader is not null && !string.IsNullOrWhiteSpace(mat.Shader.Code), + $"panel_chrome.gdshader failed to load on HUD panel #{chromeCount}"); + } + Check(chromeCount == 5, $"Expected 5 ChromePanel materials on HUD, got {chromeCount}"); + + // Pack a real Ironclad chassis with mounted modules, thermal gradient, stripped cell, and active hit-pulse + var testGrid = new ChassisGrid(Catalog.Ironclad); + Check(testGrid.TryMount(Catalog.Recoilless, "hp.weapon.main"), "Expected Recoilless to mount on hp.weapon.main"); + Check(testGrid.TryMount(Catalog.Mg762, "hp.weapon.coax"), "Expected Mg762 to mount on hp.weapon.coax"); + Check(testGrid.TryMount(Catalog.TurboCore, "hp.engine.rear"), "Expected TurboCore to mount on hp.engine.rear"); + Check(testGrid.TryMount(Catalog.CopperRad, "hp.radiator.l"), "Expected CopperRad to mount on hp.radiator.l"); + Check(testGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front"), "Expected WeldedPlate to mount on hp.armor.front"); + testGrid.InjectHardpointHeat("hp.engine.rear", 1800f); + testGrid.InjectHardpointHeat("hp.weapon.main", 900f); + testGrid.StepHeat(0.25f); + testGrid.Armor[0, 0] = 0f; // stripped armor cell + + var schematic = _main.Hud.Schematic; + schematic.SetGrid(testGrid); + schematic.TriggerHitPulse(1, 1, 1f); + + // Hit-testing verification: center of cell (1, 1) must map to (1, 1) and hardpoint "hp.weapon.main" + schematic.ComputeCellLayout(out float cellSize, out Vector2 origin); + Check(cellSize > 10f, $"Expected InventoryGridControl cellSize > 10px, got {cellSize:F2}"); + Vector2 probePos = origin + new Vector2(1.5f * cellSize, 1.5f * cellSize); + bool hitCell = schematic.TryGetCellAt(probePos, out var mappedCell); + Check(hitCell && mappedCell == new Vector2I(1, 1), + $"Expected TryGetCellAt to map center of (1,1) to (1,1), got hit={hitCell} cell={mappedCell}"); + var mappedHp = schematic.GetHardpointAt(1, 1); + Check(mappedHp is { Id: "hp.weapon.main" }, + $"Expected GetHardpointAt(1,1) to return hp.weapon.main, got {mappedHp?.Id ?? "null"}"); + + // Toggle thermal mode off -> on -> off + _main.Hud.SetThermalMode(true, instant: true); + Check(_main.Hud.ThermalMode && MathF.Abs(schematic.ThermalBlend - 1f) < 0.01f, + "Expected ThermalMode to activate immediately"); + _main.Hud.SetThermalMode(false, instant: true); + Check(!_main.Hud.ThermalMode && MathF.Abs(schematic.ThermalBlend) < 0.01f, + "Expected ThermalMode to deactivate immediately"); + + // Regression check (Finding 3): same-dimension SwapChassis updates _hardpointLookup and clears hover state + schematic._GuiInput(new InputEventMouseMotion { Position = probePos }); + Check(schematic.HoveredCell == new Vector2I(1, 1) && schematic.HoveredHardpoint is { Id: "hp.weapon.main" }, + $"Expected hover on (1,1)/hp.weapon.main before SwapChassis, got cell={schematic.HoveredCell} hp={schematic.HoveredHardpoint?.Id ?? "null"}"); + + bool hoverResetEmitted = false; + void OnSwapHoverChanged(Vector2I? cell, HardpointSpec? hp) + { + if (cell is null && hp is null) + { + hoverResetEmitted = true; + } + } + schematic.HoverChanged += OnSwapHoverChanged; + var altTankSpec = Catalog.Ironclad with + { + Id = "ironclad_alt", + Hardpoints = new[] + { + new HardpointSpec("wpn_swapped", HardpointKind.Weapon, 1, 1, 2, 2, 18f) + } + }; + testGrid.SwapChassis(altTankSpec); + schematic.SetGrid(testGrid); + schematic.HoverChanged -= OnSwapHoverChanged; + + Check(schematic.GetHardpointAt(1, 1) is { Id: "wpn_swapped" }, + $"Expected GetHardpointAt(1,1) to update to wpn_swapped after same-dimension SwapChassis, got {schematic.GetHardpointAt(1, 1)?.Id ?? "null"}"); + Check(schematic.GetHardpointAt(0, 1) is null, + $"Expected old hardpoint hp.weapon.coax at (0,1) to clear after SwapChassis, got {schematic.GetHardpointAt(0, 1)?.Id ?? "null"}"); + Check(schematic.HoveredCell is null && schematic.HoveredHardpoint is null && hoverResetEmitted, + $"Expected SwapChassis to clear hover and emit HoverChanged(null, null), cell={schematic.HoveredCell} emitted={hoverResetEmitted}"); + + // Re-seed Ironclad grid for GPU tests below + testGrid = new ChassisGrid(Catalog.Ironclad); + Check(testGrid.TryMount(Catalog.Recoilless, "hp.weapon.main"), "Expected Recoilless to remount on hp.weapon.main"); + Check(testGrid.TryMount(Catalog.Mg762, "hp.weapon.coax"), "Expected Mg762 to remount on hp.weapon.coax"); + Check(testGrid.TryMount(Catalog.TurboCore, "hp.engine.rear"), "Expected TurboCore to remount on hp.engine.rear"); + Check(testGrid.TryMount(Catalog.CopperRad, "hp.radiator.l"), "Expected CopperRad to remount on hp.radiator.l"); + Check(testGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front"), "Expected WeldedPlate to remount on hp.armor.front"); + testGrid.InjectHardpointHeat("hp.engine.rear", 1800f); + testGrid.InjectHardpointHeat("hp.weapon.main", 900f); + testGrid.StepHeat(0.25f); + testGrid.Armor[0, 0] = 0f; + + // Restore live player grid to HUD and verify layout has no overlaps or clipping + _main.Hud.Sync(_main.Session); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Vector2 vpSize = GetViewport().GetVisibleRect().Size; + Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Compact HUD panels overlapped or clipped at {vpSize}"); + _main.Hud.ToggleGarage(); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Garage HUD panels overlapped or clipped at {vpSize}"); + _main.Hud.ToggleGarage(); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + if (isHeadless) + { + return; + } + + // GPU verification on OpenGL 3.3: render isolated InventoryGridControl (tactical + thermal) & panel_chrome.gdshader + var gridVp = new SubViewport + { + Size = new Vector2I(240, 240), + TransparentBg = true, + RenderTargetUpdateMode = SubViewport.UpdateMode.Always + }; + var vpGrid = new InventoryGridControl + { + Size = new Vector2(240f, 240f), + CustomMinimumSize = new Vector2(240f, 240f) + }; + gridVp.AddChild(vpGrid); + AddChild(gridVp); + + vpGrid.SetGrid(testGrid); + vpGrid.TriggerHitPulse(1, 1, 1f); + vpGrid.SetThermalInstant(false); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var tacticalImg = gridVp.GetTexture().GetImage(); + int tacticalOpaque = CountNonZeroAlphaPixels(tacticalImg, 0.08f); + GD.Print($"SMOKE INFO: InventoryGrid GPU tactical opaque pixels={tacticalOpaque}"); + Check(tacticalOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid tactical shader, got {tacticalOpaque}"); + + vpGrid.SetThermalInstant(true); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var thermalImg = gridVp.GetTexture().GetImage(); + int thermalOpaque = CountNonZeroAlphaPixels(thermalImg, 0.08f); + int modeDiff = CountDifferentPixels(tacticalImg, thermalImg, 0.05f); + GD.Print($"SMOKE INFO: InventoryGrid GPU thermal opaque={thermalOpaque}, diff vs tactical={modeDiff}"); + Check(thermalOpaque > 4000, $"Expected > 4000 rendered pixels from InventoryGrid thermal shader, got {thermalOpaque}"); + Check(modeDiff > 500, $"Expected thermal conduit toggle to visibly change > 500 pixels, got {modeDiff}"); + + // Finding 2 GPU check: overheated (350C+, thermal_mode = 1.0f) must obey blend_premul_alpha (out_rgb <= out_a) + testGrid.InjectHardpointHeat("hp.engine.rear", 45000f); + testGrid.InjectHardpointHeat("hp.weapon.main", 25000f); + testGrid.StepHeat(0.05f); + float hotTemp = testGrid.Temperature[1, 3]; + Check(hotTemp >= 350f, $"Expected overheated cell >= 350C for premul test, got {hotTemp:F1}C"); + vpGrid.SetGrid(testGrid); + vpGrid.SetThermalInstant(true); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var overheatImg = gridVp.GetTexture().GetImage(); + int premulViolations = CountPremulViolations(overheatImg, 0.01f); + GD.Print($"SMOKE INFO: InventoryGrid GPU overheat ({hotTemp:F1}C) premul violations={premulViolations}"); + Check(premulViolations == 0, $"Expected 0 blend_premul_alpha violations (max(RGB) > A + 0.01) on overheated grid, got {premulViolations}"); + + // Finding 1 GPU check: asymmetric Raptor chassis with thermal_mode = 1.0f must leave 0 lit pixels in inactive cell holes + var raptorGrid = new ChassisGrid(Catalog.Raptor); + Check(raptorGrid.TryMount(Catalog.CopperRad, "hp.radiator.sh_l"), "Expected CopperRad on Raptor hp.radiator.sh_l"); + Check(raptorGrid.TryMount(Catalog.CopperRad, "hp.radiator.sh_r"), "Expected CopperRad on Raptor hp.radiator.sh_r"); + Check(raptorGrid.TryMount(Catalog.Autocannon, "hp.weapon.arm_l"), "Expected Autocannon on Raptor hp.weapon.arm_l"); + Check(raptorGrid.TryMount(Catalog.TurboCore, "hp.engine.chest"), "Expected TurboCore on Raptor hp.engine.chest"); + Check(raptorGrid.TryMount(Catalog.Autocannon, "hp.weapon.arm_r"), "Expected Autocannon on Raptor hp.weapon.arm_r"); + raptorGrid.InjectHardpointHeat("hp.engine.chest", 1800f); + raptorGrid.StepHeat(0.25f); + + vpGrid.SetGrid(raptorGrid); + vpGrid.SetThermalInstant(true); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var raptorImg = gridVp.GetTexture().GetImage(); + int raptorHoleScanned = 0; + int raptorHoleLit = 0; + int rw = raptorImg.GetWidth(); + int rh = raptorImg.GetHeight(); + for (int py = 0; py < rh; py++) + { + for (int px = 0; px < rw; px++) + { + if (vpGrid.TryGetCellAt(new Vector2(px + 0.5f, py + 0.5f), out var cell) && !Catalog.Raptor.IsActive(cell.X, cell.Y)) + { + raptorHoleScanned++; + Color c = raptorImg.GetPixel(px, py); + if (MathF.Max(MathF.Max(c.R, c.G), MathF.Max(c.B, c.A)) > 0.001f) + { + raptorHoleLit++; + } + } + } + } + GD.Print($"SMOKE INFO: Asymmetric Raptor hole lit pixels={raptorHoleLit} (scanned {raptorHoleScanned} hole px)"); + Check(raptorHoleScanned > 1000, $"Expected > 1000 inactive hole pixels scanned on Raptor, got {raptorHoleScanned}"); + Check(raptorHoleLit == 0, $"Expected 0 lit/opaque pixels in inactive Raptor cell holes, got {raptorHoleLit}"); + + gridVp.QueueFree(); + + // GPU verification for panel_chrome.gdshader + var chromeVp = new SubViewport + { + Size = new Vector2I(240, 120), + TransparentBg = true, + RenderTargetUpdateMode = SubViewport.UpdateMode.Always + }; + var chromeShader = GD.Load("res://panel_chrome.gdshader"); + var chromeMat = new ShaderMaterial { Shader = chromeShader }; + chromeMat.SetShaderParameter("rect_size", new Vector2(240f, 120f)); + chromeMat.SetShaderParameter("accent_color", Color.FromHtml("#e08a4a")); + var chromeImgTex = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + chromeImgTex.SetPixel(0, 0, Colors.White); + var chromeRect = new TextureRect + { + Texture = ImageTexture.CreateFromImage(chromeImgTex), + Size = new Vector2(240f, 120f), + ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize, + StretchMode = TextureRect.StretchModeEnum.Scale, + Material = chromeMat + }; + chromeVp.AddChild(chromeRect); + AddChild(chromeVp); + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var chromeImg = chromeVp.GetTexture().GetImage(); + int chromeOpaque = CountNonZeroAlphaPixels(chromeImg, 0.08f); + Color cornerPx = chromeImg.GetPixel(2, 2); + Color centerPx = chromeImg.GetPixel(120, 60); + GD.Print($"SMOKE INFO: panel_chrome GPU opaque={chromeOpaque}, corner={cornerPx}, center={centerPx}"); + Check(chromeOpaque > 10000, $"Expected > 10000 rendered pixels from panel_chrome.gdshader, got {chromeOpaque}"); + Check(cornerPx.R > centerPx.R + 0.25f, + $"Expected L-bracket corner pixel ({cornerPx}) to be accented brighter than panel center ({centerPx})"); + + chromeVp.QueueFree(); + } + + private async Task MaybeCapturePreviewAsync(bool isHeadless) + { + if (isHeadless) return; + + string? previewPath = null; + foreach (string arg in OS.GetCmdlineUserArgs()) + { + const string prefix = "--capture-preview="; + if (arg.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + previewPath = arg[prefix.Length..]; + break; + } + } + + if (string.IsNullOrWhiteSpace(previewPath)) + { + return; + } + + if (!_main.Hud.GarageExpanded) + { + _main.Hud.ToggleGarage(); + } + + // Seed realistic combat telemetry so the preview clearly showcases armor stripping, hit-flash, cargo rack, and thermal heat + var player = _main.Session.State.Player; + var grid = player.Grid; + grid.TryAddCargo(Catalog.TouringPlasma); + grid.TryAddCargo(Catalog.GoldRadiator); + grid.InjectHardpointHeat("hp.engine.rear", 1100f); + grid.InjectHardpointHeat("hp.weapon.roof", 750f); + grid.StepHeat(0.15f); + grid.Armor[0, 0] = 0f; + + // Place two nearby rival contenders cleanly in the desert ahead of the player so the preview shows multiple Brokkr GLBs grounded on terrain + float fwdX = MathF.Sin(_main.CameraYaw); + float fwdZ = MathF.Cos(_main.CameraYaw); + float rightX = -fwdZ; + float rightZ = fwdX; + if (_main.Session.State.Contenders.Count > 2) + { + var r1 = _main.Session.State.Contenders[1]; + if (r1.Alive) + { + _main.Session.SetContenderPose(r1.Id, player.X + fwdX * 19f - rightX * 5.5f, player.Z + fwdZ * 19f - rightZ * 5.5f, _main.CameraYaw + MathF.PI * 0.82f); + } + var r2 = _main.Session.State.Contenders[2]; + if (r2.Alive) + { + _main.Session.SetContenderPose(r2.Id, player.X + fwdX * 26f + rightX * 8.5f, player.Z + fwdZ * 26f + rightZ * 8.5f, _main.CameraYaw - MathF.PI * 0.72f); + } + } + + _main.Arena.Sync(_main.Session, 1.5f, 1f / 60f); + _main.Hud.Sync(_main.Session); + _main.Hud.Schematic.TriggerHitPulse(1, 0, 0.9f); + + if (_main.Arena.GetContenderVisual(player.Id) is { } pVis) + { + Vector3 vehFwd = pVis.Root.GlobalTransform.Basis.Z.Normalized(); + if (pVis.GetMountedGearNode("hp.weapon.roof") is { } roofGun) + { + Vector3 gunFwd = roofGun.GlobalTransform.Basis.Z.Normalized(); + GD.Print($"SMOKE INFO: Preview Jackal yaw={player.Yaw:F3} vehFwd={vehFwd} roofGunFwd={gunFwd} dot={vehFwd.Dot(gunFwd):F3}"); + } + } + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var frameImg = GetViewport().GetTexture().GetImage(); + var err = frameImg.SavePng(previewPath); + GD.Print($"SMOKE INFO: Saved preview screenshot ({frameImg.GetWidth()}x{frameImg.GetHeight()}) to {previewPath} (err={err})"); + Check(err == Error.Ok, $"Failed to save preview screenshot to {previewPath}: {err}"); + } + + private async Task VerifyCut3bVehiclesAndMechanismsAsync() + { + var cache = _main.Arena.AssetCache; + cache.PreloadAll(); + + Check(cache.Vehicles.Count == 15, $"Expected 15 cached vehicle GLBs, got {cache.Vehicles.Count}"); + Check(cache.Gear.Count == 6, $"Expected 6 cached gear GLBs, got {cache.Gear.Count}"); + + // 1. All 15 vehicles bind 100% of hardpoint AnchorIds and attach/unmount gear cleanly + foreach (var spec in Catalog.AllChassis) + { + var pkg = Catalog.TryGetPackage(spec.Id); + Check(pkg is not null, $"Missing VehiclePackage for '{spec.Id}'"); + if (pkg is null) continue; + + var vis = VehicleVisualInstance.Create(cache, spec.Id, VehicleVisualRole.Player); + Check(vis.BoundHardpointCount == spec.Hardpoints.Length, + $"Expected {spec.Hardpoints.Length} bound hardpoints on '{spec.Id}', got {vis.BoundHardpointCount}"); + Check(vis.Joints.Count == pkg.Joints.Count, + $"Expected {pkg.Joints.Count} bound joints on '{spec.Id}', got {vis.Joints.Count}"); + Check(MathF.Abs(vis.Template.MinY) < 0.05f, + $"Expected grounded GLB MinY ~ 0 on '{spec.Id}', got {vis.Template.MinY:F4}"); + + var grid = Catalog.CreateWithDefaultLoadout(spec); + vis.SyncMountedGear(grid); + int mountedMeshes = 0; + foreach (var m in grid.Mounted) + { + var gNode = vis.GetMountedGearNode(m.HardpointId); + if (gNode is not null && CountMeshInstances(gNode) > 0) + { + mountedMeshes++; + if (m.Spec.Kind == HardpointKind.Weapon) + { + (string frontPart, string rearPart) = m.Spec.Id switch + { + "mg_762" or "pd_flak" => ("barrel_inner", "receiver"), + "autocannon" or "flak" => ("muzzle_brake_L", "gun_housing"), + "recoilless" => ("sight_tube", "breech_band"), + _ => ("condenser_ring_2", "ivory_cowl") + }; + Vector3? frontC = ComputeSubtreeVertexCentroidInAncestor(gNode, vis.ModelRoot, frontPart); + Vector3? rearC = ComputeSubtreeVertexCentroidInAncestor(gNode, vis.ModelRoot, rearPart); + Check(frontC.HasValue && rearC.HasValue, + $"Missing weapon submeshes '{frontPart}'/'{rearPart}' on '{spec.Id}.{m.HardpointId}' ({m.Spec.Id})"); + if (frontC.HasValue && rearC.HasValue) + { + Vector3 muzzleDir = (frontC.Value - rearC.Value).Normalized(); + if (m.Spec.Id == "recoilless") + { + GD.Print($"SMOKE INFO: recoilless {spec.Id}.{m.HardpointId} sight_tube={frontC.Value} breech={rearC.Value} dir={muzzleDir}"); + Check(frontC.Value.Z > rearC.Value.Z + 0.20f, + $"Expected recoilless sight_tube (+Z) ahead of breech_band on '{spec.Id}.{m.HardpointId}', got sight={frontC.Value}, breech={rearC.Value}"); + } + Check(muzzleDir.Z > 0.75f, + $"Expected weapon '{m.Spec.Id}' on '{spec.Id}.{m.HardpointId}' mesh geometry to point forward (+Z), got dir={muzzleDir}"); + } + } + } + } + Check(mountedMeshes == grid.Mounted.Count && mountedMeshes > 0, + $"Expected all {grid.Mounted.Count} default modules on '{spec.Id}' to attach visible gear meshes, got {mountedMeshes}"); + + // Unmount first module and confirm gear node is removed cleanly + if (grid.Mounted.Count > 0) + { + string removedHp = grid.Mounted[0].HardpointId; + grid.Mounted.RemoveAt(0); + vis.SyncMountedGear(grid); + Check(vis.GetMountedGearNode(removedHp) is null, + $"Expected gear node on '{spec.Id}.{removedHp}' to be removed after unmount"); + } + + vis.Root.QueueFree(); + } + + // 2. Rig animator produces real non-zero transforms (> 0.001 rad) with zero NaNs across all mobility archetypes + VerifyRigMotion(cache, "jackal", "joint.wheel_fl", + new VehicleRigDriveInput(new Vector3(0f, 0f, 14f), 0f, 0f, 0f, -1f, 1f, 0f, 1f, 1f / 60f), + minRotRad: 0.001f); + VerifyRigMotion(cache, "hornet", "joint.rotor_l", + new VehicleRigDriveInput(new Vector3(0f, 0f, 10f), 0f, 0f, 0f, 0f, 1f, 1f, 1f, 1f / 60f), + minRotRad: 0.001f); + VerifyRigMotion(cache, "anvil", "joint.turret_yaw", + new VehicleRigDriveInput(Vector3.Zero, 0f, 0.85f, 0f, 0f, 0f, 0f, 1f, 1f / 60f), + minRotRad: 0.001f); + VerifyRigMotion(cache, "manticore", "joint.tail_yaw", + new VehicleRigDriveInput(new Vector3(0f, 0f, 6f), 0f, 0.70f, 18f, 0f, 0.8f, 0f, 1f, 1f / 60f), + minRotRad: 0.001f); + + // Breaker: verify oleo strut slide + scissor torque links + recess ram aiming + { + var breakerVis = VehicleVisualInstance.Create(cache, "breaker", VehicleVisualRole.Player); + Node3D? oleo = breakerVis.GetNamedNode("LegL.Oleo"); + Node3D? scissorUp = breakerVis.GetNamedNode("LegL.TorqueUp"); + Node3D? ram0 = breakerVis.GetNamedNode("LegL.RecessRam0"); + Check(oleo is not null && scissorUp is not null && ram0 is not null, + "Expected Breaker LegL.Oleo, LegL.TorqueUp, and LegL.RecessRam0 nodes to resolve"); + if (oleo is not null && scissorUp is not null && ram0 is not null) + { + Transform3D oleo0 = oleo.Transform; + Transform3D sc0 = scissorUp.Transform; + Transform3D ramRest = ram0.Transform; + var inp1 = new VehicleRigDriveInput(new Vector3(0f, -6f, 8f), 0f, 0.4f, 10f, 0f, 1f, 0f, 1f, 1f / 60f); + for (int s = 0; s < 10; s++) VehicleRigAnimator.Update(breakerVis, in inp1, Basis.Identity); + var inp2 = new VehicleRigDriveInput(new Vector3(0f, 3f, 8f), 0f, 0.4f, 10f, 0f, 1f, 0f, 1f, 1f / 60f); + for (int s = 0; s < 10; s++) VehicleRigAnimator.Update(breakerVis, in inp2, Basis.Identity); + + float oleoDelta = (oleo.Transform.Origin - oleo0.Origin).Length(); + float scDelta = sc0.Basis.GetRotationQuaternion().AngleTo(scissorUp.Transform.Basis.GetRotationQuaternion()); + float ramDelta = ramRest.Basis.GetRotationQuaternion().AngleTo(ram0.Transform.Basis.GetRotationQuaternion()); + GD.Print($"SMOKE INFO: Breaker mech deltas oleo={oleoDelta:F4}m scissor={scDelta:F4}rad ram={ramDelta:F4}rad"); + Check(oleoDelta > 0.0005f && !HasNaN(oleo.Transform), $"Expected Breaker LegL.Oleo motion > 0.0005m, got {oleoDelta:F5}"); + Check(scDelta > 0.001f && !HasNaN(scissorUp.Transform), $"Expected Breaker LegL.TorqueUp scissor rotation > 0.001rad, got {scDelta:F5}"); + Check(ramDelta > 0.001f && !HasNaN(ram0.Transform), $"Expected Breaker LegL.RecessRam0 aim rotation > 0.001rad, got {ramDelta:F5}"); + } + breakerVis.Root.QueueFree(); + } + + // 3. Part-by-cell armor detachment + hardpoint gear shear into DebrisSystem + { + var debris = new DebrisSystem { Name = "SmokeDebrisTest" }; + AddChild(debris); + var anvilGrid = Catalog.CreateWithDefaultLoadout(Catalog.Anvil); + var anvilVis = VehicleVisualInstance.Create(cache, "anvil", VehicleVisualRole.Player); + AddChild(anvilVis.Root); + anvilVis.SyncMountedGear(anvilGrid); + anvilVis.SyncDamageAndHeat(anvilGrid, debris, Vector3.Zero); + Check(debris.ActiveCount == 0, $"Expected 0 debris before armor strip, got {debris.ActiveCount}"); + + // Pick a cell that has detachable armor/shroud plates + int targetCx = -1, targetCy = -1; + for (int cy = 0; cy < anvilGrid.Spec.Height && targetCx < 0; cy++) + { + for (int cx = 0; cx < anvilGrid.Spec.Width; cx++) + { + if (anvilVis.CountDetachablePartsForCell(cx, cy) > 0) + { + targetCx = cx; + targetCy = cy; + break; + } + } + } + Check(targetCx >= 0, "Expected Anvil to have >= 1 cell with detachable armor/shroud parts"); + + // Strip that armor cell AND strip weapon hardpoint hp.weapon.siege_l + if (targetCx >= 0) + { + anvilGrid.Armor[targetCx, targetCy] = 0f; + } + var siegeHp = anvilGrid.FindHardpoint("hp.weapon.siege_l")!; + for (int dy = 0; dy < siegeHp.Height; dy++) + { + for (int dx = 0; dx < siegeHp.Width; dx++) + { + anvilGrid.Armor[siegeHp.X + dx, siegeHp.Y + dy] = 0f; + } + } + + anvilVis.SyncDamageAndHeat(anvilGrid, debris, new Vector3(2f, 0f, 4f)); + Check(debris.ActiveCount >= 2, + $"Expected >= 2 debris pieces (armor plate + sheared weapon gear), got {debris.ActiveCount}"); + Check(anvilVis.GetMountedGearNode("hp.weapon.siege_l") is null, + "Expected hp.weapon.siege_l gear to shear off when hardpoint becomes non-operational"); + + if (debris.GetChildCount() > 0 && debris.GetChild(0) is Node3D firstPiece) + { + Vector3 p0 = firstPiece.Position; + for (int s = 0; s < 25; s++) + { + debris.Step(1f / 60f, _main.Session.State.Terrain); + } + float moved = firstPiece.Position.DistanceTo(p0); + Check(moved > 0.1f && !HasNaN(firstPiece.Transform), + $"Expected debris piece to travel/fall > 0.1m under blast + gravity, got {moved:F3}m"); + } + + anvilVis.Root.QueueFree(); + debris.QueueFree(); + } + + // 4. Full Paladin hull + gear strip detaches every merged cell armor chunk + mounted gear under 256 cap + { + var debris = new DebrisSystem { Name = "SmokePaladinDebrisTest" }; + AddChild(debris); + var palGrid = Catalog.CreateWithDefaultLoadout(Catalog.Paladin); + var palVis = VehicleVisualInstance.Create(cache, "paladin", VehicleVisualRole.Player); + AddChild(palVis.Root); + palVis.SyncMountedGear(palGrid); + + int activeCellCount = 0; + int expectedCellChunks = 0; + for (int cy = 0; cy < palGrid.Spec.Height; cy++) + { + for (int cx = 0; cx < palGrid.Spec.Width; cx++) + { + if (palGrid.Spec.IsActive(cx, cy)) + { + activeCellCount++; + expectedCellChunks += palVis.CountDetachablePartsForCell(cx, cy); + } + palGrid.Armor[cx, cy] = 0f; + } + } + int expectedTotal = expectedCellChunks + palGrid.Mounted.Count; + palVis.SyncDamageAndHeat(palGrid, debris, new Vector3(1f, 0f, 3f)); + GD.Print($"SMOKE INFO: Full Paladin strip debris.ActiveCount={debris.ActiveCount} (activeCells={activeCellCount}, cellChunks={expectedCellChunks}, mounted={palGrid.Mounted.Count})"); + Check(debris.ActiveCount >= activeCellCount && debris.ActiveCount == expectedTotal && debris.ActiveCount <= 256, + $"Expected full Paladin strip to detach {expectedTotal} (>= {activeCellCount} active cells) pieces under 256 cap, got {debris.ActiveCount}"); + palVis.Root.QueueFree(); + debris.QueueFree(); + } + + // 5. All 15 ChassisDrop salvage wrecks ground within 0.05m of terrain & PickedUp frees drop nodes cleanly + { + var drops = _main.Session.State.GroundDrops; + int baseCount = drops.Count; + _main.Arena.Sync(_main.Session, 1.0f, 1f / 60f); + int dropNodesBefore = _main.Arena.DropGroupChildCount; + int trackedBefore = _main.Arena.ActiveDropVisualCount; + + int nextId = 90000; + var added = new List(Catalog.AllChassis.Count); + float maxGroundErr = 0f; + for (int i = 0; i < Catalog.AllChassis.Count; i++) + { + var spec = Catalog.AllChassis[i]; + float dx = -80f + i * 11f; + float dz = -40f; + var d = new GroundDrop(nextId++, dx, dz, spec, null); + drops.Add(d); + added.Add(d); + } + + _main.Arena.Sync(_main.Session, 1.0f, 1f / 60f); + Check(_main.Arena.ActiveDropVisualCount == trackedBefore + added.Count, + $"Expected {trackedBefore + added.Count} tracked drop visuals, got {_main.Arena.ActiveDropVisualCount}"); + + for (int i = 0; i < added.Count; i++) + { + var d = added[i]; + Node3D? dropNode = _main.Arena.GetNodeOrNull($"GroundDrops/Drop_{d.Id}"); + Check(dropNode is not null, $"Missing Drop_{d.Id} node for ChassisDrop '{d.Chassis!.Id}'"); + if (dropNode is not null) + { + Node3D? actorNode = dropNode.GetNodeOrNull($"Actor_{d.Chassis!.Id}"); + Check(actorNode is not null, $"Missing Actor_{d.Chassis!.Id} under Drop_{d.Id}"); + if (actorNode is not null) + { + float minWorldY = ComputeSubtreeMinWorldY(actorNode, dropNode.Position.Y); + float terrainY = _main.Session.State.Terrain.SampleHeight(d.X, d.Z); + float err = MathF.Abs(minWorldY - terrainY); + if (err > maxGroundErr) maxGroundErr = err; + Check(err <= 0.05f, + $"ChassisDrop '{d.Chassis!.Id}' buried/floating: minWorldY={minWorldY:F4}m terrainY={terrainY:F4}m err={err:F4}m"); + } + } + } + GD.Print($"SMOKE INFO: ChassisDrop max ground err={maxGroundErr:F4}m across {added.Count} chassis"); + + for (int i = 0; i < added.Count; i++) + { + added[i].PickedUp = true; + } + _main.Arena.Sync(_main.Session, 1.1f, 1f / 60f); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Check(_main.Arena.ActiveDropVisualCount == trackedBefore, + $"Expected picked-up drops removed from _dropVisuals ({trackedBefore}), got {_main.Arena.ActiveDropVisualCount}"); + Check(_main.Arena.DropGroupChildCount == dropNodesBefore, + $"Expected picked-up drop nodes freed from GroundDrops ({dropNodesBefore}), got {_main.Arena.DropGroupChildCount}"); + + drops.RemoveRange(baseCount, added.Count); + } + + // 6. All 7 walkers stay grounded (minVertexY - restMinY >= -0.05m) and swing along +Z/-Z through a full stride cycle + { + var walkerChecks = new (string Id, string? FootNode, string? PelvisNode, bool CheckSagittal)[] + { + ("raptor", "LegL.Cannon", "Pelvis", true), + ("spectre", "LegL.Cannon", "Pelvis", true), + ("manticore", "FootFL", "Hull", true), + ("bastion", "Ankle.fl", "Trunk", true), + ("breaker", "LegL.Foot", "Pelvis", true), + ("paladin", "LegL.Ankle", "Pelvis", true), + ("kestrel", null, null, false), + }; + + foreach (var (wId, footNodeName, pelvisNodeName, checkSagittal) in walkerChecks) + { + var vis = VehicleVisualInstance.Create(cache, wId, VehicleVisualRole.Player); + float restMinY = ComputeSubtreeMinWorldY(vis.ModelRoot, 0f, relativeToModelRoot: true); + float worstRelMinY = float.PositiveInfinity; + float minFootZ = float.PositiveInfinity, maxFootZ = float.NegativeInfinity; + float minFootX = float.PositiveInfinity, maxFootX = float.NegativeInfinity; + Node3D? footNode = footNodeName is not null ? vis.GetNamedNode(footNodeName) : null; + Node3D? pelvisNode = pelvisNodeName is not null ? vis.GetNamedNode(pelvisNodeName) : null; + + var walkInp = new VehicleRigDriveInput( + new Vector3(0f, 0f, 8f), 0f, 0f, 0f, 0f, 1f, 0f, 1f, 0.05f); + + for (int step = 0; step < 48; step++) + { + VehicleRigAnimator.Update(vis, in walkInp, Basis.Identity); + float curMinY = ComputeSubtreeMinWorldY(vis.ModelRoot, 0f, relativeToModelRoot: true); + float relMinY = curMinY - restMinY; + if (relMinY < worstRelMinY) worstRelMinY = relMinY; + Check(!float.IsNaN(curMinY), $"NaN vertex Y on walker '{wId}' step {step}"); + + if (footNode is not null && pelvisNode is not null) + { + Vector3 fPos = TransformPointToAncestor(footNode, pelvisNode, Vector3.Zero); + if (fPos.Z < minFootZ) minFootZ = fPos.Z; + if (fPos.Z > maxFootZ) maxFootZ = fPos.Z; + if (fPos.X < minFootX) minFootX = fPos.X; + if (fPos.X > maxFootX) maxFootX = fPos.X; + } + } + + float zSpan = footNode is not null ? maxFootZ - minFootZ : 0f; + float xSpan = footNode is not null ? maxFootX - minFootX : 0f; + GD.Print($"SMOKE INFO: Walker {wId} stride minFootY={worstRelMinY:F4}m zSpan={zSpan:F3}m xSpan={xSpan:F3}m"); + Check(worstRelMinY >= -0.05f, + $"Walker '{wId}' foot plunged below rest floor: minRelY={worstRelMinY:F4}m"); + if (checkSagittal && footNode is not null) + { + Check(zSpan > 0.12f, + $"Expected walker '{wId}' foot '{footNodeName}' to stride along Z > 0.12m, got {zSpan:F3}m"); + Check(xSpan < 0.03f, + $"Expected walker '{wId}' foot '{footNodeName}' to swing cleanly in sagittal plane (xSpan < 0.03m), got {xSpan:F3}m"); + } + vis.Root.QueueFree(); + } + } + + // 7. VehicleRigAnimator.Update with dt == 0 is a strict no-op unless snap == true + { + var anvilVis = VehicleVisualInstance.Create(cache, "anvil", VehicleVisualRole.Player); + var driveInp = new VehicleRigDriveInput( + new Vector3(0f, 0f, 6f), 0f, 0.2f, 5f, 0.2f, 0.5f, 0f, 1f, 1f / 60f); + for (int s = 0; s < 10; s++) + { + VehicleRigAnimator.Update(anvilVis, in driveInp, Basis.Identity); + } + + var beforeTransforms = new Dictionary(); + foreach (var (jid, j) in anvilVis.Joints) + { + beforeTransforms[jid] = j.Node.Transform; + } + + var zeroDtInp = new VehicleRigDriveInput( + new Vector3(0f, 0f, 12f), 0f, 1.9f, 35f, -1f, 1f, 0f, 1f, 0f); + VehicleRigAnimator.Update(anvilVis, in zeroDtInp, Basis.Identity); + + float maxDelta = 0f; + foreach (var (jid, before) in beforeTransforms) + { + Transform3D after = anvilVis.Joints[jid].Node.Transform; + float dOrigin = (after.Origin - before.Origin).Length(); + float dRot = before.Basis.GetRotationQuaternion().AngleTo(after.Basis.GetRotationQuaternion()); + maxDelta = MathF.Max(maxDelta, MathF.Max(dOrigin, dRot)); + } + + VehicleRigAnimator.Update(anvilVis, in zeroDtInp, Basis.Identity, snap: true); + Transform3D snapped = anvilVis.Joints["joint.turret_yaw"].Node.Transform; + float snapDelta = beforeTransforms["joint.turret_yaw"].Basis.GetRotationQuaternion() + .AngleTo(snapped.Basis.GetRotationQuaternion()); + + GD.Print($"SMOKE INFO: Rig dt=0 maxDelta={maxDelta:F6} snapDelta={snapDelta:F4}rad"); + Check(maxDelta < 1e-6f, $"Expected dt == 0 Update (snap=false) to be a strict no-op, got maxDelta={maxDelta:F6}"); + Check(snapDelta > 0.5f, $"Expected dt == 0 Update (snap=true) to snap turret cleanly, got snapDelta={snapDelta:F4}rad"); + anvilVis.Root.QueueFree(); + } + + // 8. Spectator halo sits >= 0.75m above mounted dorsal gear (including Patron with turbo_core) + { + _main.Arena.Sync(_main.Session, 1.5f, 1f / 60f); + bool sawPatron = false; + foreach (var s in _main.Session.State.Spectators.Spectators) + { + if (!s.Alive) continue; + var vis = _main.Arena.GetSpectatorVisual(s.Id); + float? haloY = _main.Arena.GetSpectatorHaloLocalY(s.Id); + Check(vis is not null && haloY.HasValue, $"Missing spectator visual/halo for spectator #{s.Id}"); + if (vis is not null && haloY.HasValue) + { + float topY = vis.ComputeMountedMaxY(); + float clearance = haloY.Value - topY; + if (s.Tier == SpectatorTier.Patron) + { + sawPatron = true; + GD.Print($"SMOKE INFO: Spectator #{s.Id} ({s.Tier}/{s.Grid.Spec.Id}) mountedMaxY={topY:F3}m haloY={haloY.Value:F3}m clearance={clearance:F3}m"); + } + Check(clearance >= 0.74f, + $"Spectator #{s.Id} ({s.Tier}/{s.Grid.Spec.Id}) halo clearance < 0.74m: topY={topY:F3}m haloY={haloY.Value:F3}m clearance={clearance:F3}m"); + } + } + Check(sawPatron, "Expected at least one alive Patron spectator in arena"); + } + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + } + + private void VerifyRigMotion( + VehicleAssetCache cache, + string vehicleId, + string jointId, + VehicleRigDriveInput input, + float minRotRad) + { + var vis = VehicleVisualInstance.Create(cache, vehicleId, VehicleVisualRole.Player); + Check(vis.Joints.TryGetValue(jointId, out var j), $"Missing joint '{jointId}' on '{vehicleId}'"); + if (j is not null) + { + Transform3D before = j.Node.Transform; + for (int s = 0; s < 20; s++) + { + VehicleRigAnimator.Update(vis, in input, Basis.Identity); + } + Transform3D after = j.Node.Transform; + float deltaRad = before.Basis.GetRotationQuaternion().AngleTo(after.Basis.GetRotationQuaternion()); + GD.Print($"SMOKE INFO: Rig {vehicleId}.{jointId} delta={deltaRad:F4}rad"); + Check(deltaRad > minRotRad && !HasNaN(after), + $"Expected {vehicleId}.{jointId} rotation delta > {minRotRad:F4}rad with zero NaNs, got {deltaRad:F5}"); + } + vis.Root.QueueFree(); + } + + private static int CountMeshInstances(Node cur) + { + int count = cur is MeshInstance3D ? 1 : 0; + for (int i = 0; i < cur.GetChildCount(); i++) + { + count += CountMeshInstances(cur.GetChild(i)); + } + return count; + } + + private static Vector3 TransformPointToAncestor(Node3D node, Node3D ancestor, Vector3 localPt) + { + Transform3D xf = Transform3D.Identity; + for (Node? cur = node; cur is Node3D n3d && cur != ancestor; cur = cur.GetParent()) + { + xf = n3d.Transform * xf; + } + return xf * localPt; + } + + private static Vector3? ComputeSubtreeVertexCentroidInAncestor(Node3D subRoot, Node3D ancestor, string partName) + { + Vector3 sum = Vector3.Zero; + int count = 0; + AccumulatePartCentroidRecursive(subRoot, ancestor, partName, ref sum, ref count); + return count > 0 ? sum / count : null; + } + + private static void AccumulatePartCentroidRecursive( + Node cur, + Node3D ancestor, + string partName, + ref Vector3 sum, + ref int count) + { + if (cur is MeshInstance3D mi && mi.Mesh is { } mesh && + mi.Name.ToString().Equals(partName, StringComparison.OrdinalIgnoreCase)) + { + Transform3D toAnc = Transform3D.Identity; + for (Node? p = mi; p is Node3D n3d && p != ancestor; p = p.GetParent()) + { + toAnc = n3d.Transform * toAnc; + } + int surfCount = mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arrays = mesh.SurfaceGetArrays(s); + if (arrays.Count <= (int)Mesh.ArrayType.Vertex || + arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + sum += toAnc * verts[v]; + count++; + } + } + } + + for (int i = 0; i < cur.GetChildCount(); i++) + { + AccumulatePartCentroidRecursive(cur.GetChild(i), ancestor, partName, ref sum, ref count); + } + } + + private static float ComputeSubtreeMinWorldY(Node3D root, float baseWorldY, bool relativeToModelRoot = false) + { + float minY = float.PositiveInfinity; + if (relativeToModelRoot) + { + Transform3D id = Transform3D.Identity; + for (int i = 0; i < root.GetChildCount(); i++) + { + AccumulateMinYRecursive(root.GetChild(i), id, ref minY); + } + } + else + { + AccumulateMinYRecursive(root, new Transform3D(Basis.Identity, new Vector3(0f, baseWorldY, 0f)), ref minY); + } + return minY; + } + + private static void AccumulateMinYRecursive(Node cur, Transform3D parentXf, ref float minY) + { + Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf; + if (cur is MeshInstance3D mi && mi.Mesh is { } mesh) + { + int surfCount = mesh.GetSurfaceCount(); + for (int s = 0; s < surfCount; s++) + { + var arrays = mesh.SurfaceGetArrays(s); + if (arrays.Count <= (int)Mesh.ArrayType.Vertex || + arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) + { + continue; + } + Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + for (int v = 0; v < verts.Length; v++) + { + float wy = (xf * verts[v]).Y; + if (wy < minY) + { + minY = wy; + } + } + } + } + for (int i = 0; i < cur.GetChildCount(); i++) + { + AccumulateMinYRecursive(cur.GetChild(i), xf, ref minY); + } + } + + private static bool HasNaN(Transform3D t) + { + return !t.Origin.IsFinite() + || !t.Basis.X.IsFinite() + || !t.Basis.Y.IsFinite() + || !t.Basis.Z.IsFinite(); + } + + private async Task VerifyMaxLoadPaladinGarageAsync() + { + var grid = _main.Session.State.Player.Grid; + grid.SwapChassis(Catalog.Paladin); + Check(grid.TryMount(Catalog.TouringPlasma, "hp.weapon.sh_l"), "Expected TouringPlasma on Paladin hp.weapon.sh_l"); + Check(grid.TryMount(Catalog.WeldedPlate, "hp.armor.torso"), "Expected WeldedPlate on Paladin hp.armor.torso"); + Check(grid.TryMount(Catalog.TouringPlasma, "hp.weapon.sh_r"), "Expected TouringPlasma on Paladin hp.weapon.sh_r"); + Check(grid.TryMount(Catalog.GildedLance, "hp.weapon.arm_l"), "Expected GildedLance on Paladin hp.weapon.arm_l"); + Check(grid.TryMount(Catalog.NobleCore, "hp.engine.chest"), "Expected NobleCore on Paladin hp.engine.chest"); + Check(grid.TryMount(Catalog.GildedLance, "hp.weapon.arm_r"), "Expected GildedLance on Paladin hp.weapon.arm_r"); + Check(grid.TryMount(Catalog.GoldRadiator, "hp.radiator.back_l"), "Expected GoldRadiator on Paladin hp.radiator.back_l"); + Check(grid.TryMount(Catalog.WeldedPlate, "hp.armor.legs"), "Expected WeldedPlate on Paladin hp.armor.legs"); + Check(grid.TryMount(Catalog.GoldRadiator, "hp.radiator.back_r"), "Expected GoldRadiator on Paladin hp.radiator.back_r"); + + grid.Cargo.Clear(); + var cargoSpecs = new[] + { + Catalog.TouringPlasma, Catalog.GoldRadiator, Catalog.GildedLance, + Catalog.NobleCore, Catalog.Recoilless, Catalog.Autocannon, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate + }; + for (int i = 0; i < cargoSpecs.Length; i++) + { + Check(grid.TryAddCargo(cargoSpecs[i]), $"Expected cargo slot #{i} ({cargoSpecs[i].Name}) to fit on Paladin"); + } + + if (!_main.Hud.GarageExpanded) + { + _main.Hud.ToggleGarage(); + } + _main.Hud.Sync(_main.Session); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + Vector2 vpSize = GetViewport().GetVisibleRect().Size; + Rect2 blRect = _main.Hud.BottomLeftPanelRect; + Rect2 chyronRect = _main.Hud.ChyronPanelRect; + float chyronGap = chyronRect.Position.X - blRect.End.X; + GD.Print($"SMOKE INFO: Max-load Paladin Garage rect={blRect}, chyron gap={chyronGap:F1}px at {vpSize}"); + + Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Max-load Paladin Garage panels overlapped or clipped at {vpSize}"); + Check(blRect.End.X <= 610f, $"Expected max-load Paladin Garage End.X <= 610px, got {blRect.End.X:F1}"); + Check(!blRect.HasPoint(vpSize * 0.5f), $"Expected max-load Paladin Garage not to cover viewport center {vpSize * 0.5f}, rect={blRect}"); + Check(chyronGap > 80f, $"Expected > 80px breathing room between Garage and Chyron, got {chyronGap:F1}px"); + + _main.Hud.ToggleGarage(); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + } + + private static int CountPremulViolations(Image img, float tolerance) + { + int count = 0; + int w = img.GetWidth(); + int h = img.GetHeight(); + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + Color c = img.GetPixel(x, y); + float maxRgb = MathF.Max(c.R, MathF.Max(c.G, c.B)); + if (maxRgb > c.A + tolerance) + { + count++; + } + } + } + return count; + } + + private static int CountNonZeroAlphaPixels(Image img, float minAlpha) + { + int count = 0; + int w = img.GetWidth(); + int h = img.GetHeight(); + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (img.GetPixel(x, y).A > minAlpha) count++; + } + } + return count; + } + + private static int CountDifferentPixels(Image a, Image b, float threshold) + { + int count = 0; + int w = Math.Min(a.GetWidth(), b.GetWidth()); + int h = Math.Min(a.GetHeight(), b.GetHeight()); + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + Color ca = a.GetPixel(x, y); + Color cb = b.GetPixel(x, y); + float diff = MathF.Abs(ca.R - cb.R) + MathF.Abs(ca.G - cb.G) + MathF.Abs(ca.B - cb.B) + MathF.Abs(ca.A - cb.A); + if (diff > threshold) count++; + } + } + return count; + } + + private void Check(bool condition, string message) + { + if (!condition) + { + _failures.Add(message); + } + } + + private void Finish() + { + if (_done) return; + _done = true; + foreach (var f in _failures) + { + GD.PrintErr("SMOKE FAIL: " + f); + } + GD.Print(_failures.Count == 0 ? "SMOKE PASS" : $"SMOKE FAILED ({_failures.Count})"); + GetTree().Quit(_failures.Count == 0 ? 0 : 1); + } +} diff --git a/client/tests/Smoke.tscn b/client/tests/Smoke.tscn new file mode 100644 index 0000000..d05be64 --- /dev/null +++ b/client/tests/Smoke.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/Smoke.cs" id="1"] + +[node name="Smoke" type="Node"] +script = ExtResource("1") diff --git a/client/tests/VisualProbe.cs b/client/tests/VisualProbe.cs new file mode 100644 index 0000000..05cb784 --- /dev/null +++ b/client/tests/VisualProbe.cs @@ -0,0 +1,553 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using Godot; + +namespace RustToDust.Client.Tests; + +/// +/// Live OpenGL 3.3 (gl_compatibility) visual verification probe for: +/// - Baked COLOR_0 vertex weathering (AO, edge curvature, per-island hash, rest height) +/// - Brokkr 6-layer MechPaint spatial shader (mech_paint.gdshader) + INSTANCE_CUSTOM scorch/heat +/// - 4x4 POM MultiMesh decal atlas + decal_pom.gdshader in 1 draw call +/// Captures a 1280x720 preview PNG to tools/decals/previews/visual_substrate_preview.png and %TEMP%. +/// +public partial class VisualProbe : Node3D +{ + private readonly List _failures = new(); + private readonly List _disposables = new(); + + public override void _Ready() => _ = RunAsync(); + + public override void _ExitTree() + { + foreach (var d in _disposables) + { + d.Dispose(); + } + _disposables.Clear(); + } + + private void Check(bool cond, string msg) + { + if (!cond) + { + _failures.Add(msg); + GD.PushError("VISUAL_PROBE FAIL: " + msg); + } + } + + private async Task RunAsync() + { + int exitCode = 0; + try + { + string repoRoot = Path.GetFullPath(Path.Combine(ProjectSettings.GlobalizePath("res://"), "..")); + string decalsDir = Path.Combine(repoRoot, "assets", "decals"); + string previewRepoPath = Path.Combine(repoRoot, "tools", "decals", "previews", "visual_substrate_preview.png"); + string previewTempPath = Path.Combine(Path.GetTempPath(), "visual_substrate_preview.png"); + + SetupEnvironment(); + + var mechShader = GD.Load("res://mech_paint.gdshader"); + var decalShader = GD.Load("res://decal_pom.gdshader"); + Check(mechShader is not null, "Failed to load res://mech_paint.gdshader"); + Check(decalShader is not null, "Failed to load res://decal_pom.gdshader"); + if (mechShader is null || decalShader is null) + { + Finish(1); + return; + } + + ImageTexture albedoTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_albedo.png")); + ImageTexture normalTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_normal.png")); + ImageTexture ormhTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_ormh.png")); + + var cache = new VehicleAssetCache(); + _disposables.Add(cache); + var paladinTpl = cache.GetOrLoadVehicle("paladin"); + var jackalTpl = cache.GetOrLoadVehicle("jackal"); + + VerifyBakedVertexColors("paladin", paladinTpl.BakedStaticMesh); + VerifyBakedVertexColors("jackal", jackalTpl.BakedStaticMesh); + + // Ground desert pad + var groundMesh = new PlaneMesh { Size = new Vector2(48f, 48f) }; + var groundMat = new StandardMaterial3D + { + AlbedoColor = new Color(0.42f, 0.34f, 0.24f), + Roughness = 0.94f, + Metallic = 0.02f + }; + AddChild(new MeshInstance3D { Name = "DesertPad", Mesh = groundMesh, MaterialOverride = groundMat }); + + // Shared MechPaint ShaderMaterial variants (zero per-hit cloning) + var paladinArmorMat = MakeMechPaintMat(mechShader, new Color(0.306f, 0.341f, 0.251f), metallic: 0.22f, roughness: 0.58f, wear: 1.05f, grime: 0.95f, mud: 1.15f); + var jackalArmorMat = MakeMechPaintMat(mechShader, new Color(0.388f, 0.345f, 0.255f), metallic: 0.20f, roughness: 0.56f, wear: 1.15f, grime: 0.95f, mud: 1.25f, mudTop: 0.95f); + var gunmetalMat = MakeMechPaintMat(mechShader, new Color(0.173f, 0.188f, 0.180f), metallic: 0.78f, roughness: 0.42f, wear: 0.80f, grime: 1.10f, mud: 1.05f); + var copperMat = MakeMechPaintMat(mechShader, new Color(0.612f, 0.353f, 0.204f), metallic: 0.86f, roughness: 0.34f, wear: 0.65f, grime: 0.90f, mud: 0.80f); + var orangeMat = MakeMechPaintMat(mechShader, new Color(0.851f, 0.424f, 0.153f), metallic: 0.18f, roughness: 0.44f, wear: 1.10f, grime: 0.85f, mud: 0.90f); + var markMat = MakeMechPaintMat(mechShader, new Color(0.760f, 0.730f, 0.640f), metallic: 0.10f, roughness: 0.62f, wear: 0.95f, grime: 0.80f, mud: 0.80f); + + // Spawn Paladin (left-center, 3/4 view toward camera) + var paladinMesh = (ArrayMesh)paladinTpl.BakedStaticMesh.Duplicate(); + ApplyMechPaintSurfaces(paladinMesh, paladinArmorMat, gunmetalMat, copperMat, orangeMat, markMat); + var paladinXf = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(24f)), new Vector3(-2.8f, 0f, -2.4f)); + var paladinMi = new MeshInstance3D + { + Name = "PaladinWeathered", + Mesh = paladinMesh, + Transform = paladinXf + }; + AddChild(paladinMi); + + // Spawn Jackal (right-midground, angled 3/4 toward camera) + var jackalMesh = (ArrayMesh)jackalTpl.BakedStaticMesh.Duplicate(); + ApplyMechPaintSurfaces(jackalMesh, jackalArmorMat, gunmetalMat, copperMat, orangeMat, markMat); + var jackalXf = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(-38f)), new Vector3(3.4f, 0f, 1.2f)); + var jackalMi = new MeshInstance3D + { + Name = "JackalWeathered", + Mesh = jackalMesh, + Transform = jackalXf + }; + AddChild(jackalMi); + + // Foreground angled Armor Showcase Slab (MechPaint via MultiMesh showing clean vs INSTANCE_CUSTOM scorch+heat) + var slabMesh = BuildBeveledShowcaseSlab(3.2f, 1.26f, 0.14f); + var slabMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = slabMesh, + InstanceCount = 2 + }; + var slabXf0 = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(14f)) * new Basis(Vector3.Right, Mathf.DegToRad(-22f)), new Vector3(1.15f, 1.85f, 6.2f)); + var slabXf1 = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(-18f)) * new Basis(Vector3.Right, Mathf.DegToRad(-18f)) * Basis.FromScale(new Vector3(0.45f, 0.55f, 1.0f)), new Vector3(5.35f, 0.85f, 3.8f)); + slabMm.SetInstanceTransform(0, slabXf0); + slabMm.SetInstanceCustomData(0, new Color(0.0f, 0.0f, 0f, 0f)); // clean weathered chest-height plate + slabMm.SetInstanceTransform(1, slabXf1); + slabMm.SetInstanceCustomData(1, new Color(0.90f, 0.48f, 0f, 0f)); // live combat scorch + heat_glow without cloning! + + var slabMmi = new MultiMeshInstance3D + { + Name = "ShowcaseArmorPlates", + Multimesh = slabMm, + MaterialOverride = paladinArmorMat + }; + AddChild(slabMmi); + + // Build 1 single MultiMeshInstance3D batch of POM decals across Paladin, Jackal, and the Showcase Slab + var decalMat = new ShaderMaterial { Shader = decalShader }; + decalMat.SetShaderParameter("albedo_tex", albedoTex); + decalMat.SetShaderParameter("normal_tex", normalTex); + decalMat.SetShaderParameter("ormh_tex", ormhTex); + decalMat.SetShaderParameter("use_instance_custom", true); + decalMat.SetShaderParameter("default_depth_scale", 0.06f); + decalMat.SetShaderParameter("normal_offset", 0.004f); + + var decalPlacements = new List<(Transform3D Xform, Color Custom)>(); + + // Showcase slab POM decals (close 3/4 grazing angle so 3D depth & hot rims are unmistakable) + AddSlabDecal(decalPlacements, slabXf0, -1.16f, 0.30f, 0.07f, 0.48f, tile: 0, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // louvered vent + AddSlabDecal(decalPlacements, slabXf0, -0.58f, 0.30f, 0.07f, 0.48f, tile: 1, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // bolted hatch + AddSlabDecal(decalPlacements, slabXf0, 0.00f, 0.30f, 0.07f, 0.48f, tile: 3, heat: 0.0f, opacity: 1.0f, depth: 0.080f); // slotted intake grille + AddSlabDecal(decalPlacements, slabXf0, 0.58f, 0.30f, 0.07f, 0.48f, tile: 5, heat: 0.0f, opacity: 1.0f, depth: 0.070f); // welded patch + AddSlabDecal(decalPlacements, slabXf0, 1.16f, 0.30f, 0.07f, 0.46f, tile: 8, heat: 0.0f, opacity: 0.96f, depth: 0.03f); // stencil "03" + + AddSlabDecal(decalPlacements, slabXf0, -1.16f, -0.30f, 0.07f, 0.48f, tile: 6, heat: 0.0f, opacity: 1.0f, depth: 0.085f); // lift-lug pocket + AddSlabDecal(decalPlacements, slabXf0, -0.58f, -0.30f, 0.07f, 0.48f, tile: 7, heat: 0.0f, opacity: 0.96f, depth: 0.04f); // hazard chevron + AddSlabDecal(decalPlacements, slabXf0, 0.00f, -0.30f, 0.07f, 0.50f, tile: 12, heat: 0.95f, opacity: 1.0f, depth: 0.095f); // glowing AP hole + AddSlabDecal(decalPlacements, slabXf0, 0.58f, -0.30f, 0.07f, 0.50f, tile: 13, heat: 0.75f, opacity: 1.0f, depth: 0.085f); // shrapnel gouge + AddSlabDecal(decalPlacements, slabXf0, 1.16f, -0.30f, 0.07f, 0.50f, tile: 14, heat: 0.92f, opacity: 1.0f, depth: 0.090f); // molten plasma crater + + // Raycast flush decals directly onto Paladin armor surfaces + TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-2.6f, 8.2f, 3.0f), new Vector3(0f, -0.05f, -1f), 0.72f, tile: 0, heat: 0.0f, opacity: 1.0f, depth: 0.07f); + TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-1.5f, 8.8f, 3.0f), new Vector3(-0.2f, -0.05f, -1f), 0.65f, tile: 8, heat: 0.0f, opacity: 0.95f, depth: 0.03f); + TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-2.8f, 7.1f, 3.0f), new Vector3(0.05f, 0f, -1f), 0.72f, tile: 12, heat: 0.95f, opacity: 1.0f, depth: 0.09f); + TryAddRayDecal(decalPlacements, paladinMesh, paladinXf, new Vector3(-3.6f, 7.8f, 3.0f), new Vector3(0.25f, 0f, -1f), 0.65f, tile: 10, heat: 0.0f, opacity: 0.95f, depth: 0.03f); + + // Raycast flush decals onto Jackal armor surfaces + TryAddRayDecal(decalPlacements, jackalMesh, jackalXf, new Vector3(3.4f, 3.0f, 1.5f), new Vector3(0f, -1f, 0.1f), 0.55f, tile: 9, heat: 0.0f, opacity: 0.95f, depth: 0.03f); + TryAddRayDecal(decalPlacements, jackalMesh, jackalXf, new Vector3(3.1f, 2.5f, 2.1f), new Vector3(0.2f, -0.8f, -0.5f), 0.50f, tile: 14, heat: 0.85f, opacity: 1.0f, depth: 0.08f); + + var decalQuad = new QuadMesh { Size = Vector2.One }; + var decalMm = new MultiMesh + { + TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseCustomData = true, + Mesh = decalQuad, + InstanceCount = decalPlacements.Count + }; + for (int i = 0; i < decalPlacements.Count; i++) + { + decalMm.SetInstanceTransform(i, decalPlacements[i].Xform); + decalMm.SetInstanceCustomData(i, decalPlacements[i].Custom); + } + var decalMmi = new MultiMeshInstance3D + { + Name = "PomDecalsBatch", + Multimesh = decalMm, + MaterialOverride = decalMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + AddChild(decalMmi); + + // Camera framing full Paladin (head to feet) + Jackal + close grazing showcase slab + var cam = new Camera3D + { + Name = "ProbeCamera", + Current = true, + Fov = 48f, + Near = 0.08f, + Far = 200f + }; + AddChild(cam); + cam.GlobalPosition = new Vector3(2.8f, 4.3f, 13.4f); + cam.LookAt(new Vector3(0.0f, 4.4f, 0.2f), Vector3.Up); + + // Wait several rendered frames so OpenGL 3.3 compiles all shaders and finishes drawing + for (int f = 0; f < 6; f++) + { + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + } + + if (DisplayServer.GetName() != "headless") + { + Image? cap = GetViewport().GetTexture()?.GetImage(); + Check(cap is not null && cap.GetWidth() == 1280 && cap.GetHeight() == 720, + $"Expected 1280x720 viewport capture, got {cap?.GetWidth()}x{cap?.GetHeight()}"); + if (cap is not null) + { + Directory.CreateDirectory(Path.GetDirectoryName(previewRepoPath)!); + cap.SavePng(previewRepoPath); + cap.SavePng(previewTempPath); + GD.Print($"VISUAL_PROBE SAVED: {previewRepoPath}"); + GD.Print($"VISUAL_PROBE SAVED: {previewTempPath}"); + } + } + + double drawCalls = RenderingServer.GetRenderingInfo(RenderingServer.RenderingInfo.TotalDrawCallsInFrame); + GD.Print($"VISUAL_PROBE INFO: renderer={RenderingServer.GetVideoAdapterName()} drawCalls={drawCalls} pomDecals={decalPlacements.Count}"); + Check(_failures.Count == 0, $"Encountered {_failures.Count} failures"); + } + catch (Exception ex) + { + Check(false, ex.ToString()); + } + + exitCode = _failures.Count == 0 ? 0 : 1; + GD.Print(exitCode == 0 ? "VISUAL_PROBE RESULT: PASS" : $"VISUAL_PROBE RESULT: FAIL ({_failures.Count})"); + Finish(exitCode); + } + + private void Finish(int code) + { + GetTree().Quit(code); + } + + private void SetupEnvironment() + { + var sun = new DirectionalLight3D + { + Name = "DesertSun", + LightColor = new Color(1.0f, 0.93f, 0.82f), + LightEnergy = 1.85f, + ShadowEnabled = true, + DirectionalShadowMode = DirectionalLight3D.ShadowMode.Parallel2Splits, + RotationDegrees = new Vector3(-38f, 36f, 0f) + }; + AddChild(sun); + + // Cool oblique fill light so POM recesses & metal rims catch clear specular highlights + var fill = new DirectionalLight3D + { + Name = "SkyFill", + LightColor = new Color(0.68f, 0.80f, 0.98f), + LightEnergy = 0.55f, + ShadowEnabled = false, + RotationDegrees = new Vector3(-25f, -125f, 0f) + }; + AddChild(fill); + + var skyMat = new ProceduralSkyMaterial + { + SkyTopColor = new Color(0.24f, 0.34f, 0.44f), + SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f), + GroundBottomColor = new Color(0.28f, 0.20f, 0.14f), + GroundHorizonColor = new Color(0.68f, 0.48f, 0.32f) + }; + var env = new Godot.Environment + { + BackgroundMode = Godot.Environment.BGMode.Sky, + Sky = new Sky { SkyMaterial = skyMat }, + AmbientLightSource = Godot.Environment.AmbientSource.Sky, + AmbientLightEnergy = 0.65f + }; + AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env }); + } + + private void VerifyBakedVertexColors(string name, ArrayMesh mesh) + { + int surfCount = mesh.GetSurfaceCount(); + bool foundColor = false; + float minR = 1f, maxR = 0f, minG = 1f, maxG = 0f, minB = 1f, maxB = 0f, minA = 1f, maxA = 0f; + int totalVerts = 0; + for (int s = 0; s < surfCount; s++) + { + var arrays = mesh.SurfaceGetArrays(s); + if (arrays.Count > (int)Mesh.ArrayType.Color && + arrays[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) + { + Color[] cols = arrays[(int)Mesh.ArrayType.Color].AsColorArray(); + foundColor = true; + totalVerts += cols.Length; + foreach (Color c in cols) + { + if (c.R < minR) minR = c.R; if (c.R > maxR) maxR = c.R; + if (c.G < minG) minG = c.G; if (c.G > maxG) maxG = c.G; + if (c.B < minB) minB = c.B; if (c.B > maxB) maxB = c.B; + if (c.A < minA) minA = c.A; if (c.A > maxA) maxA = c.A; + } + } + } + GD.Print($"COLOR_0 [{name}]: verts={totalVerts} AO=[{minR:F2},{maxR:F2}] Edge=[{minG:F2},{maxG:F2}] Island=[{minB:F2},{maxB:F2}] Height=[{minA:F2},{maxA:F2}]"); + Check(foundColor && totalVerts > 0, $"{name} missing baked COLOR_0 array"); + Check(minR < 0.35f && maxR > 0.85f, $"{name} AO range too narrow [{minR:F2},{maxR:F2}]"); + Check(maxG > 0.65f, $"{name} Edge curvature max too low ({maxG:F2})"); + Check(maxA - minA > 0.15f, $"{name} Rest height span too small [{minA:F2},{maxA:F2}]"); + } + + private static ImageTexture LoadTextureWithMips(string path) + { + var img = Image.LoadFromFile(path); + if (img is null) + { + throw new FileNotFoundException($"Could not load texture '{path}'", path); + } + img.GenerateMipmaps(); + return ImageTexture.CreateFromImage(img); + } + + private static ShaderMaterial MakeMechPaintMat( + Shader shader, + Color baseColor, + float metallic, + float roughness, + float wear, + float grime, + float mud, + float mudTop = 1.45f) + { + var mat = new ShaderMaterial { Shader = shader }; + mat.SetShaderParameter("base_color", baseColor); + mat.SetShaderParameter("metallic", metallic); + mat.SetShaderParameter("roughness", roughness); + mat.SetShaderParameter("wear", wear); + mat.SetShaderParameter("grime", grime); + mat.SetShaderParameter("mud", mud); + mat.SetShaderParameter("mud_top", mudTop); + return mat; + } + + private static void ApplyMechPaintSurfaces( + ArrayMesh mesh, + ShaderMaterial armorMat, + ShaderMaterial gunmetalMat, + ShaderMaterial copperMat, + ShaderMaterial orangeMat, + ShaderMaterial markMat) + { + int n = mesh.GetSurfaceCount(); + for (int s = 0; s < n; s++) + { + Material? orig = mesh.SurfaceGetMaterial(s); + string mName = (orig?.ResourceName ?? string.Empty).ToLowerInvariant(); + if (mName.Contains("glass") || mName.Contains("lamp") || mName.Contains("glow") || mName.Contains("cyan")) + { + continue; + } + if (mName.Contains("copper")) + { + mesh.SurfaceSetMaterial(s, copperMat); + } + else if (mName.Contains("signal") || mName.Contains("orange")) + { + mesh.SurfaceSetMaterial(s, orangeMat); + } + else if (mName.Contains("mark") || mName.Contains("stencil")) + { + mesh.SurfaceSetMaterial(s, markMat); + } + else if (mName.Contains("gunmetal") || mName.Contains("metal") || mName.Contains("steel") || mName.Contains("socket") || mName.Contains("pit") || mName.Contains("rubber")) + { + mesh.SurfaceSetMaterial(s, gunmetalMat); + } + else + { + mesh.SurfaceSetMaterial(s, armorMat); + } + } + } + + private static ArrayMesh BuildBeveledShowcaseSlab(float w, float h, float d) + { + // Build a subdivided box with baked COLOR_0 (flat faces G=0, sharp edges G=1, AO=0.9, island=0.42) + float hw = w * 0.5f, hh = h * 0.5f, hd = d * 0.5f; + var st = new SurfaceTool(); + st.Begin(Mesh.PrimitiveType.Triangles); + + void AddQuad(Vector3 a, Vector3 b, Vector3 c, Vector3 dPt, Vector3 nrm, float edgeA, float edgeB, float edgeC, float edgeD) + { + void V(Vector3 p, Vector2 uv, float edge) + { + float restH = Math.Clamp((p.Y + 4.2f) / 6.0f, 0f, 1f); + st.SetColor(new Color(0.92f, edge, 0.42f, restH)); + st.SetNormal(nrm); + st.SetUV(uv); + st.AddVertex(p); + } + // Clockwise front-face winding for Godot Spatial cull_back + V(a, new Vector2(0, 1), edgeA); + V(c, new Vector2(1, 0), edgeC); + V(b, new Vector2(1, 1), edgeB); + V(a, new Vector2(0, 1), edgeA); + V(dPt, new Vector2(0, 0), edgeD); + V(c, new Vector2(1, 0), edgeC); + } + + // Front (+Z) subdivided 3x1 so center interior vertices have edge=0 and outer corners have edge=0.95 + float x0 = -hw, x1 = -hw * 0.72f, x2 = hw * 0.72f, x3 = hw; + float y0 = -hh, y1 = -hh * 0.65f, y2 = hh * 0.65f, y3 = hh; + float[] xs = { x0, x1, x2, x3 }; + float[] ys = { y0, y1, y2, y3 }; + float[,] edges = { + { 0.95f, 0.85f, 0.85f, 0.95f }, + { 0.85f, 0.00f, 0.00f, 0.85f }, + { 0.85f, 0.00f, 0.00f, 0.85f }, + { 0.95f, 0.85f, 0.85f, 0.95f }, + }; + for (int iy = 0; iy < 3; iy++) + { + for (int ix = 0; ix < 3; ix++) + { + AddQuad( + new Vector3(xs[ix], ys[iy], hd), + new Vector3(xs[ix + 1], ys[iy], hd), + new Vector3(xs[ix + 1], ys[iy + 1], hd), + new Vector3(xs[ix], ys[iy + 1], hd), + Vector3.Back, + edges[iy, ix], edges[iy, ix + 1], edges[iy + 1, ix + 1], edges[iy + 1, ix]); + } + } + // Back & sides + AddQuad(new Vector3(hw, -hh, -hd), new Vector3(-hw, -hh, -hd), new Vector3(-hw, hh, -hd), new Vector3(hw, hh, -hd), Vector3.Forward, 0.9f, 0.9f, 0.9f, 0.9f); + AddQuad(new Vector3(-hw, hh, hd), new Vector3(hw, hh, hd), new Vector3(hw, hh, -hd), new Vector3(-hw, hh, -hd), Vector3.Up, 0.95f, 0.95f, 0.95f, 0.95f); + AddQuad(new Vector3(-hw, -hh, -hd), new Vector3(hw, -hh, -hd), new Vector3(hw, -hh, hd), new Vector3(-hw, -hh, hd), Vector3.Down, 0.95f, 0.95f, 0.95f, 0.95f); + AddQuad(new Vector3(-hw, -hh, -hd), new Vector3(-hw, -hh, hd), new Vector3(-hw, hh, hd), new Vector3(-hw, hh, -hd), Vector3.Left, 0.95f, 0.95f, 0.95f, 0.95f); + AddQuad(new Vector3(hw, -hh, hd), new Vector3(hw, -hh, -hd), new Vector3(hw, hh, -hd), new Vector3(hw, hh, hd), Vector3.Right, 0.95f, 0.95f, 0.95f, 0.95f); + st.GenerateTangents(); + return st.Commit(); + } + + private static void AddSlabDecal( + List<(Transform3D, Color)> list, + Transform3D slabXf, + float lx, + float ly, + float lz, + float size, + int tile, + float heat, + float opacity, + float depth) + { + var localXf = new Transform3D(Basis.FromScale(new Vector3(size, size, 1f)), new Vector3(lx, ly, lz)); + list.Add((slabXf * localXf, new Color(tile, heat, opacity, depth))); + } + + private static void TryAddRayDecal( + List<(Transform3D, Color)> list, + ArrayMesh mesh, + Transform3D meshXf, + Vector3 worldOrigin, + Vector3 worldDir, + float size, + int tile, + float heat, + float opacity, + float depth) + { + Transform3D inv = meshXf.AffineInverse(); + Vector3 localOrigin = inv * worldOrigin; + Vector3 localDir = (inv.Basis * worldDir).Normalized(); + + float bestT = float.PositiveInfinity; + Vector3 bestN = Vector3.Back; + + for (int s = 0; s < mesh.GetSurfaceCount(); s++) + { + var arr = mesh.SurfaceGetArrays(s); + if (arr.Count <= (int)Mesh.ArrayType.Vertex) continue; + Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); + int[]? indices = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array + ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() + : null; + int triCount = (indices is not null ? indices.Length : verts.Length) / 3; + for (int t = 0; t < triCount; t++) + { + int i0 = indices is not null ? indices[t * 3] : t * 3; + int i1 = indices is not null ? indices[t * 3 + 1] : t * 3 + 1; + int i2 = indices is not null ? indices[t * 3 + 2] : t * 3 + 2; + Vector3 v0 = verts[i0], v1 = verts[i1], v2 = verts[i2]; + if (RayTriangle(localOrigin, localDir, v0, v1, v2, out float hitT)) + { + if (hitT < bestT) + { + Vector3 fn = (v1 - v0).Cross(v2 - v0); + if (fn.LengthSquared() > 1e-10f) + { + fn = fn.Normalized(); + if (fn.Dot(-localDir) < 0f) fn = -fn; + bestT = hitT; + bestN = fn; + } + } + } + } + } + + if (!float.IsFinite(bestT)) + { + return; + } + + Vector3 worldHit = meshXf * (localOrigin + localDir * bestT); + Vector3 worldN = (meshXf.Basis.Inverse().Transposed() * bestN).Normalized(); + Vector3 upRef = MathF.Abs(worldN.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(worldN).Normalized(); + Vector3 up = worldN.Cross(right).Normalized(); + var basis = new Basis(right * size, up * size, worldN); + list.Add((new Transform3D(basis, worldHit), new Color(tile, heat, opacity, depth))); + } + + private static bool RayTriangle(Vector3 orig, Vector3 dir, Vector3 v0, Vector3 v1, Vector3 v2, out float t) + { + t = 0f; + Vector3 e1 = v1 - v0; + Vector3 e2 = v2 - v0; + Vector3 pvec = dir.Cross(e2); + float det = e1.Dot(pvec); + if (MathF.Abs(det) < 1e-7f) return false; + float invDet = 1f / det; + Vector3 tvec = orig - v0; + float u = tvec.Dot(pvec) * invDet; + if (u < 0f || u > 1f) return false; + Vector3 qvec = tvec.Cross(e1); + float v = dir.Dot(qvec) * invDet; + if (v < 0f || u + v > 1f) return false; + t = e2.Dot(qvec) * invDet; + return t > 0.01f; + } +} diff --git a/client/tests/VisualProbe.tscn b/client/tests/VisualProbe.tscn new file mode 100644 index 0000000..1b39cde --- /dev/null +++ b/client/tests/VisualProbe.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/VisualProbe.cs" id="1"] + +[node name="VisualProbe" type="Node3D"] +script = ExtResource("1") diff --git a/src/RustToDust.Core/Broadcast.cs b/src/RustToDust.Core/Broadcast.cs new file mode 100644 index 0000000..25e3226 --- /dev/null +++ b/src/RustToDust.Core/Broadcast.cs @@ -0,0 +1,79 @@ +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum BroadcastKind + { + MatchStart, + TouristPull, + ExemplarWakeup, + PatronClearance, + ChassisSwap, + QuickBolt, + Overheat, + Elimination, + Victory + } + + public readonly record struct BroadcastLine(float Timestamp, BroadcastKind Kind, string Text); + + public sealed class BroadcastFeed + { + private const int MaxLines = 32; + private readonly List _lines = new(); + + public IReadOnlyList Lines => _lines; + public BroadcastLine? Latest => _lines.Count > 0 ? _lines[_lines.Count - 1] : null; + public long Version { get; private set; } + + public void Emit(float timestamp, BroadcastKind kind, string text) + { + if (_lines.Count >= MaxLines) + { + _lines.RemoveAt(0); + } + _lines.Add(new BroadcastLine(timestamp, kind, text)); + Version++; + } + + public void EmitMatchStart(float timestamp) => + Emit(timestamp, BroadcastKind.MatchStart, + "Imperial Broadcast opens the desert ring. Twelve unvarnished rigs enter for the gallery's amusement."); + + public void EmitTouristPull(float timestamp, int contenderId) => + Emit(timestamp, BroadcastKind.TouristPull, + $"Contender {contenderId + 1:00} fires on a gilded tourist — crude, lucrative, and deeply impolite."); + + public void EmitExemplarWakeup(float timestamp, int contenderId) => + Emit(timestamp, BroadcastKind.ExemplarWakeup, + $"An ornate exemplar accepts the provocation of Contender {contenderId + 1:00}. The gallery hushes."); + + public void EmitPatronClearance(float timestamp, int contenderId) => + Emit(timestamp, BroadcastKind.PatronClearance, + $"Contender {contenderId + 1:00} breaches the perimeter line; ring patrons take clearance to correct their posture."); + + public void EmitChassisSwap(float timestamp, int contenderId, string chassisName) => + Emit(timestamp, BroadcastKind.ChassisSwap, + $"Contender {contenderId + 1:00} sheds a ruin and mounts a {chassisName}. Vulgar improvisation, yet watchable."); + + public void EmitQuickBolt(float timestamp, int contenderId, string moduleName, string hardpointId) => + Emit(timestamp, BroadcastKind.QuickBolt, + $"Contender {contenderId + 1:00} quick-bolts {moduleName} onto {hardpointId} mid-run. Crude fieldcraft, live fire ready."); + + public void EmitOverheat(float timestamp, int contenderId) => + Emit(timestamp, BroadcastKind.Overheat, + $"Contender {contenderId + 1:00} glows past the thermal plateau — the crowd admires the smoke."); + + public void EmitElimination(float timestamp, string killerLabel, string victimLabel, bool bySpectator) + { + string line = bySpectator + ? $"{killerLabel} restores boundary decorum over {victimLabel}. Order keeps its shine." + : $"{killerLabel} performs a decisive eviction on {victimLabel}. The gallery notes the sincerity."; + Emit(timestamp, BroadcastKind.Elimination, line); + } + + public void EmitVictory(float timestamp, int winnerId) => + Emit(timestamp, BroadcastKind.Victory, + $"Contender {winnerId + 1:00} outlasts the dust and the gallery's patience. Broadcast closes with reluctant applause."); + } +} diff --git a/src/RustToDust.Core/Catalog.cs b/src/RustToDust.Core/Catalog.cs new file mode 100644 index 0000000..77a7160 --- /dev/null +++ b/src/RustToDust.Core/Catalog.cs @@ -0,0 +1,494 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RustToDust.Core +{ + public static class Catalog + { + private static readonly Dictionary _packagesById; + private static readonly Dictionary _chassisById; + private static readonly IReadOnlyList _allChassis; + + static Catalog() + { + var loaded = VehicleCatalogLoader.LoadAll(); + _packagesById = new Dictionary(StringComparer.OrdinalIgnoreCase); + _chassisById = new Dictionary(StringComparer.OrdinalIgnoreCase); + var list = new List(loaded.Count); + + foreach (var (pkg, spec) in loaded) + { + _packagesById[pkg.Id] = pkg; + _chassisById[spec.Id] = spec; + list.Add(spec); + } + + _allChassis = list.AsReadOnly(); + } + + private static ChassisSpec RequireChassis(string id) => + _chassisById.TryGetValue(id, out var spec) + ? spec + : throw new KeyNotFoundException($"Missing chassis '{id}' in loaded vehicle.cc catalog."); + + // ---------------- CHASSIS (15 BROKKR PACKAGES LOADED FROM .CC) ---------------- + + public static ChassisSpec Jackal => RequireChassis("jackal"); + public static ChassisSpec Mule => RequireChassis("mule"); + public static ChassisSpec Ferret => RequireChassis("ferret"); + public static ChassisSpec Hornet => RequireChassis("hornet"); + public static ChassisSpec Mammoth => RequireChassis("mammoth"); + public static ChassisSpec Ironclad => RequireChassis("ironclad"); + public static ChassisSpec Anvil => RequireChassis("anvil"); + public static ChassisSpec Condor => RequireChassis("condor"); + public static ChassisSpec Breaker => RequireChassis("breaker"); + public static ChassisSpec Paladin => RequireChassis("paladin"); + public static ChassisSpec Raptor => RequireChassis("raptor"); + public static ChassisSpec Manticore => RequireChassis("manticore"); + public static ChassisSpec Bastion => RequireChassis("bastion"); + public static ChassisSpec Spectre => RequireChassis("spectre"); + public static ChassisSpec Kestrel => RequireChassis("kestrel"); + + // Backward-compatible aliases for legacy Cut 1/2 call sites + public static ChassisSpec Buggy => Jackal; + public static ChassisSpec Technical => Mule; + public static ChassisSpec Tank => Anvil; + + public static IReadOnlyList AllChassis => _allChassis; + public static IReadOnlyDictionary ChassisById => _chassisById; + public static IReadOnlyDictionary PackagesById => _packagesById; + + public static VehiclePackage? TryGetPackage(string id) => + _packagesById.TryGetValue(id, out var pkg) ? pkg : null; + + // ---------------- HUMAN SALVAGE MODULES (9) ---------------- + + public static readonly ModuleSpec Mg762 = new( + Id: "mg_762", + Name: "7.62 Machine Gun", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 5f, + Conductivity: 9f, + OptimalTemp: 65f, + PlateauWidth: 70f, + MinTemp: 0f, + MaxTemp: 155f, + HeatOutput: 34f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 12f, + WeaponRange: 165f, + FireCooldown: 0.22f, + ProjectileSpeed: 220f, + SpreadRad: 0.035f, + BurstCount: 1); + + public static readonly ModuleSpec Autocannon = new( + Id: "autocannon", + Name: "Twin 20mm Autocannon", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 2, + IsImperial: false, + ThermalMass: 10f, + Conductivity: 10f, + OptimalTemp: 75f, + PlateauWidth: 70f, + MinTemp: 0f, + MaxTemp: 170f, + HeatOutput: 75f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 22f, + WeaponRange: 210f, + FireCooldown: 0.34f, + ProjectileSpeed: 250f, + SpreadRad: 0.025f, + BurstCount: 2); + + public static readonly ModuleSpec Flak = new( + Id: "flak", + Name: "Scrap Flak Scattergun", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 6f, + Conductivity: 8f, + OptimalTemp: 65f, + PlateauWidth: 70f, + MinTemp: 0f, + MaxTemp: 165f, + HeatOutput: 90f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 8.5f, + WeaponRange: 105f, + FireCooldown: 0.65f, + ProjectileSpeed: 185f, + SpreadRad: 0.14f, + BurstCount: 5); + + public static readonly ModuleSpec PointDefenseFlak = new( + Id: "pd_flak", + Name: "Flak Point-Defense", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 6f, + Conductivity: 10f, + OptimalTemp: 65f, + PlateauWidth: 80f, + MinTemp: 0f, + MaxTemp: 165f, + HeatOutput: 24f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 11f, + WeaponRange: 175f, + FireCooldown: 0.24f, + ProjectileSpeed: 340f, + SpreadRad: 0.045f, + BurstCount: 3, + IsWideArc: true, + MinPitchDeg: -10f, + MaxPitchDeg: 85f); + + public static readonly ModuleSpec Recoilless = new( + Id: "recoilless", + Name: "105mm Recoilless Rifle", + Kind: HardpointKind.Weapon, + Width: 2, + Height: 2, + IsImperial: false, + ThermalMass: 18f, + Conductivity: 11f, + OptimalTemp: 75f, + PlateauWidth: 80f, + MinTemp: 0f, + MaxTemp: 185f, + HeatOutput: 190f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 85f, + WeaponRange: 265f, + FireCooldown: 1.45f, + ProjectileSpeed: 280f, + SpreadRad: 0.01f, + BurstCount: 1); + + public static readonly ModuleSpec DieselCore = new( + Id: "diesel_core", + Name: "Salvaged Diesel Core", + Kind: HardpointKind.Engine, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 9f, + Conductivity: 9f, + OptimalTemp: 60f, + PlateauWidth: 80f, + MinTemp: 0f, + MaxTemp: 150f, + HeatOutput: 45f, + CoolingPower: 0f, + ThrustBonus: 4500f, + TurnBonus: 0.4f, + ArmorBonus: 0f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly ModuleSpec TurboCore = new( + Id: "turbo_core", + Name: "Supercharged V8", + Kind: HardpointKind.Engine, + Width: 1, + Height: 2, + IsImperial: false, + ThermalMass: 14f, + Conductivity: 10f, + OptimalTemp: 75f, + PlateauWidth: 70f, + MinTemp: 0f, + MaxTemp: 170f, + HeatOutput: 85f, + CoolingPower: 0f, + ThrustBonus: 12500f, + TurnBonus: 0.9f, + ArmorBonus: 0f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly ModuleSpec CopperRad = new( + Id: "copper_rad", + Name: "Copper Fin Radiator", + Kind: HardpointKind.Radiator, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 6f, + Conductivity: 15f, + OptimalTemp: 85f, + PlateauWidth: 90f, + MinTemp: 0f, + MaxTemp: 210f, + HeatOutput: 0f, + CoolingPower: 120f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly ModuleSpec WeldedPlate = new( + Id: "welded_plate", + Name: "Welded Scrap Plate", + Kind: HardpointKind.Armor, + Width: 1, + Height: 1, + IsImperial: false, + ThermalMass: 12f, + Conductivity: 6f, + OptimalTemp: 60f, + PlateauWidth: 120f, + MinTemp: -20f, + MaxTemp: 240f, + HeatOutput: 0f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 45f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + // ---------------- IMPERIAL TOURIST HIGH-END MODULES (6) ---------------- + + public static readonly ModuleSpec GildedLance = new( + Id: "gilded_lance", + Name: "Gilded Thermal Lance", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 2, + IsImperial: true, + ThermalMass: 11f, + Conductivity: 14f, + OptimalTemp: 90f, + PlateauWidth: 80f, + MinTemp: 0f, + MaxTemp: 210f, + HeatOutput: 95f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 54f, + WeaponRange: 285f, + FireCooldown: 0.55f, + ProjectileSpeed: 400f, + SpreadRad: 0.004f, + BurstCount: 1); + + public static readonly ModuleSpec TouringPlasma = new( + Id: "touring_plasma", + Name: "Touring Plasma Repeater", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 1, + IsImperial: true, + ThermalMass: 8f, + Conductivity: 14f, + OptimalTemp: 95f, + PlateauWidth: 80f, + MinTemp: 0f, + MaxTemp: 205f, + HeatOutput: 68f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 26f, + WeaponRange: 210f, + FireCooldown: 0.18f, + ProjectileSpeed: 310f, + SpreadRad: 0.02f, + BurstCount: 1); + + public static readonly ModuleSpec ImperialAegisPd = new( + Id: "aegis_pd", + Name: "Aegis Imperial PD", + Kind: HardpointKind.Weapon, + Width: 1, + Height: 1, + IsImperial: true, + ThermalMass: 8f, + Conductivity: 16f, + OptimalTemp: 90f, + PlateauWidth: 90f, + MinTemp: 0f, + MaxTemp: 215f, + HeatOutput: 26f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 16f, + WeaponRange: 215f, + FireCooldown: 0.16f, + ProjectileSpeed: 420f, + SpreadRad: 0.015f, + BurstCount: 2, + IsWideArc: true, + MinPitchDeg: -10f, + MaxPitchDeg: 85f); + + public static readonly ModuleSpec GoldRadiator = new( + Id: "gold_radiator", + Name: "Gold-Leaf Phase Radiator", + Kind: HardpointKind.Radiator, + Width: 1, + Height: 1, + IsImperial: true, + ThermalMass: 7f, + Conductivity: 24f, + OptimalTemp: 100f, + PlateauWidth: 110f, + MinTemp: 0f, + MaxTemp: 260f, + HeatOutput: 0f, + CoolingPower: 290f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 0f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly ModuleSpec NobleCore = new( + Id: "noble_core", + Name: "Overclocked Noble Core", + Kind: HardpointKind.Engine, + Width: 1, + Height: 2, + IsImperial: true, + ThermalMass: 15f, + Conductivity: 16f, + OptimalTemp: 105f, + PlateauWidth: 90f, + MinTemp: 0f, + MaxTemp: 225f, + HeatOutput: 110f, + CoolingPower: 0f, + ThrustBonus: 19500f, + TurnBonus: 1.45f, + ArmorBonus: 0f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly ModuleSpec GildedPlate = new( + Id: "gilded_plate", + Name: "Gilded Ceramic Plate", + Kind: HardpointKind.Armor, + Width: 1, + Height: 1, + IsImperial: true, + ThermalMass: 16f, + Conductivity: 4f, + OptimalTemp: 80f, + PlateauWidth: 140f, + MinTemp: -20f, + MaxTemp: 280f, + HeatOutput: 0f, + CoolingPower: 0f, + ThrustBonus: 0f, + TurnBonus: 0f, + ArmorBonus: 85f, + WeaponDamage: 0f, + WeaponRange: 0f, + FireCooldown: 0f, + ProjectileSpeed: 0f, + SpreadRad: 0f, + BurstCount: 0); + + public static readonly IReadOnlyList HumanModules = new[] + { + Mg762, Autocannon, Flak, PointDefenseFlak, Recoilless, DieselCore, TurboCore, CopperRad, WeldedPlate + }; + + public static readonly IReadOnlyList ImperialModules = new[] + { + GildedLance, TouringPlasma, ImperialAegisPd, GoldRadiator, NobleCore, GildedPlate + }; + + public static readonly IReadOnlyList AllModules = new[] + { + Mg762, Autocannon, Flak, PointDefenseFlak, Recoilless, DieselCore, TurboCore, CopperRad, WeldedPlate, + GildedLance, TouringPlasma, ImperialAegisPd, GoldRadiator, NobleCore, GildedPlate + }; + + public static readonly IReadOnlyDictionary ModulesById = + AllModules.ToDictionary(m => m.Id, StringComparer.OrdinalIgnoreCase); + + public static ChassisGrid CreateStarterBuggy() + { + var grid = new ChassisGrid(Jackal); + grid.TryMount(Mg762, "hp.weapon.roof"); + grid.TryMount(DieselCore, "hp.engine.rear"); + grid.TryMount(CopperRad, "hp.radiator.rear"); + return grid; + } + + public static ChassisGrid CreateWithDefaultLoadout(ChassisSpec spec) + { + var grid = new ChassisGrid(spec); + if (_packagesById.TryGetValue(spec.Id, out var pkg)) + { + foreach (var kvp in pkg.DefaultLoadout) + { + if (ModulesById.TryGetValue(kvp.Value, out var mod)) + { + grid.TryMount(mod, kvp.Key); + } + } + } + return grid; + } + } +} diff --git a/src/RustToDust.Core/GridChassis.cs b/src/RustToDust.Core/GridChassis.cs new file mode 100644 index 0000000..742154a --- /dev/null +++ b/src/RustToDust.Core/GridChassis.cs @@ -0,0 +1,1007 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum GridPlane + { + Dorsal, + Coronal + } + + public enum MobilityKind + { + Wheeled, + Tracked, + Vtol, + Walker + } + + public enum HardpointKind + { + Weapon, + Engine, + Radiator, + Armor, + Utility + } + + public sealed record HardpointSpec( + string Id, + HardpointKind Kind, + int X, + int Y, + int Width, + int Height, + float ArmorBonus, + float MinPitchDeg = -15f, + float MaxPitchDeg = 45f, + bool IsWideArc = false); + + public sealed record ModuleSpec( + string Id, + string Name, + HardpointKind Kind, + int Width, + int Height, + bool IsImperial, + float ThermalMass, + float Conductivity, + float OptimalTemp, + float PlateauWidth, + float MinTemp, + float MaxTemp, + float HeatOutput, + float CoolingPower, + float ThrustBonus, + float TurnBonus, + float ArmorBonus, + float WeaponDamage, + float WeaponRange, + float FireCooldown, + float ProjectileSpeed, + float SpreadRad, + int BurstCount, + bool IsWideArc = false, + float MinPitchDeg = -15f, + float MaxPitchDeg = 45f) + { + /// + /// Exact Aetheria trapezoidal plateau curve: + /// 0 outside [MinTemp, MaxTemp], 1 on [OptimalTemp - PlateauWidth/2, OptimalTemp + PlateauWidth/2], + /// linear ramp between bounds and plateau. + /// + public float Performance(float temperature) + { + if (temperature <= MinTemp || temperature >= MaxTemp) + { + return 0f; + } + + float halfPlateau = PlateauWidth * 0.5f; + float lowPlateau = OptimalTemp - halfPlateau; + float highPlateau = OptimalTemp + halfPlateau; + + if (temperature >= lowPlateau && temperature <= highPlateau) + { + return 1f; + } + + if (temperature < lowPlateau) + { + float span = MathF.Max(1e-5f, lowPlateau - MinTemp); + return Math.Clamp((temperature - MinTemp) / span, 0f, 1f); + } + + float upperSpan = MathF.Max(1e-5f, MaxTemp - highPlateau); + return Math.Clamp((MaxTemp - temperature) / upperSpan, 0f, 1f); + } + } + + public sealed record ChassisSpec( + string Id, + string Name, + GridPlane Plane, + int Width, + int Height, + bool[] Mask, + HardpointSpec[] Hardpoints, + float HullConductivity, + float BaseCellThermalMass, + float BaseCellArmor, + float MassKg, + float BaseThrust, + float BaseTurnRate, + float MaxSpeed, + float HalfWidth, + float HalfHeight, + float HalfLength, + int CargoCapacity, + MobilityKind Mobility = MobilityKind.Wheeled, + float HoverMaxAltitudeM = 0f, + string VehicleClass = "") + { + public bool IsWalker => + Mobility == MobilityKind.Walker || + Plane == GridPlane.Coronal || + string.Equals(Id, "manticore", StringComparison.OrdinalIgnoreCase) || + string.Equals(Id, "bastion", StringComparison.OrdinalIgnoreCase); + + public bool IsVtol => Mobility == MobilityKind.Vtol; + + public bool IsActive(int x, int y) => + x >= 0 && x < Width && y >= 0 && y < Height && Mask[y * Width + x]; + } + + public sealed class MountedModule + { + public MountedModule(ModuleSpec spec, string hardpointId, float initialTemp) + { + Spec = spec; + HardpointId = hardpointId; + CurrentTemp = initialTemp; + CurrentPerformance = spec.Performance(initialTemp); + } + + public ModuleSpec Spec { get; } + public string HardpointId { get; } + public float Cooldown { get; set; } + public float CurrentTemp { get; set; } + public float CurrentPerformance { get; set; } + } + + public readonly record struct HitResult( + int CellX, + int CellY, + float ArmorDamage, + float CoreDamage, + bool CoreDestroyed); + + public sealed class ChassisGrid + { + public const float AmbientTemp = 20f; + public const float RadiationExponent = 1.6f; + public const float RadiationMultiplier = 0.015f; + + private static readonly (int Dx, int Dy)[] CardinalOffsets = + { + (1, 0), (-1, 0), (0, 1), (0, -1) + }; + + private float[,] _netHeat; + private float[,] _cellThermalMass; + private float[,] _cellConductivity; + + public ChassisGrid(ChassisSpec spec) + { + Spec = spec ?? throw new ArgumentNullException(nameof(spec)); + Temperature = new float[spec.Width, spec.Height]; + Armor = new float[spec.Width, spec.Height]; + MaxArmor = new float[spec.Width, spec.Height]; + BorderCells = new bool[spec.Width, spec.Height]; + _netHeat = new float[spec.Width, spec.Height]; + _cellThermalMass = new float[spec.Width, spec.Height]; + _cellConductivity = new float[spec.Width, spec.Height]; + InitializeGridState(spec, preserveCoreRatio: false, previousRatio: 1f); + } + + public ChassisSpec Spec { get; private set; } + public float[,] Temperature { get; private set; } + public float[,] Armor { get; private set; } + public float[,] MaxArmor { get; private set; } + public bool[,] BorderCells { get; private set; } + public List Mounted { get; } = new(); + public List Cargo { get; } = new(); + + public float CoreHp { get; private set; } + public float MaxCoreHp { get; private set; } + public bool IsDestroyed => CoreHp <= 0f; + public int HitSequence { get; private set; } + public int LastHitX { get; private set; } + public int LastHitY { get; private set; } + + public static bool CanFit(HardpointSpec hp, ModuleSpec mod) => + mod.Kind == hp.Kind && mod.Width <= hp.Width && mod.Height <= hp.Height; + + public HardpointSpec? FindHardpoint(string hardpointId) + { + for (int i = 0; i < Spec.Hardpoints.Length; i++) + { + if (Spec.Hardpoints[i].Id == hardpointId) + { + return Spec.Hardpoints[i]; + } + } + return null; + } + + public bool IsHardpointOperational(HardpointSpec hp) + { + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int x = hp.X + dx; + int y = hp.Y + dy; + if (Spec.IsActive(x, y) && Armor[x, y] > 0.01f) + { + return true; + } + } + } + return false; + } + + public bool IsHardpointOperational(string hardpointId) => + FindHardpoint(hardpointId) is { } hp && IsHardpointOperational(hp); + + public MountedModule? GetMountedOn(string hardpointId) + { + for (int i = 0; i < Mounted.Count; i++) + { + if (Mounted[i].HardpointId == hardpointId) + { + return Mounted[i]; + } + } + return null; + } + + public bool TryMount(ModuleSpec mod, string hardpointId, List? displacedOut = null) + { + var hp = FindHardpoint(hardpointId); + if (hp is null || !CanFit(hp, mod)) + { + return false; + } + + var existing = GetMountedOn(hardpointId); + if (existing is not null) + { + Mounted.Remove(existing); + if (Cargo.Count < Spec.CargoCapacity) + { + Cargo.Add(existing.Spec); + } + else + { + displacedOut?.Add(existing.Spec); + } + } + + float avgTemp = GetHardpointAverageTemp(hp); + Mounted.Add(new MountedModule(mod, hardpointId, avgTemp)); + RecalculateArmorAndThermal(grantNewArmorDelta: true); + return true; + } + + public bool TryEquipFromCargo(int cargoIndex, string hardpointId, List? displacedOut = null) + { + if (cargoIndex < 0 || cargoIndex >= Cargo.Count) + { + return false; + } + + var mod = Cargo[cargoIndex]; + var hp = FindHardpoint(hardpointId); + if (hp is null || !CanFit(hp, mod)) + { + return false; + } + + Cargo.RemoveAt(cargoIndex); + if (!TryMount(mod, hardpointId, displacedOut)) + { + Cargo.Insert(cargoIndex, mod); + return false; + } + return true; + } + + public bool TryAddCargo(ModuleSpec mod) + { + if (Cargo.Count >= Spec.CargoCapacity) + { + return false; + } + Cargo.Add(mod); + return true; + } + + public HardpointSpec? FindFirstEmptyCompatibleHardpoint(ModuleSpec mod) + { + for (int i = 0; i < Spec.Hardpoints.Length; i++) + { + var hp = Spec.Hardpoints[i]; + if (GetMountedOn(hp.Id) is null && CanFit(hp, mod)) + { + return hp; + } + } + return null; + } + + public bool TryQuickBoltOrCargo(ModuleSpec mod, out string? boltedHardpointId) + { + var freeHp = FindFirstEmptyCompatibleHardpoint(mod); + if (freeHp is not null && TryMount(mod, freeHp.Id)) + { + boltedHardpointId = freeHp.Id; + return true; + } + + boltedHardpointId = null; + return TryAddCargo(mod); + } + + public void InjectHeat(int x, int y, float heat) + { + if (!Spec.IsActive(x, y) || heat == 0f) + { + return; + } + float tm = MathF.Max(1f, _cellThermalMass[x, y]); + Temperature[x, y] = MathF.Max(AmbientTemp, Temperature[x, y] + heat / tm); + } + + public void InjectHardpointHeat(string hardpointId, float heat) + { + var hp = FindHardpoint(hardpointId); + if (hp is null || heat == 0f) + { + return; + } + + int activeCells = CountActiveCellsInHardpoint(hp); + if (activeCells == 0) + { + return; + } + + float perCell = heat / activeCells; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int x = hp.X + dx; + int y = hp.Y + dy; + if (Spec.IsActive(x, y)) + { + InjectHeat(x, y, perCell); + } + } + } + } + + public void StepHeat(float dt) + { + if (dt <= 0f) + { + return; + } + + int w = Spec.Width; + int h = Spec.Height; + int substeps = Math.Max(1, (int)MathF.Ceiling(dt / 0.02f)); + float subDt = dt / substeps; + + for (int step = 0; step < substeps; step++) + { + Array.Clear(_netHeat, 0, _netHeat.Length); + + // 4-neighbor weighted conduction (conservative pairwise transfer) + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + + float t = Temperature[x, y]; + float c = _cellConductivity[x, y]; + + if (x + 1 < w && Spec.IsActive(x + 1, y)) + { + float pairCond = 0.5f * (c + _cellConductivity[x + 1, y]); + float flow = pairCond * (Temperature[x + 1, y] - t) * subDt; + _netHeat[x, y] += flow; + _netHeat[x + 1, y] -= flow; + } + + if (y + 1 < h && Spec.IsActive(x, y + 1)) + { + float pairCond = 0.5f * (c + _cellConductivity[x, y + 1]); + float flow = pairCond * (Temperature[x, y + 1] - t) * subDt; + _netHeat[x, y] += flow; + _netHeat[x, y + 1] -= flow; + } + } + } + + // Border-only radiative cooling + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y) || !BorderCells[x, y]) + { + continue; + } + + float t = MathF.Max(0f, Temperature[x, y]); + float radLoss = MathF.Pow(t, RadiationExponent) * RadiationMultiplier * subDt; + _netHeat[x, y] -= radLoss; + } + } + + // Active radiator cooling scaled by radiator's Performance(temp) + for (int i = 0; i < Mounted.Count; i++) + { + var mod = Mounted[i]; + if (mod.Spec.Kind != HardpointKind.Radiator || mod.Spec.CoolingPower <= 0f) + { + continue; + } + + var hp = FindHardpoint(mod.HardpointId); + if (hp is null) + { + continue; + } + + float perf = mod.Spec.Performance(mod.CurrentTemp); + if (perf <= 0f) + { + continue; + } + + int activeCells = CountActiveCellsInHardpoint(hp); + if (activeCells == 0) + { + continue; + } + + float coolPerCell = (mod.Spec.CoolingPower * perf * subDt) / activeCells; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int cx = hp.X + dx; + int cy = hp.Y + dy; + if (Spec.IsActive(cx, cy)) + { + _netHeat[cx, cy] -= coolPerCell; + } + } + } + } + + // Integrate temperature with desert ambient floor + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + Temperature[x, y] = AmbientTemp; + continue; + } + + float tm = MathF.Max(1f, _cellThermalMass[x, y]); + float next = Temperature[x, y] + _netHeat[x, y] / tm; + Temperature[x, y] = MathF.Max(AmbientTemp, next); + } + } + + UpdateMountedTelemetry(); + } + } + + public HitResult ApplyHit(float localRight, float localForward, float localHeightNorm, float damage, float heatTransfer) + { + (int cx, int cy) = ResolveHitCell(localRight, localForward, localHeightNorm); + if (!Spec.IsActive(cx, cy)) + { + return new HitResult(0, 0, 0f, 0f, IsDestroyed); + } + + if (heatTransfer > 0f) + { + InjectHeat(cx, cy, heatTransfer); + } + + float absorbed = MathF.Min(Armor[cx, cy], MathF.Max(0f, damage)); + Armor[cx, cy] -= absorbed; + float spill = MathF.Max(0f, damage - absorbed); + + if (spill > 0f && CoreHp > 0f) + { + CoreHp = MathF.Max(0f, CoreHp - spill); + } + + HitSequence++; + LastHitX = cx; + LastHitY = cy; + + return new HitResult(cx, cy, absorbed, spill, IsDestroyed); + } + + public List SwapChassis(ChassisSpec next) + { + if (next is null) + { + throw new ArgumentNullException(nameof(next)); + } + + var previousMounted = new List(Mounted.Count); + for (int i = 0; i < Mounted.Count; i++) + { + previousMounted.Add(Mounted[i].Spec); + } + var previousCargo = new List(Cargo); + float coreRatio = MaxCoreHp > 0f ? CoreHp / MaxCoreHp : 1f; + + Mounted.Clear(); + Cargo.Clear(); + + Spec = next; + Temperature = new float[next.Width, next.Height]; + Armor = new float[next.Width, next.Height]; + MaxArmor = new float[next.Width, next.Height]; + BorderCells = new bool[next.Width, next.Height]; + _netHeat = new float[next.Width, next.Height]; + _cellThermalMass = new float[next.Width, next.Height]; + _cellConductivity = new float[next.Width, next.Height]; + + InitializeGridState(next, preserveCoreRatio: true, previousRatio: MathF.Max(0.75f, coreRatio)); + + var dropped = new List(); + + // Transfer every mounted module that fits a free hardpoint on the new chassis + foreach (var mod in previousMounted) + { + HardpointSpec? chosen = null; + for (int i = 0; i < next.Hardpoints.Length; i++) + { + var hp = next.Hardpoints[i]; + if (GetMountedOn(hp.Id) is null && CanFit(hp, mod)) + { + chosen = hp; + break; + } + } + + if (chosen is not null) + { + Mounted.Add(new MountedModule(mod, chosen.Id, AmbientTemp)); + } + else if (Cargo.Count < next.CargoCapacity) + { + Cargo.Add(mod); + } + else + { + dropped.Add(mod); + } + } + + foreach (var item in previousCargo) + { + if (Cargo.Count < next.CargoCapacity) + { + Cargo.Add(item); + } + else + { + dropped.Add(item); + } + } + + RecalculateArmorAndThermal(grantNewArmorDelta: true); + UpdateMountedTelemetry(); + return dropped; + } + + public float LegIntegrity + { + get + { + if (Spec.Plane != GridPlane.Coronal) + { + return 1f; + } + + int legStartY = Math.Max(0, Spec.Height - 2); + float cur = 0f; + float max = 0f; + for (int y = legStartY; y < Spec.Height; y++) + { + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + cur += Armor[x, y]; + max += MaxArmor[x, y]; + } + } + + if (max <= 0f) + { + return 1f; + } + + float ratio = Math.Clamp(cur / max, 0f, 1f); + return 0.25f + 0.75f * ratio; + } + } + + public float ComputeEngineThermalPerformance() + { + float sum = 0f; + int count = 0; + for (int i = 0; i < Mounted.Count; i++) + { + var m = Mounted[i]; + if (m.Spec.Kind == HardpointKind.Engine) + { + sum += m.CurrentPerformance; + count++; + } + } + return count > 0 ? Math.Clamp(sum / count, 0f, 1f) : 0.4f; + } + + public float ComputeDriveThrust() + { + float engineThrust = 0f; + float enginePerfSum = 0f; + int engineCount = 0; + + for (int i = 0; i < Mounted.Count; i++) + { + var m = Mounted[i]; + if (m.Spec.Kind == HardpointKind.Engine) + { + engineThrust += m.Spec.ThrustBonus * m.CurrentPerformance; + enginePerfSum += m.CurrentPerformance; + engineCount++; + } + } + + float baseFactor = engineCount > 0 ? Math.Clamp(enginePerfSum / engineCount, 0.25f, 1f) : 0.4f; + return (Spec.BaseThrust * baseFactor + engineThrust) * LegIntegrity; + } + + public float ComputeTurnRate() + { + float bonus = 0f; + float enginePerfSum = 0f; + int engineCount = 0; + + for (int i = 0; i < Mounted.Count; i++) + { + var m = Mounted[i]; + if (m.Spec.Kind == HardpointKind.Engine) + { + bonus += m.Spec.TurnBonus * m.CurrentPerformance; + enginePerfSum += m.CurrentPerformance; + engineCount++; + } + } + + float baseFactor = engineCount > 0 ? Math.Clamp(enginePerfSum / engineCount, 0.35f, 1f) : 0.5f; + return (Spec.BaseTurnRate * baseFactor + bonus) * (0.5f + 0.5f * LegIntegrity); + } + + public float TotalArmorRatio() + { + float cur = 0f; + float max = 0f; + for (int y = 0; y < Spec.Height; y++) + { + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + cur += Armor[x, y]; + max += MaxArmor[x, y]; + } + } + return max > 0f ? cur / max : 0f; + } + + private (int X, int Y) ResolveHitCell(float localRight, float localForward, float localHeightNorm) + { + int w = Spec.Width; + int h = Spec.Height; + + if (Spec.Plane == GridPlane.Coronal) + { + float targetX = (Math.Clamp(localRight, -1f, 1f) * 0.5f + 0.5f) * (w - 1); + float targetY = (1f - Math.Clamp(localHeightNorm, 0f, 1f)) * (h - 1); + + int bestX = 0; + int bestY = 0; + float bestDistSq = float.PositiveInfinity; + + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + float dx = x - targetX; + float dy = y - targetY; + float d2 = dx * dx + dy * dy; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestX = x; + bestY = y; + } + } + } + return (bestX, bestY); + } + + // GridPlane.Dorsal: map (localRight, localForward) onto the outer active cell facing the hit. + // Row y=0 is front (+localForward), row y=Height-1 is rear (-localForward). + float dirX = localRight; + float dirY = -localForward; + float len = MathF.Sqrt(dirX * dirX + dirY * dirY); + if (len < 1e-4f) + { + dirX = 0f; + dirY = -1f; + } + else + { + dirX /= len; + dirY /= len; + } + + int bestDx = 0; + int bestDy = 0; + float bestScore = float.NegativeInfinity; + + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + + float nx = (x + 0.5f) / w - 0.5f; + float ny = (y + 0.5f) / h - 0.5f; + + float proj = nx * dirX + ny * dirY; + float alignPenalty = ((nx - dirX * 0.5f) * (nx - dirX * 0.5f) + (ny - dirY * 0.5f) * (ny - dirY * 0.5f)) * 0.05f; + float borderBoost = BorderCells[x, y] ? 0.1f : 0f; + float score = proj + borderBoost - alignPenalty; + + if (score > bestScore) + { + bestScore = score; + bestDx = x; + bestDy = y; + } + } + } + + return (bestDx, bestDy); + } + + private void InitializeGridState(ChassisSpec spec, bool preserveCoreRatio, float previousRatio) + { + int activeCount = 0; + for (int y = 0; y < spec.Height; y++) + { + for (int x = 0; x < spec.Width; x++) + { + Temperature[x, y] = AmbientTemp; + if (!spec.IsActive(x, y)) + { + BorderCells[x, y] = false; + continue; + } + + activeCount++; + bool isBorder = false; + for (int i = 0; i < CardinalOffsets.Length; i++) + { + int nx = x + CardinalOffsets[i].Dx; + int ny = y + CardinalOffsets[i].Dy; + if (!spec.IsActive(nx, ny)) + { + isBorder = true; + break; + } + } + BorderCells[x, y] = isBorder; + } + } + + MaxCoreHp = 100f + activeCount * 8f + spec.BaseCellArmor * 2.5f; + CoreHp = preserveCoreRatio ? MaxCoreHp * Math.Clamp(previousRatio, 0.05f, 1f) : MaxCoreHp; + + RecalculateArmorAndThermal(grantNewArmorDelta: false); + for (int y = 0; y < spec.Height; y++) + { + for (int x = 0; x < spec.Width; x++) + { + Armor[x, y] = MaxArmor[x, y]; + } + } + } + + private void RecalculateArmorAndThermal(bool grantNewArmorDelta) + { + int w = Spec.Width; + int h = Spec.Height; + + float[,] previousMax = (float[,])MaxArmor.Clone(); + + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + MaxArmor[x, y] = 0f; + Armor[x, y] = 0f; + _cellThermalMass[x, y] = 1f; + _cellConductivity[x, y] = 0f; + continue; + } + + MaxArmor[x, y] = Spec.BaseCellArmor; + _cellThermalMass[x, y] = Spec.BaseCellThermalMass; + _cellConductivity[x, y] = Spec.HullConductivity; + } + } + + for (int i = 0; i < Spec.Hardpoints.Length; i++) + { + var hp = Spec.Hardpoints[i]; + if (hp.ArmorBonus == 0f) + { + continue; + } + + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int x = hp.X + dx; + int y = hp.Y + dy; + if (Spec.IsActive(x, y)) + { + MaxArmor[x, y] += hp.ArmorBonus; + } + } + } + } + + for (int i = 0; i < Mounted.Count; i++) + { + var mod = Mounted[i]; + var hp = FindHardpoint(mod.HardpointId); + if (hp is null) + { + continue; + } + + int activeCells = CountActiveCellsInHardpoint(hp); + if (activeCells == 0) + { + continue; + } + + float tmShare = mod.Spec.ThermalMass / activeCells; + float armorShare = mod.Spec.ArmorBonus / activeCells; + + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int x = hp.X + dx; + int y = hp.Y + dy; + if (!Spec.IsActive(x, y)) + { + continue; + } + + _cellThermalMass[x, y] += tmShare; + _cellConductivity[x, y] = MathF.Max(_cellConductivity[x, y], mod.Spec.Conductivity); + MaxArmor[x, y] += armorShare; + } + } + } + + if (grantNewArmorDelta) + { + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + float delta = MaxArmor[x, y] - previousMax[x, y]; + if (delta > 0f) + { + Armor[x, y] = MathF.Min(MaxArmor[x, y], Armor[x, y] + delta); + } + else + { + Armor[x, y] = MathF.Min(Armor[x, y], MaxArmor[x, y]); + } + } + } + } + } + + private int CountActiveCellsInHardpoint(HardpointSpec hp) + { + int count = 0; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + if (Spec.IsActive(hp.X + dx, hp.Y + dy)) + { + count++; + } + } + } + return count; + } + + private float GetHardpointAverageTemp(HardpointSpec hp) + { + float sum = 0f; + int count = 0; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int x = hp.X + dx; + int y = hp.Y + dy; + if (Spec.IsActive(x, y)) + { + sum += Temperature[x, y]; + count++; + } + } + } + return count > 0 ? sum / count : AmbientTemp; + } + + private void UpdateMountedTelemetry() + { + for (int i = 0; i < Mounted.Count; i++) + { + var mod = Mounted[i]; + var hp = FindHardpoint(mod.HardpointId); + if (hp is null) + { + continue; + } + float avgTemp = GetHardpointAverageTemp(hp); + mod.CurrentTemp = avgTemp; + mod.CurrentPerformance = mod.Spec.Performance(avgTemp); + } + } + } +} diff --git a/src/RustToDust.Core/MatchRules.cs b/src/RustToDust.Core/MatchRules.cs new file mode 100644 index 0000000..927c29b --- /dev/null +++ b/src/RustToDust.Core/MatchRules.cs @@ -0,0 +1,532 @@ +using System; +using System.Numerics; + +namespace RustToDust.Core +{ + public delegate bool LineOfSightCheck(float ax, float ay, float az, float bx, float by, float bz); + + public static class MatchRules + { + public const float VtolMinClearanceAgl = 2.5f; + + public static float GetObserverEyeY(float y, float halfHeight) => y + halfHeight * 1.4f; + public static float GetTargetAimY(float y, float halfHeight) => y + halfHeight * 0.35f; + + public static (float MinPitchDeg, float MaxPitchDeg) GetEffectivePitchArc(HardpointSpec hp, ModuleSpec? mod) + { + if (mod is not null && mod.IsWideArc) + { + return (MathF.Min(hp.MinPitchDeg, mod.MinPitchDeg), MathF.Max(hp.MaxPitchDeg, mod.MaxPitchDeg)); + } + if (hp.IsWideArc) + { + return (MathF.Min(hp.MinPitchDeg, -10f), MathF.Max(hp.MaxPitchDeg, 85f)); + } + return (hp.MinPitchDeg, hp.MaxPitchDeg); + } + + public static float ComputeLocalPitchDeg(Vector3 aimDelta, Quaternion chassisQuat) + { + Vector3 local = Vector3.Transform(aimDelta, Quaternion.Conjugate(chassisQuat)); + float horiz = MathF.Sqrt(local.X * local.X + local.Z * local.Z); + return MathF.Atan2(local.Y, horiz) * (180f / MathF.PI); + } + + public static float NormalizeAngle(float rad) + { + if (!float.IsFinite(rad)) + { + return 0f; + } + rad = MathF.IEEERemainder(rad, MathF.Tau); + if (rad > MathF.PI) rad -= MathF.Tau; + if (rad < -MathF.PI) rad += MathF.Tau; + return rad; + } + + public static void ApplyPlayerInput(MatchState state, PlayerInput input) + { + var player = state.Player; + if (!player.Alive) + { + player.ThrottleCmd = 0f; + player.SteerCmd = 0f; + player.VerticalThrottleCmd = 0f; + player.FireCmd = false; + player.BrakeCmd = true; + return; + } + + player.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f); + player.SteerCmd = Math.Clamp(input.Steer, -1f, 1f); + player.VerticalThrottleCmd = Math.Clamp(input.VerticalThrottle, -1f, 1f); + player.AimX = input.AimWorldX; + player.AimY = input.AimWorldY; + player.AimZ = input.AimWorldZ; + player.FireCmd = input.Fire; + player.BrakeCmd = input.Brake; + + if (input.InteractPickup) + { + state.TryInteractNearestDrop(0); + } + } + + public static void UpdateAiContenders(MatchState state, float dt, LineOfSightCheck? hasLos = null, int tickIndex = -1) + { + float safeLimit = MathF.Max(30f, state.Spectators.SafeRadius - 25f); + + for (int i = 0; i < state.Contenders.Count; i++) + { + var ai = state.Contenders[i]; + if (ai.IsPlayer || !ai.Alive) + { + continue; + } + + ai.AiScavengeCooldown = MathF.Max(0f, ai.AiScavengeCooldown - dt); + AutoEquipAiCargo(state, ai); + + float distFromCenter = MathF.Sqrt(ai.X * ai.X + ai.Z * ai.Z); + float goalX = 0f; + float goalZ = 0f; + bool hasGoal = false; + bool wantFire = false; + float aimX = ai.X + MathF.Sin(ai.Yaw) * 25f; + float aimZ = ai.Z + MathF.Cos(ai.Yaw) * 25f; + + // 1. Stay inside the shrinking Safe Circle + if (distFromCenter > safeLimit) + { + goalX = 0f; + goalZ = 0f; + hasGoal = true; + } + + // 2. Find nearest hostile contender with actual line-of-sight (staggered every 3 ticks when tickIndex >= 0) + ContenderState? target = null; + float bestEnemyDistSq = 215f * 215f; + bool refreshLos = tickIndex < 0 || ((ai.Id + tickIndex) % 3 == 0); + if (refreshLos) + { + float aiEyeY = GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight); + for (int j = 0; j < state.Contenders.Count; j++) + { + var other = state.Contenders[j]; + if (other.Id == ai.Id || !other.Alive) + { + continue; + } + + float dx = other.X - ai.X; + float dz = other.Z - ai.Z; + float d2 = dx * dx + dz * dz; + if (d2 >= bestEnemyDistSq) + { + continue; + } + + if (hasLos is not null && + !hasLos(ai.X, aiEyeY, ai.Z, other.X, GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight), other.Z)) + { + continue; + } + + bestEnemyDistSq = d2; + target = other; + } + ai.AiTargetContenderId = target?.Id; + } + else if (ai.AiTargetContenderId is { } tid && tid >= 0 && tid < state.Contenders.Count) + { + var cached = state.Contenders[tid]; + if (cached.Alive && cached.Id != ai.Id) + { + float dx = cached.X - ai.X; + float dz = cached.Z - ai.Z; + float d2 = dx * dx + dz * dz; + if (d2 < bestEnemyDistSq) + { + bestEnemyDistSq = d2; + target = cached; + } + else + { + ai.AiTargetContenderId = null; + } + } + else + { + ai.AiTargetContenderId = null; + } + } + + // 3. Scavenge nearby upgrades when safe + if (!hasGoal && ai.AiScavengeCooldown <= 0f) + { + GroundDrop? bestDrop = null; + float bestDropDistSq = 85f * 85f; + for (int d = 0; d < state.GroundDrops.Count; d++) + { + var drop = state.GroundDrops[d]; + if (drop.PickedUp) + { + continue; + } + + if (drop.Chassis is not null && drop.Chassis.MassKg <= ai.Grid.Spec.MassKg) + { + continue; + } + + float dx = drop.X - ai.X; + float dz = drop.Z - ai.Z; + float d2 = dx * dx + dz * dz; + if (d2 < bestDropDistSq) + { + bestDropDistSq = d2; + bestDrop = drop; + } + } + + if (bestDrop is not null) + { + goalX = bestDrop.X; + goalZ = bestDrop.Z; + hasGoal = true; + + if (bestDropDistSq <= MatchState.PickupRadius * MatchState.PickupRadius) + { + if (bestDrop.Module is not null) + { + state.TryPickupNearbyModule(ai.Id); + } + else if (bestDrop.Chassis is not null) + { + state.TrySwapNearbyChassis(ai.Id); + } + ai.AiScavengeCooldown = 2.5f; + } + } + } + + // 4. Combat or third-party gunfire investigation + if (target is not null) + { + aimX = target.X; + aimZ = target.Z; + float dist = MathF.Sqrt(bestEnemyDistSq); + wantFire = dist <= 165f; + + if (!hasGoal) + { + if (dist > 75f) + { + goalX = target.X; + goalZ = target.Z; + } + else + { + // Orbit target instead of ramming headlong + float tangentAngle = MathF.Atan2(ai.Z - target.Z, ai.X - target.X) + 0.7f; + goalX = target.X + MathF.Cos(tangentAngle) * 52f; + goalZ = target.Z + MathF.Sin(tangentAngle) * 52f; + } + hasGoal = true; + } + } + else if (!hasGoal && state.LastGunfireX.HasValue && state.LastGunfireZ.HasValue && + state.Time - state.LastGunfireTime < 12f) + { + float gdx = state.LastGunfireX.Value - ai.X; + float gdz = state.LastGunfireZ.Value - ai.Z; + if (gdx * gdx + gdz * gdz <= 340f * 340f) + { + goalX = state.LastGunfireX.Value; + goalZ = state.LastGunfireZ.Value; + hasGoal = true; + } + } + + if (!hasGoal) + { + float patrolAngle = ai.Id * 0.9f + state.Time * 0.12f; + float r = MathF.Min(safeLimit * 0.65f, 190f); + goalX = MathF.Cos(patrolAngle) * r; + goalZ = MathF.Sin(patrolAngle) * r; + } + + float toGoalX = goalX - ai.X; + float toGoalZ = goalZ - ai.Z; + float desiredYaw = MathF.Atan2(toGoalX, toGoalZ); + float yawError = NormalizeAngle(desiredYaw - ai.Yaw); + + ai.SteerCmd = Math.Clamp(yawError * 1.8f, -1f, 1f); + ai.ThrottleCmd = MathF.Abs(yawError) > 1.25f ? 0.35f : 0.85f; + ai.BrakeCmd = false; + if (ai.Grid.Spec.IsVtol) + { + float groundH = state.Terrain.SampleHeight(ai.X, ai.Z); + float currentAgl = ai.Y - ai.Grid.Spec.HalfHeight - groundH; + float desiredAgl = target is null + ? MathF.Min(ai.Grid.Spec.HoverMaxAltitudeM * 0.6f, 22f) + : MathF.Min(ai.Grid.Spec.HoverMaxAltitudeM * 0.45f, 14f + 4f * MathF.Sin(state.Time * 0.9f + ai.Id)); + ai.VerticalThrottleCmd = Math.Clamp((desiredAgl - currentAgl) * 0.25f, -1f, 1f); + } + else + { + ai.VerticalThrottleCmd = 0f; + } + ai.AimX = aimX; + ai.AimY = target is not null ? GetTargetAimY(target.Y, target.Grid.Spec.HalfHeight) : float.NaN; + ai.AimZ = aimZ; + ai.FireCmd = wantFire; + } + } + + public static void ComputeSpectatorBehavior( + SpectatorState spec, + MatchState state, + out float goalX, + out float goalZ, + out float aimX, + out float aimZ, + out bool shouldFire) + { + if (spec.Stance == SpectatorStance.Neutral || !spec.TargetContenderId.HasValue) + { + (goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes); + aimX = 0f; + aimZ = 0f; + shouldFire = false; + return; + } + + ContenderState? target = null; + int targetId = spec.TargetContenderId.Value; + if (targetId >= 0 && targetId < state.Contenders.Count) + { + target = state.Contenders[targetId]; + } + + if (target is null || !target.Alive) + { + (goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes); + aimX = 0f; + aimZ = 0f; + shouldFire = false; + return; + } + + // Occluded behind terrain/cover: never shoot through rock! Never fall back to live target.X/Z while occluded. + if (!spec.HasTargetLos) + { + shouldFire = false; + bool hasMemory = spec.TimeSinceLastSeen < SpectatorRing.TargetMemoryDuration; + float focusX = spec.LastKnownTargetX; + float focusZ = spec.LastKnownTargetZ; + aimX = focusX; + aimZ = focusZ; + + if (!hasMemory) + { + var (anchorX, anchorZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes); + float toFocusX = focusX - spec.X; + float toFocusZ = focusZ - spec.Z; + float toFocusLen = MathF.Sqrt(toFocusX * toFocusX + toFocusZ * toFocusZ); + bool hasValidFocus = (focusX != 0f || focusZ != 0f) && toFocusLen > 12f && toFocusLen < 240f; + float centerX = hasValidFocus ? focusX : anchorX; + float centerZ = hasValidFocus ? focusZ : anchorZ; + + float bestX = centerX; + float bestZ = centerZ; + float bestH = state.Terrain.SampleHeight(bestX, bestZ); + float maxBound = TerrainField.HalfExtent - 18f; + for (int k = 0; k < 4; k++) + { + float ang = spec.Id * 0.7f + k * (MathF.PI * 0.5f); + float cx = Math.Clamp(centerX + MathF.Cos(ang) * 26f, -maxBound, maxBound); + float cz = Math.Clamp(centerZ + MathF.Sin(ang) * 26f, -maxBound, maxBound); + float h = state.Terrain.SampleHeight(cx, cz); + if (h > bestH) + { + bestH = h; + bestX = cx; + bestZ = cz; + } + } + + goalX = bestX; + goalZ = bestZ; + return; + } + + float fdx = focusX - spec.X; + float fdz = focusZ - spec.Z; + float fLen = MathF.Sqrt(fdx * fdx + fdz * fdz); + if (fLen < 1f) + { + (goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes); + return; + } + + float dirX = fdx / fLen; + float dirZ = fdz / fLen; + float perpX = -dirZ; + float perpZ = dirX; + float sideSign = (spec.Id & 1) == 0 ? 1f : -1f; + + // Evaluate flanking steps (left flank, right flank, crest-climb toward last-known position) + float step = MathF.Min(42f, fLen * 0.65f); + float cand1X = spec.X + (dirX * 0.65f + perpX * 0.76f * sideSign) * step; + float cand1Z = spec.Z + (dirZ * 0.65f + perpZ * 0.76f * sideSign) * step; + float cand2X = spec.X + (dirX * 0.65f - perpX * 0.76f * sideSign) * step; + float cand2Z = spec.Z + (dirZ * 0.65f - perpZ * 0.76f * sideSign) * step; + + float h1 = state.Terrain.SampleHeight(cand1X, cand1Z); + float h2 = state.Terrain.SampleHeight(cand2X, cand2Z); + + // Prefer the flanking shoulder that gets higher ground (sightline over ridge) unless it is a steep cliff + if (h1 >= h2) + { + goalX = cand1X; + goalZ = cand1Z; + } + else + { + goalX = cand2X; + goalZ = cand2Z; + } + return; + } + + aimX = target.X; + aimZ = target.Z; + + float dx = target.X - spec.X; + float dz = target.Z - spec.Z; + float dist = MathF.Sqrt(dx * dx + dz * dz); + + if (dist > spec.PreferredRange) + { + goalX = target.X; + goalZ = target.Z; + } + else + { + float angle = MathF.Atan2(spec.Z - target.Z, spec.X - target.X) + (spec.Tier == SpectatorTier.Exemplar ? 0.9f : 0.4f); + goalX = target.X + MathF.Cos(angle) * (spec.PreferredRange * 0.85f); + goalZ = target.Z + MathF.Sin(angle) * (spec.PreferredRange * 0.85f); + } + + shouldFire = dist <= 255f; + + // Tourists self-throttle when their Imperial weapons run hot + if (shouldFire && spec.Tier == SpectatorTier.Tourist) + { + for (int i = 0; i < spec.Grid.Mounted.Count; i++) + { + var m = spec.Grid.Mounted[i]; + if (m.Spec.Kind == HardpointKind.Weapon && + m.CurrentTemp > m.Spec.OptimalTemp + m.Spec.PlateauWidth * 0.45f) + { + shouldFire = false; + break; + } + } + } + } + + public static void AdvanceTracers(MatchState state, float dt) + { + for (int i = state.Tracers.Count - 1; i >= 0; i--) + { + var t = state.Tracers[i]; + float nextTtl = t.Ttl - dt; + if (nextTtl <= 0f) + { + state.Tracers.RemoveAt(i); + } + else + { + state.Tracers[i] = t with { Ttl = nextTtl }; + } + } + } + + public static void UpdateMatchOutcome(MatchState state) + { + if (state.Phase != MatchPhase.Active) + { + return; + } + + if (!state.Player.Alive) + { + state.Phase = MatchPhase.Defeat; + return; + } + + int aliveCount = 0; + for (int i = 0; i < state.Contenders.Count; i++) + { + if (state.Contenders[i].Alive) + { + aliveCount++; + } + } + + if (aliveCount <= 1 && state.Player.Alive) + { + state.Phase = MatchPhase.Victory; + state.Broadcast.EmitVictory(state.Time, state.Player.Id); + } + } + + private static void AutoEquipAiCargo(MatchState state, ContenderState ai) + { + if (ai.Grid.Cargo.Count == 0) + { + return; + } + + for (int c = ai.Grid.Cargo.Count - 1; c >= 0; c--) + { + var item = ai.Grid.Cargo[c]; + for (int h = 0; h < ai.Grid.Spec.Hardpoints.Length; h++) + { + var hp = ai.Grid.Spec.Hardpoints[h]; + if (!ChassisGrid.CanFit(hp, item)) + { + continue; + } + + var mounted = ai.Grid.GetMountedOn(hp.Id); + if (mounted is null || IsBetterModule(item, mounted.Spec)) + { + state.TryEquipCargo(ai.Id, c, hp.Id); + break; + } + } + } + } + + private static bool IsBetterModule(ModuleSpec candidate, ModuleSpec current) + { + if (candidate.IsImperial && !current.IsImperial) + { + return true; + } + + return candidate.Kind switch + { + HardpointKind.Weapon => candidate.WeaponDamage * MathF.Max(1, candidate.BurstCount) > + current.WeaponDamage * MathF.Max(1, current.BurstCount), + HardpointKind.Engine => candidate.ThrustBonus > current.ThrustBonus, + HardpointKind.Radiator => candidate.CoolingPower > current.CoolingPower, + HardpointKind.Armor => candidate.ArmorBonus > current.ArmorBonus, + _ => false + }; + } + } +} diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs new file mode 100644 index 0000000..1c2d8cd --- /dev/null +++ b/src/RustToDust.Core/MatchState.cs @@ -0,0 +1,601 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum MatchPhase + { + Active, + Victory, + Defeat + } + + public readonly record struct PlayerInput( + float Throttle, + float Steer, + float AimWorldX, + float AimWorldZ, + bool Fire, + bool InteractPickup, + bool Brake, + float AimWorldY = float.NaN, + float VerticalThrottle = 0f); + + public readonly record struct TracerEvent( + float StartX, + float StartY, + float StartZ, + float EndX, + float EndY, + float EndZ, + uint ColorRgba, + float Ttl); + + public readonly record struct ArenaBoxSpec( + float X, + float Y, + float Z, + float HalfX, + float HalfY, + float HalfZ, + bool IsBoundary); + + public sealed class PlayerContactMemory + { + public bool VisibleToPlayer { get; set; } + public float LastSeenAge { get; set; } = float.PositiveInfinity; + public float LastSeenX { get; set; } + public float LastSeenZ { get; set; } + public bool HasEverBeenSeen { get; set; } + public bool FaintHorizonPing { get; set; } + } + + public sealed class GroundDrop + { + public GroundDrop(int id, float x, float z, ChassisSpec? chassis, ModuleSpec? module) + { + Id = id; + X = x; + Z = z; + Chassis = chassis; + Module = module; + } + + public int Id { get; } + public float X { get; } + public float Z { get; } + public ChassisSpec? Chassis { get; } + public ModuleSpec? Module { get; } + public bool PickedUp { get; set; } + } + + public sealed class ContenderState + { + public ContenderState(int id, string name, bool isPlayer, ChassisGrid grid, float x, float z, float yaw) + { + Id = id; + Name = name; + IsPlayer = isPlayer; + Grid = grid; + X = x; + Y = grid.Spec.HalfHeight + 0.1f; + Z = z; + Yaw = yaw; + AimX = x + MathF.Sin(yaw) * 20f; + AimY = Y; + AimZ = z + MathF.Cos(yaw) * 20f; + } + + public int Id { get; } + public string Name { get; } + public bool IsPlayer { get; } + public ChassisGrid Grid { get; } + public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + public float Yaw { get; set; } + public float AimX { get; set; } + public float AimY { get; set; } + public float AimZ { get; set; } + public float Speed { get; set; } + public int Kills { get; set; } + public bool OverheatWarned { get; set; } + + public float ThrottleCmd { get; set; } + public float SteerCmd { get; set; } + public float VerticalThrottleCmd { get; set; } + public float TargetHoverAltAgl { get; set; } = 3.0f; + public bool FireCmd { get; set; } + public bool BrakeCmd { get; set; } + public float AiScavengeCooldown { get; set; } + public int? AiTargetContenderId { get; set; } + public bool AllWeaponsOutOfArc { get; set; } + public int OutOfArcWeaponCount { get; set; } + public int InArcWeaponCount { get; set; } + public int DisabledWeaponCount { get; set; } + + public bool Alive => !Grid.IsDestroyed; + } + + public sealed class MatchState + { + public const int ContenderCount = 12; + public const float ArenaHalfExtent = 772f; + public const float PickupRadius = 7.0f; + public const float ContactGhostDuration = 5.0f; + public const float TouristHorizonMaxRange = 420f; + + private int _nextDropId = 1; + + public MatchState(int seed = 42) + { + Seed = seed; + Rng = new Random(seed); + Spectators = new SpectatorRing(seed + 101); + Broadcast = new BroadcastFeed(); + var rawCover = BuildCoverBoxes(); + Terrain = TerrainField.Generate((ulong)seed, rawCover); + ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain); + ArenaBoundaryBoxes = BuildBoundaryBoxes(); + + SpawnContenders(); + ScatterInitialLoot(); + Broadcast.EmitMatchStart(0f); + } + + public int Seed { get; } + public Random Rng { get; } + public float Time { get; set; } + public MatchPhase Phase { get; set; } = MatchPhase.Active; + + public TerrainField Terrain { get; } + public List Contenders { get; } = new(); + public SpectatorRing Spectators { get; } + public List GroundDrops { get; } = new(); + public List Tracers { get; } = new(); + public BroadcastFeed Broadcast { get; } + public IReadOnlyList ArenaCoverBoxes { get; } + public IReadOnlyList ArenaBoundaryBoxes { get; } + + public Dictionary ContenderContacts { get; } = new(); + public Dictionary SpectatorContacts { get; } = new(); + public int PlayerDetectedByCount { get; set; } + + public float? LastGunfireX { get; set; } + public float? LastGunfireZ { get; set; } + public float LastGunfireTime { get; set; } = -100f; + + public ContenderState Player => Contenders[0]; + + public event Action? ChassisSwapped; + + public static bool IsContactOnRadar(PlayerContactMemory? mem) + { + if (mem is null) + { + return false; + } + return mem.VisibleToPlayer || mem.FaintHorizonPing || (mem.HasEverBeenSeen && mem.LastSeenAge <= ContactGhostDuration); + } + + public PlayerContactMemory GetOrCreateContenderContact(int contenderId) + { + if (!ContenderContacts.TryGetValue(contenderId, out var mem)) + { + mem = new PlayerContactMemory(); + ContenderContacts[contenderId] = mem; + } + return mem; + } + + public PlayerContactMemory GetOrCreateSpectatorContact(int spectatorId) + { + if (!SpectatorContacts.TryGetValue(spectatorId, out var mem)) + { + mem = new PlayerContactMemory(); + SpectatorContacts[spectatorId] = mem; + } + return mem; + } + + public GroundDrop SpawnModuleDrop(float x, float z, ModuleSpec module) + { + var drop = new GroundDrop(_nextDropId++, x, z, null, module); + GroundDrops.Add(drop); + return drop; + } + + public GroundDrop SpawnChassisDrop(float x, float z, ChassisSpec chassis) + { + var drop = new GroundDrop(_nextDropId++, x, z, chassis, null); + GroundDrops.Add(drop); + return drop; + } + + public bool TryEquipCargo(int cargoIndex, string hardpointId) => + TryEquipCargo(0, cargoIndex, hardpointId); + + public bool TryEquipCargo(int contenderId, int cargoIndex, string hardpointId) + { + if (contenderId < 0 || contenderId >= Contenders.Count) + { + return false; + } + + var contender = Contenders[contenderId]; + if (!contender.Alive) + { + return false; + } + + var displaced = new List(); + bool ok = contender.Grid.TryEquipFromCargo(cargoIndex, hardpointId, displaced); + if (!ok) + { + return false; + } + + for (int i = 0; i < displaced.Count; i++) + { + SpawnModuleDrop(contender.X + 1.5f, contender.Z + 1.5f, displaced[i]); + } + return true; + } + + public GroundDrop? FindNearestInteractableDrop(int contenderId = 0) + { + if (contenderId < 0 || contenderId >= Contenders.Count) + { + return null; + } + + var contender = Contenders[contenderId]; + if (!contender.Alive) + { + return null; + } + + GroundDrop? nearest = null; + float bestDistSq = PickupRadius * PickupRadius; + + for (int i = 0; i < GroundDrops.Count; i++) + { + var d = GroundDrops[i]; + if (d.PickedUp || (d.Module is null && d.Chassis is null)) + { + continue; + } + + float dx = d.X - contender.X; + float dz = d.Z - contender.Z; + float d2 = dx * dx + dz * dz; + if (d2 <= bestDistSq) + { + bestDistSq = d2; + nearest = d; + } + } + + return nearest; + } + + public bool TryInteractNearestDrop(int contenderId = 0) + { + var nearest = FindNearestInteractableDrop(contenderId); + if (nearest is null) + { + return false; + } + + var contender = Contenders[contenderId]; + if (nearest.Module is not null) + { + return ExecuteModuleDropPickup(contenderId, contender, nearest); + } + if (nearest.Chassis is not null) + { + return ExecuteChassisDropSwap(contender, nearest); + } + return false; + } + + public bool TryPickupNearbyModule(int contenderId = 0) + { + if (contenderId < 0 || contenderId >= Contenders.Count) + { + return false; + } + + var contender = Contenders[contenderId]; + if (!contender.Alive) + { + return false; + } + + GroundDrop? nearest = null; + float bestDistSq = PickupRadius * PickupRadius; + + for (int i = 0; i < GroundDrops.Count; i++) + { + var d = GroundDrops[i]; + if (d.PickedUp || d.Module is null) + { + continue; + } + + float dx = d.X - contender.X; + float dz = d.Z - contender.Z; + float d2 = dx * dx + dz * dz; + if (d2 <= bestDistSq) + { + bestDistSq = d2; + nearest = d; + } + } + + return nearest is not null && ExecuteModuleDropPickup(contenderId, contender, nearest); + } + + public bool TrySwapNearbyChassis(int contenderId = 0) + { + if (contenderId < 0 || contenderId >= Contenders.Count) + { + return false; + } + + var contender = Contenders[contenderId]; + if (!contender.Alive) + { + return false; + } + + GroundDrop? nearest = null; + float bestDistSq = PickupRadius * PickupRadius; + + for (int i = 0; i < GroundDrops.Count; i++) + { + var d = GroundDrops[i]; + if (d.PickedUp || d.Chassis is null) + { + continue; + } + + float dx = d.X - contender.X; + float dz = d.Z - contender.Z; + float d2 = dx * dx + dz * dz; + if (d2 <= bestDistSq) + { + bestDistSq = d2; + nearest = d; + } + } + + return nearest is not null && ExecuteChassisDropSwap(contender, nearest); + } + + private bool ExecuteModuleDropPickup(int contenderId, ContenderState contender, GroundDrop drop) + { + if (drop.Module is null) + { + return false; + } + + if (!contender.Grid.TryQuickBoltOrCargo(drop.Module, out string? boltedHardpointId)) + { + return false; + } + + drop.PickedUp = true; + if (boltedHardpointId is not null) + { + Broadcast.EmitQuickBolt(Time, contenderId, drop.Module.Name, boltedHardpointId); + } + return true; + } + + private bool ExecuteChassisDropSwap(ContenderState contender, GroundDrop drop) + { + if (drop.Chassis is null) + { + return false; + } + + var oldChassis = contender.Grid.Spec; + var overflow = contender.Grid.SwapChassis(drop.Chassis); + drop.PickedUp = true; + + SpawnChassisDrop(contender.X - 2.2f, contender.Z - 2.2f, oldChassis); + for (int i = 0; i < overflow.Count; i++) + { + SpawnModuleDrop(contender.X + 1.5f + i * 0.7f, contender.Z - 1.5f, overflow[i]); + } + + contender.TargetHoverAltAgl = contender.Grid.Spec.IsVtol ? 10.0f : 3.0f; + contender.VerticalThrottleCmd = 0f; + contender.Y = Terrain.SampleHeight(contender.X, contender.Z) + contender.Grid.Spec.HalfHeight + + (contender.Grid.Spec.IsVtol ? contender.TargetHoverAltAgl : 0.15f); + contender.AiScavengeCooldown = 4.0f; + Broadcast.EmitChassisSwap(Time, contender.Id, contender.Grid.Spec.Name); + ChassisSwapped?.Invoke(contender); + return true; + } + + private void SpawnContenders() + { + var aiRoster = new List(Catalog.AllChassis); + for (int k = aiRoster.Count - 1; k > 0; k--) + { + int j = Rng.Next(k + 1); + (aiRoster[k], aiRoster[j]) = (aiRoster[j], aiRoster[k]); + } + + // Spawn 12 contenders (player + 11 AI) spread across r ~ 240..460m (well inside SafeRadius = 560m) + for (int i = 0; i < ContenderCount; i++) + { + float angle = (i / (float)ContenderCount) * MathF.Tau + (float)(Rng.NextDouble() - 0.5) * 0.16f; + float baseR = 250f + (float)Rng.NextDouble() * 195f; + float x = MathF.Cos(angle) * baseR; + float z = MathF.Sin(angle) * baseR; + + // Nudge radially inside [240, 460] if landing on a steep mesa cliff edge + for (int step = 0; step < 8; step++) + { + var (_, ny, _) = Terrain.SampleNormal(x, z); + if (ny >= 0.88f) + { + break; + } + float r = 245f + ((baseR - 245f + step * 28f) % 210f); + x = MathF.Cos(angle) * r; + z = MathF.Sin(angle) * r; + } + + float yaw = MathF.Atan2(-x, -z); + string name = i == 0 ? "Contender 01 (You)" : $"Contender {i + 1:00}"; + var grid = i == 0 + ? Catalog.CreateStarterBuggy() + : Catalog.CreateWithDefaultLoadout(aiRoster[(i - 1) % aiRoster.Count]); + var contender = new ContenderState(i, name, i == 0, grid, x, z, yaw); + if (grid.Spec.IsVtol) + { + contender.TargetHoverAltAgl = 10f; + } + contender.Y = Terrain.SampleHeight(x, z) + contender.Grid.Spec.HalfHeight + + (grid.Spec.IsVtol ? contender.TargetHoverAltAgl : 0.15f); + contender.AimY = contender.Y; + Contenders.Add(contender); + if (i > 0) + { + ContenderContacts[i] = new PlayerContactMemory(); + } + } + + for (int i = 0; i < Spectators.Spectators.Count; i++) + { + SpectatorContacts[Spectators.Spectators[i].Id] = new PlayerContactMemory(); + } + } + + private void ScatterInitialLoot() + { + // 14 deterministic salvageable chassis wrecks covering all non-starter vehicles in the 15-vehicle roster + var chassisPool = new List(Catalog.AllChassis.Count); + for (int i = 0; i < Catalog.AllChassis.Count; i++) + { + var c = Catalog.AllChassis[i]; + if (!string.Equals(c.Id, Catalog.Jackal.Id, StringComparison.OrdinalIgnoreCase)) + { + chassisPool.Add(c); + } + } + + for (int i = 0; i < chassisPool.Count; i++) + { + float angle = (i / (float)chassisPool.Count) * MathF.Tau + 0.35f; + float r = i >= chassisPool.Count - 3 ? (55f + (i % 3) * 18f) : (135f + (i % 4) * 85f); + SpawnChassisDrop(MathF.Cos(angle) * r, MathF.Sin(angle) * r, chassisPool[i]); + } + + // 26 ground salvage module drops spread across canyons, passes, and ruins (including 1x1 Wide-Arc PD!) + ModuleSpec[] salvagePool = + { + Catalog.Autocannon, Catalog.Flak, Catalog.PointDefenseFlak, Catalog.Recoilless, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762, + Catalog.DieselCore, Catalog.PointDefenseFlak, Catalog.Autocannon, Catalog.Flak, + Catalog.Recoilless, Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, + Catalog.Autocannon, Catalog.PointDefenseFlak, Catalog.Recoilless, Catalog.Flak, + Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762, + Catalog.Autocannon, Catalog.ImperialAegisPd + }; + + for (int i = 0; i < salvagePool.Length; i++) + { + float angle = (i / (float)salvagePool.Length) * MathF.Tau + 0.19f; + float r = 75f + (i % 5) * 95f; + SpawnModuleDrop(MathF.Cos(angle) * r, MathF.Sin(angle) * r, salvagePool[i]); + } + } + + private static IReadOnlyList BuildCoverBoxes() + { + // 36 deterministic ruin walls / cover blocks spaced >= 90m apart across the 1.5km valley + var boxes = new List(36); + + // Inner plaza ring (4 blocks at r = 68m) + for (int i = 0; i < 4; i++) + { + float a = (i / 4f) * MathF.Tau + 0.35f; + bool rot = i % 2 == 0; + boxes.Add(new ArenaBoxSpec( + MathF.Cos(a) * 68f, 2.0f, MathF.Sin(a) * 68f, + rot ? 5.2f : 1.6f, 2.0f, rot ? 1.6f : 5.2f, false)); + } + + // Inner-mid ruins (8 blocks at r = 175m) + for (int i = 0; i < 8; i++) + { + float a = (i / 8f) * MathF.Tau + 0.15f; + bool bunker = i % 3 == 0; + boxes.Add(new ArenaBoxSpec( + MathF.Cos(a) * 175f, 2.3f, MathF.Sin(a) * 175f, + bunker ? 3.8f : (i % 2 == 0 ? 5.8f : 1.8f), + 2.3f, + bunker ? 3.8f : (i % 2 == 0 ? 1.8f : 5.8f), + false)); + } + + // Mid-valley pass ruins (12 blocks at r = 335m) + for (int i = 0; i < 12; i++) + { + float a = (i / 12f) * MathF.Tau + 0.22f; + bool bunker = i % 2 == 0; + boxes.Add(new ArenaBoxSpec( + MathF.Cos(a) * 335f, 2.4f, MathF.Sin(a) * 335f, + bunker ? 4.0f : 6.0f, 2.4f, bunker ? 4.0f : 1.8f, false)); + } + + // Outer rim ruins (12 blocks at r = 515m) + for (int i = 0; i < 12; i++) + { + float a = (i / 12f) * MathF.Tau + 0.08f; + bool tall = i % 3 == 0; + boxes.Add(new ArenaBoxSpec( + MathF.Cos(a) * 515f, tall ? 2.8f : 2.2f, MathF.Sin(a) * 515f, + tall ? 3.6f : 5.6f, tall ? 2.8f : 2.2f, tall ? 3.6f : 1.8f, false)); + } + + return boxes; + } + + private static IReadOnlyList SeatBoxesOnTerrain(IReadOnlyList raw, TerrainField terrain) + { + var seated = new ArenaBoxSpec[raw.Count]; + for (int i = 0; i < raw.Count; i++) + { + var b = raw[i]; + float minY = terrain.SampleHeight(b.X, b.Z); + minY = MathF.Min(minY, terrain.SampleHeight(b.X - b.HalfX, b.Z - b.HalfZ)); + minY = MathF.Min(minY, terrain.SampleHeight(b.X + b.HalfX, b.Z - b.HalfZ)); + minY = MathF.Min(minY, terrain.SampleHeight(b.X - b.HalfX, b.Z + b.HalfZ)); + minY = MathF.Min(minY, terrain.SampleHeight(b.X + b.HalfX, b.Z + b.HalfZ)); + seated[i] = b with { Y = minY + b.HalfY }; + } + return seated; + } + + private static IReadOnlyList BuildBoundaryBoxes() + { + const float wallY = 12f; + const float wallHalfH = 60f; + const float wallHalfThick = 4f; + const float span = ArenaHalfExtent + wallHalfThick; + return new ArenaBoxSpec[] + { + new(0f, wallY, ArenaHalfExtent, span, wallHalfH, wallHalfThick, true), + new(0f, wallY, -ArenaHalfExtent, span, wallHalfH, wallHalfThick, true), + new(ArenaHalfExtent, wallY, 0f, wallHalfThick, wallHalfH, span, true), + new(-ArenaHalfExtent, wallY, 0f, wallHalfThick, wallHalfH, span, true) + }; + } + } +} diff --git a/src/RustToDust.Core/RustToDust.Core.csproj b/src/RustToDust.Core/RustToDust.Core.csproj new file mode 100644 index 0000000..04d0cf7 --- /dev/null +++ b/src/RustToDust.Core/RustToDust.Core.csproj @@ -0,0 +1,14 @@ + + + + net8.0 + enable + disable + + + + + + + + diff --git a/src/RustToDust.Core/SpectatorRing.cs b/src/RustToDust.Core/SpectatorRing.cs new file mode 100644 index 0000000..ad163f5 --- /dev/null +++ b/src/RustToDust.Core/SpectatorRing.cs @@ -0,0 +1,831 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum SpectatorTier + { + Tourist, + Patron, + Exemplar + } + + public enum SpectatorStance + { + Neutral, + Cleared, + Provoked + } + + public readonly record struct RingContact(int Id, float X, float Z, bool Alive, float Y = 0f, float HalfHeight = 1f); + + public sealed class SpectatorState + { + public SpectatorState( + int id, + SpectatorTier tier, + ChassisGrid grid, + float ringAngle, + float ringOffset, + float radarSignature, + float aimSpreadRad, + float maxSpeed, + float preferredRange) + { + Id = id; + Tier = tier; + Grid = grid; + RingAngle = ringAngle; + RingOffset = ringOffset; + RadarSignature = radarSignature; + AimSpreadRad = aimSpreadRad; + MaxSpeed = maxSpeed; + PreferredRange = preferredRange; + } + + public int Id { get; } + public SpectatorTier Tier { get; } + public ChassisGrid Grid { get; } + public float RingAngle { get; set; } + public float RingOffset { get; } + public float RadarSignature { get; } + public float AimSpreadRad { get; } + public float MaxSpeed { get; } + public float PreferredRange { get; } + + public SpectatorStance Stance { get; set; } = SpectatorStance.Neutral; + public int? TargetContenderId { get; set; } + public bool BroadcastWakeupEmitted { get; set; } + + public bool HasTargetLos { get; set; } + public float LastKnownTargetX { get; set; } + public float LastKnownTargetY { get; set; } + public float LastKnownTargetZ { get; set; } + public float TimeSinceLastSeen { get; set; } = float.PositiveInfinity; + + public bool HasNeutralAnchor { get; set; } + public float NeutralAnchorX { get; set; } + public float NeutralAnchorZ { get; set; } + public float NeutralAnchorSafeRadius { get; set; } + + public float X { get; set; } + public float Y { get; set; } + public float Z { get; set; } + public float Yaw { get; set; } + public bool Alive => !Grid.IsDestroyed; + } + + public sealed class SpectatorRing + { + public const float InitialRadius = 560f; + public const float MinRadius = 85f; + public const float GraceDuration = 30f; + public const float ShrinkDuration = 360f; + public const int DefaultSpectatorCount = 56; + public const float TargetMemoryDuration = 4.0f; + + private sealed class ContenderAwareness + { + public bool HasKnownPos; + public float LastKnownX; + public float LastKnownY; + public float LastKnownZ; + public float TimeSinceSeen = TargetMemoryDuration + 1f; + } + + private readonly List _spectators = new(); + private readonly Dictionary _aliveById = new(); + private readonly Dictionary _awarenessByContender = new(); + + public SpectatorRing(int seed = 1337, int count = DefaultSpectatorCount) + { + var rng = new Random(seed); + SafeRadius = InitialRadius; + SpawnRing(rng, count); + } + + public float SafeRadius { get; private set; } + public IReadOnlyList Spectators => _spectators; + + public void UpdateSafeRadius(float matchTime) + { + if (matchTime <= GraceDuration) + { + SafeRadius = InitialRadius; + return; + } + + float t = Math.Clamp((matchTime - GraceDuration) / ShrinkDuration, 0f, 1f); + SafeRadius = InitialRadius + (MinRadius - InitialRadius) * t; + } + + public void UpdateClearance(ReadOnlySpan contenders) => + UpdateClearance(contenders, 0f, null); + + public void UpdateClearance( + ReadOnlySpan contenders, + float dt, + Func? hasLos, + int tickIndex = -1) + { + _aliveById.Clear(); + for (int i = 0; i < contenders.Length; i++) + { + _aliveById[contenders[i].Id] = contenders[i].Alive; + } + + // Step 1: Update per-contender ring awareness ONLY from spectators with live LOS. + for (int c = 0; c < contenders.Length; c++) + { + var contender = contenders[c]; + var aw = GetOrCreateAwareness(contender.Id); + if (!contender.Alive || ComputeOutsideDist(contender) <= 0f) + { + aw.HasKnownPos = false; + aw.TimeSinceSeen = TargetMemoryDuration + 1f; + continue; + } + + aw.TimeSinceSeen += dt; + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive) + { + continue; + } + if (tickIndex >= 0 && spec.Stance == SpectatorStance.Neutral && ((spec.Id + tickIndex) % 6 != 0)) + { + continue; + } + + if (hasLos is null || hasLos(spec, contender)) + { + aw.HasKnownPos = true; + aw.LastKnownX = contender.X; + aw.LastKnownY = contender.Y; + aw.LastKnownZ = contender.Z; + aw.TimeSinceSeen = 0f; + break; + } + } + } + + // Step 2: Maintain existing Provoked and Cleared assignments sticky while target is valid. + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive) + { + ResetToNeutral(spec); + continue; + } + + if (spec.Stance == SpectatorStance.Provoked) + { + if (!spec.TargetContenderId.HasValue || + !TryFindAliveContact(contenders, spec.TargetContenderId.Value, out var contact)) + { + ResetToNeutral(spec); + } + else + { + UpdateWatcherTracking(spec, contact, dt, hasLos); + } + } + else if (spec.Stance == SpectatorStance.Cleared) + { + if (!spec.TargetContenderId.HasValue || + !TryFindAliveContact(contenders, spec.TargetContenderId.Value, out var contact) || + ComputeOutsideDist(contact) <= 0f) + { + ResetToNeutral(spec); + } + else + { + UpdateWatcherTracking(spec, contact, dt, hasLos); + } + } + else + { + spec.TargetContenderId = null; + spec.HasTargetLos = false; + spec.TimeSinceLastSeen = TargetMemoryDuration + 1f; + } + } + + // Step 3: Balance Cleared assignments per outside contender without reading occluded coords. + for (int c = 0; c < contenders.Length; c++) + { + var contender = contenders[c]; + if (!contender.Alive) + { + continue; + } + + float outsideDist = ComputeOutsideDist(contender); + if (outsideDist <= 0f) + { + continue; + } + + int allowedCleared = Math.Min(8, 1 + (int)(outsideDist / 12f)); + int currentCleared = CountClearedFor(contender.Id); + + // Drop excess if outsideDist shrank (prefer dropping stale no-LOS watchers first). + while (currentCleared > allowedCleared) + { + int dropIdx = FindExcessClearedToDrop(contender.Id); + if (dropIdx < 0) + { + break; + } + ResetToNeutral(_spectators[dropIdx]); + currentCleared--; + } + + // If full with a stale expired no-LOS watcher while a Neutral watcher has live LOS, rotate one slot. + if (currentCleared == allowedCleared && hasLos is not null && AnyNeutralHasLos(contender, hasLos, tickIndex)) + { + int staleIdx = FindStaleNoLosCleared(contender.Id); + if (staleIdx >= 0) + { + ResetToNeutral(_spectators[staleIdx]); + currentCleared--; + } + } + + // Pass 1: Spectators with direct live LOS to the offender. + while (currentCleared < allowedCleared) + { + int bestIdx = -1; + float bestDistSq = float.PositiveInfinity; + + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive || spec.Stance != SpectatorStance.Neutral) + { + continue; + } + if (tickIndex >= 0 && ((spec.Id + tickIndex) % 6 != 0)) + { + continue; + } + + if (hasLos is not null && !hasLos(spec, contender)) + { + continue; + } + + float dx = spec.X - contender.X; + float dz = spec.Z - contender.Z; + float d2 = dx * dx + dz * dz; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestIdx = i; + } + } + + if (bestIdx < 0) + { + break; + } + + var chosen = _spectators[bestIdx]; + chosen.Stance = SpectatorStance.Cleared; + chosen.TargetContenderId = contender.Id; + chosen.HasTargetLos = true; + chosen.LastKnownTargetX = contender.X; + chosen.LastKnownTargetY = contender.Y; + chosen.LastKnownTargetZ = contender.Z; + chosen.TimeSinceLastSeen = 0f; + currentCleared++; + } + + // Pass 2: Reinforce from already-observed LastKnownPos ONLY (never read live occluded contender.X/Z). + if (currentCleared < allowedCleared && + hasLos is not null && + _awarenessByContender.TryGetValue(contender.Id, out var aw) && + aw.HasKnownPos) + { + const float maxPass2RadiusSq = 240f * 240f; + while (currentCleared < allowedCleared) + { + int bestIdx = -1; + float bestDistSq = float.PositiveInfinity; + + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive || spec.Stance != SpectatorStance.Neutral) + { + continue; + } + + float dx = spec.X - aw.LastKnownX; + float dz = spec.Z - aw.LastKnownZ; + float d2 = dx * dx + dz * dz; + if (d2 <= maxPass2RadiusSq && d2 < bestDistSq) + { + bestDistSq = d2; + bestIdx = i; + } + } + + if (bestIdx < 0) + { + break; + } + + var chosen = _spectators[bestIdx]; + chosen.Stance = SpectatorStance.Cleared; + chosen.TargetContenderId = contender.Id; + chosen.HasTargetLos = false; + chosen.LastKnownTargetX = aw.LastKnownX; + chosen.LastKnownTargetY = aw.LastKnownY; + chosen.LastKnownTargetZ = aw.LastKnownZ; + chosen.TimeSinceLastSeen = aw.TimeSinceSeen; + currentCleared++; + } + } + } + } + + public bool OnSpectatorDamaged( + SpectatorState spectator, + int attackerContenderId, + float? incomingDirX = null, + float? incomingDirZ = null) + { + if (!spectator.Alive) + { + return false; + } + + if (spectator.Stance == SpectatorStance.Neutral || spectator.Stance == SpectatorStance.Cleared) + { + bool sameTargetWithFreshMemory = spectator.TargetContenderId == attackerContenderId && + (spectator.HasTargetLos || spectator.TimeSinceLastSeen < TargetMemoryDuration); + + spectator.Stance = SpectatorStance.Provoked; + spectator.TargetContenderId = attackerContenderId; + + if (!sameTargetWithFreshMemory) + { + spectator.HasTargetLos = false; + if (_awarenessByContender.TryGetValue(attackerContenderId, out var aw) && + aw.HasKnownPos && + aw.TimeSinceSeen < TargetMemoryDuration) + { + spectator.LastKnownTargetX = aw.LastKnownX; + spectator.LastKnownTargetY = aw.LastKnownY; + spectator.LastKnownTargetZ = aw.LastKnownZ; + spectator.TimeSinceLastSeen = aw.TimeSinceSeen; + } + else if (incomingDirX.HasValue && incomingDirZ.HasValue) + { + float dLen = MathF.Sqrt(incomingDirX.Value * incomingDirX.Value + incomingDirZ.Value * incomingDirZ.Value); + float nx = dLen > 1e-4f ? incomingDirX.Value / dLen : MathF.Sin(spectator.Yaw); + float nz = dLen > 1e-4f ? incomingDirZ.Value / dLen : MathF.Cos(spectator.Yaw); + spectator.LastKnownTargetX = spectator.X + nx * 60f; + spectator.LastKnownTargetY = spectator.Y; + spectator.LastKnownTargetZ = spectator.Z + nz * 60f; + spectator.TimeSinceLastSeen = 0.5f; + } + else + { + spectator.LastKnownTargetX = spectator.X + MathF.Sin(spectator.Yaw) * 40f; + spectator.LastKnownTargetY = spectator.Y; + spectator.LastKnownTargetZ = spectator.Z + MathF.Cos(spectator.Yaw) * 40f; + spectator.TimeSinceLastSeen = TargetMemoryDuration; + } + } + return true; + } + + return false; + } + + private ContenderAwareness GetOrCreateAwareness(int contenderId) + { + if (!_awarenessByContender.TryGetValue(contenderId, out var aw)) + { + aw = new ContenderAwareness(); + _awarenessByContender[contenderId] = aw; + } + return aw; + } + + private float ComputeOutsideDist(in RingContact contact) + { + float distFromCenter = MathF.Sqrt(contact.X * contact.X + contact.Z * contact.Z); + return MathF.Max(0f, distFromCenter - SafeRadius); + } + + private static void ResetToNeutral(SpectatorState spec) + { + spec.Stance = SpectatorStance.Neutral; + spec.TargetContenderId = null; + spec.HasTargetLos = false; + spec.TimeSinceLastSeen = TargetMemoryDuration + 1f; + } + + private static void UpdateWatcherTracking( + SpectatorState spec, + in RingContact contact, + float dt, + Func? hasLos) + { + bool los = hasLos is null || hasLos(spec, contact); + if (los) + { + spec.HasTargetLos = true; + spec.LastKnownTargetX = contact.X; + spec.LastKnownTargetY = contact.Y; + spec.LastKnownTargetZ = contact.Z; + spec.TimeSinceLastSeen = 0f; + } + else + { + spec.HasTargetLos = false; + spec.TimeSinceLastSeen += dt; + } + } + + private static bool TryFindAliveContact(ReadOnlySpan contenders, int id, out RingContact contact) + { + for (int i = 0; i < contenders.Length; i++) + { + if (contenders[i].Id == id && contenders[i].Alive) + { + contact = contenders[i]; + return true; + } + } + contact = default; + return false; + } + + private int FindExcessClearedToDrop(int contenderId) + { + int bestIdx = -1; + bool bestNoLos = false; + float bestAge = -1f; + float bestDistSq = -1f; + + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive || spec.Stance != SpectatorStance.Cleared || spec.TargetContenderId != contenderId) + { + continue; + } + + bool noLos = !spec.HasTargetLos; + float age = spec.TimeSinceLastSeen; + float dx = spec.X - spec.LastKnownTargetX; + float dz = spec.Z - spec.LastKnownTargetZ; + float d2 = dx * dx + dz * dz; + + if (bestIdx < 0 || + (noLos && !bestNoLos) || + (noLos == bestNoLos && (age > bestAge + 1e-4f || (MathF.Abs(age - bestAge) <= 1e-4f && d2 > bestDistSq)))) + { + bestIdx = i; + bestNoLos = noLos; + bestAge = age; + bestDistSq = d2; + } + } + + return bestIdx; + } + + private bool AnyNeutralHasLos(in RingContact contender, Func hasLos, int tickIndex) + { + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (spec.Alive && spec.Stance == SpectatorStance.Neutral && + (tickIndex < 0 || ((spec.Id + tickIndex) % 6 == 0)) && + hasLos(spec, contender)) + { + return true; + } + } + return false; + } + + private int FindStaleNoLosCleared(int contenderId) + { + int bestIdx = -1; + float bestAge = TargetMemoryDuration; + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (spec.Alive && + spec.Stance == SpectatorStance.Cleared && + spec.TargetContenderId == contenderId && + !spec.HasTargetLos && + spec.TimeSinceLastSeen >= bestAge) + { + bestAge = spec.TimeSinceLastSeen; + bestIdx = i; + } + } + return bestIdx; + } + + public void AdvancePerimeterOrbits(float dt) + { + for (int i = 0; i < _spectators.Count; i++) + { + var spec = _spectators[i]; + if (!spec.Alive || spec.Stance != SpectatorStance.Neutral) + { + continue; + } + + // Only ostentatious Tourists orbit continuously in plain sight; + // Patrons and Exemplars hold their chosen high-ground / ambush positions. + if (spec.Tier == SpectatorTier.Tourist) + { + spec.RingAngle += 0.02f * dt; + } + } + } + + public (float X, float Z) GetPerimeterSlot(SpectatorState spec) + { + float r = SafeRadius + spec.RingOffset; + return (MathF.Cos(spec.RingAngle) * r, MathF.Sin(spec.RingAngle) * r); + } + + public (float X, float Z) GetNeutralGoal( + SpectatorState spec, + TerrainField? terrain, + IReadOnlyList? coverBoxes) + { + if (spec.Tier == SpectatorTier.Tourist || terrain is null) + { + return GetPerimeterSlot(spec); + } + + if (spec.HasNeutralAnchor && MathF.Abs(SafeRadius - spec.NeutralAnchorSafeRadius) < 8f) + { + return (spec.NeutralAnchorX, spec.NeutralAnchorZ); + } + + float bestX = MathF.Cos(spec.RingAngle) * (SafeRadius + spec.RingOffset); + float bestZ = MathF.Sin(spec.RingAngle) * (SafeRadius + spec.RingOffset); + float bestScore = float.NegativeInfinity; + float maxBound = TerrainField.HalfExtent - 18f; + + for (int ai = -3; ai <= 3; ai++) + { + float angle = spec.RingAngle + ai * 0.075f; + float cosA = MathF.Cos(angle); + float sinA = MathF.Sin(angle); + + for (int ri = 0; ri < 3; ri++) + { + float r = SafeRadius + 18f + ri * 26f; + float cx = Math.Clamp(cosA * r, -maxBound, maxBound); + float cz = Math.Clamp(sinA * r, -maxBound, maxBound); + + float distLen = MathF.Sqrt(cx * cx + cz * cz); + float inX = distLen > 1f ? -cx / distLen : 0f; + float inZ = distLen > 1f ? -cz / distLen : -1f; + + float hHere = terrain.SampleHeight(cx, cz); + float hInward = terrain.SampleHeight(cx + inX * 26f, cz + inZ * 26f); + + float score; + if (spec.Tier == SpectatorTier.Patron) + { + // Patrons claim elevated vantage points overlooking the arena interior + score = hHere * 2.0f + MathF.Max(0f, hHere - hInward) * 1.1f; + } + else + { + // Exemplars seek reverse-slope / low-profile / cover-adjacent ambush spots + float reverseSlope = MathF.Max(0f, hInward - hHere) * 3.0f; + float lowProfile = -hHere * 0.8f; + float coverBonus = 0f; + if (coverBoxes is not null) + { + for (int b = 0; b < coverBoxes.Count; b++) + { + var box = coverBoxes[b]; + float bx = box.X - cx; + float bz = box.Z - cz; + float bDist2 = bx * bx + bz * bz; + if (bDist2 < 28f * 28f && bDist2 > 4f * 4f) + { + // Prefer cover standing between the exemplar and the interior + float forwardDot = bx * inX + bz * inZ; + if (forwardDot > 2f) + { + coverBonus = 14f; + break; + } + } + } + } + score = reverseSlope + lowProfile + coverBonus; + } + + if (score > bestScore) + { + bestScore = score; + bestX = cx; + bestZ = cz; + } + } + } + + spec.NeutralAnchorX = bestX; + spec.NeutralAnchorZ = bestZ; + spec.NeutralAnchorSafeRadius = SafeRadius; + spec.HasNeutralAnchor = true; + return (bestX, bestZ); + } + + public int CountClearedFor(int contenderId) + { + int count = 0; + for (int i = 0; i < _spectators.Count; i++) + { + var s = _spectators[i]; + if (s.Alive && s.Stance == SpectatorStance.Cleared && s.TargetContenderId == contenderId) + { + count++; + } + } + return count; + } + + public int CountProvokedFor(int contenderId) + { + int count = 0; + for (int i = 0; i < _spectators.Count; i++) + { + var s = _spectators[i]; + if (s.Alive && s.Stance == SpectatorStance.Provoked && s.TargetContenderId == contenderId) + { + count++; + } + } + return count; + } + + public static List RollSalvageDrops(SpectatorState spec, Random rng) + { + var drops = new List(); + switch (spec.Tier) + { + case SpectatorTier.Tourist: + { + int count = rng.Next(1, 3); + for (int i = 0; i < count; i++) + { + drops.Add(Catalog.ImperialModules[rng.Next(Catalog.ImperialModules.Count)]); + } + break; + } + case SpectatorTier.Patron: + { + if (rng.NextDouble() < 0.5) + { + drops.Add(Catalog.ImperialModules[rng.Next(Catalog.ImperialModules.Count)]); + } + else + { + drops.Add(Catalog.HumanModules[rng.Next(Catalog.HumanModules.Count)]); + } + break; + } + case SpectatorTier.Exemplar: + { + if (rng.NextDouble() < 0.4) + { + drops.Add(Catalog.WeldedPlate); + } + break; + } + } + return drops; + } + + private void SpawnRing(Random rng, int count) + { + int touristCount = (int)MathF.Round(count * 0.45f); + int patronCount = (int)MathF.Round(count * 0.35f); + + var tiers = new List(count); + for (int i = 0; i < count; i++) + { + if (i < touristCount) tiers.Add(SpectatorTier.Tourist); + else if (i < touristCount + patronCount) tiers.Add(SpectatorTier.Patron); + else tiers.Add(SpectatorTier.Exemplar); + } + + for (int i = tiers.Count - 1; i > 0; i--) + { + int j = rng.Next(i + 1); + (tiers[i], tiers[j]) = (tiers[j], tiers[i]); + } + + for (int i = 0; i < count; i++) + { + float angle = (i / (float)count) * MathF.Tau; + float ringOffset = 25f + (float)rng.NextDouble() * 50f; + var tier = tiers[i]; + + var spec = CreateSpectator(1000 + i, tier, angle, ringOffset); + (float px, float pz) = GetPerimeterSlot(spec); + spec.X = px; + spec.Y = spec.Grid.Spec.HalfHeight + 0.1f; + spec.Z = pz; + spec.Yaw = MathF.Atan2(-px, -pz); + _spectators.Add(spec); + } + } + + private static void MountRequired(ChassisGrid grid, ModuleSpec mod, string hardpointId) + { + if (!grid.TryMount(mod, hardpointId)) + { + throw new InvalidOperationException( + $"Failed to mount '{mod.Id}' onto '{grid.Spec.Id}.{hardpointId}'."); + } + } + + private static SpectatorState CreateSpectator(int id, SpectatorTier tier, float angle, float ringOffset) + { + switch (tier) + { + case SpectatorTier.Tourist: + { + var grid = new ChassisGrid(Catalog.Paladin); + MountRequired(grid, Catalog.GildedLance, "hp.weapon.arm_l"); + MountRequired(grid, Catalog.ImperialAegisPd, "hp.weapon.sh_l"); + MountRequired(grid, Catalog.TouringPlasma, "hp.weapon.sh_r"); + MountRequired(grid, Catalog.NobleCore, "hp.engine.chest"); + MountRequired(grid, Catalog.GoldRadiator, "hp.radiator.back_l"); + MountRequired(grid, Catalog.GildedPlate, "hp.armor.torso"); + return new SpectatorState( + id, tier, grid, angle, ringOffset, + radarSignature: 1.0f, + aimSpreadRad: 0.14f, + maxSpeed: 18f, + preferredRange: 95f); + } + case SpectatorTier.Patron: + { + var grid = new ChassisGrid(Catalog.Raptor); + MountRequired(grid, Catalog.Autocannon, "hp.weapon.arm_l"); + MountRequired(grid, Catalog.Flak, "hp.weapon.arm_r"); + MountRequired(grid, Catalog.TurboCore, "hp.engine.chest"); + MountRequired(grid, Catalog.CopperRad, "hp.radiator.sh_l"); + return new SpectatorState( + id, tier, grid, angle, ringOffset, + radarSignature: 0.6f, + aimSpreadRad: 0.055f, + maxSpeed: 26f, + preferredRange: 82f); + } + default: // Exemplar + { + var exemplarSpec = Catalog.Raptor with + { + Id = "exemplar_frame", + Name = "Exemplar Frame", + BaseCellArmor = 22f, + MassKg = 1150f, + BaseThrust = 26000f, + BaseTurnRate = 6.2f, + MaxSpeed = 40f, + HalfWidth = 0.8f, + HalfHeight = 1.55f, + HalfLength = 0.8f + }; + var grid = new ChassisGrid(exemplarSpec); + MountRequired(grid, Catalog.GildedLance, "hp.weapon.arm_r"); + MountRequired(grid, Catalog.TouringPlasma, "hp.weapon.arm_l"); + MountRequired(grid, Catalog.NobleCore, "hp.engine.chest"); + MountRequired(grid, Catalog.GoldRadiator, "hp.radiator.sh_l"); + MountRequired(grid, Catalog.GoldRadiator, "hp.radiator.sh_r"); + return new SpectatorState( + id, tier, grid, angle, ringOffset, + radarSignature: 0.18f, + aimSpreadRad: 0.006f, + maxSpeed: 40f, + preferredRange: 58f); + } + } + } + } +} diff --git a/src/RustToDust.Core/TerrainField.cs b/src/RustToDust.Core/TerrainField.cs new file mode 100644 index 0000000..dba91a2 --- /dev/null +++ b/src/RustToDust.Core/TerrainField.cs @@ -0,0 +1,712 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum TerrainBrushKind + { + DuneRidge, + Mesa, + SalvagePad, + Road, + Crater, + Track, + Scorch + } + + public readonly record struct TerrainBrush( + int Id, + TerrainBrushKind Kind, + float X, + float Z, + float RotationRad, + float RadiusX, + float RadiusZ, + float HeightDelta, + float Roughness, + float Metallic, + float AlbedoR, + float AlbedoG, + float AlbedoB, + bool Dynamic); + + public sealed class TerrainField + { + public const float ArenaSize = 1536f; + public const float HalfExtent = 768f; + public const int TileGridCount = 8; + public const float TileSize = ArenaSize / TileGridCount; // 192m + public const float MinWorldHeight = -18f; + public const float MaxWorldHeight = 52f; + public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m + public const int MaxDynamicDecals = 256; + + private readonly record struct BrushPrecomp( + float CosR, + float SinR, + float InvRx, + float InvRz, + float MaxRadiusSq) + { + public static BrushPrecomp From(in TerrainBrush b) + { + float maxR = MathF.Max(0.1f, MathF.Max(b.RadiusX, b.RadiusZ)); + return new BrushPrecomp( + MathF.Cos(b.RotationRad), + MathF.Sin(b.RotationRad), + 1f / MathF.Max(0.1f, b.RadiusX), + 1f / MathF.Max(0.1f, b.RadiusZ), + maxR * maxR); + } + } + + private readonly List _brushes = new(); + private readonly List _brushPrecomps = new(); + private readonly List[,] _tileBrushIndices = new List[TileGridCount, TileGridCount]; + private readonly float[,] _tileMaxHeight = new float[TileGridCount, TileGridCount]; + private readonly Queue _dynamicDecalSlots = new(); + private int _nextBrushId = 1; + + public TerrainField(ulong seed) + { + Seed = seed; + TileVersions = new int[TileGridCount, TileGridCount]; + for (int tz = 0; tz < TileGridCount; tz++) + { + for (int tx = 0; tx < TileGridCount; tx++) + { + _tileBrushIndices[tx, tz] = new List(32); + } + } + } + + public ulong Seed { get; } + public IReadOnlyList Brushes => _brushes; + public int[,] TileVersions { get; } + public ulong DirtyTileMask { get; private set; } + + public void ClearDirtyMask() => DirtyTileMask = 0UL; + + public IReadOnlyList GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz]; + + public static TerrainField Generate(ulong seed, IReadOnlyList coverBoxes) + { + var field = new TerrainField(seed); + var rng = new Random((int)(seed ^ (seed >> 32))); + + // 1. Flat compacted salvage pads around cover ruins & center plaza (keeps cover seated cleanly near ~0m) + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.SalvagePad, + X: 0f, + Z: 0f, + RotationRad: 0f, + RadiusX: 28f, + RadiusZ: 28f, + HeightDelta: 0.20f, + Roughness: 0.90f, + Metallic: 0.05f, + AlbedoR: 0.44f, + AlbedoG: 0.40f, + AlbedoB: 0.35f, + Dynamic: false)); + + for (int i = 0; i < coverBoxes.Count; i++) + { + var box = coverBoxes[i]; + float padR = MathF.Max(box.HalfX, box.HalfZ) + 12f; + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.SalvagePad, + X: box.X, + Z: box.Z, + RotationRad: 0f, + RadiusX: padR, + RadiusZ: padR, + HeightDelta: 0.10f + (float)rng.NextDouble() * 0.25f, + Roughness: 0.92f, + Metallic: 0.04f, + AlbedoR: 0.42f, + AlbedoG: 0.38f, + AlbedoB: 0.34f, + Dynamic: false)); + } + + // 2. Dirt track ring segments around the mid-valley loop (r ~ 260..290m) + const int roadCount = 16; + for (int i = 0; i < roadCount; i++) + { + float angle = (i / (float)roadCount) * MathF.Tau + 0.14f; + float r = 275f + (float)(rng.NextDouble() * 20.0 - 10.0); + float rx = MathF.Cos(angle) * r; + float rz = MathF.Sin(angle) * r; + float tangentRot = angle + MathF.PI * 0.5f; + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Road, + X: rx, + Z: rz, + RotationRad: tangentRot, + RadiusX: 64f, + RadiusZ: 11f, + HeightDelta: -0.22f, + Roughness: 0.94f, + Metallic: 0.02f, + AlbedoR: 0.56f, + AlbedoG: 0.40f, + AlbedoB: 0.25f, + Dynamic: false)); + } + + // 3. Tall flat-topped rust mesas & buttes (+22m..+44m, radius 45..110m) for huge landmarks and full hull-down cover + int mesaCount = 0; + int attempts = 0; + while (mesaCount < 14 && attempts < 500) + { + attempts++; + float angle = (float)(rng.NextDouble() * MathF.Tau); + float dist = 125f + (float)rng.NextDouble() * 520f; + float x = MathF.Cos(angle) * dist; + float z = MathF.Sin(angle) * dist; + float rx = 45f + (float)rng.NextDouble() * 65f; + float rz = 45f + (float)rng.NextDouble() * 65f; + + if (MathF.Abs(field.SampleHeight(x, z)) > 4.0f) + { + continue; + } + + var candidate = new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Mesa, + X: x, + Z: z, + RotationRad: (float)(rng.NextDouble() * MathF.PI), + RadiusX: rx, + RadiusZ: rz, + HeightDelta: 22f + (float)rng.NextDouble() * 22f, + Roughness: 0.86f, + Metallic: 0.08f, + AlbedoR: 0.48f, + AlbedoG: 0.25f, + AlbedoB: 0.17f, + Dynamic: false); + + if (!IsBrushClearOfCover(in candidate, coverBoxes)) + { + continue; + } + + field.AddBrush(candidate); + mesaCount++; + } + + // 4. Sweeping high sand dune ridges (+10m..+26m, RadiusX 90..180m, RadiusZ 30..65m) forming blind crests + int duneCount = 0; + attempts = 0; + while (duneCount < 30 && attempts < 700) + { + attempts++; + float x = (float)(rng.NextDouble() * 1280.0 - 640.0); + float z = (float)(rng.NextDouble() * 1280.0 - 640.0); + float radiusX = 90f + (float)rng.NextDouble() * 90f; + float radiusZ = 30f + (float)rng.NextDouble() * 35f; + + if (field.SampleHeight(x, z) > 15f) + { + continue; + } + + float heightDelta = 10f + (float)rng.NextDouble() * 16f; + float rot = (float)(rng.NextDouble() * MathF.PI); + var candidate = new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.DuneRidge, + X: x, + Z: z, + RotationRad: rot, + RadiusX: radiusX, + RadiusZ: radiusZ, + HeightDelta: heightDelta, + Roughness: 0.89f, + Metallic: 0.02f, + AlbedoR: 0.78f, + AlbedoG: 0.56f, + AlbedoB: 0.34f, + Dynamic: false); + + if (!IsBrushClearOfCover(in candidate, coverBoxes)) + { + continue; + } + + field.AddBrush(candidate); + duneCount++; + } + + // 5. Deep dry canyons / arroyos (-8m..-16m carved washes) letting buggies run concealed below the skyline + int canyonCount = 0; + attempts = 0; + while (canyonCount < 12 && attempts < 450) + { + attempts++; + float x = (float)(rng.NextDouble() * 1160.0 - 580.0); + float z = (float)(rng.NextDouble() * 1160.0 - 580.0); + float radiusX = 42f + (float)rng.NextDouble() * 34f; + float radiusZ = 115f + (float)rng.NextDouble() * 85f; + + float curH = field.SampleHeight(x, z); + if (curH < -2.5f || curH > 12f) + { + continue; + } + + float heightDelta = -(8f + (float)rng.NextDouble() * 7.5f); + float rot = (float)(rng.NextDouble() * MathF.PI); + var candidate = new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.DuneRidge, + X: x, + Z: z, + RotationRad: rot, + RadiusX: radiusX, + RadiusZ: radiusZ, + HeightDelta: heightDelta, + Roughness: 0.96f, + Metallic: 0.02f, + AlbedoR: 0.54f, + AlbedoG: 0.38f, + AlbedoB: 0.25f, + Dynamic: false); + + if (!IsBrushClearOfCover(in candidate, coverBoxes)) + { + continue; + } + + field.AddBrush(candidate); + canyonCount++; + } + + // Bump all initial tile versions to 1 so clients detect initial bake needed + for (int tz = 0; tz < TileGridCount; tz++) + { + for (int tx = 0; tx < TileGridCount; tx++) + { + field.TileVersions[tx, tz] = 1; + field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx); + } + } + + return field; + } + + public void StampCrater(float x, float z, float radius, float depth) + { + float clampedR = Math.Clamp(radius, 1.2f, 16f); + float clampedDepth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f); + AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Crater, + X: x, + Z: z, + RotationRad: 0f, + RadiusX: clampedR, + RadiusZ: clampedR, + HeightDelta: -clampedDepth, + Roughness: 0.96f, + Metallic: 0.12f, + AlbedoR: 0.15f, + AlbedoG: 0.12f, + AlbedoB: 0.10f, + Dynamic: true)); + } + + public void StampTrack(float x, float z, float yaw, float width, float length) + { + SetDynamicDecal(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Track, + X: x, + Z: z, + RotationRad: -yaw + MathF.PI * 0.5f, + RadiusX: Math.Clamp(length * 0.5f, 0.8f, 6f), + RadiusZ: Math.Clamp(width * 0.5f, 0.5f, 4f), + HeightDelta: -0.04f, + Roughness: 0.95f, + Metallic: 0.02f, + AlbedoR: 0.42f, + AlbedoG: 0.29f, + AlbedoB: 0.18f, + Dynamic: true)); + } + + public void StampScorch(float x, float z, float radius) + { + float r = Math.Clamp(radius, 0.8f, 10f); + SetDynamicDecal(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Scorch, + X: x, + Z: z, + RotationRad: 0f, + RadiusX: r, + RadiusZ: r, + HeightDelta: 0f, + Roughness: 0.95f, + Metallic: 0.10f, + AlbedoR: 0.14f, + AlbedoG: 0.11f, + AlbedoB: 0.10f, + Dynamic: true)); + } + + public float SampleHeight(float x, float z) + { + float cx = Math.Clamp(x, -HalfExtent, HalfExtent); + float cz = Math.Clamp(z, -HalfExtent, HalfExtent); + WorldToTile(cx, cz, out int tx, out int tz); + + float h = 0f; + var indices = _tileBrushIndices[tx, tz]; + for (int i = 0; i < indices.Count; i++) + { + int idx = indices[i]; + var b = _brushes[idx]; + if (b.Kind == TerrainBrushKind.Scorch) + { + continue; + } + h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz); + } + + return Math.Clamp(h, MinWorldHeight, MaxWorldHeight); + } + + public (float Nx, float Ny, float Nz) SampleNormal(float x, float z) + { + const float eps = 0.5f; + float hL = SampleHeight(x - eps, z); + float hR = SampleHeight(x + eps, z); + float hD = SampleHeight(x, z - eps); + float hU = SampleHeight(x, z + eps); + + float nx = hL - hR; + float ny = 2f * eps; + float nz = hD - hU; + float len = MathF.Sqrt(nx * nx + ny * ny + nz * nz); + if (len < 1e-5f) + { + return (0f, 1f, 0f); + } + return (nx / len, ny / len, nz / len); + } + + public bool Raycast( + float ox, float oy, float oz, + float dx, float dy, float dz, + float maxDistance, + out float hitX, out float hitY, out float hitZ, out float hitDist) + { + float prevT = 0f; + float prevDiff = oy - SampleHeight(ox, oz); + if (prevDiff <= 0f) + { + hitX = ox; + hitY = oy; + hitZ = oz; + hitDist = 0f; + return true; + } + + float t = 1.5f; + while (prevT < maxDistance) + { + float ct = MathF.Min(t, maxDistance); + float px = ox + dx * ct; + float py = oy + dy * ct; + float pz = oz + dz * ct; + + float cx = Math.Clamp(px, -HalfExtent, HalfExtent); + float cz = Math.Clamp(pz, -HalfExtent, HalfExtent); + WorldToTile(cx, cz, out int tx, out int tz); + if (py <= _tileMaxHeight[tx, tz]) + { + float diff = py - SampleHeight(px, pz); + if (diff <= 0f) + { + // Binary refine between prevT and ct + float lo = prevT; + float hi = ct; + for (int iter = 0; iter < 5; iter++) + { + float mid = 0.5f * (lo + hi); + float mx = ox + dx * mid; + float my = oy + dy * mid; + float mz = oz + dz * mid; + if (my - SampleHeight(mx, mz) > 0f) + { + lo = mid; + } + else + { + hi = mid; + } + } + + hitDist = 0.5f * (lo + hi); + hitX = ox + dx * hitDist; + hitZ = oz + dz * hitDist; + hitY = SampleHeight(hitX, hitZ); + return true; + } + } + + prevT = ct; + if (ct >= maxDistance) + { + break; + } + + float step = ct < 160f ? 1.5f : 2.5f; + if (py > _tileMaxHeight[tx, tz] + 1.5f) + { + float farT = MathF.Min(ct + 14f, maxDistance); + float fx = Math.Clamp(ox + dx * farT, -HalfExtent, HalfExtent); + float fz = Math.Clamp(oz + dz * farT, -HalfExtent, HalfExtent); + WorldToTile(fx, fz, out int ftx, out int ftz); + float fy = oy + dy * farT; + if (ftx == tx && ftz == tz && fy > _tileMaxHeight[tx, tz] + 0.5f) + { + step = MathF.Max(step, farT - ct); + } + } + t = ct + step; + } + + hitX = 0f; + hitY = 0f; + hitZ = 0f; + hitDist = maxDistance; + return false; + } + + private static float EvaluateBrushHeightFast(in TerrainBrush b, in BrushPrecomp p, float worldX, float worldZ) + { + float dx = worldX - b.X; + float dz = worldZ - b.Z; + if (dx * dx + dz * dz >= p.MaxRadiusSq) + { + return 0f; + } + + float lx = dx * p.CosR + dz * p.SinR; + float lz = -dx * p.SinR + dz * p.CosR; + + float u = lx * p.InvRx; + float v = lz * p.InvRz; + float r2 = u * u + v * v; + if (r2 >= 1f) + { + return 0f; + } + + return EvaluateBrushKernel(in b, u, r2); + } + + public static float EvaluateBrushHeight(in TerrainBrush b, float worldX, float worldZ) + { + float dx = worldX - b.X; + float dz = worldZ - b.Z; + float cosR = MathF.Cos(b.RotationRad); + float sinR = MathF.Sin(b.RotationRad); + float lx = dx * cosR + dz * sinR; + float lz = -dx * sinR + dz * cosR; + + float u = lx / MathF.Max(0.1f, b.RadiusX); + float v = lz / MathF.Max(0.1f, b.RadiusZ); + float r2 = u * u + v * v; + if (r2 >= 1f) + { + return 0f; + } + + return EvaluateBrushKernel(in b, u, r2); + } + + private static float EvaluateBrushKernel(in TerrainBrush b, float u, float r2) + { + switch (b.Kind) + { + case TerrainBrushKind.DuneRidge: + { + float env = 1f - r2; + env *= env; + float ridge = MathF.Max(0f, 1f - u * u); + float asym = 1f + 0.32f * u; + return b.HeightDelta * env * (0.35f + 0.65f * ridge) * asym; + } + case TerrainBrushKind.Mesa: + { + float r = MathF.Sqrt(r2); + float t = Math.Clamp((1f - r) / 0.45f, 0f, 1f); + float plateau = t * t * (3f - 2f * t); + return b.HeightDelta * plateau; + } + case TerrainBrushKind.SalvagePad: + case TerrainBrushKind.Road: + case TerrainBrushKind.Track: + { + float env = 1f - r2; + return b.HeightDelta * env * env; + } + case TerrainBrushKind.Crater: + { + float r = MathF.Sqrt(r2); + float depth = MathF.Abs(b.HeightDelta); + float pitT = Math.Clamp(1f - r / 0.62f, 0f, 1f); + float pit = -depth * pitT * pitT * (3f - 2f * pitT); + float rimT = MathF.Sin(MathF.PI * Math.Clamp((r - 0.55f) / 0.45f, 0f, 1f)); + float rim = (0.32f * depth) * rimT * rimT; + return pit + rim; + } + default: + return 0f; + } + } + + private TerrainBrush AddBrush(TerrainBrush template) + { + var brush = template with { Id = _nextBrushId++ }; + int index = _brushes.Count; + _brushes.Add(brush); + _brushPrecomps.Add(BrushPrecomp.From(in brush)); + RegisterBrushInTiles(index, in brush, incrementTileVersion: true); + return brush; + } + + private TerrainBrush SetDynamicDecal(TerrainBrush template) + { + var brush = template with { Id = _nextBrushId++ }; + if (_dynamicDecalSlots.Count >= MaxDynamicDecals) + { + int slot = _dynamicDecalSlots.Dequeue(); + var prev = _brushes[slot]; + UnregisterBrushFromTiles(slot, in prev); + _brushes[slot] = brush; + _brushPrecomps[slot] = BrushPrecomp.From(in brush); + RegisterBrushInTiles(slot, in brush, incrementTileVersion: true); + _dynamicDecalSlots.Enqueue(slot); + return brush; + } + + int index = _brushes.Count; + _brushes.Add(brush); + _brushPrecomps.Add(BrushPrecomp.From(in brush)); + RegisterBrushInTiles(index, in brush, incrementTileVersion: true); + _dynamicDecalSlots.Enqueue(index); + return brush; + } + + private static float GetBrushMaxPositiveHeight(in TerrainBrush b) => b.Kind switch + { + TerrainBrushKind.DuneRidge => b.HeightDelta > 0f ? b.HeightDelta * 1.33f : 0f, + TerrainBrushKind.Mesa => b.HeightDelta > 0f ? b.HeightDelta : 0f, + TerrainBrushKind.SalvagePad or TerrainBrushKind.Road or TerrainBrushKind.Track => b.HeightDelta > 0f ? b.HeightDelta : 0f, + TerrainBrushKind.Crater => 0.33f * MathF.Abs(b.HeightDelta), + _ => 0f + }; + + private void RecomputeTileMaxHeight(int tx, int tz) + { + float sum = 0f; + var indices = _tileBrushIndices[tx, tz]; + for (int i = 0; i < indices.Count; i++) + { + sum += GetBrushMaxPositiveHeight(_brushes[indices[i]]); + } + _tileMaxHeight[tx, tz] = Math.Min(MaxWorldHeight, sum + 0.05f); + } + + private void RegisterBrushInTiles(int index, in TerrainBrush brush, bool incrementTileVersion) + { + float maxPos = GetBrushMaxPositiveHeight(in brush); + GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz); + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + _tileBrushIndices[tx, tz].Add(index); + _tileMaxHeight[tx, tz] = Math.Min(MaxWorldHeight, _tileMaxHeight[tx, tz] + maxPos + 0.05f); + if (incrementTileVersion) + { + TileVersions[tx, tz]++; + DirtyTileMask |= 1UL << (tz * TileGridCount + tx); + } + } + } + } + + private void UnregisterBrushFromTiles(int index, in TerrainBrush brush) + { + GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz); + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + _tileBrushIndices[tx, tz].Remove(index); + RecomputeTileMaxHeight(tx, tz); + TileVersions[tx, tz]++; + DirtyTileMask |= 1UL << (tz * TileGridCount + tx); + } + } + } + + private static void GetBrushTileBounds(in TerrainBrush brush, out int minTx, out int maxTx, out int minTz, out int maxTz) + { + const float gutterPaddingMeters = 3.5f; + float extent = MathF.Sqrt(brush.RadiusX * brush.RadiusX + brush.RadiusZ * brush.RadiusZ) + gutterPaddingMeters; + float minX = brush.X - extent; + float maxX = brush.X + extent; + float minZ = brush.Z - extent; + float maxZ = brush.Z + extent; + + WorldToTile(Math.Clamp(minX, -HalfExtent, HalfExtent), Math.Clamp(minZ, -HalfExtent, HalfExtent), out minTx, out minTz); + WorldToTile(Math.Clamp(maxX, -HalfExtent, HalfExtent), Math.Clamp(maxZ, -HalfExtent, HalfExtent), out maxTx, out maxTz); + } + + public static void WorldToTile(float x, float z, out int tx, out int tz) + { + float nx = (x + HalfExtent) / TileSize; + float nz = (z + HalfExtent) / TileSize; + tx = Math.Clamp((int)MathF.Floor(nx), 0, TileGridCount - 1); + tz = Math.Clamp((int)MathF.Floor(nz), 0, TileGridCount - 1); + } + + private static bool IsBrushClearOfCover(in TerrainBrush candidate, IReadOnlyList coverBoxes) + { + if (MathF.Abs(EvaluateBrushHeight(in candidate, 0f, 0f)) > 0.25f) + { + return false; + } + + const float margin = 2.0f; + for (int i = 0; i < coverBoxes.Count; i++) + { + var c = coverBoxes[i]; + float hx = c.HalfX + margin; + float hz = c.HalfZ + margin; + + if (MathF.Abs(EvaluateBrushHeight(in candidate, c.X, c.Z)) > 0.25f || + MathF.Abs(EvaluateBrushHeight(in candidate, c.X - hx, c.Z - hz)) > 0.25f || + MathF.Abs(EvaluateBrushHeight(in candidate, c.X + hx, c.Z - hz)) > 0.25f || + MathF.Abs(EvaluateBrushHeight(in candidate, c.X - hx, c.Z + hz)) > 0.25f || + MathF.Abs(EvaluateBrushHeight(in candidate, c.X + hx, c.Z + hz)) > 0.25f) + { + return false; + } + } + return true; + } + } +} diff --git a/src/RustToDust.Core/VehicleCatalogLoader.cs b/src/RustToDust.Core/VehicleCatalogLoader.cs new file mode 100644 index 0000000..3336ffe --- /dev/null +++ b/src/RustToDust.Core/VehicleCatalogLoader.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace RustToDust.Core +{ + public static class VehicleCatalogLoader + { + public static string LocateVehiclesDirectory() + { + string? envRoot = Environment.GetEnvironmentVariable("RTD_ASSETS_DIR"); + if (!string.IsNullOrWhiteSpace(envRoot)) + { + string envVehicles = Path.Combine(envRoot, "vehicles"); + if (HasVehiclePackages(envVehicles)) + { + return Path.GetFullPath(envVehicles); + } + } + + foreach (string start in new[] { AppContext.BaseDirectory, Directory.GetCurrentDirectory() }) + { + if (string.IsNullOrWhiteSpace(start) || !Directory.Exists(start)) + { + continue; + } + + var dir = new DirectoryInfo(Path.GetFullPath(start)); + while (dir is not null) + { + string candidate = Path.Combine(dir.FullName, "assets", "vehicles"); + if (HasVehiclePackages(candidate)) + { + return candidate; + } + dir = dir.Parent; + } + } + + throw new DirectoryNotFoundException( + $"Could not locate 'assets/vehicles' containing vehicle.cc packages from BaseDirectory '{AppContext.BaseDirectory}' or CurrentDirectory '{Directory.GetCurrentDirectory()}'."); + } + + private static bool HasVehiclePackages(string vehiclesDir) + { + if (!Directory.Exists(vehiclesDir)) + { + return false; + } + return Directory.EnumerateFiles(vehiclesDir, "vehicle.cc", SearchOption.AllDirectories).Any(); + } + + public static IReadOnlyList<(VehiclePackage Package, ChassisSpec Spec)> LoadAll(string? vehiclesDirectory = null) + { + string root = vehiclesDirectory ?? LocateVehiclesDirectory(); + if (!Directory.Exists(root)) + { + throw new DirectoryNotFoundException($"Vehicles directory not found: {root}"); + } + + var results = new List<(VehiclePackage Package, ChassisSpec Spec)>(); + foreach (string dir in Directory.GetDirectories(root).OrderBy(d => d, StringComparer.Ordinal)) + { + string ccPath = Path.Combine(dir, "vehicle.cc"); + if (!File.Exists(ccPath)) + { + continue; + } + + var pkg = VehiclePackageStore.Read(ccPath); + var spec = pkg.ToChassisSpec(); + results.Add((pkg, spec)); + } + + if (results.Count == 0) + { + throw new InvalidOperationException($"No vehicle.cc archives found under {root}."); + } + + return results; + } + } +} diff --git a/src/RustToDust.Core/VehiclePackage.cs b/src/RustToDust.Core/VehiclePackage.cs new file mode 100644 index 0000000..2d8a0b0 --- /dev/null +++ b/src/RustToDust.Core/VehiclePackage.cs @@ -0,0 +1,339 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +namespace RustToDust.Core +{ + [CultDocument("rtd.vehicle_package", "1"), MessagePackObject] + public sealed class VehiclePackage + { + [CultName, Key(0)] public string Id { get; set; } = string.Empty; + [Key(1)] public string Name { get; set; } = string.Empty; + [Key(2)] public string VehicleClass { get; set; } = string.Empty; + [Key(3)] public MobilityKind Mobility { get; set; } + [Key(4)] public GridPlane Plane { get; set; } + [Key(5)] public int GridWidth { get; set; } + [Key(6)] public int GridHeight { get; set; } + [Key(7)] public string[] Mask { get; set; } = Array.Empty(); + [Key(8)] public float MassKg { get; set; } + [Key(9)] public float MaxSpeed { get; set; } + [Key(10)] public float TurnRate { get; set; } + [Key(11)] public float ThrustNewtons { get; set; } + [Key(12)] public float HoverMaxAltitudeM { get; set; } + [Key(13)] public float ArmorPerCell { get; set; } + [Key(14)] public float Conductivity { get; set; } + [Key(15)] public int CargoCapacity { get; set; } + [Key(16)] public float HalfWidth { get; set; } + [Key(17)] public float HalfHeight { get; set; } + [Key(18)] public float HalfLength { get; set; } + [Key(19)] public string ModelAsset { get; set; } = string.Empty; + [Key(20)] public Dictionary DefaultLoadout { get; set; } = new(); + [Key(21)] public List Hardpoints { get; set; } = new(); + [Key(22)] public List Joints { get; set; } = new(); + [Key(23)] public VehicleMechanismsRecord? Mechanisms { get; set; } + [Key(24)] public List PartCells { get; set; } = new(); + [Key(25)] public float BaseCellThermalMass { get; set; } = 12f; + + public ChassisSpec ToChassisSpec() + { + bool[] boolMask = ParseMaskRows(Mask, GridWidth, GridHeight); + var hps = new HardpointSpec[Hardpoints.Count]; + for (int i = 0; i < Hardpoints.Count; i++) + { + var hp = Hardpoints[i]; + hps[i] = new HardpointSpec( + Id: hp.Id, + Kind: hp.Kind, + X: hp.X, + Y: hp.Y, + Width: hp.W, + Height: hp.H, + ArmorBonus: hp.ArmorBonus, + MinPitchDeg: hp.MinPitchDeg, + MaxPitchDeg: hp.MaxPitchDeg, + IsWideArc: hp.IsWideArc); + } + + return new ChassisSpec( + Id: Id, + Name: Name, + Plane: Plane, + Width: GridWidth, + Height: GridHeight, + Mask: boolMask, + Hardpoints: hps, + HullConductivity: Conductivity, + BaseCellThermalMass: BaseCellThermalMass, + BaseCellArmor: ArmorPerCell, + MassKg: MassKg, + BaseThrust: ThrustNewtons, + BaseTurnRate: TurnRate, + MaxSpeed: MaxSpeed, + HalfWidth: HalfWidth, + HalfHeight: HalfHeight, + HalfLength: HalfLength, + CargoCapacity: CargoCapacity, + Mobility: Mobility, + HoverMaxAltitudeM: HoverMaxAltitudeM, + VehicleClass: VehicleClass); + } + + public static bool[] ParseMaskRows(string[] rows, int width, int height) + { + if (rows.Length != height) + { + throw new InvalidOperationException($"Mask row count {rows.Length} != GridHeight {height}."); + } + + var mask = new bool[width * height]; + for (int y = 0; y < height; y++) + { + if (rows[y].Length != width) + { + throw new InvalidOperationException($"Mask row {y} length {rows[y].Length} != GridWidth {width}."); + } + for (int x = 0; x < width; x++) + { + mask[y * width + x] = rows[y][x] == '#'; + } + } + return mask; + } + } + + [MessagePackObject] + public sealed class VehicleHardpointRecord + { + [Key(0)] public string Id { get; set; } = string.Empty; + [Key(1)] public string AnchorId { get; set; } = string.Empty; + [Key(2)] public HardpointKind Kind { get; set; } + [Key(3)] public int X { get; set; } + [Key(4)] public int Y { get; set; } + [Key(5)] public int W { get; set; } + [Key(6)] public int H { get; set; } + [Key(7)] public float MinPitchDeg { get; set; } + [Key(8)] public float MaxPitchDeg { get; set; } + [Key(9)] public bool IsWideArc { get; set; } + [Key(10)] public float ArmorBonus { get; set; } + [Key(11), CultElementId(nameof(Id))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class VehicleJointRecord + { + [Key(0)] public string Id { get; set; } = string.Empty; + [Key(1)] public string NodeName { get; set; } = string.Empty; + [Key(2)] public float[] Axis { get; set; } = Array.Empty(); + [Key(3)] public float MinVal { get; set; } + [Key(4)] public float MaxVal { get; set; } + [Key(5), CultElementId(nameof(Id))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class VehiclePartCellRecord + { + [Key(0)] public string NodeName { get; set; } = string.Empty; + [Key(1)] public int CellX { get; set; } + [Key(2)] public int CellY { get; set; } + [Key(3)] public string Kind { get; set; } = string.Empty; + [Key(4), CultElementId] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class VehicleMechanismsRecord + { + [Key(0)] public string Frame { get; set; } = string.Empty; + [Key(1)] public float[] RootOrigin { get; set; } = Array.Empty(); + [Key(2)] public List Dofs { get; set; } = new(); + [Key(3)] public List Rams { get; set; } = new(); + [Key(4)] public List Scissors { get; set; } = new(); + [Key(5)] public List Struts { get; set; } = new(); + } + + [MessagePackObject] + public sealed class MechanismDofRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public int Parent { get; set; } + [Key(2)] public string Kind { get; set; } = string.Empty; + [Key(3)] public string? Mechanism { get; set; } + [Key(4)] public string? Side { get; set; } + [Key(5)] public float[] Origin { get; set; } = Array.Empty(); + [Key(6)] public float[] Axis { get; set; } = Array.Empty(); + [Key(7)] public float Lo { get; set; } + [Key(8)] public float Hi { get; set; } + [Key(9)] public int Depth { get; set; } + [Key(10)] public string? StoppedBy { get; set; } + [Key(11)] public float? ComplianceDampingRatio { get; set; } + [Key(12)] public float? ComplianceHertz { get; set; } + [Key(13), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class MechanismRamRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public string BarrelBone { get; set; } = string.Empty; + [Key(2)] public string RodBone { get; set; } = string.Empty; + [Key(3)] public string[] Spans { get; set; } = Array.Empty(); + [Key(4)] public float Bore { get; set; } + [Key(5)] public float Body { get; set; } + [Key(6)] public float Inner { get; set; } + [Key(7)] public float Extension { get; set; } + [Key(8)] public float Rest { get; set; } + [Key(9)] public float[] Stroke { get; set; } = Array.Empty(); + [Key(10)] public int? AParentDof { get; set; } + [Key(11)] public float[]? APos { get; set; } + [Key(12)] public int? BParentDof { get; set; } + [Key(13)] public float[]? BPos { get; set; } + [Key(14)] public float[]? PinDir { get; set; } + [Key(15), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class MechanismScissorRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public string UpperBone { get; set; } = string.Empty; + [Key(2)] public string LowerBone { get; set; } = string.Empty; + [Key(3)] public float Arm { get; set; } + [Key(4)] public int? AParentDof { get; set; } + [Key(5)] public float[]? APos { get; set; } + [Key(6)] public int? BParentDof { get; set; } + [Key(7)] public float[]? BPos { get; set; } + [Key(8)] public float[]? OutDir { get; set; } + [Key(9), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class MechanismStrutRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public string? Side { get; set; } + [Key(2)] public string Dof { get; set; } = string.Empty; + [Key(3)] public float Travel { get; set; } + [Key(4)] public float Hertz { get; set; } + [Key(5)] public float DampingRatio { get; set; } + [Key(6), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + public static class VehiclePackageStore + { + public static CultDocumentRegistry Registry { get; } = + CultDocumentRegistry.ForTypes(new[] { typeof(VehiclePackage) }); + + public static CultRecordKey PackageKey(string id) => new("vehicle:" + id); + + public static CultCache Open(string path, bool writable = false) + { + var options = new CultCacheOpenOptions + { + Registry = Registry, + ReadOnly = !writable, + FlushOnDispose = false, + StoreFlushOnDispose = false, + UseDirectoryStore = false + }; + return CultCacheMessagePack.Create(path, options); + } + + public static VehiclePackage Read(string path) + { + if (!File.Exists(path)) + { + throw new FileNotFoundException($"Vehicle package archive not found: {path}", path); + } + + using var cache = Open(path, writable: false); + var records = cache.GetAll().ToArray(); + if (records.Length != 1) + { + throw new InvalidOperationException($"{path} must contain exactly 1 VehiclePackage record, found {records.Length}."); + } + + var pkg = records[0]; + Validate(pkg, path); + return pkg; + } + + public static void Write(string path, VehiclePackage pkg) + { + if (pkg is null) throw new ArgumentNullException(nameof(pkg)); + Validate(pkg, path); + + string fullPath = Path.GetFullPath(path); + string dir = Path.GetDirectoryName(fullPath) ?? "."; + Directory.CreateDirectory(dir); + + string workspace = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + string tempFile = Path.Combine(workspace, "vehicle.cc"); + try + { + Directory.CreateDirectory(workspace); + using (var cache = Open(tempFile, writable: true)) + { + cache.UpsertAsync(typeof(VehiclePackage), pkg, PackageKey(pkg.Id)).GetAwaiter().GetResult(); + cache.FlushAsync().GetAwaiter().GetResult(); + } + + if (File.Exists(fullPath)) + { + File.Replace(tempFile, fullPath, null); + } + else + { + File.Move(tempFile, fullPath); + } + } + finally + { + if (Directory.Exists(workspace)) + { + Directory.Delete(workspace, recursive: true); + } + } + } + + public static void Validate(VehiclePackage pkg, string sourcePath) + { + if (string.IsNullOrWhiteSpace(pkg.Id)) + throw new InvalidOperationException($"{sourcePath}: VehiclePackage.Id is empty."); + if (string.IsNullOrWhiteSpace(pkg.ModelAsset)) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: ModelAsset is empty."); + if (pkg.GridWidth <= 0 || pkg.GridHeight <= 0) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: invalid grid dimensions {pkg.GridWidth}x{pkg.GridHeight}."); + + bool[] mask = VehiclePackage.ParseMaskRows(pkg.Mask, pkg.GridWidth, pkg.GridHeight); + foreach (var hp in pkg.Hardpoints) + { + if (string.IsNullOrWhiteSpace(hp.Id) || string.IsNullOrWhiteSpace(hp.AnchorId)) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: hardpoint has empty Id or AnchorId."); + if (hp.X < 0 || hp.Y < 0 || hp.W <= 0 || hp.H <= 0 || hp.X + hp.W > pkg.GridWidth || hp.Y + hp.H > pkg.GridHeight) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: hardpoint {hp.Id} out of grid bounds."); + for (int cy = hp.Y; cy < hp.Y + hp.H; cy++) + { + for (int cx = hp.X; cx < hp.X + hp.W; cx++) + { + if (!mask[cy * pkg.GridWidth + cx]) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: hardpoint {hp.Id} covers inactive cell ({cx},{cy})."); + } + } + } + + if (pkg.PartCells.Count == 0) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: PartCells is empty."); + + foreach (var pc in pkg.PartCells) + { + if (pc.CellX < 0 || pc.CellX >= pkg.GridWidth || pc.CellY < 0 || pc.CellY >= pkg.GridHeight || !mask[pc.CellY * pkg.GridWidth + pc.CellX]) + { + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: PartCell '{pc.NodeName}' mapped to inactive/out-of-bounds cell ({pc.CellX},{pc.CellY})."); + } + } + } + } +} diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs new file mode 100644 index 0000000..7b69638 --- /dev/null +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -0,0 +1,1892 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Numerics; +using RustToDust.Core; +using Ymir.Box3D; + +namespace RustToDust.Ymir +{ + public sealed class ArenaSession : IDisposable + { + public const float FixedDt = 1f / 60f; + public const int SubStepCount = 4; + public const int WorldBodyCapacity = 384; + + private const ulong GroundStableId = 1; + private const ulong StaticBoxStableIdBase = 10; + public const ulong ContenderStableIdBase = 1000; + private const ulong SpectatorStableIdBase = 3000; + + private readonly Box3DSoaWorld _world; + private readonly Dictionary _contenderBodies = new(); + private readonly Dictionary _spectatorBodies = new(); + private readonly Dictionary _entityByStableId = new(); + private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount]; + private int _stepTick; + private bool _forceFullDetectionRefresh = true; + private bool _disposed; + + public ArenaSession(int seed = 42) + { + State = new MatchState(seed); + State.ChassisSwapped += OnContenderChassisSwapped; + + _world = new Box3DSoaWorld( + capacity: WorldBodyCapacity, + gravityX: 0f, + gravityY: -20f, + gravityZ: 0f); + + BuildStaticArena(); + SpawnContenderBodies(); + SpawnSpectatorBodies(); + UpdatePlayerDetectionMemory(); + } + + public static bool PerfEnabled; + public static double PerfRingMs; + public static double PerfAiMs; + public static double PerfDriveMs; + public static double PerfWorldMs; + public static double PerfBodySyncMs; + public static double PerfDetectMs; + public static double PerfWeaponsMs; + + public MatchState State { get; } + public Box3DSoaWorld World => _world; + + public bool TryEquipCargo(int cargoIndex, string hardpointId) => + State.TryEquipCargo(cargoIndex, hardpointId); + + public bool TrySwapNearbyChassis() => + State.TrySwapNearbyChassis(0); + + public Box3DSoaBodyHandle? GetContenderBody(int contenderId) => + _contenderBodies.TryGetValue(contenderId, out var h) ? h : null; + + public Box3DSoaBodyHandle? GetSpectatorBody(int spectatorId) => + _spectatorBodies.TryGetValue(spectatorId, out var h) ? h : null; + + public void SetContenderPose(int contenderId, float x, float z, float? yaw = null) + { + if (contenderId < 0 || contenderId >= State.Contenders.Count) + { + return; + } + var c = State.Contenders[contenderId]; + c.X = x; + c.Z = z; + if (yaw.HasValue) c.Yaw = yaw.Value; + + if (_contenderBodies.TryGetValue(contenderId, out var oldHandle)) + { + _world.RemoveBody(oldHandle); + _contenderBodies.Remove(contenderId); + } + if (c.Alive) + { + SpawnContenderBody(c); + } + _forceFullDetectionRefresh = true; + } + + public void SetSpectatorPose(int spectatorId, float x, float z, float? yaw = null) + { + SpectatorState? spec = null; + int index = -1; + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + if (State.Spectators.Spectators[i].Id == spectatorId) + { + spec = State.Spectators.Spectators[i]; + index = i; + break; + } + } + if (spec is null) + { + return; + } + + spec.X = x; + spec.Z = z; + if (yaw.HasValue) spec.Yaw = yaw.Value; + + if (_spectatorBodies.TryGetValue(spectatorId, out var oldHandle)) + { + _world.RemoveBody(oldHandle); + _spectatorBodies.Remove(spectatorId); + } + if (spec.Alive) + { + SpawnSpectatorBody(index, spec); + } + _forceFullDetectionRefresh = true; + } + + public bool HasLineOfSight(float ax, float ay, float az, float bx, float by, float bz) + { + var delta = new Vector3(bx - ax, by - ay, bz - az); + float dist = delta.Length(); + if (dist <= 0.25f) + { + return true; + } + + Vector3 dir = delta / dist; + if (State.Terrain.Raycast( + ax, ay, az, + dir.X, dir.Y, dir.Z, + MathF.Max(0.1f, dist - 0.5f), + out _, out _, out _, out _)) + { + return false; + } + + // Only static cover/boundary boxes block LOS; dynamic vehicles do not occlude terrain/cover sightlines. + return !IntersectsAnyStaticBox(ax, ay, az, dir.X, dir.Y, dir.Z, dist); + } + + private bool IntersectsAnyStaticBox(float ox, float oy, float oz, float dx, float dy, float dz, float maxDist) + { + var boxes = State.ArenaCoverBoxes; + for (int i = 0; i < boxes.Count; i++) + { + var b = boxes[i]; + if (RayIntersectsAabb(ox, oy, oz, dx, dy, dz, maxDist, b)) + { + return true; + } + } + var bounds = State.ArenaBoundaryBoxes; + for (int i = 0; i < bounds.Count; i++) + { + var b = bounds[i]; + if (RayIntersectsAabb(ox, oy, oz, dx, dy, dz, maxDist, b)) + { + return true; + } + } + return false; + } + + private static bool RayIntersectsAabb( + float ox, float oy, float oz, + float dx, float dy, float dz, + float maxDist, + in ArenaBoxSpec box) + { + float tMin = 0f; + float tMax = maxDist; + + if (!SlabTest(ox, dx, box.X - box.HalfX, box.X + box.HalfX, ref tMin, ref tMax)) return false; + if (!SlabTest(oy, dy, box.Y - box.HalfY, box.Y + box.HalfY, ref tMin, ref tMax)) return false; + if (!SlabTest(oz, dz, box.Z - box.HalfZ, box.Z + box.HalfZ, ref tMin, ref tMax)) return false; + return tMax >= tMin; + } + + private static bool SlabTest(float o, float d, float minB, float maxB, ref float tMin, ref float tMax) + { + if (MathF.Abs(d) < 1e-6f) + { + return o >= minB && o <= maxB; + } + float invD = 1f / d; + float t1 = (minB - o) * invD; + float t2 = (maxB - o) * invD; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + return tMax >= tMin; + } + + public void Step(PlayerInput input) + { + ObjectDisposedException.ThrowIf(_disposed, this); + + _stepTick++; + State.Time += FixedDt; + MatchRules.AdvanceTracers(State, FixedDt); + State.Spectators.UpdateSafeRadius(State.Time); + State.Spectators.AdvancePerimeterOrbits(FixedDt); + + if (!PerfEnabled) + { + UpdateRingClearance(); + MatchRules.ApplyPlayerInput(State, input); + MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight, _forceFullDetectionRefresh ? -1 : _stepTick); + + ApplyPhysicsDrives(); + _world.Step(FixedDt, SubStepCount); + SyncBodiesFromWorld(); + + UpdatePlayerDetectionMemory(); + StepThermalAndCooldowns(); + ProcessWeapons(); + MatchRules.UpdateMatchOutcome(State); + return; + } + + double toMs = 1000.0 / Stopwatch.Frequency; + long t0 = Stopwatch.GetTimestamp(); + UpdateRingClearance(); + long t1 = Stopwatch.GetTimestamp(); + MatchRules.ApplyPlayerInput(State, input); + MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight, _forceFullDetectionRefresh ? -1 : _stepTick); + long t2 = Stopwatch.GetTimestamp(); + ApplyPhysicsDrives(); + long t3 = Stopwatch.GetTimestamp(); + _world.Step(FixedDt, SubStepCount); + long t4 = Stopwatch.GetTimestamp(); + SyncBodiesFromWorld(); + long t5 = Stopwatch.GetTimestamp(); + UpdatePlayerDetectionMemory(); + long t6 = Stopwatch.GetTimestamp(); + StepThermalAndCooldowns(); + ProcessWeapons(); + long t7 = Stopwatch.GetTimestamp(); + MatchRules.UpdateMatchOutcome(State); + + PerfRingMs += (t1 - t0) * toMs; + PerfAiMs += (t2 - t1) * toMs; + PerfDriveMs += (t3 - t2) * toMs; + PerfWorldMs += (t4 - t3) * toMs; + PerfBodySyncMs += (t5 - t4) * toMs; + PerfDetectMs += (t6 - t5) * toMs; + PerfWeaponsMs += (t7 - t6) * toMs; + } + + private void BuildStaticArena() + { + // Safety floor slab at y = -20m below the lowest possible terrain valley (-18m); + // primary terrain support comes from 4-corner spring-damper sampling of State.Terrain. + _world.AddStaticBox( + GroundStableId, + (0f, -20f, 0f), + (800f, 1f, 800f), + friction: 0.25f, + restitution: 0.05f); + + ulong nextId = StaticBoxStableIdBase; + for (int i = 0; i < State.ArenaBoundaryBoxes.Count; i++) + { + var b = State.ArenaBoundaryBoxes[i]; + _world.AddStaticBox( + nextId++, + (b.X, b.Y, b.Z), + (b.HalfX, b.HalfY, b.HalfZ), + friction: 0.35f, + restitution: 0.1f); + } + + for (int i = 0; i < State.ArenaCoverBoxes.Count; i++) + { + var b = State.ArenaCoverBoxes[i]; + _world.AddStaticBox( + nextId++, + (b.X, b.Y, b.Z), + (b.HalfX, b.HalfY, b.HalfZ), + friction: 0.4f, + restitution: 0.05f); + } + } + + private void SpawnContenderBodies() + { + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + SpawnContenderBody(c); + } + } + + private void SpawnContenderBody(ContenderState c) + { + var spec = c.Grid.Spec; + float volume = 8f * spec.HalfWidth * spec.HalfHeight * spec.HalfLength; + float density = spec.MassKg / MathF.Max(0.1f, volume); + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw); + ulong stableId = ContenderStableIdBase + (ulong)c.Id; + float clearance = spec.IsVtol + ? Math.Clamp(c.TargetHoverAltAgl, MatchRules.VtolMinClearanceAgl, MathF.Max(MatchRules.VtolMinClearanceAgl, spec.HoverMaxAltitudeM)) + : 0.15f; + float spawnY = State.Terrain.SampleHeight(c.X, c.Z) + spec.HalfHeight + clearance; + c.Y = spawnY; + + var handle = _world.AddBox( + stableId, + (c.X, spawnY, c.Z), + (spec.HalfWidth, spec.HalfHeight, spec.HalfLength), + density, + (q.X, q.Y, q.Z, q.W), + friction: 0.2f, + restitution: 0.1f); + + _contenderBodies[c.Id] = handle; + _entityByStableId[stableId] = (true, c.Id); + } + + private void OnContenderChassisSwapped(ContenderState c) + { + if (_contenderBodies.TryGetValue(c.Id, out var oldHandle)) + { + _world.RemoveBody(oldHandle); + _contenderBodies.Remove(c.Id); + } + if (c.Alive) + { + SpawnContenderBody(c); + } + _forceFullDetectionRefresh = true; + } + + private void SpawnSpectatorBodies() + { + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + SpawnSpectatorBody(i, State.Spectators.Spectators[i]); + } + } + + private void SpawnSpectatorBody(int index, SpectatorState s) + { + var spec = s.Grid.Spec; + float volume = 8f * spec.HalfWidth * spec.HalfHeight * spec.HalfLength; + float density = spec.MassKg / MathF.Max(0.1f, volume); + var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, s.Yaw); + ulong stableId = SpectatorStableIdBase + (ulong)s.Id; + float spawnY = State.Terrain.SampleHeight(s.X, s.Z) + spec.HalfHeight + 0.15f; + s.Y = spawnY; + + var handle = _world.AddBox( + stableId, + (s.X, spawnY, s.Z), + (spec.HalfWidth, spec.HalfHeight, spec.HalfLength), + density, + (q.X, q.Y, q.Z, q.W), + friction: 0.2f, + restitution: 0.1f); + + _spectatorBodies[s.Id] = handle; + _entityByStableId[stableId] = (false, index); + } + + private void UpdateRingClearance() + { + Span contacts = stackalloc RingContact[State.Contenders.Count]; + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + contacts[i] = new RingContact(c.Id, c.X, c.Z, c.Alive, c.Y, c.Grid.Spec.HalfHeight); + } + State.Spectators.UpdateClearance(contacts, FixedDt, HasSpectatorLos, _forceFullDetectionRefresh ? -1 : _stepTick); + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (s.Alive && s.Stance != SpectatorStance.Neutral && !s.BroadcastWakeupEmitted && s.TargetContenderId.HasValue) + { + s.BroadcastWakeupEmitted = true; + if (s.Stance == SpectatorStance.Provoked) + { + if (s.Tier == SpectatorTier.Tourist) + { + State.Broadcast.EmitTouristPull(State.Time, s.TargetContenderId.Value); + } + else if (s.Tier == SpectatorTier.Exemplar) + { + State.Broadcast.EmitExemplarWakeup(State.Time, s.TargetContenderId.Value); + } + } + else if (s.Tier == SpectatorTier.Patron) + { + State.Broadcast.EmitPatronClearance(State.Time, s.TargetContenderId.Value); + } + } + else if (s.Stance == SpectatorStance.Neutral) + { + s.BroadcastWakeupEmitted = false; + } + } + } + + private bool HasSpectatorLos(SpectatorState spec, RingContact target) + { + return HasLineOfSight( + spec.X, MatchRules.GetObserverEyeY(spec.Y, spec.Grid.Spec.HalfHeight), spec.Z, + target.X, MatchRules.GetTargetAimY(target.Y, target.HalfHeight), target.Z); + } + + private void ApplyPhysicsDrives() + { + var view = _world.View; + + // Contenders + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.Alive || !_contenderBodies.TryGetValue(c.Id, out var handle)) + { + continue; + } + + int lane = handle.Lane; + float mass = view.Mass[lane]; + if (mass <= 0f) + { + continue; + } + + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); + + if (c.Grid.Spec.IsVtol) + { + ApplyVtolFlightDrive(c, lane, mass, pos, q, vel, angVel, view); + continue; + } + + ComputeTerrainSupport( + pos, q, vel, angVel, mass, c.Grid.Spec, + out Vector3 supportForce, + out Vector3 supportTorque, + out Vector3 terrainNormal, + out int groundedCorners); + + var forward = Vector3.Transform(Vector3.UnitZ, q); + forward.Y = 0f; + if (forward.LengthSquared() < 1e-4f) forward = Vector3.UnitZ; + else forward = Vector3.Normalize(forward); + + var right = Vector3.Cross(forward, Vector3.UnitY); + var up = Vector3.Transform(Vector3.UnitY, q); + + Vector3 driveForward = forward; + Vector3 driveRight = right; + if (groundedCorners > 0) + { + Vector3 fSlope = forward - terrainNormal * Vector3.Dot(forward, terrainNormal); + if (fSlope.LengthSquared() > 1e-4f) driveForward = Vector3.Normalize(fSlope); + Vector3 rSlope = right - terrainNormal * Vector3.Dot(right, terrainNormal); + if (rSlope.LengthSquared() > 1e-4f) driveRight = Vector3.Normalize(rSlope); + } + + float thrust = c.Grid.ComputeDriveThrust(); + float maxSpeed = MathF.Max(4f, c.Grid.Spec.MaxSpeed); + float forwardSpeed = Vector3.Dot(vel, driveForward); + float lateralSpeed = Vector3.Dot(vel, driveRight); + float gripScale = groundedCorners > 0 ? (0.4f + 0.6f * (groundedCorners / 4f)) : 0.12f; + + Vector3 force = supportForce; + // On steep cliffs (ny < 0.78), strip inward horizontal thrust so vehicles slide along the slope instead of burrowing + Vector3 effectiveDriveFwd = driveForward; + if (groundedCorners > 0 && terrainNormal.Y < 0.78f) + { + Vector3 cliffHoriz = new Vector3(terrainNormal.X, 0f, terrainNormal.Z); + if (cliffHoriz.LengthSquared() > 1e-4f) + { + cliffHoriz = Vector3.Normalize(cliffHoriz); + float intoCliff = Vector3.Dot(effectiveDriveFwd, cliffHoriz); + if (intoCliff < 0f) + { + effectiveDriveFwd -= cliffHoriz * intoCliff; + effectiveDriveFwd.Y = MathF.Min(effectiveDriveFwd.Y, 0.25f); + } + } + } + // Drive thrust along slope-aligned forward with smooth terminal velocity drag at MaxSpeed + force += effectiveDriveFwd * (c.ThrottleCmd * thrust - (thrust / maxSpeed) * forwardSpeed) * gripScale; + // Lateral tire / stride grip + force -= driveRight * (lateralSpeed * mass * 8.5f * gripScale); + + if (c.BrakeCmd && groundedCorners > 0) + { + var horizVel = new Vector3(vel.X, 0f, vel.Z); + force -= horizVel * (mass * 7f); + } + + // Engine heat from throttle + if (MathF.Abs(c.ThrottleCmd) > 0.05f) + { + for (int m = 0; m < c.Grid.Mounted.Count; m++) + { + var mod = c.Grid.Mounted[m]; + if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f) + { + c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * MathF.Abs(c.ThrottleCmd) * FixedDt); + } + } + } + + float turnRate = c.Grid.ComputeTurnRate(); + // Steer > 0 turns right (clockwise looking from +Y down => negative Y torque when +Z is forward) + float targetYawVel = -c.SteerCmd * turnRate; + float hx = view.Size0[lane]; + float hz = view.Size2[lane]; + float iy = mass * (hx * hx + hz * hz) / 3f; + + Vector3 torque = ComputeRightingTorque(c.Grid.Spec, q, up, angVel, mass, terrainNormal, supportTorque, terrainBlend: 0.85f); + torque.Y = iy * (targetYawVel - angVel.Y) * 8f; + + view.ForceX[lane] = force.X; + view.ForceY[lane] = force.Y; + view.ForceZ[lane] = force.Z; + view.TorqueX[lane] = torque.X; + view.TorqueY[lane] = torque.Y; + view.TorqueZ[lane] = torque.Z; + } + + // Spectators + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || !_spectatorBodies.TryGetValue(s.Id, out var handle)) + { + continue; + } + + int lane = handle.Lane; + float mass = view.Mass[lane]; + if (mass <= 0f) + { + continue; + } + + MatchRules.ComputeSpectatorBehavior(s, State, out float goalX, out float goalZ, out float aimX, out float aimZ, out _); + + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); + var up = Vector3.Transform(Vector3.UnitY, q); + + ComputeTerrainSupport( + pos, q, vel, angVel, mass, s.Grid.Spec, + out Vector3 supportForce, + out Vector3 supportTorque, + out Vector3 terrainNormal, + out _); + + Vector3 toGoal = new Vector3(goalX - pos.X, 0f, goalZ - pos.Z); + float dist = toGoal.Length(); + Vector3 desiredVel = dist > 0.5f ? Vector3.Normalize(toGoal) * MathF.Min(s.MaxSpeed, dist * 1.5f) : Vector3.Zero; + Vector3 horizVel = new Vector3(vel.X, 0f, vel.Z); + Vector3 force = supportForce + (desiredVel - horizVel) * (mass * 4.5f); + + float desiredYaw = s.Stance == SpectatorStance.Neutral + ? MathF.Atan2(-pos.X, -pos.Z) + : MathF.Atan2(aimX - pos.X, aimZ - pos.Z); + var forward = Vector3.Transform(Vector3.UnitZ, q); + float currentYaw = MathF.Atan2(forward.X, forward.Z); + float yawErr = MatchRules.NormalizeAngle(desiredYaw - currentYaw); + + float hx = view.Size0[lane]; + float hz = view.Size2[lane]; + float iy = mass * (hx * hx + hz * hz) / 3f; + + Vector3 torque = ComputeRightingTorque(s.Grid.Spec, q, up, angVel, mass, terrainNormal, supportTorque, terrainBlend: 0.7f); + torque.Y = iy * (Math.Clamp(yawErr * 3f, -5f, 5f) - angVel.Y) * 8f; + + view.ForceX[lane] = force.X; + view.ForceY[lane] = force.Y; + view.ForceZ[lane] = force.Z; + view.TorqueX[lane] = torque.X; + view.TorqueY[lane] = torque.Y; + view.TorqueZ[lane] = torque.Z; + } + } + + private void ApplyVtolFlightDrive( + ContenderState c, + int lane, + float mass, + Vector3 pos, + Quaternion q, + Vector3 vel, + Vector3 angVel, + Box3DSoaView view) + { + var spec = c.Grid.Spec; + float minAlt = MatchRules.VtolMinClearanceAgl; + float maxAlt = MathF.Max(minAlt, spec.HoverMaxAltitudeM); + const float verticalSpeed = 14f; + float enginePerf = c.Grid.ComputeEngineThermalPerformance(); + c.TargetHoverAltAgl = Math.Clamp(c.TargetHoverAltAgl + c.VerticalThrottleCmd * verticalSpeed * FixedDt, minAlt, maxAlt); + + var forward = Vector3.Transform(Vector3.UnitZ, q); + forward.Y = 0f; + if (forward.LengthSquared() < 1e-4f) forward = Vector3.UnitZ; + else forward = Vector3.Normalize(forward); + var right = Vector3.Cross(forward, Vector3.UnitY); + var up = Vector3.Transform(Vector3.UnitY, q); + + Vector3 horizVel = new Vector3(vel.X, 0f, vel.Z); + float perimDist = MathF.Max(spec.HalfWidth, spec.HalfLength) + 2.5f; + + // Sample terrain at center, 4-point perimeter (HalfLength + 2.5m), and horizontal velocity lookahead (0.20s, 0.35s) + float ghCenter = State.Terrain.SampleHeight(pos.X, pos.Z); + float ghFront = State.Terrain.SampleHeight(pos.X + forward.X * perimDist, pos.Z + forward.Z * perimDist); + float ghBack = State.Terrain.SampleHeight(pos.X - forward.X * perimDist, pos.Z - forward.Z * perimDist); + float ghRight = State.Terrain.SampleHeight(pos.X + right.X * perimDist, pos.Z + right.Z * perimDist); + float ghLeft = State.Terrain.SampleHeight(pos.X - right.X * perimDist, pos.Z - right.Z * perimDist); + float ghLook1 = State.Terrain.SampleHeight(pos.X + horizVel.X * 0.20f, pos.Z + horizVel.Z * 0.20f); + float ghLook2 = State.Terrain.SampleHeight(pos.X + horizVel.X * 0.35f, pos.Z + horizVel.Z * 0.35f); + float ghSafe = MathF.Max( + ghCenter, + MathF.Max( + MathF.Max(ghFront, ghBack), + MathF.Max(MathF.Max(ghRight, ghLeft), MathF.Max(ghLook1, ghLook2)))); + + float ghHullMax = MathF.Max( + ghCenter, + MathF.Max( + MathF.Max( + State.Terrain.SampleHeight(pos.X + forward.X * spec.HalfLength, pos.Z + forward.Z * spec.HalfLength), + State.Terrain.SampleHeight(pos.X - forward.X * spec.HalfLength, pos.Z - forward.Z * spec.HalfLength)), + MathF.Max( + State.Terrain.SampleHeight(pos.X + right.X * spec.HalfWidth, pos.Z + right.Z * spec.HalfWidth), + State.Terrain.SampleHeight(pos.X - right.X * spec.HalfWidth, pos.Z - right.Z * spec.HalfWidth)))); + + var (tnx, tny, tnz) = State.Terrain.SampleNormal(pos.X, pos.Z); + var terrainNormal = new Vector3(tnx, tny, tnz); + + float bottomY = pos.Y - spec.HalfHeight; + float bottomAgl = bottomY - ghHullMax; + float targetCenterY = ghSafe + spec.HalfHeight + c.TargetHoverAltAgl; + float altErr = targetCenterY - pos.Y; + + // Hover lift authority scales with engine thermal performance (overheated 0.00 -> loses climb authority and sinks gently) + float hoverSupportFrac = Math.Clamp(enginePerf / 0.25f, 0f, 1f); + float baseHoverAccel = 20f * (0.85f + 0.15f * hoverSupportFrac); + float altGain = 32f * enginePerf; + float maxEngineLift = mass * (17.5f + 30.5f * enginePerf); + float headroom = MathF.Max(0f, maxAlt - bottomAgl); + float maxSafeClimbVel = MathF.Sqrt(2f * 16f * headroom); + float desiredVelY = 0f; + if (c.VerticalThrottleCmd > 0f && c.TargetHoverAltAgl < maxAlt - 0.05f) + { + desiredVelY = MathF.Min(c.VerticalThrottleCmd * verticalSpeed * enginePerf, maxSafeClimbVel); + } + else if (c.VerticalThrottleCmd < 0f && c.TargetHoverAltAgl > minAlt + 0.05f) + { + desiredVelY = c.VerticalThrottleCmd * verticalSpeed; + } + // Clamp downward hover thrust >= 0 (gravity-only descent — never slam down when flying off a cliff) + float rawHover = mass * (baseHoverAccel + altErr * altGain - (vel.Y - desiredVelY) * 14f); + if (c.VerticalThrottleCmd > 0f && vel.Y > maxSafeClimbVel && bottomAgl > minAlt) + { + rawHover = MathF.Min(rawHover, mass * 16f); + } + float hoverForceY = Math.Clamp(rawHover, 0f, maxEngineLift); + + // Ground-proximity cushion + hard arrest whenever bottom clearance drops below VtolMinClearanceAgl (2.5m) + if (bottomAgl < minAlt) + { + hoverForceY += mass * (minAlt - bottomAgl) * 35f; + if (bottomAgl < 1.2f) + { + hoverForceY += mass * (1.2f - bottomAgl) * 140f; + } + if (vel.Y < 0f) + { + float availDist = MathF.Max(0.15f, bottomAgl - 0.65f); + float reqDecel = (vel.Y * vel.Y) / (2f * availDist) + 20f; + float arrestAccel = MathF.Min(reqDecel, (-vel.Y / FixedDt) + 20f); + hoverForceY += mass * arrestAccel; + } + } + + float thrust = c.Grid.ComputeDriveThrust(); + float maxSpeed = MathF.Max(6f, spec.MaxSpeed); + float forwardSpeed = Vector3.Dot(horizVel, forward); + float lateralSpeed = Vector3.Dot(horizVel, right); + + Vector3 force = Vector3.UnitY * hoverForceY; + + // Steep-cliff deflection: never fly through solid terrain walls + float vDotN = Vector3.Dot(vel, terrainNormal); + if (bottomAgl < minAlt && vDotN < 0f) + { + float deflectMag = MathF.Min(-vDotN * mass * 28f, -vDotN * mass / FixedDt); + force += terrainNormal * deflectMag; + } + + // Direction-agnostic cliff-approach braking (protects forward, reverse, and strafing into steep mesas) + float ghLookMax = MathF.Max(ghLook1, ghLook2); + float lookClearance = bottomY - ghLookMax; + Vector3 driveForce = forward * (c.ThrottleCmd * thrust) - forward * ((thrust / maxSpeed) * forwardSpeed); + + if (ghLookMax > ghCenter + 0.8f && lookClearance < minAlt + 2.0f) + { + float brakeFrac = Math.Clamp(((minAlt + 2.0f) - lookClearance) / 4.0f, 0f, 1f); + float horizSpeed = horizVel.Length(); + if (horizSpeed > 0.1f) + { + Vector3 horizDir = horizVel / horizSpeed; + float intoLook = Vector3.Dot(driveForce, horizDir); + if (intoLook > 0f) + { + driveForce -= horizDir * (intoLook * brakeFrac * 0.95f); + } + float maxBrake = (horizSpeed * mass) / FixedDt; + float desiredBrake = horizSpeed * mass * 16f * brakeFrac; + force -= horizDir * MathF.Min(desiredBrake, maxBrake); + } + } + + Vector3 cliffPush = Vector3.Zero; + if (ghFront > bottomY - minAlt) cliffPush -= forward * Math.Clamp((ghFront - (bottomY - minAlt)) / 2f, 0f, 1f); + if (ghBack > bottomY - minAlt) cliffPush += forward * Math.Clamp((ghBack - (bottomY - minAlt)) / 2f, 0f, 1f); + if (ghRight > bottomY - minAlt) cliffPush -= right * Math.Clamp((ghRight - (bottomY - minAlt)) / 2f, 0f, 1f); + if (ghLeft > bottomY - minAlt) cliffPush += right * Math.Clamp((ghLeft - (bottomY - minAlt)) / 2f, 0f, 1f); + + if (cliffPush.LengthSquared() > 1e-4f) + { + Vector3 cliffDir = Vector3.Normalize(cliffPush); + float driveIntoCliff = Vector3.Dot(driveForce, cliffDir); + if (driveIntoCliff < 0f) + { + driveForce -= cliffDir * driveIntoCliff; + } + float velIntoCliff = Vector3.Dot(horizVel, cliffDir); + if (velIntoCliff < 0f) + { + float stopMag = MathF.Min(-velIntoCliff * mass * 24f, -velIntoCliff * mass / FixedDt); + force += cliffDir * stopMag; + } + force += cliffDir * (mass * 12f * Math.Clamp(cliffPush.Length(), 0f, 1f)); + } + + force += driveForce; + force -= right * (lateralSpeed * mass * 3.8f); + if (c.BrakeCmd) + { + force -= horizVel * (mass * 3.5f); + } + + // Engine heat from hover lift + horizontal thrust + float liftWork = 0.25f + 0.55f * MathF.Abs(c.VerticalThrottleCmd); + float heatFraction = MathF.Max(MathF.Abs(c.ThrottleCmd), liftWork); + for (int m = 0; m < c.Grid.Mounted.Count; m++) + { + var mod = c.Grid.Mounted[m]; + if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f) + { + c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * heatFraction * FixedDt); + } + } + + // Gentle bank-into-turn and subtle nose-down pitch into forward thrust + float speedScale = Math.Clamp(MathF.Abs(forwardSpeed) / MathF.Max(8f, maxSpeed * 0.5f), 0f, 1f); + float bankRad = -c.SteerCmd * speedScale * 0.26f; + float nosePitchRad = c.ThrottleCmd * 0.11f; + Vector3 desiredUp = Vector3.Normalize(Vector3.UnitY + right * MathF.Sin(bankRad) + forward * MathF.Sin(nosePitchRad)); + + Vector3 tiltAxis = Vector3.Cross(up, desiredUp); + float maxFoot = MathF.Max(spec.HalfWidth, spec.HalfLength); + float iTilt = MathF.Max(1f, (spec.HalfHeight * spec.HalfHeight + maxFoot * maxFoot) / 3f); + Vector3 torque = tiltAxis * (mass * 30f * iTilt) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 9.5f * iTilt); + + float turnRate = c.Grid.ComputeTurnRate(); + float targetYawVel = -c.SteerCmd * turnRate; + float hx = view.Size0[lane]; + float hz = view.Size2[lane]; + float iy = mass * (hx * hx + hz * hz) / 3f; + torque.Y = iy * (targetYawVel - angVel.Y) * 8f; + + view.ForceX[lane] = force.X; + view.ForceY[lane] = force.Y; + view.ForceZ[lane] = force.Z; + view.TorqueX[lane] = torque.X; + view.TorqueY[lane] = torque.Y; + view.TorqueZ[lane] = torque.Z; + } + + private static Vector3 ComputeRightingTorque( + ChassisSpec spec, + Quaternion q, + Vector3 up, + Vector3 angVel, + float mass, + Vector3 terrainNormal, + Vector3 supportTorque, + float terrainBlend) + { + bool isWalker = spec.IsWalker; + float blend = isWalker ? MathF.Min(terrainBlend, 0.30f) : terrainBlend; + Vector3 desiredUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, blend)); + + float maxDesiredTiltRad = isWalker + ? MathF.PI / 15f // 12 degrees target cap so dynamic overshoot stays <= 15-20 deg + : MathF.PI * 38f / 180f; // 38 degrees max slope alignment so cliff walls don't back-flip vehicles + { + float dotY = Math.Clamp(desiredUp.Y, -1f, 1f); + if (MathF.Acos(dotY) > maxDesiredTiltRad) + { + Vector3 horiz = new Vector3(desiredUp.X, 0f, desiredUp.Z); + float hLen = horiz.Length(); + desiredUp = hLen > 1e-4f + ? Vector3.UnitY * MathF.Cos(maxDesiredTiltRad) + (horiz / hLen) * MathF.Sin(maxDesiredTiltRad) + : Vector3.UnitY; + } + } + + float upDot = Vector3.Dot(up, desiredUp); + Vector3 tiltAxis = Vector3.Cross(up, desiredUp); + if (upDot < 0.2f) + { + Vector3 fallbackAxis = Vector3.Transform(Vector3.UnitZ, q); + fallbackAxis.Y = 0f; + fallbackAxis = fallbackAxis.LengthSquared() > 1e-4f + ? Vector3.Normalize(fallbackAxis) + : Vector3.UnitX; + + float axisLen = tiltAxis.Length(); + Vector3 recoveryDir = axisLen > 0.15f ? tiltAxis / axisLen : fallbackAxis; + tiltAxis = recoveryDir * MathF.Max(axisLen, 1.0f); + } + + float maxFoot = MathF.Max(spec.HalfWidth, spec.HalfLength); + float iTilt = MathF.Max(1f, (spec.HalfHeight * spec.HalfHeight + maxFoot * maxFoot) / 3f); + float rightingGain = (isWalker ? 48f : 28f) * iTilt; + float dampingGain = (isWalker ? 11f : 8.5f) * iTilt; + + float tiltLimitRad = isWalker ? MathF.PI / 12f : MathF.PI * 48f / 180f; + float worldTiltRad = MathF.Acos(Math.Clamp(up.Y, -1f, 1f)); + Vector3 arrestTorque = Vector3.Zero; + if (worldTiltRad > tiltLimitRad) + { + Vector3 toUpright = Vector3.Cross(up, Vector3.UnitY); + if (toUpright.LengthSquared() > 1e-6f) + { + Vector3 uprightDir = Vector3.Normalize(toUpright); + float supOut = Vector3.Dot(supportTorque, uprightDir); + if (supOut < 0f) + { + supportTorque -= uprightDir * supOut; + } + + float angOut = Vector3.Dot(new Vector3(angVel.X, 0f, angVel.Z), uprightDir); + if (angOut < 0f) + { + arrestTorque = uprightDir * (-angOut * mass * iTilt * (isWalker ? 28f : 18f)); + } + } + + rightingGain *= 1f + (worldTiltRad - tiltLimitRad) * (isWalker ? 6f : 4f); + } + + return supportTorque + arrestTorque + tiltAxis * (mass * rightingGain) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * dampingGain); + } + + private void ComputeTerrainSupport( + Vector3 pos, + Quaternion q, + Vector3 vel, + Vector3 angVel, + float mass, + ChassisSpec spec, + out Vector3 supportForce, + out Vector3 supportTorque, + out Vector3 terrainNormal, + out int groundedCorners) + { + supportForce = Vector3.Zero; + supportTorque = Vector3.Zero; + groundedCorners = 0; + + var (nx, ny, nz) = State.Terrain.SampleNormal(pos.X, pos.Z); + terrainNormal = new Vector3(nx, ny, nz); + + // Blend smoothly from pure vertical on flat ground to surface normal on steep mesa/dune slopes + float slopeBlend = Math.Clamp((0.985f - terrainNormal.Y) / 0.18f, 0f, 1f); + Vector3 supportDir = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, slopeBlend)); + float orthoScale = MathF.Max(0.35f, terrainNormal.Y); + + float hx = MathF.Min(spec.HalfWidth * 0.9f, 2.4f); + float hz = MathF.Min(spec.HalfLength * 0.9f, 2.8f); + float bottomY = -spec.HalfHeight; + const float restTravel = 0.20f; + float kSpring = mass * 85f; + float cDamp = mass * 10.5f; + float torqueScale = spec.IsWalker ? 0.12f : 1.0f; + float maxPen = 0f; + + Span corners = stackalloc Vector3[4] + { + new Vector3(-hx, bottomY, -hz), + new Vector3( hx, bottomY, -hz), + new Vector3(-hx, bottomY, hz), + new Vector3( hx, bottomY, hz) + }; + + for (int k = 0; k < 4; k++) + { + Vector3 r = Vector3.Transform(corners[k], q); + Vector3 wp = pos + r; + float gh = State.Terrain.SampleHeight(wp.X, wp.Z); + float pen = (gh + restTravel) - wp.Y; + if (pen > 0f) + { + groundedCorners++; + maxPen = MathF.Max(maxPen, pen); + float vCornerN = Vector3.Dot(vel + Vector3.Cross(angVel, r), supportDir); + float penEff = pen * orthoScale; + float bumpExtra = pen > 0.20f ? mass * 220f * (pen - 0.20f) : 0f; + float fN = Math.Clamp(kSpring * penEff + bumpExtra - cDamp * vCornerN, 0f, mass * 65f); + Vector3 cornerForce = supportDir * fN; + supportForce += cornerForce; + supportTorque += Vector3.Cross(r, cornerForce) * torqueScale; + } + } + + // Center skid-plate bump-stop prevents belly clipping when straddling sharp ridge crests at speed + float ghCenter = State.Terrain.SampleHeight(pos.X, pos.Z); + float centerGap = (pos.Y - spec.HalfHeight) - ghCenter; + float centerPen = (ghCenter + 0.08f) - (pos.Y - spec.HalfHeight); + if (centerPen > 0f) + { + groundedCorners = Math.Max(groundedCorners, 1); + maxPen = MathF.Max(maxPen, centerPen); + float vCenterN = Vector3.Dot(vel, supportDir); + float centerExtra = centerPen > 0.20f ? mass * 220f * (centerPen - 0.20f) : 0f; + float fCenter = Math.Clamp(mass * 120f * (centerPen * orthoScale) + centerExtra - mass * 10f * vCenterN, 0f, mass * 65f); + supportForce += supportDir * fCenter; + } + + // Prevent large overhangs from catapulting the chassis when the belly center is already well above ground + if (centerGap > 1.2f && supportForce.Y > 0f) + { + float overhangAtten = Math.Clamp(1f - (centerGap - 1.2f) / 1.8f, 0f, 1f); + supportForce *= overhangAtten; + supportTorque *= overhangAtten; + } + + // Base lift attenuation on normal separation velocity vDotN rather than world vel.Y so steep uphill + // climbs (vDotN <= 0) retain full support while separating crests (vDotN > 2.0) don't sky-launch. + float vDotN = Vector3.Dot(vel, terrainNormal); + float sepScale = vDotN > 2.0f ? Math.Clamp(1f - (vDotN - 2.0f) / 2.0f, 0f, 1f) : 1f; + float maxSpringY = vDotN > 2.0f ? mass * 20f * sepScale : mass * 75f; + if (supportForce.Y > maxSpringY && supportForce.Y > 1e-4f) + { + supportForce *= maxSpringY / supportForce.Y; + } + + // Steep-slope normal velocity projection: when contacting terrain and moving inward (vDotN < 0), + // arrest inward normal velocity up to vDotN = 0 regardless of upward world vel.Y. + if (maxPen > 0f && vDotN < 0f) + { + float deflectMag = MathF.Min(-vDotN * mass * 42f, -vDotN * mass / FixedDt); + supportForce += terrainNormal * deflectMag; + } + } + + private void SyncBodiesFromWorld() + { + var view = _world.View; + + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.Alive || !_contenderBodies.TryGetValue(c.Id, out var handle)) + { + continue; + } + + int lane = handle.Lane; + float prevX = c.X; + float prevZ = c.Z; + c.X = view.PositionX[lane]; + c.Y = view.PositionY[lane]; + c.Z = view.PositionZ[lane]; + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var forward = Vector3.Transform(Vector3.UnitZ, q); + c.Yaw = MathF.Atan2(forward.X, forward.Z); + float vx = view.VelocityX[lane]; + float vz = view.VelocityZ[lane]; + c.Speed = MathF.Sqrt(vx * vx + vz * vz); + + float stepDist = MathF.Sqrt((c.X - prevX) * (c.X - prevX) + (c.Z - prevZ) * (c.Z - prevZ)); + float groundY = State.Terrain.SampleHeight(c.X, c.Z); + if (c.Speed > 2.0f && c.Y - c.Grid.Spec.HalfHeight <= groundY + 0.65f) + { + _trackDistAccum[i] += stepDist; + if (_trackDistAccum[i] >= 2.2f) + { + _trackDistAccum[i] = 0f; + State.Terrain.StampTrack(c.X, c.Z, c.Yaw, c.Grid.Spec.HalfWidth * 1.4f, 2.5f); + } + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || !_spectatorBodies.TryGetValue(s.Id, out var handle)) + { + continue; + } + + int lane = handle.Lane; + s.X = view.PositionX[lane]; + s.Y = view.PositionY[lane]; + s.Z = view.PositionZ[lane]; + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var forward = Vector3.Transform(Vector3.UnitZ, q); + s.Yaw = MathF.Atan2(forward.X, forward.Z); + } + } + + private void UpdatePlayerDetectionMemory() + { + var p = State.Player; + if (!p.Alive) + { + State.PlayerDetectedByCount = 0; + return; + } + + float pEyeY = MatchRules.GetObserverEyeY(p.Y, p.Grid.Spec.HalfHeight); + float pTargetY = MatchRules.GetTargetAimY(p.Y, p.Grid.Spec.HalfHeight); + int detectedBy = 0; + + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (c.IsPlayer) + { + continue; + } + + var mem = State.GetOrCreateContenderContact(c.Id); + if (!c.Alive) + { + mem.VisibleToPlayer = false; + mem.FaintHorizonPing = false; + mem.LastSeenAge = float.PositiveInfinity; + continue; + } + + float dxC = c.X - p.X; + float dzC = c.Z - p.Z; + float distSqC = dxC * dxC + dzC * dzC; + int rivalPeriod = distSqC > 240f * 240f ? 6 : 3; + if (!_forceFullDetectionRefresh && ((c.Id + _stepTick) % rivalPeriod != 0)) + { + if (!mem.VisibleToPlayer && mem.HasEverBeenSeen) + { + mem.LastSeenAge += FixedDt; + } + else if (mem.VisibleToPlayer && distSqC <= 240f * 240f) + { + detectedBy++; + } + continue; + } + + bool playerSees = HasLineOfSight( + p.X, pEyeY, p.Z, + c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z); + + if (playerSees) + { + mem.VisibleToPlayer = true; + mem.FaintHorizonPing = false; + mem.LastSeenAge = 0f; + mem.LastSeenX = c.X; + mem.LastSeenZ = c.Z; + mem.HasEverBeenSeen = true; + + if (distSqC <= 240f * 240f && + HasLineOfSight(c.X, MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight), c.Z, p.X, pTargetY, p.Z)) + { + detectedBy++; + } + } + else + { + mem.VisibleToPlayer = false; + mem.FaintHorizonPing = false; + if (mem.HasEverBeenSeen) + { + mem.LastSeenAge += FixedDt; + } + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + var mem = State.GetOrCreateSpectatorContact(s.Id); + if (!s.Alive) + { + mem.VisibleToPlayer = false; + mem.FaintHorizonPing = false; + mem.LastSeenAge = float.PositiveInfinity; + continue; + } + + bool checkLosThisTick = _forceFullDetectionRefresh || + s.Stance != SpectatorStance.Neutral || + ((s.Id + _stepTick) % 12 == 0); + + if (checkLosThisTick) + { + bool playerSees = HasLineOfSight( + p.X, pEyeY, p.Z, + s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z); + + if (playerSees) + { + mem.VisibleToPlayer = true; + mem.FaintHorizonPing = false; + mem.LastSeenAge = 0f; + mem.LastSeenX = s.X; + mem.LastSeenZ = s.Z; + mem.HasEverBeenSeen = true; + } + else + { + mem.VisibleToPlayer = false; + if (mem.HasEverBeenSeen) + { + mem.LastSeenAge += FixedDt; + } + + // Spectator wall horizon rule: gaudy Tourists (RadarSignature >= 0.9) ping faintly over moderate crests at medium range; + // low-signature Exemplars vanish completely when terrain-occluded. + bool horizonPing = false; + if (s.RadarSignature >= 0.9f) + { + float dx = s.X - p.X; + float dz = s.Z - p.Z; + if (dx * dx + dz * dz <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange) + { + horizonPing = HasLineOfSight( + p.X, pEyeY + 14f, p.Z, + s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight) + 14f, s.Z); + } + } + mem.FaintHorizonPing = horizonPing; + } + } + else if (!mem.VisibleToPlayer && mem.HasEverBeenSeen) + { + mem.LastSeenAge += FixedDt; + } + + if (s.Stance != SpectatorStance.Neutral && + s.TargetContenderId == p.Id && + s.HasTargetLos) + { + detectedBy++; + } + } + + _forceFullDetectionRefresh = false; + State.PlayerDetectedByCount = detectedBy; + } + + private void StepThermalAndCooldowns() + { + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.Alive) + { + continue; + } + + c.Grid.StepHeat(FixedDt); + bool anyOverheat = false; + for (int m = 0; m < c.Grid.Mounted.Count; m++) + { + var mod = c.Grid.Mounted[m]; + if (mod.Cooldown > 0f) + { + mod.Cooldown = MathF.Max(0f, mod.Cooldown - FixedDt); + } + if (mod.CurrentTemp > mod.Spec.OptimalTemp + mod.Spec.PlateauWidth * 0.6f) + { + anyOverheat = true; + } + } + + if (anyOverheat && !c.OverheatWarned) + { + c.OverheatWarned = true; + State.Broadcast.EmitOverheat(State.Time, c.Id); + } + else if (!anyOverheat) + { + c.OverheatWarned = false; + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive) + { + continue; + } + + s.Grid.StepHeat(FixedDt); + for (int m = 0; m < s.Grid.Mounted.Count; m++) + { + if (s.Grid.Mounted[m].Cooldown > 0f) + { + s.Grid.Mounted[m].Cooldown = MathF.Max(0f, s.Grid.Mounted[m].Cooldown - FixedDt); + } + } + } + } + + private void ProcessWeapons() + { + var view = _world.View; + + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.Alive || !_contenderBodies.TryGetValue(c.Id, out var handle)) + { + continue; + } + + int lane = handle.Lane; + var shooterQuat = new Quaternion( + view.RotationX[lane], + view.RotationY[lane], + view.RotationZ[lane], + view.RotationW[lane]); + ulong shooterStableId = ContenderStableIdBase + (ulong)c.Id; + + if (c.IsPlayer) + { + UpdateWeaponArcTelemetry(c, shooterQuat, shooterStableId); + } + + if (c.FireCmd) + { + FireMountedWeapons( + shooterStableId, + shooterContender: c, + shooterLabel: c.Name, + isSpectatorShooter: false, + shooterGrid: c.Grid, + shooterPos: new Vector3(c.X, c.Y, c.Z), + shooterYaw: c.Yaw, + shooterQuat: shooterQuat, + aimX: c.AimX, + aimY: c.AimY, + aimZ: c.AimZ, + extraSpread: 0f, + view: view); + } + + if (!c.Grid.Spec.IsVtol) + { + TryAutoPointDefenseFire(c, shooterStableId, shooterQuat, view); + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral || !_spectatorBodies.TryGetValue(s.Id, out var specHandle)) + { + continue; + } + + MatchRules.ComputeSpectatorBehavior(s, State, out _, out _, out float aimX, out float aimZ, out bool shouldFire); + if (!shouldFire) + { + continue; + } + + int lane = specHandle.Lane; + var specQuat = new Quaternion( + view.RotationX[lane], + view.RotationY[lane], + view.RotationZ[lane], + view.RotationW[lane]); + ulong shooterStableId = SpectatorStableIdBase + (ulong)s.Id; + FireMountedWeapons( + shooterStableId, + shooterContender: null, + shooterLabel: $"{s.Tier} Spectator", + isSpectatorShooter: true, + shooterGrid: s.Grid, + shooterPos: new Vector3(s.X, s.Y, s.Z), + shooterYaw: s.Yaw, + shooterQuat: specQuat, + aimX: aimX, + aimY: float.NaN, + aimZ: aimZ, + extraSpread: s.AimSpreadRad, + view: view); + } + } + + private void UpdateWeaponArcTelemetry(ContenderState c, Quaternion shooterQuat, ulong shooterStableId) + { + float targetY = !float.IsNaN(c.AimY) ? c.AimY : ResolveAimTargetY(c.AimX, c.AimZ, shooterStableId); + var shooterPos = new Vector3(c.X, c.Y, c.Z); + int inArc = 0; + int outArc = 0; + int disabled = 0; + + for (int m = 0; m < c.Grid.Mounted.Count; m++) + { + var mod = c.Grid.Mounted[m]; + if (mod.Spec.Kind != HardpointKind.Weapon) + { + continue; + } + + var hp = c.Grid.FindHardpoint(mod.HardpointId); + if (hp is null) + { + continue; + } + + if (!c.Grid.IsHardpointOperational(hp)) + { + disabled++; + continue; + } + + Vector3 muzzle = ComputeWeaponMuzzle(shooterPos, c.Yaw, c.Grid.Spec, c.AimX, c.AimZ); + Vector3 aimDelta = new Vector3(c.AimX - muzzle.X, targetY - muzzle.Y, c.AimZ - muzzle.Z); + float pitchDeg = MatchRules.ComputeLocalPitchDeg(aimDelta, shooterQuat); + var (minPitch, maxPitch) = MatchRules.GetEffectivePitchArc(hp, mod.Spec); + if (pitchDeg >= minPitch && pitchDeg <= maxPitch) + { + inArc++; + } + else + { + outArc++; + } + } + + c.InArcWeaponCount = inArc; + c.OutOfArcWeaponCount = outArc; + c.DisabledWeaponCount = disabled; + c.AllWeaponsOutOfArc = outArc > 0 && inArc == 0; + } + + private void TryAutoPointDefenseFire( + ContenderState shooter, + ulong shooterStableId, + Quaternion shooterQuat, + Box3DSoaView view) + { + const float maxPdTrackRange = 140f; + var shooterPos = new Vector3(shooter.X, shooter.Y, shooter.Z); + + for (int m = 0; m < shooter.Grid.Mounted.Count; m++) + { + var mod = shooter.Grid.Mounted[m]; + if (mod.Spec.Kind != HardpointKind.Weapon || + !mod.Spec.IsWideArc || + mod.Cooldown > 0f || + mod.CurrentPerformance <= 0.05f) + { + continue; + } + + // Avoid self-cooking on auto-PD if close to thermal ceiling + if (mod.CurrentTemp > mod.Spec.OptimalTemp + mod.Spec.PlateauWidth * 0.45f) + { + continue; + } + + var hp = shooter.Grid.FindHardpoint(mod.HardpointId); + if (hp is null || !shooter.Grid.IsHardpointOperational(hp)) + { + continue; + } + + var (minPitch, maxPitch) = MatchRules.GetEffectivePitchArc(hp, mod.Spec); + float range = MathF.Min(maxPdTrackRange, MathF.Max(5f, mod.Spec.WeaponRange)); + float rangeSq = range * range; + + ContenderState? bestVtol = null; + float bestDistSq = rangeSq; + + for (int j = 0; j < State.Contenders.Count; j++) + { + var other = State.Contenders[j]; + if (other.Id == shooter.Id || !other.Alive || !other.Grid.Spec.IsVtol) + { + continue; + } + + float groundH = State.Terrain.SampleHeight(other.X, other.Z); + float agl = (other.Y - other.Grid.Spec.HalfHeight) - groundH; + if (agl <= 2.0f) + { + continue; + } + + float targetY = MatchRules.GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight); + Vector3 muzzle = ComputeWeaponMuzzle(shooterPos, shooter.Yaw, shooter.Grid.Spec, other.X, other.Z); + Vector3 delta = new Vector3(other.X - muzzle.X, targetY - muzzle.Y, other.Z - muzzle.Z); + float d2 = delta.LengthSquared(); + if (d2 > bestDistSq) + { + continue; + } + + float pitchDeg = MatchRules.ComputeLocalPitchDeg(delta, shooterQuat); + if (pitchDeg < minPitch || pitchDeg > maxPitch) + { + continue; + } + + if (!HasLineOfSight(muzzle.X, muzzle.Y, muzzle.Z, other.X, targetY, other.Z)) + { + continue; + } + + bestDistSq = d2; + bestVtol = other; + } + + if (bestVtol is null) + { + continue; + } + + float aimY = MatchRules.GetTargetAimY(bestVtol.Y, bestVtol.Grid.Spec.HalfHeight); + FireSingleWeapon( + mod, + shooterStableId, + shooter, + shooter.Name, + isSpectatorShooter: false, + shooter.Grid, + shooterPos, + shooter.Yaw, + shooterQuat, + bestVtol.X, + aimY, + bestVtol.Z, + extraSpread: 0f, + view: view); + } + } + + private void FireMountedWeapons( + ulong shooterStableId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + ChassisGrid shooterGrid, + Vector3 shooterPos, + float shooterYaw, + Quaternion shooterQuat, + float aimX, + float aimY, + float aimZ, + float extraSpread, + Box3DSoaView view) + { + float targetY = !float.IsNaN(aimY) ? aimY : ResolveAimTargetY(aimX, aimZ, shooterStableId); + + for (int m = 0; m < shooterGrid.Mounted.Count; m++) + { + var mod = shooterGrid.Mounted[m]; + var hp = shooterGrid.FindHardpoint(mod.HardpointId); + if (mod.Spec.Kind != HardpointKind.Weapon || + mod.Cooldown > 0f || + mod.CurrentPerformance <= 0.05f || + hp is null || + !shooterGrid.IsHardpointOperational(hp)) + { + continue; + } + + FireSingleWeapon( + mod, + shooterStableId, + shooterContender, + shooterLabel, + isSpectatorShooter, + shooterGrid, + shooterPos, + shooterYaw, + shooterQuat, + aimX, + targetY, + aimZ, + extraSpread, + view); + } + } + + private static Vector3 ComputeWeaponMuzzle( + Vector3 shooterPos, + float shooterYaw, + ChassisSpec spec, + float aimX, + float aimZ) + { + Vector3 horizDir = new Vector3(aimX - shooterPos.X, 0f, aimZ - shooterPos.Z); + if (horizDir.LengthSquared() < 1e-3f) + { + horizDir = Vector3.UnitZ; + } + else + { + horizDir = Vector3.Normalize(horizDir); + } + + float cosYaw = MathF.Cos(shooterYaw); + float sinYaw = MathF.Sin(shooterYaw); + float localDirX = horizDir.X * cosYaw - horizDir.Z * sinYaw; + float localDirZ = horizDir.X * sinYaw + horizDir.Z * cosYaw; + float clearance = + MathF.Abs(localDirX) * spec.HalfWidth + + MathF.Abs(localDirZ) * spec.HalfLength + + 0.35f; + + return new Vector3( + shooterPos.X + horizDir.X * clearance, + shooterPos.Y + spec.HalfHeight * 0.25f, + shooterPos.Z + horizDir.Z * clearance); + } + + private void FireSingleWeapon( + MountedModule mod, + ulong shooterStableId, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + ChassisGrid shooterGrid, + Vector3 shooterPos, + float shooterYaw, + Quaternion shooterQuat, + float aimX, + float targetY, + float aimZ, + float extraSpread, + Box3DSoaView view) + { + var hp = shooterGrid.FindHardpoint(mod.HardpointId); + Vector3 muzzle = ComputeWeaponMuzzle(shooterPos, shooterYaw, shooterGrid.Spec, aimX, aimZ); + Vector3 aimDelta = new Vector3(aimX - muzzle.X, targetY - muzzle.Y, aimZ - muzzle.Z); + if (hp is not null) + { + float pitchDeg = MatchRules.ComputeLocalPitchDeg(aimDelta, shooterQuat); + var (minPitch, maxPitch) = MatchRules.GetEffectivePitchArc(hp, mod.Spec); + if (pitchDeg < minPitch || pitchDeg > maxPitch) + { + return; + } + } + + Vector3 baseAim = aimDelta.LengthSquared() < 1e-4f + ? Vector3.UnitZ + : Vector3.Normalize(aimDelta); + + int burst = Math.Max(1, mod.Spec.BurstCount); + float totalSpread = mod.Spec.SpreadRad + extraSpread; + float range = MathF.Max(5f, mod.Spec.WeaponRange); + uint tracerColor = mod.Spec.IsImperial + ? 0xFFD966FFu + : (mod.Spec.IsWideArc ? 0x66E6FFFFu : 0xFF8833FFu); + + for (int b = 0; b < burst; b++) + { + float yawJitter = ((float)State.Rng.NextDouble() * 2f - 1f) * totalSpread; + float pitchJitter = ((float)State.Rng.NextDouble() * 2f - 1f) * (totalSpread * 0.35f); + var dir = ApplyAimSpread(baseAim, yawJitter, pitchJitter); + + var hit = _world.CastRayClosest( + (muzzle.X, muzzle.Y, muzzle.Z), + (dir.X * range, dir.Y * range, dir.Z * range)); + + float boxDist = hit.Hit + ? Vector3.Distance(muzzle, new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z)) + : range; + + bool hitTerrain = State.Terrain.Raycast( + muzzle.X, muzzle.Y, muzzle.Z, + dir.X, dir.Y, dir.Z, + boxDist, + out float tx, out float ty, out float tz, out float terrainDist); + + Vector3 endPt; + if (hitTerrain && terrainDist < boxDist) + { + endPt = new Vector3(tx, ty, tz); + StampTerrainWeaponImpact(mod.Spec.Id, tx, tz, burstIndex: b); + } + else + { + endPt = hit.Hit + ? new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z) + : muzzle + dir * range; + + if (hit.Hit && hit.StableId != shooterStableId && _entityByStableId.TryGetValue(hit.StableId, out var targetRef)) + { + ApplyHitToTarget( + targetRef, + hit.Point, + mod.Spec.WeaponDamage * mod.CurrentPerformance, + mod.Spec.HeatOutput * 0.25f, + shooterContender, + shooterLabel, + isSpectatorShooter, + view); + } + } + + State.Tracers.Add(new TracerEvent( + muzzle.X, muzzle.Y, muzzle.Z, + endPt.X, endPt.Y, endPt.Z, + tracerColor, + 0.09f)); + } + + shooterGrid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput); + mod.Cooldown = mod.Spec.FireCooldown; + + if (shooterContender is not null) + { + State.LastGunfireX = shooterPos.X; + State.LastGunfireZ = shooterPos.Z; + State.LastGunfireTime = State.Time; + } + } + + private void ApplyHitToTarget( + (bool IsContender, int Index) targetRef, + (float X, float Y, float Z) hitPoint, + float damage, + float heatTransfer, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter, + Box3DSoaView view) + { + if (targetRef.IsContender) + { + var target = State.Contenders[targetRef.Index]; + if (!target.Alive || !_contenderBodies.TryGetValue(target.Id, out var body)) + { + return; + } + + var (localRight, localForward, localHeightNorm) = ComputeLocalHitCoords(hitPoint, body.Lane, target.Grid.Spec, view); + var result = target.Grid.ApplyHit(localRight, localForward, localHeightNorm, damage, heatTransfer); + if (result.CoreDestroyed) + { + HandleContenderEliminated(target, shooterContender, shooterLabel, isSpectatorShooter); + } + } + else + { + var spec = State.Spectators.Spectators[targetRef.Index]; + if (!spec.Alive || !_spectatorBodies.TryGetValue(spec.Id, out var body)) + { + return; + } + + if (shooterContender is not null) + { + float inDx = shooterContender.X - hitPoint.X; + float inDz = shooterContender.Z - hitPoint.Z; + float inLen = MathF.Sqrt(inDx * inDx + inDz * inDz); + float? inDirX = inLen > 1e-3f ? inDx / inLen : null; + float? inDirZ = inLen > 1e-3f ? inDz / inLen : null; + + bool newlyProvoked = State.Spectators.OnSpectatorDamaged(spec, shooterContender.Id, inDirX, inDirZ); + if (newlyProvoked) + { + spec.BroadcastWakeupEmitted = true; + if (spec.Tier == SpectatorTier.Tourist) + { + State.Broadcast.EmitTouristPull(State.Time, shooterContender.Id); + } + else if (spec.Tier == SpectatorTier.Exemplar) + { + State.Broadcast.EmitExemplarWakeup(State.Time, shooterContender.Id); + } + } + } + + var (localRight, localForward, localHeightNorm) = ComputeLocalHitCoords(hitPoint, body.Lane, spec.Grid.Spec, view); + var result = spec.Grid.ApplyHit(localRight, localForward, localHeightNorm, damage, heatTransfer); + if (result.CoreDestroyed) + { + HandleSpectatorDestroyed(spec, shooterContender, shooterLabel); + } + } + } + + private void HandleContenderEliminated( + ContenderState victim, + ContenderState? shooterContender, + string shooterLabel, + bool isSpectatorShooter) + { + if (_contenderBodies.TryGetValue(victim.Id, out var handle)) + { + _world.RemoveBody(handle); + _contenderBodies.Remove(victim.Id); + } + + if (shooterContender is not null) + { + shooterContender.Kills++; + } + + State.SpawnChassisDrop(victim.X, victim.Z, victim.Grid.Spec); + for (int i = 0; i < victim.Grid.Mounted.Count; i++) + { + State.SpawnModuleDrop(victim.X + (i - 1) * 0.9f, victim.Z + 1.2f, victim.Grid.Mounted[i].Spec); + } + + State.Terrain.StampCrater(victim.X, victim.Z, radius: 5.2f, depth: 1.3f); + State.Terrain.StampScorch(victim.X, victim.Z, radius: 6.2f); + State.Broadcast.EmitElimination(State.Time, shooterLabel, victim.Name, isSpectatorShooter); + } + + private void HandleSpectatorDestroyed(SpectatorState spec, ContenderState? shooterContender, string shooterLabel) + { + if (_spectatorBodies.TryGetValue(spec.Id, out var handle)) + { + _world.RemoveBody(handle); + _spectatorBodies.Remove(spec.Id); + } + + if (shooterContender is not null) + { + shooterContender.Kills++; + } + + var drops = SpectatorRing.RollSalvageDrops(spec, State.Rng); + for (int i = 0; i < drops.Count; i++) + { + State.SpawnModuleDrop(spec.X + (i - 0.5f) * 1.1f, spec.Z, drops[i]); + } + + State.Terrain.StampCrater(spec.X, spec.Z, radius: 4.5f, depth: 1.1f); + State.Terrain.StampScorch(spec.X, spec.Z, radius: 5.4f); + State.Broadcast.EmitElimination(State.Time, shooterLabel, $"{spec.Tier} Spectator", false); + } + + private void StampTerrainWeaponImpact(string weaponId, float x, float z, int burstIndex) + { + switch (weaponId) + { + case "recoilless": + State.Terrain.StampCrater(x, z, radius: 4.2f, depth: 1.05f); + State.Terrain.StampScorch(x, z, radius: 4.5f); + break; + case "gilded_lance": + State.Terrain.StampCrater(x, z, radius: 3.0f, depth: 0.70f); + State.Terrain.StampScorch(x, z, radius: 3.6f); + break; + case "flak": + if (burstIndex == 0) + { + State.Terrain.StampCrater(x, z, radius: 2.0f, depth: 0.35f); + } + break; + case "touring_plasma": + State.Terrain.StampScorch(x, z, radius: 1.3f); + break; + } + } + + private static (float LocalRight, float LocalForward, float LocalHeightNorm) ComputeLocalHitCoords( + (float X, float Y, float Z) hitPoint, + int lane, + ChassisSpec spec, + Box3DSoaView view) + { + var bodyPos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var bodyQuat = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var local = Vector3.Transform(new Vector3(hitPoint.X, hitPoint.Y, hitPoint.Z) - bodyPos, Quaternion.Conjugate(bodyQuat)); + + float localRight = Math.Clamp(-local.X / MathF.Max(0.1f, spec.HalfWidth), -1f, 1f); + float localForward = Math.Clamp(local.Z / MathF.Max(0.1f, spec.HalfLength), -1f, 1f); + float localHeightNorm = Math.Clamp((local.Y / MathF.Max(0.1f, spec.HalfHeight)) * 0.5f + 0.5f, 0f, 1f); + return (localRight, localForward, localHeightNorm); + } + + private float ResolveAimTargetY(float aimX, float aimZ, ulong shooterStableId) + { + float bestDistSq = 9f * 9f; + float bestY = State.Terrain.SampleHeight(aimX, aimZ) + 0.9f; + + for (int i = 0; i < State.Contenders.Count; i++) + { + var c = State.Contenders[i]; + if (!c.Alive || ContenderStableIdBase + (ulong)c.Id == shooterStableId) + { + continue; + } + float dx = c.X - aimX; + float dz = c.Z - aimZ; + float d2 = dx * dx + dz * dz; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestY = c.Y; + } + } + + for (int i = 0; i < State.Spectators.Spectators.Count; i++) + { + var s = State.Spectators.Spectators[i]; + if (!s.Alive || SpectatorStableIdBase + (ulong)s.Id == shooterStableId) + { + continue; + } + float dx = s.X - aimX; + float dz = s.Z - aimZ; + float d2 = dx * dx + dz * dz; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestY = s.Y; + } + } + + return bestY; + } + + private static Vector3 ApplyAimSpread(Vector3 baseDir, float yawOffset, float pitchOffset) + { + var yawQ = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawOffset); + var rotated = Vector3.Transform(baseDir, yawQ); + var right = Vector3.Cross(rotated, Vector3.UnitY); + if (right.LengthSquared() > 1e-4f) + { + var pitchQ = Quaternion.CreateFromAxisAngle(Vector3.Normalize(right), pitchOffset); + rotated = Vector3.Transform(rotated, pitchQ); + } + return Vector3.Normalize(rotated); + } + + public void Dispose() + { + if (_disposed) + { + return; + } + _disposed = true; + State.ChassisSwapped -= OnContenderChassisSwapped; + _world.Dispose(); + } + } +} diff --git a/src/RustToDust.Ymir/RustToDust.Ymir.csproj b/src/RustToDust.Ymir/RustToDust.Ymir.csproj new file mode 100644 index 0000000..ad53000 --- /dev/null +++ b/src/RustToDust.Ymir/RustToDust.Ymir.csproj @@ -0,0 +1,14 @@ + + + + net8.0 + enable + disable + + + + + + + + diff --git a/tests/RustToDust.Tests/ArenaSessionTests.cs b/tests/RustToDust.Tests/ArenaSessionTests.cs new file mode 100644 index 0000000..f929e24 --- /dev/null +++ b/tests/RustToDust.Tests/ArenaSessionTests.cs @@ -0,0 +1,135 @@ +using System; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class ArenaSessionTests + { + [Fact] + public void DrivingAndFiring_MovesBuggyInYmirAndBuildsWeaponHeat() + { + using var session = new ArenaSession(seed: 42); + var player = session.State.Player; + float startX = player.X; + float startZ = player.Z; + float startYaw = player.Yaw; + int tracerTicks = 0; + + for (int tick = 0; tick < 120; tick++) + { + session.Step(new PlayerInput( + Throttle: 1f, + Steer: 0.45f, + AimWorldX: player.X + 40f, + AimWorldZ: player.Z + 10f, + Fire: true, + InteractPickup: false, + Brake: false)); + + if (session.State.Tracers.Count > 0) + { + tracerTicks++; + } + } + + float dx = player.X - startX; + float dz = player.Z - startZ; + float displacement = MathF.Sqrt(dx * dx + dz * dz); + float yawDelta = MathF.Abs(MatchRules.NormalizeAngle(player.Yaw - startYaw)); + + Assert.True(displacement > 10f, $"Expected >10m displacement, got {displacement:F2}m"); + Assert.True(yawDelta > 0.2f, $"Expected yaw change >0.2 rad, got {yawDelta:F2} rad"); + + var weapon = player.Grid.GetMountedOn("hp.weapon.roof"); + Assert.NotNull(weapon); + Assert.True(weapon!.CurrentTemp > ChassisGrid.AmbientTemp + 5f); + Assert.True(tracerTicks > 0); + } + + [Fact] + public void ChassisSwap_ToManticoreAndRaptor_ReplacesBodyWithoutLeakingYmirLanes() + { + using var session = new ArenaSession(seed: 77); + var player = session.State.Player; + int initialFreeSlots = session.World.FreeBodySlots; + + // Step once to settle world + session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false)); + + // Spawn Manticore (Dorsal) right beside player and swap + session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Manticore); + Assert.True(session.TrySwapNearbyChassis()); + Assert.Equal("manticore", player.Grid.Spec.Id); + Assert.Equal(GridPlane.Dorsal, player.Grid.Spec.Plane); + + // Step so Ymir reclaims old tombstone lane + session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false)); + Assert.Equal(initialFreeSlots, session.World.FreeBodySlots); + + // Now spawn Raptor (Coronal) beside player and swap + session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Raptor); + Assert.True(session.TrySwapNearbyChassis()); + Assert.Equal("raptor", player.Grid.Spec.Id); + Assert.Equal(GridPlane.Coronal, player.Grid.Spec.Plane); + + session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false)); + Assert.Equal(initialFreeSlots, session.World.FreeBodySlots); + } + + [Fact] + public void Raycast_RespectsStaticCoverWalls() + { + using var session = new ArenaSession(seed: 12); + var c0 = session.State.ArenaCoverBoxes[0]; + float rayStartZ = c0.Z - c0.HalfZ - 5f; + float raySpanZ = c0.HalfZ * 2f + 10f; + + // A ray from one side of cover block #0 to the other must hit the static cover wall! + var blockedHit = session.World.CastRayClosest((c0.X, c0.Y, rayStartZ), (0f, 0f, raySpanZ)); + Assert.True(blockedHit.Hit); + Assert.True(blockedHit.Point.Z < c0.Z, $"Expected cover hit before z={c0.Z:F2}, got z={blockedHit.Point.Z:F2}"); + Assert.InRange(blockedHit.StableId, 10UL, 99UL); // Static cover StableId range + + // Ray high above the cover block passes unobstructed + var clearHit = session.World.CastRayClosest((c0.X, c0.Y + c0.HalfY + 2.0f, rayStartZ), (0f, 0f, raySpanZ)); + Assert.False(clearHit.Hit); + } + + [Fact] + public void BroadsideFire_UsesDirectionalSupportRadiusNotMaxExtent() + { + using var session = new ArenaSession(seed: 19); + var player = session.State.Player; + + // Swap to Tank / Anvil (HalfWidth = 1.93m, HalfLength = 2.83m) where broadside vs forward differs by ~0.9m. + session.State.SpawnChassisDrop(player.X + 0.5f, player.Z + 0.5f, Catalog.Tank); + Assert.True(session.TrySwapNearbyChassis()); + Assert.Equal(Catalog.Tank.Id, player.Grid.Spec.Id); + + // Step once to settle body, then aim strictly perpendicular (broadside) to player's Yaw. + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, false)); + float broadsideX = MathF.Cos(player.Yaw); + float broadsideZ = -MathF.Sin(player.Yaw); + + session.Step(new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: player.X + broadsideX * 30f, + AimWorldZ: player.Z + broadsideZ * 30f, + Fire: true, + InteractPickup: false, + Brake: true)); + + Assert.NotEmpty(session.State.Tracers); + var tracer = session.State.Tracers[^1]; + float dx = tracer.StartX - player.X; + float dz = tracer.StartZ - player.Z; + float muzzleHorizDist = MathF.Sqrt(dx * dx + dz * dz); + + // Expected broadside clearance = HalfWidth (1.65) + 0.35 = 2.00m (well below HalfLength + 0.55 = 3.20m) + Assert.InRange(muzzleHorizDist, player.Grid.Spec.HalfWidth + 0.25f, player.Grid.Spec.HalfWidth + 0.50f); + } + } +} diff --git a/tests/RustToDust.Tests/DetectionLosTests.cs b/tests/RustToDust.Tests/DetectionLosTests.cs new file mode 100644 index 0000000..f44210c --- /dev/null +++ b/tests/RustToDust.Tests/DetectionLosTests.cs @@ -0,0 +1,424 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class DetectionLosTests + { + private static TerrainBrush FindTallMesa(TerrainField terrain) + { + for (int i = 0; i < terrain.Brushes.Count; i++) + { + var b = terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f) + { + return b; + } + } + throw new InvalidOperationException("Expected at least one tall Mesa in generated terrain."); + } + + [Fact] + public void MesaBetweenSpectatorAndContender_BlocksLosAndPreventsFiringThroughTerrain() + { + using var session = new ArenaSession(seed: 42); + var mesa = FindTallMesa(session.State.Terrain); + var player = session.State.Player; + var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron); + + // Place player and spectator on opposite sides of the tall mesa + float playerX = mesa.X - mesa.RadiusX - 18f; + float specX = mesa.X + mesa.RadiusX + 18f; + session.SetContenderPose(player.Id, playerX, mesa.Z); + session.SetSpectatorPose(spec.Id, specX, mesa.Z); + + // Provoke this spectator onto the player so it actively hunts, while terrain blocks sightline + session.State.Spectators.OnSpectatorDamaged(spec, player.Id); + float initialCoreHp = player.Grid.CoreHp; + + for (int tick = 0; tick < 10; tick++) + { + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + + Assert.False(session.HasLineOfSight( + spec.X, MatchRules.GetObserverEyeY(spec.Y, spec.Grid.Spec.HalfHeight), spec.Z, + player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z)); + Assert.False(spec.HasTargetLos); + + MatchRules.ComputeSpectatorBehavior(spec, session.State, out _, out _, out _, out _, out bool shouldFire); + Assert.False(shouldFire, "Occluded spectator must NOT fire through a mesa"); + } + + Assert.Equal(initialCoreHp, player.Grid.CoreHp); + } + + [Fact] + public void CrestingRidge_RestoresLosAndAllowsSpectatorEngagement() + { + using var session = new ArenaSession(seed: 42); + var mesa = FindTallMesa(session.State.Terrain); + var player = session.State.Player; + var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron); + + // Start occluded across the mesa + session.SetContenderPose(player.Id, mesa.X - mesa.RadiusX - 18f, mesa.Z); + session.SetSpectatorPose(spec.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z); + session.State.Spectators.OnSpectatorDamaged(spec, player.Id); + + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + Assert.False(spec.HasTargetLos); + + // Now player crests onto the high mesa plateau overlooking the spectator + session.SetContenderPose(player.Id, mesa.X + mesa.RadiusX * 0.25f, mesa.Z); + session.SetSpectatorPose(spec.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z); + + bool sawTracer = false; + for (int tick = 0; tick < 30; tick++) + { + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + if (session.State.Tracers.Count > 0) + { + sawTracer = true; + } + } + + Assert.True(spec.HasTargetLos, "Cresting the mesa must restore spectator LOS"); + MatchRules.ComputeSpectatorBehavior(spec, session.State, out _, out _, out _, out _, out bool shouldFire); + Assert.True(shouldFire, "Spectator with restored LOS within range should be cleared to fire"); + Assert.True(sawTracer, "Expected spectator to fire weapons once LOS was restored"); + } + + [Fact] + public void LowSignatureExemplar_HiddenBehindRidge_IsInvisibleOnRadar_WhileInLosContactIsVisible() + { + using var session = new ArenaSession(seed: 42); + var mesa = FindTallMesa(session.State.Terrain); + var player = session.State.Player; + var exemplar = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar); + var visibleRival = session.State.Contenders[1]; + + Assert.True(exemplar.RadarSignature <= 0.25f); + + // Reset memory so exemplar has never been seen yet, then hide it on the far side of the mesa + session.State.SpectatorContacts[exemplar.Id] = new PlayerContactMemory(); + session.SetContenderPose(player.Id, mesa.X - mesa.RadiusX - 18f, mesa.Z); + session.SetSpectatorPose(exemplar.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z); + + // Place rival contender nearby in clear open LOS on the player's side of the mesa + session.SetContenderPose(visibleRival.Id, mesa.X - mesa.RadiusX - 50f, mesa.Z + 12f); + + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + + var exMem = session.State.SpectatorContacts[exemplar.Id]; + Assert.False(exMem.VisibleToPlayer); + Assert.False(exMem.FaintHorizonPing); + Assert.False(MatchState.IsContactOnRadar(exMem), "Hidden low-signature Exemplar must vanish off player radar"); + + var rivalMem = session.State.ContenderContacts[visibleRival.Id]; + Assert.True(rivalMem.VisibleToPlayer, "In-LOS contact must be live-visible to player"); + Assert.True(MatchState.IsContactOnRadar(rivalMem)); + } + + [Fact] + public void StaticCoverWall_BlocksLineOfSight() + { + using var session = new ArenaSession(seed: 12); + var box = session.State.ArenaCoverBoxes[0]; + var player = session.State.Player; + var rival = session.State.Contenders[1]; + + // Ensure rival is a low-profile ground vehicle shorter than the 4m ruin cover wall + if (rival.Grid.Spec.IsVtol || rival.Grid.Spec.HalfHeight * 2f >= box.HalfY * 2f) + { + session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 4f); + session.State.SpawnChassisDrop(box.X, box.Z + box.HalfZ + 4f, Catalog.Jackal); + Assert.True(session.State.TrySwapNearbyChassis(rival.Id)); + } + + session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f); + session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 4f); + + bool los = session.HasLineOfSight( + player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, + rival.X, MatchRules.GetTargetAimY(rival.Y, rival.Grid.Spec.HalfHeight), rival.Z); + + Assert.False(los, "Static cover ruin wall between two vehicles must block HasLineOfSight"); + } + + [Fact] + public void NeutralTierPositioning_PatronsClaimHigherGroundThanTouristsAndExemplars_AndHoldSpots() + { + var state = new MatchState(seed: 42); + var ring = state.Spectators; + + var touristHeights = new List(); + var patronHeights = new List(); + var exemplarHeights = new List(); + var initialGoals = new Dictionary(); + + for (int i = 0; i < ring.Spectators.Count; i++) + { + var s = ring.Spectators[i]; + var (gx, gz) = ring.GetNeutralGoal(s, state.Terrain, state.ArenaCoverBoxes); + initialGoals[s.Id] = (gx, gz); + float h = state.Terrain.SampleHeight(gx, gz); + + switch (s.Tier) + { + case SpectatorTier.Tourist: touristHeights.Add(h); break; + case SpectatorTier.Patron: patronHeights.Add(h); break; + case SpectatorTier.Exemplar: exemplarHeights.Add(h); break; + } + } + + float avgPatronH = patronHeights.Average(); + float avgTouristH = touristHeights.Average(); + float avgExemplarH = exemplarHeights.Average(); + + Assert.True(avgPatronH > avgTouristH + 1.0f, + $"Expected Patrons ({avgPatronH:F2}m) to claim higher ground than Tourists ({avgTouristH:F2}m)"); + Assert.True(avgPatronH > avgExemplarH + 1.0f, + $"Expected Patrons ({avgPatronH:F2}m) to claim higher ground than Exemplars ({avgExemplarH:F2}m)"); + + // Advance perimeter orbits while SafeRadius is within grace period: Tourists orbit, Patrons & Exemplars hold! + ring.AdvancePerimeterOrbits(15f); + + for (int i = 0; i < ring.Spectators.Count; i++) + { + var s = ring.Spectators[i]; + var (gx, gz) = ring.GetNeutralGoal(s, state.Terrain, state.ArenaCoverBoxes); + var prev = initialGoals[s.Id]; + float moved = MathF.Sqrt((gx - prev.X) * (gx - prev.X) + (gz - prev.Z) * (gz - prev.Z)); + + if (s.Tier == SpectatorTier.Tourist) + { + Assert.True(moved > 10f, "Expected Neutral Tourists to continue orbiting perimeter"); + } + else + { + Assert.True(moved < 0.01f, $"Expected Neutral {s.Tier} to hold chosen vantage/ambush spot, moved {moved:F2}m"); + } + } + } + + [Fact] + public void OccludedSpectators_DoNotLeakLiveTargetAfterMemoryExpires_FiveSeconds() + { + using var session = new ArenaSession(seed: 42); + // Shrink safe circle so the tall mesa perimeter is outside SafeRadius + session.State.Time = 360f; + session.State.Spectators.UpdateSafeRadius(session.State.Time); + + TerrainBrush mesa = default; + float bestMinRadius = -1f; + for (int i = 0; i < session.State.Terrain.Brushes.Count; i++) + { + var b = session.State.Terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f) + { + float minR = MathF.Min(b.RadiusX, b.RadiusZ); + if (minR > bestMinRadius) + { + bestMinRadius = minR; + mesa = b; + } + } + } + Assert.True(bestMinRadius > 0f, "Expected at least one tall Mesa in generated terrain."); + + var player = session.State.Player; + var tourists = session.State.Spectators.Spectators.Where(s => s.Tier == SpectatorTier.Tourist).ToList(); + var provokedSpec = tourists[0]; + var clearedSpec = tourists[1]; + + // Place player on the side of the mesa further from center (strictly outside SafeRadius) + float xNeg = mesa.X - mesa.RadiusX - 18f; + float xPos = mesa.X + mesa.RadiusX + 18f; + bool negIsFurther = (xNeg * xNeg + mesa.Z * mesa.Z) >= (xPos * xPos + mesa.Z * mesa.Z); + float occludedX = negIsFurther ? xNeg : xPos; + float specSideX = negIsFurther ? (mesa.X + mesa.RadiusX + 45f) : (mesa.X - mesa.RadiusX - 45f); + + // Keep AI contenders safely inside the safe circle and other spectators behind the mesa shadow so they don't peek around the flank + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(session.State.Contenders[i].Id, (i - 6) * 12f, 0f); + } + for (int i = 0; i < session.State.Spectators.Spectators.Count; i++) + { + var other = session.State.Spectators.Spectators[i]; + if (other.Id != provokedSpec.Id && other.Id != clearedSpec.Id) + { + float farX = (mesa.X >= 0f ? -1f : 1f) * 680f; + float farZ = (mesa.Z >= 0f ? -1f : 1f) * 680f; + session.SetSpectatorPose(other.Id, farX, farZ); + } + } + + // Briefly establish visual contact for provokedSpec at initial spot, then move player behind the mesa + session.SetContenderPose(player.Id, specSideX - (negIsFurther ? 12f : -12f), mesa.Z); + session.SetSpectatorPose(provokedSpec.Id, specSideX, mesa.Z); + session.State.Spectators.OnSpectatorDamaged(provokedSpec, player.Id); + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + Assert.True(provokedSpec.HasTargetLos, "Expected initial LOS before player drops behind cover"); + + float provokedKnownX = provokedSpec.LastKnownTargetX; + float provokedKnownZ = provokedSpec.LastKnownTargetZ; + + // Now hide player behind the mesa and place clearedSpec on the opposite side closest to the breach + session.SetContenderPose(player.Id, occludedX, mesa.Z - 14f); + session.SetSpectatorPose(provokedSpec.Id, specSideX, mesa.Z - 4f); + session.SetSpectatorPose(clearedSpec.Id, specSideX, mesa.Z + 4f); + + // Verify clearedSpec gets Pass-2 Cleared assignment without LOS + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + Assert.False(provokedSpec.HasTargetLos); + Assert.Equal(SpectatorStance.Cleared, clearedSpec.Stance); + Assert.False(clearedSpec.HasTargetLos); + + float clearedInitialKnownX = clearedSpec.LastKnownTargetX; + float clearedInitialKnownZ = clearedSpec.LastKnownTargetZ; + + // Run 300 ticks (5.0s > 4.0s TargetMemoryDuration) while player moves laterally behind cover + for (int tick = 0; tick < 300; tick++) + { + float latZ = mesa.Z - 14f + (tick / 299f) * 28f; + if (tick % 10 == 0) + { + session.SetContenderPose(player.Id, occludedX, latZ); + } + + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + + Assert.False(provokedSpec.HasTargetLos, $"Provoked spectator regained unexpected LOS at tick {tick}"); + Assert.False(clearedSpec.HasTargetLos, $"Cleared spectator regained unexpected LOS at tick {tick}"); + + if (tick == 270) // 4.5s > 4.0s memory window + { + Assert.True(provokedSpec.TimeSinceLastSeen >= 4.5f, + $"Provoked TimeSinceLastSeen reset unexpectedly: {provokedSpec.TimeSinceLastSeen:F2}s"); + Assert.True(clearedSpec.TimeSinceLastSeen >= 4.5f, + $"Cleared TimeSinceLastSeen reset unexpectedly: {clearedSpec.TimeSinceLastSeen:F2}s"); + } + } + + // Neither spectator's LastKnownTarget or aim vector may track the player's new occluded position + float provokedDistToPlayer = MathF.Sqrt( + (provokedSpec.LastKnownTargetX - player.X) * (provokedSpec.LastKnownTargetX - player.X) + + (provokedSpec.LastKnownTargetZ - player.Z) * (provokedSpec.LastKnownTargetZ - player.Z)); + Assert.Equal(provokedKnownX, provokedSpec.LastKnownTargetX, precision: 3); + Assert.Equal(provokedKnownZ, provokedSpec.LastKnownTargetZ, precision: 3); + Assert.True(provokedDistToPlayer > 25f, + $"Provoked LastKnownTarget leaked live player position (dist={provokedDistToPlayer:F2}m)"); + + float clearedDistToPlayer = MathF.Sqrt( + (clearedSpec.LastKnownTargetX - player.X) * (clearedSpec.LastKnownTargetX - player.X) + + (clearedSpec.LastKnownTargetZ - player.Z) * (clearedSpec.LastKnownTargetZ - player.Z)); + Assert.Equal(clearedInitialKnownX, clearedSpec.LastKnownTargetX, precision: 3); + Assert.Equal(clearedInitialKnownZ, clearedSpec.LastKnownTargetZ, precision: 3); + Assert.True(clearedDistToPlayer > 20f, + $"Cleared LastKnownTarget leaked live player position (dist={clearedDistToPlayer:F2}m)"); + + MatchRules.ComputeSpectatorBehavior(provokedSpec, session.State, out _, out _, out float pAimX, out float pAimZ, out bool pFire); + Assert.False(pFire); + Assert.Equal(provokedKnownX, pAimX, precision: 3); + Assert.Equal(provokedKnownZ, pAimZ, precision: 3); + + MatchRules.ComputeSpectatorBehavior(clearedSpec, session.State, out _, out _, out float cAimX, out float cAimZ, out bool cFire); + Assert.False(cFire); + Assert.Equal(clearedInitialKnownX, cAimX, precision: 3); + Assert.Equal(clearedInitialKnownZ, cAimZ, precision: 3); + } + + [Fact] + public void Probe2_OccludedLateralArc_FullRingDoesNotLeakOrTrackPlayerPosition() + { + var ring = new SpectatorRing(seed: 42); + Assert.Equal(56, ring.Spectators.Count); + const float dt = 1f / 60f; + + // Phase 1 (10 ticks): Player pops out of safe circle briefly at 0 degrees with LOS to nearby 0-deg watchers. + float startR = ring.SafeRadius + 15f; + for (int tick = 0; tick < 10; tick++) + { + var contact = new RingContact(0, startR, 0f, true); + ring.UpdateClearance(new[] { contact }, dt, (spec, _) => + { + float specAng = MathF.Atan2(spec.Z, spec.X); + return MathF.Abs(specAng) < 0.45f; + }); + } + + int initialCleared = ring.CountClearedFor(0); + Assert.True(initialCleared >= 1, "Expected at least one Cleared spectator at 0 degrees during initial pop-out"); + Assert.Contains(ring.Spectators, s => s.Stance == SpectatorStance.Cleared && s.HasTargetLos); + + // Phase 2 (600 ticks = 10s): 100% occlusion while player moves laterally 0 -> 80 deg and steps further out. + float playerX = startR; + float playerZ = 0f; + float maxArcRad = 80f * (MathF.PI / 180f); + + for (int tick = 0; tick < 600; tick++) + { + float t = tick / 599f; + float angle = t * maxArcRad; + float r = ring.SafeRadius + 15f + t * 70f; + playerX = MathF.Cos(angle) * r; + playerZ = MathF.Sin(angle) * r; + + var contact = new RingContact(0, playerX, playerZ, true); + ring.UpdateClearance(new[] { contact }, dt, static (_, _) => false); + + foreach (var s in ring.Spectators) + { + Assert.False(s.HasTargetLos, $"No spectator may have LOS during occluded arc (tick {tick}, spec {s.Id})"); + if (s.Stance == SpectatorStance.Cleared) + { + float targetAngle = MathF.Atan2(s.LastKnownTargetZ, s.LastKnownTargetX); + Assert.True(MathF.Abs(targetAngle) < 0.35f, + $"Cleared spectator {s.Id} leaked lateral angle {targetAngle * 180f / MathF.PI:F1} deg at tick {tick}"); + } + } + } + + // At end of 80-deg hidden move, no spectator has LastKnownTarget near the player's hidden position, + // and spectators stationed along 35..90 degrees remain Neutral. + foreach (var s in ring.Spectators) + { + if (s.Stance == SpectatorStance.Cleared) + { + float dx = s.LastKnownTargetX - playerX; + float dz = s.LastKnownTargetZ - playerZ; + float distToHiddenPlayer = MathF.Sqrt(dx * dx + dz * dz); + Assert.True(distToHiddenPlayer > 400f, + $"Cleared spectator {s.Id} LastKnownTarget ({s.LastKnownTargetX:F1}, {s.LastKnownTargetZ:F1}) too close to hidden player ({distToHiddenPlayer:F1}m)"); + } + + float specAngleDeg = MathF.Atan2(s.Z, s.X) * (180f / MathF.PI); + if (specAngleDeg >= 35f && specAngleDeg <= 95f) + { + Assert.Equal(SpectatorStance.Neutral, s.Stance); + } + } + } + + [Fact] + public void OnSpectatorDamaged_WithoutLos_SeedsIncomingDirectionInsteadOfStaleTarget() + { + var ring = new SpectatorRing(seed: 77); + var spec = ring.Spectators[0]; + spec.LastKnownTargetX = 0f; + spec.LastKnownTargetZ = 0f; + + bool provoked = ring.OnSpectatorDamaged(spec, attackerContenderId: 0, incomingDirX: 0f, incomingDirZ: 1f); + Assert.True(provoked); + Assert.Equal(SpectatorStance.Provoked, spec.Stance); + Assert.False(spec.HasTargetLos); + Assert.True(spec.LastKnownTargetZ > spec.Z + 10f, + $"Expected LastKnownTarget to point along incoming +Z direction, got Z={spec.LastKnownTargetZ:F1} vs spec.Z={spec.Z:F1}"); + } + } +} diff --git a/tests/RustToDust.Tests/GridHeatTests.cs b/tests/RustToDust.Tests/GridHeatTests.cs new file mode 100644 index 0000000..cba59dc --- /dev/null +++ b/tests/RustToDust.Tests/GridHeatTests.cs @@ -0,0 +1,130 @@ +using System.Collections.Generic; +using RustToDust.Core; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class GridHeatTests + { + [Fact] + public void Conduction_SpreadsHeatFromHotHardpointToNeighbors() + { + var grid = Catalog.CreateStarterBuggy(); + // hp.weapon.roof is at (1, 0) 1x2. Neighbors (0, 0) and (1, 2) start at ambient 20f. + grid.InjectHardpointHeat("hp.weapon.roof", 600f); + float hotBefore = grid.Temperature[1, 0]; + Assert.True(hotBefore > ChassisGrid.AmbientTemp + 20f); + Assert.Equal(ChassisGrid.AmbientTemp, grid.Temperature[0, 0]); + Assert.Equal(ChassisGrid.AmbientTemp, grid.Temperature[1, 2]); + + for (int i = 0; i < 30; i++) + { + grid.StepHeat(1f / 60f); + } + + Assert.True(grid.Temperature[0, 0] > ChassisGrid.AmbientTemp + 1f); + Assert.True(grid.Temperature[1, 2] > ChassisGrid.AmbientTemp + 1f); + Assert.True(grid.Temperature[1, 0] < hotBefore); + } + + [Fact] + public void Radiation_CoolsBorderCellsWhileInteriorCellsDoNotRadiateDirectly() + { + var grid = new ChassisGrid(Catalog.Tank); // 4x5 full grid: interior cells exist at (1..2, 1..3) + for (int y = 0; y < grid.Spec.Height; y++) + { + for (int x = 0; x < grid.Spec.Width; x++) + { + grid.Temperature[x, y] = 120f; + } + } + + // Single 60Hz substep: neighbors are all 120f so net conduction is 0. + // Only BorderCells lose heat to radiation; interior cell (1, 2) must stay at 120f. + grid.StepHeat(1f / 60f); + + Assert.True(grid.BorderCells[0, 0]); + Assert.False(grid.BorderCells[1, 2]); + Assert.True(grid.Temperature[0, 0] < 120f); + Assert.Equal(120f, grid.Temperature[1, 2], precision: 5); + } + + [Fact] + public void ModulePerformance_MatchesTrapezoidalPlateauCurve() + { + var mod = Catalog.Mg762; // Min=0, Optimal=65, Plateau=70 => [30, 100], Max=155 + + Assert.Equal(0f, mod.Performance(-5f)); + Assert.Equal(0f, mod.Performance(0f)); + Assert.Equal(0.5f, mod.Performance(15f), precision: 4); + Assert.Equal(1f, mod.Performance(30f), precision: 4); + Assert.Equal(1f, mod.Performance(65f), precision: 4); + Assert.Equal(1f, mod.Performance(100f), precision: 4); + Assert.Equal(0.5f, mod.Performance(127.5f), precision: 4); + Assert.Equal(0f, mod.Performance(155f)); + Assert.Equal(0f, mod.Performance(210f)); + } + + [Fact] + public void DorsalHit_FrontStrikesFrontRowAndRearStrikesRearRow() + { + var grid = new ChassisGrid(Catalog.Tank); + + var frontHit = grid.ApplyHit(localRight: 0f, localForward: 1f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f); + var rearHit = grid.ApplyHit(localRight: 0f, localForward: -1f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f); + var leftHit = grid.ApplyHit(localRight: -1f, localForward: 0f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f); + var rightHit = grid.ApplyHit(localRight: 1f, localForward: 0f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f); + + Assert.Equal(0, frontHit.CellY); + Assert.Equal(grid.Spec.Height - 1, rearHit.CellY); + Assert.Equal(0, leftHit.CellX); + Assert.Equal(grid.Spec.Width - 1, rightHit.CellX); + } + + [Fact] + public void CoronalHit_HighVsLowElevationStrikesUpperVsLowerBipedCells() + { + var grid = new ChassisGrid(Catalog.Raptor); + float initialLegs = grid.LegIntegrity; + Assert.Equal(1f, initialLegs); + + var highHit = grid.ApplyHit(localRight: 0f, localForward: 1f, localHeightNorm: 0.95f, damage: 20f, heatTransfer: 0f); + var lowHit = grid.ApplyHit(localRight: -0.4f, localForward: 1f, localHeightNorm: 0.05f, damage: 35f, heatTransfer: 0f); + + Assert.True(highHit.CellY <= 1); + Assert.True(lowHit.CellY >= grid.Spec.Height - 2); + Assert.True(grid.LegIntegrity < initialLegs); + } + + [Fact] + public void LooseFitAndSwapChassis_PreservesCompatibleGearAndStowsOverflow() + { + // Ironclad has 2x2 main turret hardpoint: smaller 1x1 weapon fits loosely; 2x2 weapon must NOT fit 1x2 Jackal roof. + var tankGrid = new ChassisGrid(Catalog.Ironclad); + Assert.True(tankGrid.TryMount(Catalog.Recoilless, "hp.weapon.main")); // 2x2 into 2x2 + Assert.True(tankGrid.TryMount(Catalog.Mg762, "hp.weapon.coax")); // 1x1 into 1x1 + Assert.True(tankGrid.TryMount(Catalog.TurboCore, "hp.engine.rear")); // 1x2 into 2x2 + Assert.True(tankGrid.TryMount(Catalog.GoldRadiator, "hp.radiator.l")); // 1x1 into 1x2 + Assert.True(tankGrid.TryMount(Catalog.WeldedPlate, "hp.armor.front")); // 1x1 into 4x1 + Assert.True(tankGrid.TryMount(Catalog.GildedPlate, "hp.armor.skirts")); // 1x1 into 1x2 + + // Fill cargo so swapping down to Jackal (capacity 4) overflows 2 items to ground! + Assert.True(tankGrid.TryAddCargo(Catalog.Flak)); + Assert.True(tankGrid.TryAddCargo(Catalog.CopperRad)); + Assert.True(tankGrid.TryAddCargo(Catalog.DieselCore)); + + List dropped = tankGrid.SwapChassis(Catalog.Jackal); + + // Jackal has 1x2 Weapon (mg_762 fits, recoilless 2x2 does not!), 1x2 Engine (turbo_core fits), 1x1 Radiator (gold_radiator fits), 0 Armor hardpoints. + Assert.Equal("jackal", tankGrid.Spec.Id); + Assert.Contains(tankGrid.Mounted, m => m.Spec.Id == "mg_762"); + Assert.Contains(tankGrid.Mounted, m => m.Spec.Id == "turbo_core"); + Assert.Contains(tankGrid.Mounted, m => m.Spec.Id == "gold_radiator"); + Assert.DoesNotContain(tankGrid.Mounted, m => m.Spec.Id == "recoilless"); + + // 6 mounted on Ironclad: 3 transferred, 3 leftover + 3 cargo = 6 items -> 4 in Jackal Cargo, 2 dropped! + Assert.Equal(Catalog.Jackal.CargoCapacity, tankGrid.Cargo.Count); + Assert.Equal(2, dropped.Count); + } + } +} diff --git a/tests/RustToDust.Tests/RustToDust.Tests.csproj b/tests/RustToDust.Tests/RustToDust.Tests.csproj new file mode 100644 index 0000000..95cfcf3 --- /dev/null +++ b/tests/RustToDust.Tests/RustToDust.Tests.csproj @@ -0,0 +1,21 @@ + + + + net10.0 + enable + disable + false + + + + + + + + + + + + + + diff --git a/tests/RustToDust.Tests/SpectatorRingTests.cs b/tests/RustToDust.Tests/SpectatorRingTests.cs new file mode 100644 index 0000000..7b54630 --- /dev/null +++ b/tests/RustToDust.Tests/SpectatorRingTests.cs @@ -0,0 +1,150 @@ +using System; +using System.Linq; +using RustToDust.Core; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class SpectatorRingTests + { + [Fact] + public void Clearance_ZeroInsideSafeCircle_MonotonicOutside() + { + var ring = new SpectatorRing(seed: 101); + float r = ring.SafeRadius; // 560f + Assert.Equal(56, ring.Spectators.Count); + + // Inside safe circle -> 0 cleared + ring.UpdateClearance(new[] { new RingContact(0, r - 20f, 0f, true) }); + Assert.Equal(0, ring.CountClearedFor(0)); + + // Just outside safe circle (+5m) -> 1 cleared + ring.UpdateClearance(new[] { new RingContact(0, r + 5f, 0f, true) }); + int clearedNear = ring.CountClearedFor(0); + Assert.Equal(1, clearedNear); + + // Further outside (+30m) -> 1 + floor(30/12) = 3 cleared + ring.UpdateClearance(new[] { new RingContact(0, r + 30f, 0f, true) }); + int clearedMid = ring.CountClearedFor(0); + Assert.True(clearedMid > clearedNear); + + // Far outside (+100m) -> capped at 8 cleared + ring.UpdateClearance(new[] { new RingContact(0, r + 100f, 0f, true) }); + int clearedFar = ring.CountClearedFor(0); + Assert.Equal(8, clearedFar); + + // Stepping back inside safe circle revokes non-provoked clearance back to 0 + ring.UpdateClearance(new[] { new RingContact(0, 0f, 0f, true) }); + Assert.Equal(0, ring.CountClearedFor(0)); + } + + [Fact] + public void Provocation_AttackingNeutralSpectatorLocksOntoAttackerEvenInsideSafeCircle() + { + var ring = new SpectatorRing(seed: 202); + var targetSpec = ring.Spectators[0]; + Assert.Equal(SpectatorStance.Neutral, targetSpec.Stance); + + // Contender 0 is dead center (well inside SafeRadius) + var contenders = new[] { new RingContact(0, 0f, 0f, true) }; + ring.UpdateClearance(contenders); + Assert.Equal(0, ring.CountClearedFor(0)); + + bool provoked = ring.OnSpectatorDamaged(targetSpec, attackerContenderId: 0); + Assert.True(provoked); + Assert.Equal(SpectatorStance.Provoked, targetSpec.Stance); + Assert.Equal(0, targetSpec.TargetContenderId); + + // Subsequent clearance updates inside the safe circle must NOT clear Provoked lock + ring.UpdateClearance(contenders); + Assert.Equal(SpectatorStance.Provoked, targetSpec.Stance); + Assert.Equal(1, ring.CountProvokedFor(0)); + + // Once attacker dies, provocation reverts to Neutral + ring.UpdateClearance(new[] { new RingContact(0, 0f, 0f, false) }); + Assert.Equal(SpectatorStance.Neutral, targetSpec.Stance); + Assert.Null(targetSpec.TargetContenderId); + } + + [Fact] + public void SalvageDrops_TouristDropsImperialGearWhileExemplarDoesNot() + { + var ring = new SpectatorRing(seed: 303); + var rng = new Random(99); + + var tourists = ring.Spectators.Where(s => s.Tier == SpectatorTier.Tourist).ToList(); + var exemplars = ring.Spectators.Where(s => s.Tier == SpectatorTier.Exemplar).ToList(); + + Assert.NotEmpty(tourists); + Assert.NotEmpty(exemplars); + + foreach (var tourist in tourists) + { + var drops = SpectatorRing.RollSalvageDrops(tourist, rng); + Assert.InRange(drops.Count, 1, 2); + Assert.All(drops, d => Assert.True(d.IsImperial)); + } + + foreach (var exemplar in exemplars) + { + var drops = SpectatorRing.RollSalvageDrops(exemplar, rng); + Assert.DoesNotContain(drops, d => d.IsImperial); + } + } + + [Fact] + public void SpawnedSpectators_EveryTierMountsEngineAndWeapon() + { + var ring = new SpectatorRing(seed: 42); + + Assert.Contains(ring.Spectators, s => s.Tier == SpectatorTier.Tourist); + Assert.Contains(ring.Spectators, s => s.Tier == SpectatorTier.Patron); + Assert.Contains(ring.Spectators, s => s.Tier == SpectatorTier.Exemplar); + + foreach (var spec in ring.Spectators) + { + Assert.Contains(spec.Grid.Mounted, m => m.Spec.Kind == HardpointKind.Engine); + Assert.Contains(spec.Grid.Mounted, m => m.Spec.Kind == HardpointKind.Weapon); + } + } + + [Fact] + public void Provocation_AttackingClearedSpectatorSwitchesToProvokedAndPersistsInsideSafeCircle() + { + var ring = new SpectatorRing(seed: 505); + float outsideR = ring.SafeRadius + 15f; + + // Contender 0 steps outside safe circle -> clears at least 1 spectator + ring.UpdateClearance(new[] { new RingContact(0, outsideR, 0f, true) }); + var clearedSpec = ring.Spectators.FirstOrDefault(s => s.Stance == SpectatorStance.Cleared); + Assert.NotNull(clearedSpec); + + // Contender 0 fights back against the Cleared spectator + bool provoked = ring.OnSpectatorDamaged(clearedSpec!, attackerContenderId: 0); + Assert.True(provoked); + Assert.Equal(SpectatorStance.Provoked, clearedSpec!.Stance); + Assert.Equal(0, clearedSpec.TargetContenderId); + + // Returning inside the safe circle must NOT clear the Provoked lock + ring.UpdateClearance(new[] { new RingContact(0, 0f, 0f, true) }); + Assert.Equal(SpectatorStance.Provoked, clearedSpec.Stance); + Assert.Equal(1, ring.CountProvokedFor(0)); + } + + [Fact] + public void BroadcastFeed_VersionAdvancesPastRingBufferCap() + { + var feed = new BroadcastFeed(); + for (int i = 0; i < 40; i++) + { + long prev = feed.Version; + feed.Emit(i, BroadcastKind.TouristPull, $"line-{i}"); + Assert.Equal(prev + 1, feed.Version); + } + + Assert.Equal(32, feed.Lines.Count); + Assert.Equal(40, feed.Version); + Assert.Equal("line-39", feed.Latest?.Text); + } + } +} diff --git a/tests/RustToDust.Tests/TerrainTests.cs b/tests/RustToDust.Tests/TerrainTests.cs new file mode 100644 index 0000000..2bb5cba --- /dev/null +++ b/tests/RustToDust.Tests/TerrainTests.cs @@ -0,0 +1,398 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class TerrainTests + { + [Fact] + public void Generate_ProducesDeterministicNonFlatReliefWithinBounds() + { + Assert.Equal(1536f, TerrainField.ArenaSize); + Assert.Equal(8, TerrainField.TileGridCount); + Assert.Equal(192f, TerrainField.TileSize); + Assert.Equal(-18f, TerrainField.MinWorldHeight); + Assert.Equal(52f, TerrainField.MaxWorldHeight); + + var emptyCover = Array.Empty(); + var a = TerrainField.Generate(42UL, emptyCover); + var b = TerrainField.Generate(42UL, emptyCover); + var c = TerrainField.Generate(999UL, emptyCover); + + float minH = float.PositiveInfinity; + float maxH = float.NegativeInfinity; + bool anyDifferentSeed = false; + + for (int gx = -700; gx <= 700; gx += 50) + { + for (int gz = -700; gz <= 700; gz += 50) + { + float ha = a.SampleHeight(gx, gz); + float hb = b.SampleHeight(gx, gz); + float hc = c.SampleHeight(gx, gz); + + Assert.Equal(ha, hb); + if (MathF.Abs(ha - hc) > 0.05f) + { + anyDifferentSeed = true; + } + + minH = MathF.Min(minH, ha); + maxH = MathF.Max(maxH, ha); + } + } + + Assert.True(maxH - minH >= 25f, $"Expected dramatic mesa/dune/canyon relief >= 25m span, got [{minH:F2}, {maxH:F2}]"); + Assert.InRange(minH, TerrainField.MinWorldHeight, -3.0f); + Assert.InRange(maxH, 18.0f, TerrainField.MaxWorldHeight); + Assert.True(anyDifferentSeed, "Different seeds should generate distinct desert relief"); + } + + [Fact] + public void StampCrater_LowersCenterRaisesRimAndDirtyOnlyOverlappingTiles() + { + var terrain = TerrainField.Generate(42UL, Array.Empty()); + terrain.ClearDirtyMask(); + + // Tile (3, 3) spans X in [-192, 0), Z in [-192, 0). + // Point (-96, -96) with radius 6m is strictly inside tile (3, 3) and nowhere else. + const float cx = -96f; + const float cz = -96f; + const float radius = 6f; + const float depth = 1.6f; + + float beforeCenter = terrain.SampleHeight(cx, cz); + float beforeRim = terrain.SampleHeight(cx + radius * 0.775f, cz); + + terrain.StampCrater(cx, cz, radius, depth); + + float afterCenter = terrain.SampleHeight(cx, cz); + float afterRim = terrain.SampleHeight(cx + radius * 0.775f, cz); + + Assert.True(afterCenter < beforeCenter - 1.0f, + $"Expected crater center to drop >1.0m (before {beforeCenter:F2}, after {afterCenter:F2})"); + Assert.True(afterRim > beforeRim + 0.2f, + $"Expected crater ejecta rim to rise >0.2m (before {beforeRim:F2}, after {afterRim:F2})"); + + // Only tile (3, 3) should have incremented from version 1 to 2 + for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + { + for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + { + int expected = (tx == 3 && tz == 3) ? 2 : 1; + Assert.Equal(expected, terrain.TileVersions[tx, tz]); + } + } + Assert.Equal(1UL << (3 * TerrainField.TileGridCount + 3), terrain.DirtyTileMask); + } + + [Fact] + public void Raycast_DetectsBlockingMesaAndClearsAboveCrest() + { + var terrain = TerrainField.Generate(42UL, Array.Empty()); + TerrainBrush? tallMesa = null; + for (int i = 0; i < terrain.Brushes.Count; i++) + { + var b = terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f) + { + tallMesa = b; + break; + } + } + + Assert.NotNull(tallMesa); + var mesa = tallMesa!.Value; + + float startX = mesa.X - mesa.RadiusX - 25f; + float endX = mesa.X + mesa.RadiusX + 25f; + float span = endX - startX; + float lowY = terrain.SampleHeight(startX, mesa.Z) + 4f; + + bool blocked = terrain.Raycast( + startX, lowY, mesa.Z, + 1f, 0f, 0f, + span, + out float hx, out _, out _, out _); + + Assert.True(blocked, "Expected low ray across tall mesa to be blocked by terrain"); + Assert.InRange(hx, startX, endX); + + float highY = terrain.SampleHeight(mesa.X, mesa.Z) + 6f; + bool clear = terrain.Raycast( + startX, highY, mesa.Z, + 1f, 0f, 0f, + span, + out _, out _, out _, out _); + + Assert.False(clear, "Expected ray above mesa plateau to pass unobstructed"); + } + + [Fact] + public void StampTrack_BoundsDynamicDecalCount() + { + var terrain = TerrainField.Generate(7UL, Array.Empty()); + int initialCount = terrain.Brushes.Count; + + for (int i = 0; i < TerrainField.MaxDynamicDecals + 40; i++) + { + float x = -80f + (i % 40) * 4f; + float z = -80f + (i / 40) * 8f; + terrain.StampTrack(x, z, yaw: 0.4f, width: 1.6f, length: 2.5f); + } + + Assert.Equal(initialCount + TerrainField.MaxDynamicDecals, terrain.Brushes.Count); + } + + [Fact] + public void ArenaSession_BuggyDrivesAcrossDunesWithoutNanAndTracksElevation() + { + using var session = new ArenaSession(seed: 42); + var player = session.State.Player; + int initialBrushes = session.State.Terrain.Brushes.Count; + + float minGround = float.PositiveInfinity; + float maxGround = float.NegativeInfinity; + + for (int tick = 0; tick < 360; tick++) + { + float steer = MathF.Sin(tick * 0.025f) * 0.45f; + session.Step(new PlayerInput( + Throttle: 1f, + Steer: steer, + AimWorldX: player.X + 30f, + AimWorldZ: player.Z, + Fire: false, + InteractPickup: false, + Brake: false)); + + Assert.False(float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z), + $"NaN pose at tick {tick}"); + + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + minGround = MathF.Min(minGround, gh); + maxGround = MathF.Max(maxGround, gh); + + // Chassis should remain supported near the terrain surface (never sink under -12m or rocket into orbit) + float bottomY = player.Y - player.Grid.Spec.HalfHeight; + Assert.InRange(bottomY - gh, -0.75f, 4.0f); + } + + Assert.True(session.State.Terrain.Brushes.Count > initialBrushes, + "Driving across dust should stamp tire track brushes"); + Assert.True(maxGround - minGround > 0.25f, + $"Expected buggy to traverse non-flat terrain (span {maxGround - minGround:F2}m)"); + } + + [Theory] + [InlineData(42)] + [InlineData(101)] + [InlineData(999)] + public void CoverBoxes_HaveFlatFootprintWithinHalfMeterAcrossAllCorners(int seed) + { + var state = new MatchState(seed); + float maxCoverCornerDelta = 0f; + + foreach (var box in state.ArenaCoverBoxes) + { + float[] heights = + { + state.Terrain.SampleHeight(box.X, box.Z), + state.Terrain.SampleHeight(box.X - box.HalfX, box.Z - box.HalfZ), + state.Terrain.SampleHeight(box.X + box.HalfX, box.Z - box.HalfZ), + state.Terrain.SampleHeight(box.X - box.HalfX, box.Z + box.HalfZ), + state.Terrain.SampleHeight(box.X + box.HalfX, box.Z + box.HalfZ) + }; + + float minH = float.PositiveInfinity; + float maxH = float.NegativeInfinity; + for (int i = 0; i < heights.Length; i++) + { + minH = MathF.Min(minH, heights[i]); + maxH = MathF.Max(maxH, heights[i]); + } + + maxCoverCornerDelta = MathF.Max(maxCoverCornerDelta, maxH - minH); + float boxBottom = box.Y - box.HalfY; + Assert.True(boxBottom <= minH + 0.01f, + $"Cover box at ({box.X}, {box.Z}) bottom {boxBottom:F2}m floats above corner height {minH:F2}m"); + } + + Assert.Equal(36, state.ArenaCoverBoxes.Count); + Assert.True(maxCoverCornerDelta <= 0.6f, + $"Expected MaxCoverCornerDelta <= 0.6m for seed {seed}, got {maxCoverCornerDelta:F3}m"); + } + + [Fact] + public void RoadBrushes_MajorAxisRunsTangentiallyToFormRingLoop() + { + var terrain = TerrainField.Generate(42UL, Array.Empty()); + var roads = new List(); + for (int i = 0; i < terrain.Brushes.Count; i++) + { + if (terrain.Brushes[i].Kind == TerrainBrushKind.Road) + { + roads.Add(terrain.Brushes[i]); + } + } + + Assert.Equal(16, roads.Count); + foreach (var road in roads) + { + Assert.True(road.RadiusX > road.RadiusZ, + $"Expected Road RadiusX ({road.RadiusX}) > RadiusZ ({road.RadiusZ}) so major axis follows tangential u"); + + float rLen = MathF.Sqrt(road.X * road.X + road.Z * road.Z); + float radX = road.X / rLen; + float radZ = road.Z / rLen; + float axisX = MathF.Cos(road.RotationRad); + float axisZ = MathF.Sin(road.RotationRad); + float radialDot = MathF.Abs(radX * axisX + radZ * axisZ); + + Assert.True(radialDot < 1e-4f, + $"Expected Road major axis to be tangential (dot ~ 0), got {radialDot:F4}"); + } + } + + [Theory] + [InlineData(42)] + [InlineData(101)] + public void SteepMesaAndDuneTraversal_AllSixChassis_NoTunnelingSkyLaunchOrOverturning(int seed) + { + foreach (var chassis in Catalog.AllChassis) + { + RunSteepTerrainStress(seed, chassis, testDune: false); + RunSteepTerrainStress(seed, chassis, testDune: true); + } + } + + private static void RunSteepTerrainStress(int seed, ChassisSpec chassis, bool testDune) + { + using var session = new ArenaSession(seed); + var player = session.State.Player; + + TerrainBrush targetBrush = default; + float startX = 0f; + float startZ = 0f; + float bestScore = -1f; + for (int i = 0; i < session.State.Terrain.Brushes.Count; i++) + { + var b = session.State.Terrain.Brushes[i]; + bool matches = testDune + ? b.Kind == TerrainBrushKind.DuneRidge && b.HeightDelta >= 14f + : b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f; + if (!matches) + { + continue; + } + + if (MathF.Sqrt(b.X * b.X + b.Z * b.Z) > SpectatorRing.InitialRadius - 90f) + { + continue; + } + + float peakH = session.State.Terrain.SampleHeight(b.X, b.Z); + for (int k = 0; k < 8; k++) + { + float localAng = k * (MathF.PI * 0.25f); + float localX = MathF.Cos(localAng) * (b.RadiusX + 18f); + float localZ = MathF.Sin(localAng) * (b.RadiusZ + 18f); + float cosR = MathF.Cos(b.RotationRad); + float sinR = MathF.Sin(b.RotationRad); + float candX = b.X + localX * cosR - localZ * sinR; + float candZ = b.Z + localX * sinR + localZ * cosR; + if (MathF.Sqrt(candX * candX + candZ * candZ) > SpectatorRing.InitialRadius - 35f) + { + continue; + } + + float baseH = session.State.Terrain.SampleHeight(candX, candZ); + float relief = peakH - baseH; + if (relief > bestScore) + { + bestScore = relief; + targetBrush = b; + startX = candX; + startZ = candZ; + } + } + } + Assert.True(bestScore >= 10f, $"Expected a climbable {(testDune ? "dune" : "mesa")} approach inside safe circle in seed {seed}"); + + // Keep AI contenders on the opposite side of the safe zone so combat does not kill the vehicle mid-traversal + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(session.State.Contenders[i].Id, -targetBrush.X * 0.5f + (i - 6) * 14f, -targetBrush.Z * 0.5f); + } + + float yawToTarget = MathF.Atan2(targetBrush.X - startX, targetBrush.Z - startZ); + session.SetContenderPose(player.Id, startX, startZ, yawToTarget); + + if (chassis.Id != player.Grid.Spec.Id) + { + session.State.SpawnChassisDrop(player.X, player.Z, chassis); + Assert.True(session.TrySwapNearbyChassis(), $"Expected swap to {chassis.Id} to succeed"); + Assert.Equal(chassis.Id, player.Grid.Spec.Id); + } + + float startGroundY = session.State.Terrain.SampleHeight(player.X, player.Z); + float maxGroundY = startGroundY; + float minBottomRel = float.PositiveInfinity; + float maxAirGap = float.NegativeInfinity; + float minUpDot = float.PositiveInfinity; + + for (int tick = 0; tick < 600; tick++) + { + float steer = MathF.Sin(tick * 0.03f) * 0.15f; + session.Step(new PlayerInput( + Throttle: 1f, + Steer: steer, + AimWorldX: targetBrush.X, + AimWorldZ: targetBrush.Z, + Fire: false, + InteractPickup: false, + Brake: false)); + + Assert.False( + float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z), + $"NaN pose at tick {tick} (seed={seed}, chassis={chassis.Id}, dune={testDune})"); + + var body = session.GetContenderBody(player.Id); + Assert.True(body.HasValue, $"Expected live contender body at tick {tick} (seed={seed}, chassis={chassis.Id})"); + + int lane = body!.Value.Lane; + var view = session.World.View; + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var up = Vector3.Transform(Vector3.UnitY, q); + Assert.False(float.IsNaN(up.Y), $"NaN orientation at tick {tick}"); + + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + float bottomRel = (player.Y - player.Grid.Spec.HalfHeight) - gh; + + maxGroundY = MathF.Max(maxGroundY, gh); + minBottomRel = MathF.Min(minBottomRel, bottomRel); + maxAirGap = MathF.Max(maxAirGap, bottomRel); + minUpDot = MathF.Min(minUpDot, up.Y); + } + + float climbProgress = maxGroundY - startGroundY; + float minRequiredClimb = testDune ? 4.0f : 2.0f; + float minAllowedUpDot = chassis.IsWalker ? 0.927f : 0.50f; + // VTOLs spawn at 10m AGL and glide under gravity over mesa cliff drops instead of slamming downward + float maxAllowedAirGap = chassis.IsVtol ? targetBrush.HeightDelta + 15f : 5.0f; + + Assert.True(climbProgress >= minRequiredClimb, + $"Insufficient uphill climb progress (seed={seed}, chassis={chassis.Id}, dune={testDune}): climb={climbProgress:F2}m start=({startX:F1},{startZ:F1},h={startGroundY:F2}) end=({player.X:F1},{player.Z:F1},maxH={maxGroundY:F2}) brush=({targetBrush.X:F1},{targetBrush.Z:F1},rx={targetBrush.RadiusX:F1},rz={targetBrush.RadiusZ:F1},rot={targetBrush.RotationRad:F2},dh={targetBrush.HeightDelta:F1})"); + Assert.True(minBottomRel >= -0.35f, + $"Terrain tunneling detected (seed={seed}, chassis={chassis.Id}, dune={testDune}): minBottomRel={minBottomRel:F2}m"); + Assert.True(maxAirGap <= maxAllowedAirGap, + $"Excessive sky launch detected (seed={seed}, chassis={chassis.Id}, dune={testDune}): maxAirGap={maxAirGap:F2}m (max={maxAllowedAirGap:F1}m)"); + Assert.True(minUpDot >= minAllowedUpDot, + $"Excessive chassis tilt (seed={seed}, chassis={chassis.Id}, dune={testDune}): minUpDot={minUpDot:F3} (req>={minAllowedUpDot:F3})"); + } + } +} diff --git a/tests/RustToDust.Tests/VehiclePackageTests.cs b/tests/RustToDust.Tests/VehiclePackageTests.cs new file mode 100644 index 0000000..703d86a --- /dev/null +++ b/tests/RustToDust.Tests/VehiclePackageTests.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using RustToDust.Core; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class VehiclePackageTests + { + private static readonly string[] Expected15Ids = + { + "jackal", "mule", "ferret", "hornet", "mammoth", + "ironclad", "anvil", "condor", "breaker", "paladin", + "raptor", "manticore", "bastion", "spectre", "kestrel" + }; + + [Fact] + public void All15VehicleArchives_LoadFromCultCacheAndMatchManifests() + { + Assert.Equal(15, Catalog.AllChassis.Count); + Assert.Equal(15, Catalog.PackagesById.Count); + + string vehiclesRoot = VehicleCatalogLoader.LocateVehiclesDirectory(); + foreach (string id in Expected15Ids) + { + string ccPath = Path.Combine(vehiclesRoot, id, "vehicle.cc"); + string manifestPath = Path.Combine(vehiclesRoot, id, "manifest.json"); + Assert.True(File.Exists(ccPath), $"Missing vehicle.cc for {id}"); + Assert.True(File.Exists(manifestPath), $"Missing manifest.json for {id}"); + + VehiclePackage pkg = VehiclePackageStore.Read(ccPath); + Assert.Equal(id, pkg.Id); + Assert.True(File.Exists(Path.Combine(vehiclesRoot, id, pkg.ModelAsset)), $"Missing GLB {pkg.ModelAsset}"); + + using var doc = JsonDocument.Parse(File.ReadAllText(manifestPath)); + var root = doc.RootElement; + + Assert.Equal(root.GetProperty("gridWidth").GetInt32(), pkg.GridWidth); + Assert.Equal(root.GetProperty("gridHeight").GetInt32(), pkg.GridHeight); + + var manifestHps = root.GetProperty("hardpoints").EnumerateArray().ToArray(); + Assert.Equal(manifestHps.Length, pkg.Hardpoints.Count); + for (int i = 0; i < manifestHps.Length; i++) + { + string expectedId = manifestHps[i].GetProperty("id").GetString()!; + string expectedAnchor = manifestHps[i].GetProperty("modelNodeId").GetString()!; + Assert.Equal(expectedId, pkg.Hardpoints[i].Id); + Assert.Equal(expectedAnchor, pkg.Hardpoints[i].AnchorId); + } + + var manifestJoints = root.GetProperty("joints").EnumerateArray().ToArray(); + Assert.Equal(manifestJoints.Length, pkg.Joints.Count); + for (int i = 0; i < manifestJoints.Length; i++) + { + Assert.Equal(manifestJoints[i].GetProperty("id").GetString(), pkg.Joints[i].Id); + } + + var boundsSize = root.GetProperty("bounds").GetProperty("size").EnumerateArray().Select(e => e.GetSingle()).ToArray(); + Assert.Equal(boundsSize[0] * 0.5f, pkg.HalfWidth, precision: 3); + Assert.Equal(boundsSize[1] * 0.5f, pkg.HalfHeight, precision: 3); + Assert.Equal(boundsSize[2] * 0.5f, pkg.HalfLength, precision: 3); + + Assert.NotEmpty(pkg.PartCells); + var spec = pkg.ToChassisSpec(); + Assert.All(pkg.PartCells, pc => + { + Assert.False(string.IsNullOrWhiteSpace(pc.NodeName)); + Assert.True(spec.IsActive(pc.CellX, pc.CellY), $"{id}: PartCell '{pc.NodeName}' mapped to inactive ({pc.CellX},{pc.CellY})"); + }); + } + } + + [Fact] + public void BreakerArchive_RoundTripsFullMechanismHierarchy() + { + string vehiclesRoot = VehicleCatalogLoader.LocateVehiclesDirectory(); + string manifestPath = Path.Combine(vehiclesRoot, "breaker", "manifest.json"); + using var doc = JsonDocument.Parse(File.ReadAllText(manifestPath)); + var mechJson = doc.RootElement.GetProperty("mechanisms"); + + var breaker = Catalog.PackagesById["breaker"]; + Assert.NotNull(breaker.Mechanisms); + Assert.Equal(mechJson.GetProperty("dofs").GetArrayLength(), breaker.Mechanisms!.Dofs.Count); + Assert.Equal(35, breaker.Mechanisms.Dofs.Count); + Assert.Equal(mechJson.GetProperty("rams").GetArrayLength(), breaker.Mechanisms.Rams.Count); + Assert.Equal(4, breaker.Mechanisms.Rams.Count); + Assert.Equal(2, breaker.Mechanisms.Scissors.Count); + Assert.Equal(2, breaker.Mechanisms.Struts.Count); + + Assert.Equal("LegL.Hip", breaker.Mechanisms.Dofs[0].Name); + Assert.Equal( + new[] { "LegL.RecessRam0", "LegL.RecessRam1", "LegR.RecessRam0", "LegR.RecessRam1" }, + breaker.Mechanisms.Rams.Select(r => r.Name).ToArray()); + Assert.Equal("LegL.Torque", breaker.Mechanisms.Scissors[0].Name); + Assert.Equal("LegL.Oleo", breaker.Mechanisms.Struts[0].Name); + Assert.Equal(0.2f, breaker.Mechanisms.Struts[0].Travel, precision: 4); + } + + [Fact] + public void AliasesAndVtolBalance_MatchSpecification() + { + Assert.Same(Catalog.Jackal, Catalog.Buggy); + Assert.Same(Catalog.Mule, Catalog.Technical); + Assert.Same(Catalog.Anvil, Catalog.Tank); + + // VTOL glass-cannon balance vs ground equivalents + Assert.Equal(MobilityKind.Vtol, Catalog.Hornet.Mobility); + Assert.Equal(MobilityKind.Vtol, Catalog.Condor.Mobility); + Assert.Equal(42f, Catalog.Hornet.HoverMaxAltitudeM); + Assert.Equal(36f, Catalog.Condor.HoverMaxAltitudeM); + Assert.Equal(0f, Catalog.Jackal.HoverMaxAltitudeM); + Assert.Equal(0f, Catalog.Anvil.HoverMaxAltitudeM); + + Assert.True(Catalog.Hornet.BaseCellArmor < Catalog.Jackal.BaseCellArmor, + $"Hornet armor ({Catalog.Hornet.BaseCellArmor}) must be lighter than Jackal ({Catalog.Jackal.BaseCellArmor})"); + Assert.True(Catalog.Hornet.BaseCellArmor < Catalog.Ferret.BaseCellArmor, + $"Hornet armor ({Catalog.Hornet.BaseCellArmor}) must be lighter than Ferret ({Catalog.Ferret.BaseCellArmor})"); + Assert.True(Catalog.Condor.BaseCellArmor < Catalog.Ironclad.BaseCellArmor, + $"Condor armor ({Catalog.Condor.BaseCellArmor}) must be lighter than Ironclad ({Catalog.Ironclad.BaseCellArmor})"); + Assert.True(Catalog.Condor.BaseCellArmor < Catalog.Anvil.BaseCellArmor, + $"Condor armor ({Catalog.Condor.BaseCellArmor}) must be lighter than Anvil ({Catalog.Anvil.BaseCellArmor})"); + + // All 14 non-starter chassis spawn as salvageable drops in MatchState + var state = new MatchState(seed: 42); + var droppedChassisIds = state.GroundDrops + .Where(d => d.Chassis is not null) + .Select(d => d.Chassis!.Id) + .ToHashSet(StringComparer.Ordinal); + foreach (string id in Expected15Ids.Where(x => x != "jackal")) + { + Assert.Contains(id, droppedChassisIds); + } + } + } +} diff --git a/tests/RustToDust.Tests/VtolAndArcTests.cs b/tests/RustToDust.Tests/VtolAndArcTests.cs new file mode 100644 index 0000000..ee6d6ab --- /dev/null +++ b/tests/RustToDust.Tests/VtolAndArcTests.cs @@ -0,0 +1,503 @@ +using System; +using System.Linq; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class VtolAndArcTests + { + private static void IsolateContenders(ArenaSession session, params int[] keepIds) + { + var keep = keepIds.ToHashSet(); + for (int i = 0; i < session.State.Contenders.Count; i++) + { + var c = session.State.Contenders[i]; + if (!keep.Contains(c.Id)) + { + session.SetContenderPose(c.Id, -650f + i * 10f, -650f); + } + } + for (int i = 0; i < session.State.Spectators.Spectators.Count; i++) + { + var s = session.State.Spectators.Spectators[i]; + session.SetSpectatorPose(s.Id, 650f, -650f + i * 4f); + } + } + + [Fact] + public void Vtol_HornetAndCondor_ClimbHoverAndDescendViaVerticalThrottle() + { + foreach (var vtolSpec in new[] { Catalog.Hornet, Catalog.Condor }) + { + using var session = new ArenaSession(seed: 42); + IsolateContenders(session, 0); + var player = session.State.Player; + session.SetContenderPose(player.Id, 0f, 0f, 0f); + + session.State.SpawnChassisDrop(player.X, player.Z, vtolSpec); + Assert.True(session.TrySwapNearbyChassis()); + Assert.Equal(vtolSpec.Id, player.Grid.Spec.Id); + Assert.True(player.Grid.Spec.IsVtol); + + float gh0 = session.State.Terrain.SampleHeight(player.X, player.Z); + float initialAgl = player.Y - vtolSpec.HalfHeight - gh0; + + // Climb with VerticalThrottle = +1 for 2.5s (150 ticks) + for (int t = 0; t < 150; t++) + { + session.Step(new PlayerInput(0.4f, 0.1f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 1f)); + } + + float ghClimbed = session.State.Terrain.SampleHeight(player.X, player.Z); + float climbedAgl = player.Y - vtolSpec.HalfHeight - ghClimbed; + Assert.True(climbedAgl > initialAgl + 12f, + $"{vtolSpec.Id}: expected climb > 12m, got initial={initialAgl:F2}m -> climbed={climbedAgl:F2}m"); + Assert.True(climbedAgl <= vtolSpec.HoverMaxAltitudeM + 2.0f, + $"{vtolSpec.Id}: exceeded HoverMaxAltitudeM {vtolSpec.HoverMaxAltitudeM}m (got {climbedAgl:F2}m)"); + + // Hold hover with VerticalThrottle = 0 for 2.0s (120 ticks) -> settles to TargetHoverAltAgl and holds steady + for (int t = 0; t < 60; t++) + { + session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f)); + } + float ghSettled = session.State.Terrain.SampleHeight(player.X, player.Z); + float settledAgl = player.Y - vtolSpec.HalfHeight - ghSettled; + for (int t = 0; t < 60; t++) + { + session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f)); + } + float ghHeld = session.State.Terrain.SampleHeight(player.X, player.Z); + float heldAgl = player.Y - vtolSpec.HalfHeight - ghHeld; + Assert.InRange(heldAgl, player.TargetHoverAltAgl - 1.5f, player.TargetHoverAltAgl + 1.5f); + Assert.InRange(heldAgl, settledAgl - 1.0f, settledAgl + 1.0f); + + // Descend with VerticalThrottle = -1 for 3s (180 ticks) - should settle smoothly near 2.5m clearance + for (int t = 0; t < 180; t++) + { + session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: -1f)); + } + float ghDesc = session.State.Terrain.SampleHeight(player.X, player.Z); + float descAgl = player.Y - vtolSpec.HalfHeight - ghDesc; + Assert.True(descAgl < heldAgl - 8f, $"{vtolSpec.Id}: expected descent from {heldAgl:F2}m, got {descAgl:F2}m"); + Assert.InRange(descAgl, 1.5f, 4.5f); + } + } + + [Fact] + public void MwllTriangle_ZenithBlindSpot_MainCannonBlocked_WideArcPdAndDistantGroundRigHit() + { + using var session = new ArenaSession(seed: 42); + var player = session.State.Player; + var overheadVtol = session.State.Contenders[1]; + var distantGroundRig = session.State.Contenders[2]; + IsolateContenders(session, player.Id, overheadVtol.Id); + + // Swap player to Anvil (heavy tracked tank, weapons capped at +30 deg pitch) + session.SetContenderPose(player.Id, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil); + Assert.True(session.TrySwapNearbyChassis()); + Assert.Equal("anvil", player.Grid.Spec.Id); + + // Swap contender 1 to Hornet and position it high overhead (~14m horizontal, ~38m above player => ~+69 deg pitch!) + session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); + session.State.SpawnChassisDrop(0f, 14f, Catalog.Hornet); + Assert.True(session.State.TrySwapNearbyChassis(overheadVtol.Id)); + Assert.Equal("hornet", overheadVtol.Grid.Spec.Id); + overheadVtol.AiScavengeCooldown = 999f; + overheadVtol.TargetHoverAltAgl = 38f; + session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); + // Step once to seat bodies cleanly + session.Step(new PlayerInput(0f, 0f, overheadVtol.X, overheadVtol.Z, false, false, true, AimWorldY: overheadVtol.Y)); + + float vtolArmorBefore = overheadVtol.Grid.TotalArmorRatio(); + + // 1. Anvil's main cannons (-10..+30 deg) CANNOT fire at +69 deg overhead VTOL + for (int t = 0; t < 20; t++) + { + overheadVtol.TargetHoverAltAgl = 38f; + session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); + session.Step(new PlayerInput( + 0f, 0f, + overheadVtol.X, overheadVtol.Z, + Fire: true, + InteractPickup: false, + Brake: true, + AimWorldY: overheadVtol.Y)); + } + Assert.True(player.AllWeaponsOutOfArc, + $"Expected Anvil main cannons to report AllWeaponsOutOfArc (in={player.InArcWeaponCount}, out={player.OutOfArcWeaponCount}, pY={player.Y:F1}, vY={overheadVtol.Y:F1}, vSpec={overheadVtol.Grid.Spec.Id}, vAlt={overheadVtol.TargetHoverAltAgl:F1}, vAlive={overheadVtol.Alive}, vPos=({overheadVtol.X:F1},{overheadVtol.Z:F1}))"); + Assert.All(player.Grid.Mounted.Where(m => m.Spec.Kind == HardpointKind.Weapon), w => Assert.Equal(0f, w.Cooldown)); + Assert.Equal(vtolArmorBefore, overheadVtol.Grid.TotalArmorRatio()); + + // 2. Mount a 1x1 Wide-Arc PointDefenseFlak (-10..+85 deg) onto Anvil's hp.weapon.sponson_r -> CAN hit overhead VTOL! + Assert.True(player.Grid.TryMount(Catalog.PointDefenseFlak, "hp.weapon.sponson_r")); + int pdTracers = 0; + for (int t = 0; t < 25; t++) + { + overheadVtol.TargetHoverAltAgl = 38f; + session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f); + session.Step(new PlayerInput( + 0f, 0f, + overheadVtol.X, overheadVtol.Z, + Fire: true, + InteractPickup: false, + Brake: true, + AimWorldY: overheadVtol.Y)); + pdTracers += session.State.Tracers.Count; + } + Assert.False(player.AllWeaponsOutOfArc, "Expected Wide-Arc PD module to clear overhead out-of-arc block"); + Assert.True(pdTracers > 0, "Expected Wide-Arc PD to fire at overhead VTOL"); + Assert.True(overheadVtol.Grid.TotalArmorRatio() < vtolArmorBefore, + "Expected Wide-Arc PD burst to damage overhead VTOL"); + + // 3. Second ground rig (Anvil, MaxPitchDeg = 30 deg) placed 140m away (~+15 deg pitch) CAN hit the overhead VTOL! + session.SetContenderPose(distantGroundRig.Id, 0f, 154f, MathF.PI); + session.State.SpawnChassisDrop(0f, 154f, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(distantGroundRig.Id)); + session.SetContenderPose(distantGroundRig.Id, 0f, 154f, MathF.PI); + // Unmount player's PD so only distant rig shoots now + player.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_r"); + + float vtolArmorBeforeDistant = overheadVtol.Grid.TotalArmorRatio(); + for (int t = 0; t < 90; t++) + { + session.Step(new PlayerInput(0f, 0f, 0f, -20f, false, false, true)); + } + Assert.True(overheadVtol.Grid.TotalArmorRatio() < vtolArmorBeforeDistant, + "Expected distant ground rig 140m away (~15 deg pitch) to hit the hovering Hornet inside its 30 deg cannon arc"); + } + + [Fact] + public void GroundRigWithWideArcPd_AutoTracksNearbyAirborneVtolWithoutManualFire() + { + using var session = new ArenaSession(seed: 42); + var player = session.State.Player; + var overheadVtol = session.State.Contenders[1]; + IsolateContenders(session, player.Id, overheadVtol.Id); + + // Swap player to Jackal, mount Wide-Arc PD, leave Fire = false and aim elsewhere! + session.SetContenderPose(player.Id, 0f, 0f, 0f); + Assert.True(player.Grid.TryMount(Catalog.PointDefenseFlak, "hp.weapon.roof")); + + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + session.State.SpawnChassisDrop(20f, 25f, Catalog.Hornet); + Assert.True(session.State.TrySwapNearbyChassis(overheadVtol.Id)); + Assert.Equal("hornet", overheadVtol.Grid.Spec.Id); + overheadVtol.AiScavengeCooldown = 999f; + overheadVtol.TargetHoverAltAgl = 28f; + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + + float vtolArmorBefore = overheadVtol.Grid.TotalArmorRatio(); + bool sawAutoTracer = false; + for (int t = 0; t < 45; t++) + { + overheadVtol.TargetHoverAltAgl = 28f; + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + session.Step(new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: 0f, + AimWorldZ: -50f, + Fire: false, + InteractPickup: false, + Brake: true)); + if (session.State.Tracers.Count > 0) + { + sawAutoTracer = true; + } + } + + Assert.True(sawAutoTracer, "Expected auto-PD to fire tracers at airborne VTOL within 140m even while Fire=false"); + Assert.True(overheadVtol.Grid.TotalArmorRatio() < vtolArmorBefore, + $"Expected auto-PD tracking to hit airborne VTOL (before={vtolArmorBefore:F3}, after={overheadVtol.Grid.TotalArmorRatio():F3}, vY={overheadVtol.Y:F1}, vSpec={overheadVtol.Grid.Spec.Id}, tracers={session.State.Tracers.Count}, lastTracer={(session.State.Tracers.Count > 0 ? $"{session.State.Tracers[^1].EndX:F1},{session.State.Tracers[^1].EndY:F1},{session.State.Tracers[^1].EndZ:F1}" : "none")})"); + } + + [Fact] + public void QuickBolt_MountsScavengedModuleIntoEmptyMatchingHardpointBeforeCargo() + { + var state = new MatchState(seed: 42); + var player = state.Player; + + // Swap to Anvil (starter Jackal transfers 1 weapon into hp.weapon.sponson_l, leaving hp.weapon.siege_l, hp.weapon.siege_r, hp.weapon.sponson_r empty!) + state.SpawnChassisDrop(player.X, player.Z, Catalog.Anvil); + Assert.True(state.TrySwapNearbyChassis()); + Assert.Null(player.Grid.GetMountedOn("hp.weapon.siege_l")); + int cargoBefore = player.Grid.Cargo.Count; + + // Drop 1x1 PointDefenseFlak right at player and press [E] + state.SpawnModuleDrop(player.X + 0.5f, player.Z, Catalog.PointDefenseFlak); + MatchRules.ApplyPlayerInput(state, new PlayerInput( + 0f, 0f, player.X, player.Z + 10f, + Fire: false, + InteractPickup: true, + Brake: false)); + + // Must bolt straight onto empty hp.weapon.siege_l, NOT Cargo! + var mountedSiege = player.Grid.GetMountedOn("hp.weapon.siege_l"); + Assert.NotNull(mountedSiege); + Assert.Equal(Catalog.PointDefenseFlak.Id, mountedSiege!.Spec.Id); + Assert.Equal(cargoBefore, player.Grid.Cargo.Count); + Assert.Equal(BroadcastKind.QuickBolt, state.Broadcast.Latest?.Kind); + + // Now fill remaining weapon slots; next weapon pickup must fall back to Cargo! + Assert.True(player.Grid.TryMount(Catalog.Autocannon, "hp.weapon.siege_r")); + Assert.True(player.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_r")); + state.SpawnModuleDrop(player.X + 0.5f, player.Z, Catalog.Flak); + MatchRules.ApplyPlayerInput(state, new PlayerInput( + 0f, 0f, player.X, player.Z + 10f, + Fire: false, + InteractPickup: true, + Brake: false)); + + Assert.Equal(cargoBefore + 1, player.Grid.Cargo.Count); + Assert.Equal(Catalog.Flak.Id, player.Grid.Cargo[^1].Id); + } + + [Fact] + public void Vtol_ReverseIntoTallMesaAndCliffDrop_ZeroUndergroundTicks() + { + using var session = new ArenaSession(seed: 42); + var player = session.State.Player; + IsolateContenders(session, player.Id); + + // Pick the tallest Mesa in generated terrain + TerrainBrush tallMesa = default; + float bestHeight = -1f; + for (int i = 0; i < session.State.Terrain.Brushes.Count; i++) + { + var b = session.State.Terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta > bestHeight) + { + bestHeight = b.HeightDelta; + tallMesa = b; + } + } + Assert.True(bestHeight >= 22f, "Expected a tall Mesa in seed 42"); + + session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Hornet); + Assert.True(session.TrySwapNearbyChassis()); + Assert.Equal("hornet", player.Grid.Spec.Id); + + // 1. Reverse (-Z/+X away from yaw) straight into the tall Mesa cliff face + float startX = tallMesa.X - tallMesa.RadiusX - 24f; + session.SetContenderPose(player.Id, startX, tallMesa.Z, -MathF.PI * 0.5f); // facing -X so Throttle=-1 reverses into +X Mesa + player.TargetHoverAltAgl = 10f; + + float minReverseAgl = float.PositiveInfinity; + int undergroundReverseTicks = 0; + for (int t = 0; t < 240; t++) + { + session.Step(new PlayerInput(-1f, 0f, player.X - 30f, player.Z, false, false, false)); + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh; + if (agl < minReverseAgl) minReverseAgl = agl; + if (agl < 0f) undergroundReverseTicks++; + } + + Assert.Equal(0, undergroundReverseTicks); + Assert.True(minReverseAgl >= 0.5f, $"Reverse into +{bestHeight:F1}m mesa dipped too low: minAgl={minReverseAgl:F2}m"); + + // 2. Drive off the Mesa cliff edge onto the surrounding plain (must never slam underground) + session.SetContenderPose(player.Id, tallMesa.X + tallMesa.RadiusX * 0.15f, tallMesa.Z, MathF.PI * 0.5f); // facing +X off edge + player.TargetHoverAltAgl = 10f; + // Re-seat on plateau top + float plateauGh = session.State.Terrain.SampleHeight(player.X, player.Z); + session.SetContenderPose(player.Id, player.X, player.Z, MathF.PI * 0.5f); + Assert.True(plateauGh > 15f, $"Expected plateau height > 15m, got {plateauGh:F2}m"); + + float minDropAgl = float.PositiveInfinity; + int undergroundDropTicks = 0; + for (int t = 0; t < 240; t++) + { + session.Step(new PlayerInput(1f, 0f, player.X + 30f, player.Z, false, false, false)); + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh; + if (agl < minDropAgl) minDropAgl = agl; + if (agl < 0f) undergroundDropTicks++; + } + + Assert.Equal(0, undergroundDropTicks); + Assert.True(minDropAgl >= 0.5f, $"Cliff drop off +{bestHeight:F1}m mesa dipped too low: minAgl={minDropAgl:F2}m"); + } + + [Fact] + public void Vtol_OverheatedEngineToZeroPerf_LosesClimbAuthorityAndSinksTowardMinClearance() + { + using var session = new ArenaSession(seed: 42); + var player = session.State.Player; + IsolateContenders(session, player.Id); + + session.SetContenderPose(player.Id, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, Catalog.Hornet); + Assert.True(session.TrySwapNearbyChassis()); + + // Establish steady 20m hover + player.TargetHoverAltAgl = 20f; + session.SetContenderPose(player.Id, 0f, 0f, 0f); + for (int t = 0; t < 45; t++) + { + session.Step(new PlayerInput(0f, 0f, 0f, 30f, false, false, false)); + } + float hoverAglBefore = (player.Y - player.Grid.Spec.HalfHeight) - session.State.Terrain.SampleHeight(player.X, player.Z); + Assert.InRange(hoverAglBefore, 17.5f, 22.5f); + + // Overheat engine to Performance == 0.00 continuously during sink check + for (int t = 0; t < 150; t++) + { + player.Grid.InjectHardpointHeat("hp.engine.core", 15000f); + session.Step(new PlayerInput(0f, 0f, 0f, 30f, false, false, false, VerticalThrottle: 1f)); + } + + float hoverAglAfter = (player.Y - player.Grid.Spec.HalfHeight) - session.State.Terrain.SampleHeight(player.X, player.Z); + Assert.Equal(0f, player.Grid.ComputeEngineThermalPerformance(), precision: 2); + Assert.True(hoverAglAfter < hoverAglBefore - 5f, + $"Expected overheated VTOL (enginePerf=0.00) to sink from {hoverAglBefore:F2}m, got {hoverAglAfter:F2}m"); + Assert.True(hoverAglAfter >= 0.5f, $"Overheated sink went underground: {hoverAglAfter:F2}m"); + } + + [Fact] + public void StrippedZeroArmorHardpoint_DisablesManualFireAndAutoPointDefense() + { + // 1. Manual FireMountedWeapons disabled when hardpoint armor == 0 + using (var session = new ArenaSession(seed: 42)) + { + var player = session.State.Player; + var target = session.State.Contenders[1]; + IsolateContenders(session, player.Id, target.Id); + + session.SetContenderPose(player.Id, 0f, 0f, 0f); + session.SetContenderPose(target.Id, 0f, 30f, MathF.PI); + target.Grid.Mounted.RemoveAll(m => m.Spec.Kind == HardpointKind.Weapon); + float targetArmorBefore = target.Grid.TotalArmorRatio(); + + var roofHp = player.Grid.FindHardpoint("hp.weapon.roof"); + Assert.NotNull(roofHp); + Assert.True(player.Grid.IsHardpointOperational(roofHp!)); + + // Strip all armor cells under hp.weapon.roof to 0 + for (int dy = 0; dy < roofHp!.Height; dy++) + { + for (int dx = 0; dx < roofHp.Width; dx++) + { + player.Grid.Armor[roofHp.X + dx, roofHp.Y + dy] = 0f; + } + } + Assert.False(player.Grid.IsHardpointOperational(roofHp)); + + int tracersFired = 0; + for (int t = 0; t < 20; t++) + { + session.Step(new PlayerInput(0f, 0f, target.X, target.Z, Fire: true, InteractPickup: false, Brake: true, AimWorldY: target.Y)); + tracersFired += session.State.Tracers.Count(tr => + MathF.Abs(tr.StartX - player.X) < 10f && MathF.Abs(tr.StartZ - player.Z) < 10f); + } + + Assert.Equal(0, tracersFired); + Assert.Equal(targetArmorBefore, target.Grid.TotalArmorRatio()); + Assert.True(player.DisabledWeaponCount > 0); + Assert.All(player.Grid.Mounted.Where(m => m.Spec.Kind == HardpointKind.Weapon), w => Assert.Equal(0f, w.Cooldown)); + } + + // 2. Auto-PD TryAutoPointDefenseFire disabled when PD hardpoint armor == 0 + using (var session = new ArenaSession(seed: 42)) + { + var player = session.State.Player; + var overheadVtol = session.State.Contenders[1]; + IsolateContenders(session, player.Id, overheadVtol.Id); + + session.SetContenderPose(player.Id, 0f, 0f, 0f); + Assert.True(player.Grid.TryMount(Catalog.PointDefenseFlak, "hp.weapon.roof")); + var roofHp = player.Grid.FindHardpoint("hp.weapon.roof")!; + for (int dy = 0; dy < roofHp.Height; dy++) + { + for (int dx = 0; dx < roofHp.Width; dx++) + { + player.Grid.Armor[roofHp.X + dx, roofHp.Y + dy] = 0f; + } + } + Assert.False(player.Grid.IsHardpointOperational(roofHp)); + + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + session.State.SpawnChassisDrop(20f, 25f, Catalog.Hornet); + Assert.True(session.State.TrySwapNearbyChassis(overheadVtol.Id)); + overheadVtol.Grid.Mounted.RemoveAll(m => m.Spec.Kind == HardpointKind.Weapon); + overheadVtol.AiScavengeCooldown = 999f; + overheadVtol.TargetHoverAltAgl = 28f; + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + + float vtolArmorBefore = overheadVtol.Grid.TotalArmorRatio(); + int pdTracers = 0; + for (int t = 0; t < 45; t++) + { + overheadVtol.TargetHoverAltAgl = 28f; + session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f); + session.Step(new PlayerInput(0f, 0f, 0f, -50f, Fire: false, InteractPickup: false, Brake: true)); + pdTracers += session.State.Tracers.Count(tr => + MathF.Abs(tr.StartX - player.X) < 10f && MathF.Abs(tr.StartZ - player.Z) < 10f); + } + + Assert.Equal(0, pdTracers); + Assert.Equal(vtolArmorBefore, overheadVtol.Grid.TotalArmorRatio()); + } + } + + [Fact] + public void SwapChassis_VtolToGroundToVtol_ResetsTargetHoverAltAgl() + { + using var session = new ArenaSession(seed: 42); + var player = session.State.Player; + IsolateContenders(session, player.Id); + + session.SetContenderPose(player.Id, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, Catalog.Hornet); + Assert.True(session.TrySwapNearbyChassis()); + Assert.Equal(10f, player.TargetHoverAltAgl); + + player.TargetHoverAltAgl = 42f; + player.VerticalThrottleCmd = 1f; + + // Swap to ground rig + session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Jackal); + Assert.True(session.TrySwapNearbyChassis()); + Assert.Equal(3.0f, player.TargetHoverAltAgl); + Assert.Equal(0f, player.VerticalThrottleCmd); + + // Swap back to VTOL -> must spawn cleanly at 10m hover, NOT stale 42m + session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Condor); + Assert.True(session.TrySwapNearbyChassis()); + Assert.Equal(10.0f, player.TargetHoverAltAgl); + Assert.Equal(0f, player.VerticalThrottleCmd); + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh; + Assert.InRange(agl, 9.5f, 10.5f); + } + + [Fact] + public void InteractPickup_UsesUnifiedNearestDropPriority_ChassisCloserThanModule() + { + var state = new MatchState(seed: 42); + var player = state.Player; + + // Remove pre-scattered drops near player to keep test deterministic + state.GroundDrops.Clear(); + + var modDrop = state.SpawnModuleDrop(player.X + 3.0f, player.Z, Catalog.Flak); + var chassisDrop = state.SpawnChassisDrop(player.X + 0.5f, player.Z, Catalog.Anvil); + + var nearest = state.FindNearestInteractableDrop(0); + Assert.Same(chassisDrop, nearest); + + MatchRules.ApplyPlayerInput(state, new PlayerInput( + 0f, 0f, player.X, player.Z + 10f, + Fire: false, + InteractPickup: true, + Brake: false)); + + Assert.Equal(Catalog.Anvil.Id, player.Grid.Spec.Id); + Assert.True(chassisDrop.PickedUp); + Assert.False(modDrop.PickedUp); + } + } +} diff --git a/tools/VehiclePacker/Program.cs b/tools/VehiclePacker/Program.cs new file mode 100644 index 0000000..7e0d6af --- /dev/null +++ b/tools/VehiclePacker/Program.cs @@ -0,0 +1,924 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Numerics; +using System.Text; +using System.Text.Json; +using RustToDust.Core; + +namespace VehiclePacker +{ + internal sealed record HardpointTune( + float ArmorBonus, + float MinPitchDeg = -15f, + float MaxPitchDeg = 45f, + bool IsWideArc = false); + + internal sealed record VehicleTuning( + MobilityKind Mobility, + float MassKg, + float MaxSpeed, + float TurnRate, + float ThrustNewtons, + float HoverMaxAltitudeM, + float ArmorPerCell, + float Conductivity, + float BaseCellThermalMass, + int CargoCapacity, + Dictionary DefaultLoadout, + Dictionary HardpointTuning); + + internal static class Program + { + private static readonly Dictionary Tunings = BuildTunings(); + + private static int Main(string[] args) + { + string vehiclesRoot = args.Length > 0 + ? Path.GetFullPath(args[0]) + : LocateDefaultVehiclesRoot(); + + if (!Directory.Exists(vehiclesRoot)) + { + Console.Error.WriteLine($"Vehicles directory not found: {vehiclesRoot}"); + return 1; + } + + int packedCount = 0; + foreach (string dir in Directory.GetDirectories(vehiclesRoot).OrderBy(d => d, StringComparer.Ordinal)) + { + string id = Path.GetFileName(dir); + string manifestPath = Path.Combine(dir, "manifest.json"); + string glbPath = Path.Combine(dir, $"{id}.glb"); + if (!File.Exists(manifestPath) || !File.Exists(glbPath)) + { + continue; + } + + if (!Tunings.TryGetValue(id, out var tuning)) + { + Console.Error.WriteLine($"Missing gameplay tuning entry for vehicle '{id}'."); + return 2; + } + + var pkg = BuildPackage(id, manifestPath, glbPath, tuning); + string outPath = Path.Combine(dir, "vehicle.cc"); + VehiclePackageStore.Write(outPath, pkg); + var roundTrip = VehiclePackageStore.Read(outPath); + + Console.WriteLine( + $"Packed {roundTrip.Id,-10} | {roundTrip.Mobility,-7} | {roundTrip.Plane,-7} | " + + $"{roundTrip.GridWidth}x{roundTrip.GridHeight} | arm={roundTrip.ArmorPerCell,2:F0} | " + + $"hps={roundTrip.Hardpoints.Count} | joints={roundTrip.Joints.Count,2} | " + + $"partCells={roundTrip.PartCells.Count,3} | {new FileInfo(outPath).Length / 1024.0:F1} KiB"); + packedCount++; + } + + Console.WriteLine($"Done: packed {packedCount} vehicle.cc archives."); + return packedCount == 15 ? 0 : 3; + } + + private static string LocateDefaultVehiclesRoot() + { + foreach (string start in new[] { Directory.GetCurrentDirectory(), AppContext.BaseDirectory }) + { + var dir = new DirectoryInfo(Path.GetFullPath(start)); + while (dir is not null) + { + string candidate = Path.Combine(dir.FullName, "assets", "vehicles"); + if (Directory.Exists(candidate)) + { + return candidate; + } + dir = dir.Parent; + } + } + throw new DirectoryNotFoundException("Could not locate assets/vehicles directory."); + } + + private static VehiclePackage BuildPackage(string id, string manifestPath, string glbPath, VehicleTuning tuning) + { + using var manifestDoc = JsonDocument.Parse(File.ReadAllText(manifestPath, Encoding.UTF8)); + var root = manifestDoc.RootElement; + + string manifestId = root.GetProperty("id").GetString()!; + if (!string.Equals(manifestId, id, StringComparison.Ordinal)) + { + throw new InvalidOperationException($"{manifestPath}: id '{manifestId}' != directory '{id}'."); + } + + string name = root.GetProperty("name").GetString()!; + string vClass = root.GetProperty("class").GetString()!; + var plane = Enum.Parse(root.GetProperty("plane").GetString()!, ignoreCase: true); + int gw = root.GetProperty("gridWidth").GetInt32(); + int gh = root.GetProperty("gridHeight").GetInt32(); + + var maskBools = root.GetProperty("mask").EnumerateArray().Select(e => e.GetBoolean()).ToArray(); + if (maskBools.Length != gw * gh) + { + throw new InvalidOperationException($"{id}: mask length {maskBools.Length} != {gw * gh}."); + } + + var maskRows = new string[gh]; + for (int y = 0; y < gh; y++) + { + var sb = new StringBuilder(gw); + for (int x = 0; x < gw; x++) + { + sb.Append(maskBools[y * gw + x] ? '#' : '.'); + } + maskRows[y] = sb.ToString(); + } + + var boundsSize = root.GetProperty("bounds").GetProperty("size").EnumerateArray().Select(e => e.GetSingle()).ToArray(); + var boundsMin = root.GetProperty("bounds").GetProperty("min").EnumerateArray().Select(e => e.GetSingle()).ToArray(); + var boundsMax = root.GetProperty("bounds").GetProperty("max").EnumerateArray().Select(e => e.GetSingle()).ToArray(); + + var (gltfJsonBytes, binBlob) = ReadGlbChunks(glbPath); + using var gltfDoc = JsonDocument.Parse(gltfJsonBytes); + var gltf = gltfDoc.RootElement; + + var hardpoints = ParseHardpoints(id, root.GetProperty("hardpoints"), gltf, tuning); + var joints = ParseJoints(id, root.GetProperty("joints"), gltf); + var mechanisms = root.TryGetProperty("mechanisms", out var mechElem) && mechElem.ValueKind == JsonValueKind.Object + ? ParseMechanisms(mechElem) + : null; + var partCells = ComputePartCells(gltf, binBlob, plane, gw, gh, maskBools, boundsMin, boundsMax); + + return new VehiclePackage + { + Id = id, + Name = name, + VehicleClass = vClass, + Mobility = tuning.Mobility, + Plane = plane, + GridWidth = gw, + GridHeight = gh, + Mask = maskRows, + MassKg = tuning.MassKg, + MaxSpeed = tuning.MaxSpeed, + TurnRate = tuning.TurnRate, + ThrustNewtons = tuning.ThrustNewtons, + HoverMaxAltitudeM = tuning.HoverMaxAltitudeM, + ArmorPerCell = tuning.ArmorPerCell, + Conductivity = tuning.Conductivity, + BaseCellThermalMass = tuning.BaseCellThermalMass, + CargoCapacity = tuning.CargoCapacity, + HalfWidth = boundsSize[0] * 0.5f, + HalfHeight = boundsSize[1] * 0.5f, + HalfLength = boundsSize[2] * 0.5f, + ModelAsset = $"{id}.glb", + DefaultLoadout = new Dictionary(tuning.DefaultLoadout, StringComparer.Ordinal), + Hardpoints = hardpoints, + Joints = joints, + Mechanisms = mechanisms, + PartCells = partCells + }; + } + + private static List ParseHardpoints( + string vehicleId, + JsonElement hpsElem, + JsonElement gltf, + VehicleTuning tuning) + { + var rtdAnchors = new HashSet(StringComparer.Ordinal); + if (gltf.TryGetProperty("nodes", out var nodes)) + { + foreach (var n in nodes.EnumerateArray()) + { + if (n.TryGetProperty("extras", out var ex) && + ex.TryGetProperty("rtd.id", out var rtdId) && + rtdId.ValueKind == JsonValueKind.String) + { + rtdAnchors.Add(rtdId.GetString()!); + } + } + } + + var list = new List(); + foreach (var hp in hpsElem.EnumerateArray()) + { + string hpId = hp.GetProperty("id").GetString()!; + string modelNodeId = hp.GetProperty("modelNodeId").GetString()!; + if (!rtdAnchors.Contains(modelNodeId)) + { + throw new InvalidOperationException($"{vehicleId}: GLB missing extras[\"rtd.id\"] == '{modelNodeId}'."); + } + + var kind = Enum.Parse(hp.GetProperty("kind").GetString()!, ignoreCase: true); + int x = hp.GetProperty("x").GetInt32(); + int y = hp.GetProperty("y").GetInt32(); + int w = hp.GetProperty("w").GetInt32(); + int h = hp.GetProperty("h").GetInt32(); + + HardpointTune tune = tuning.HardpointTuning.TryGetValue(hpId, out var found) + ? found + : new HardpointTune(ArmorBonus: kind == HardpointKind.Armor ? 14f : (kind == HardpointKind.Engine ? 8f : 6f)); + + list.Add(new VehicleHardpointRecord + { + Id = hpId, + AnchorId = modelNodeId, + Kind = kind, + X = x, + Y = y, + W = w, + H = h, + MinPitchDeg = tune.MinPitchDeg, + MaxPitchDeg = tune.MaxPitchDeg, + IsWideArc = tune.IsWideArc, + ArmorBonus = tune.ArmorBonus + }); + } + return list; + } + + private static List ParseJoints(string vehicleId, JsonElement jointsElem, JsonElement gltf) + { + var nodeByJointId = new Dictionary(StringComparer.Ordinal); + if (gltf.TryGetProperty("nodes", out var nodes)) + { + foreach (var n in nodes.EnumerateArray()) + { + if (n.TryGetProperty("extras", out var ex) && + ex.TryGetProperty("rtd.joint", out var rtdJoint) && + rtdJoint.ValueKind == JsonValueKind.String) + { + string jid = rtdJoint.GetString()!; + string nodeName = n.TryGetProperty("name", out var nm) ? nm.GetString() ?? jid : jid; + nodeByJointId[jid] = nodeName; + } + } + } + + var list = new List(); + foreach (var j in jointsElem.EnumerateArray()) + { + string jid = j.GetProperty("id").GetString()!; + if (!nodeByJointId.TryGetValue(jid, out var nodeName)) + { + throw new InvalidOperationException($"{vehicleId}: GLB missing extras[\"rtd.joint\"] == '{jid}'."); + } + + list.Add(new VehicleJointRecord + { + Id = jid, + NodeName = nodeName, + Axis = j.GetProperty("axis").EnumerateArray().Select(e => e.GetSingle()).ToArray(), + MinVal = j.GetProperty("min").GetSingle(), + MaxVal = j.GetProperty("max").GetSingle() + }); + } + return list; + } + + private static VehicleMechanismsRecord ParseMechanisms(JsonElement mechElem) + { + var rec = new VehicleMechanismsRecord + { + Frame = mechElem.GetProperty("frame").GetString() ?? string.Empty, + RootOrigin = mechElem.GetProperty("rootOrigin").EnumerateArray().Select(e => e.GetSingle()).ToArray() + }; + + if (mechElem.TryGetProperty("dofs", out var dofsElem)) + { + foreach (var d in dofsElem.EnumerateArray()) + { + float? damp = null; + float? hz = null; + if (d.TryGetProperty("compliance", out var comp) && comp.ValueKind == JsonValueKind.Object) + { + if (comp.TryGetProperty("damping_ratio", out var dr)) damp = dr.GetSingle(); + if (comp.TryGetProperty("hertz", out var h)) hz = h.GetSingle(); + } + rec.Dofs.Add(new MechanismDofRecord + { + Name = d.GetProperty("name").GetString()!, + Parent = d.GetProperty("parent").GetInt32(), + Kind = d.GetProperty("kind").GetString()!, + Mechanism = d.TryGetProperty("mechanism", out var m) && m.ValueKind == JsonValueKind.String ? m.GetString() : null, + Side = d.TryGetProperty("side", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null, + Origin = d.GetProperty("origin").EnumerateArray().Select(e => e.GetSingle()).ToArray(), + Axis = d.GetProperty("axis").EnumerateArray().Select(e => e.GetSingle()).ToArray(), + Lo = d.GetProperty("lo").GetSingle(), + Hi = d.GetProperty("hi").GetSingle(), + Depth = d.GetProperty("depth").GetInt32(), + StoppedBy = d.TryGetProperty("stopped_by", out var sb) && sb.ValueKind == JsonValueKind.String ? sb.GetString() : null, + ComplianceDampingRatio = damp, + ComplianceHertz = hz + }); + } + } + + if (mechElem.TryGetProperty("rams", out var ramsElem)) + { + foreach (var r in ramsElem.EnumerateArray()) + { + rec.Rams.Add(new MechanismRamRecord + { + Name = r.GetProperty("name").GetString()!, + BarrelBone = r.GetProperty("barrel_bone").GetString()!, + RodBone = r.GetProperty("rod_bone").GetString()!, + Spans = r.TryGetProperty("spans", out var sp) ? sp.EnumerateArray().Select(e => e.GetString()!).ToArray() : Array.Empty(), + Bore = r.TryGetProperty("bore", out var br) && br.ValueKind == JsonValueKind.Number ? br.GetSingle() : 0f, + Body = r.TryGetProperty("body", out var bd) && bd.ValueKind == JsonValueKind.Number ? bd.GetSingle() : 0f, + Inner = r.TryGetProperty("inner", out var inn) && inn.ValueKind == JsonValueKind.Number ? inn.GetSingle() : 0f, + Extension = r.TryGetProperty("extension", out var ext) && ext.ValueKind == JsonValueKind.Number ? ext.GetSingle() : 0f, + Rest = r.TryGetProperty("rest", out var rst) && rst.ValueKind == JsonValueKind.Number ? rst.GetSingle() : 0f, + Stroke = r.TryGetProperty("stroke", out var st) && st.ValueKind == JsonValueKind.Array ? st.EnumerateArray().Select(e => e.GetSingle()).ToArray() : Array.Empty(), + AParentDof = r.TryGetProperty("a_parent_dof", out var apd) && apd.ValueKind == JsonValueKind.Number ? apd.GetInt32() : null, + APos = r.TryGetProperty("a_pos", out var ap) && ap.ValueKind == JsonValueKind.Array ? ap.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, + BParentDof = r.TryGetProperty("b_parent_dof", out var bpd) && bpd.ValueKind == JsonValueKind.Number ? bpd.GetInt32() : null, + BPos = r.TryGetProperty("b_pos", out var bp) && bp.ValueKind == JsonValueKind.Array ? bp.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, + PinDir = r.TryGetProperty("pin_dir", out var pd) && pd.ValueKind == JsonValueKind.Array ? pd.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null + }); + } + } + + if (mechElem.TryGetProperty("scissors", out var scissorsElem)) + { + foreach (var sc in scissorsElem.EnumerateArray()) + { + rec.Scissors.Add(new MechanismScissorRecord + { + Name = sc.GetProperty("name").GetString()!, + UpperBone = sc.GetProperty("upper_bone").GetString()!, + LowerBone = sc.GetProperty("lower_bone").GetString()!, + Arm = sc.TryGetProperty("arm", out var arm) && arm.ValueKind == JsonValueKind.Number ? arm.GetSingle() : 0f, + AParentDof = sc.TryGetProperty("a_parent_dof", out var apd) && apd.ValueKind == JsonValueKind.Number ? apd.GetInt32() : null, + APos = sc.TryGetProperty("a_pos", out var ap) && ap.ValueKind == JsonValueKind.Array ? ap.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, + BParentDof = sc.TryGetProperty("b_parent_dof", out var bpd) && bpd.ValueKind == JsonValueKind.Number ? bpd.GetInt32() : null, + BPos = sc.TryGetProperty("b_pos", out var bp) && bp.ValueKind == JsonValueKind.Array ? bp.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, + OutDir = sc.TryGetProperty("out_dir", out var od) && od.ValueKind == JsonValueKind.Array ? od.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null + }); + } + } + + if (mechElem.TryGetProperty("struts", out var strutsElem)) + { + foreach (var st in strutsElem.EnumerateArray()) + { + rec.Struts.Add(new MechanismStrutRecord + { + Name = st.GetProperty("name").GetString()!, + Side = st.TryGetProperty("side", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null, + Dof = st.GetProperty("dof").GetString()!, + Travel = st.GetProperty("travel").GetSingle(), + Hertz = st.GetProperty("hertz").GetSingle(), + DampingRatio = st.GetProperty("damping_ratio").GetSingle() + }); + } + } + + return rec; + } + + private static (byte[] JsonBytes, byte[] BinBytes) ReadGlbChunks(string glbPath) + { + byte[] data = File.ReadAllBytes(glbPath); + if (data.Length < 20) throw new InvalidDataException($"{glbPath}: GLB too small."); + + uint magic = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(0, 4)); + uint version = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4, 4)); + if (magic != 0x46546C67 || version != 2) + throw new InvalidDataException($"{glbPath}: invalid GLB header."); + + uint jsonLen = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12, 4)); + uint jsonType = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16, 4)); + if (jsonType != 0x4E4F534A) + throw new InvalidDataException($"{glbPath}: first chunk is not JSON."); + + byte[] jsonBytes = data.AsSpan(20, (int)jsonLen).ToArray(); + byte[] binBytes = Array.Empty(); + int binOff = 20 + (int)jsonLen; + if (binOff + 8 <= data.Length) + { + uint binLen = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(binOff, 4)); + uint binType = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(binOff + 4, 4)); + if (binType == 0x004E4942) + { + binBytes = data.AsSpan(binOff + 8, (int)binLen).ToArray(); + } + } + return (jsonBytes, binBytes); + } + + private static List ComputePartCells( + JsonElement gltf, + byte[] binBlob, + GridPlane plane, + int gw, + int gh, + bool[] mask, + float[] boundsMin, + float[] boundsMax) + { + var nodes = gltf.GetProperty("nodes").EnumerateArray().ToArray(); + var meshes = gltf.GetProperty("meshes").EnumerateArray().ToArray(); + var accessors = gltf.GetProperty("accessors").EnumerateArray().ToArray(); + var bufferViews = gltf.GetProperty("bufferViews").EnumerateArray().ToArray(); + + var parentOf = new Dictionary(); + for (int i = 0; i < nodes.Length; i++) + { + if (nodes[i].TryGetProperty("children", out var ch)) + { + foreach (var c in ch.EnumerateArray()) + { + parentOf[c.GetInt32()] = i; + } + } + } + + // Exclude hardpoint slot_frame.* subtrees and rtd.id anchor subtrees + var hpNodeSet = new HashSet(); + void MarkSubtree(int idx) + { + if (!hpNodeSet.Add(idx)) return; + if (nodes[idx].TryGetProperty("children", out var ch)) + { + foreach (var c in ch.EnumerateArray()) + { + MarkSubtree(c.GetInt32()); + } + } + } + + for (int i = 0; i < nodes.Length; i++) + { + string nodeName = nodes[i].TryGetProperty("name", out var nm) ? nm.GetString() ?? "" : ""; + bool isSlotFrame = nodeName.StartsWith("slot_frame.", StringComparison.Ordinal); + bool hasRtdId = nodes[i].TryGetProperty("extras", out var ex) && ex.TryGetProperty("rtd.id", out _); + if (isSlotFrame || hasRtdId) + { + if (parentOf.TryGetValue(i, out int p) && + nodes[p].TryGetProperty("name", out var pnm) && + (pnm.GetString() ?? "").StartsWith("slot_frame.", StringComparison.Ordinal)) + { + MarkSubtree(p); + } + else + { + MarkSubtree(i); + } + } + } + + var rootIndices = new List(); + if (gltf.TryGetProperty("scenes", out var scenes) && scenes.GetArrayLength() > 0) + { + int sceneIdx = gltf.TryGetProperty("scene", out var si) ? si.GetInt32() : 0; + foreach (var r in scenes[sceneIdx].GetProperty("nodes").EnumerateArray()) + { + rootIndices.Add(r.GetInt32()); + } + } + else + { + for (int i = 0; i < nodes.Length; i++) + { + if (!parentOf.ContainsKey(i)) rootIndices.Add(i); + } + } + + float spanX = MathF.Max(1e-4f, boundsMax[0] - boundsMin[0]); + float spanY = MathF.Max(1e-4f, boundsMax[1] - boundsMin[1]); + float spanZ = MathF.Max(1e-4f, boundsMax[2] - boundsMin[2]); + + var results = new List(); + var visited = new HashSet(); + + void Walk(int nodeIdx, Matrix4x4 parentWorld) + { + if (!visited.Add(nodeIdx)) return; + var node = nodes[nodeIdx]; + Matrix4x4 local = ReadNodeLocalMatrix(node); + // Column-vector math: world = parentWorld * local; System.Numerics uses row-vectors for Transform, so multiply in reverse order + Matrix4x4 world = local * parentWorld; + + if (!hpNodeSet.Contains(nodeIdx) && node.TryGetProperty("mesh", out var meshProp)) + { + int meshIdx = meshProp.GetInt32(); + Vector3 centroid = ComputeMeshWorldCentroid(meshes[meshIdx], accessors, bufferViews, binBlob, world); + + // +X is vehicle LEFT (cell x=0), -X is vehicle RIGHT (cell x=gw-1) + float ux = Math.Clamp((boundsMax[0] - centroid.X) / spanX, 0f, 1f); + // Dorsal: +Z is FRONT (cell y=0), -Z is REAR (cell y=gh-1) + // Coronal: +Y is TOP (cell y=0), minY is FEET (cell y=gh-1) + float uy = plane == GridPlane.Dorsal + ? Math.Clamp((boundsMax[2] - centroid.Z) / spanZ, 0f, 1f) + : Math.Clamp((boundsMax[1] - centroid.Y) / spanY, 0f, 1f); + + float targetX = ux * (gw - 1); + float targetY = uy * (gh - 1); + (int cellX, int cellY) = FindNearestActiveCell(targetX, targetY, gw, gh, mask); + + string nodeName = node.TryGetProperty("name", out var nm) ? nm.GetString() ?? $"node_{nodeIdx}" : $"node_{nodeIdx}"; + string partKind = ClassifyPartKind(nodeName); + + results.Add(new VehiclePartCellRecord + { + NodeName = nodeName, + CellX = cellX, + CellY = cellY, + Kind = partKind + }); + } + + if (node.TryGetProperty("children", out var ch)) + { + foreach (var c in ch.EnumerateArray()) + { + Walk(c.GetInt32(), world); + } + } + } + + foreach (int r in rootIndices) + { + Walk(r, Matrix4x4.Identity); + } + + return results; + } + + private static Matrix4x4 ReadNodeLocalMatrix(JsonElement node) + { + if (node.TryGetProperty("matrix", out var mElem)) + { + float[] m = mElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + // glTF stores column-major 4x4; System.Numerics Matrix4x4 fields M11..M44 match row-major so transpose on construction + return new Matrix4x4( + m[0], m[1], m[2], m[3], + m[4], m[5], m[6], m[7], + m[8], m[9], m[10], m[11], + m[12], m[13], m[14], m[15]); + } + + Vector3 scale = Vector3.One; + if (node.TryGetProperty("scale", out var sElem)) + { + float[] s = sElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + scale = new Vector3(s[0], s[1], s[2]); + } + + Quaternion rot = Quaternion.Identity; + if (node.TryGetProperty("rotation", out var rElem)) + { + float[] r = rElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + rot = new Quaternion(r[0], r[1], r[2], r[3]); + } + + Vector3 trans = Vector3.Zero; + if (node.TryGetProperty("translation", out var tElem)) + { + float[] t = tElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + trans = new Vector3(t[0], t[1], t[2]); + } + + return Matrix4x4.CreateScale(scale) * Matrix4x4.CreateFromQuaternion(rot) * Matrix4x4.CreateTranslation(trans); + } + + private static Vector3 ComputeMeshWorldCentroid( + JsonElement mesh, + JsonElement[] accessors, + JsonElement[] bufferViews, + byte[] binBlob, + Matrix4x4 world) + { + Vector3 sum = Vector3.Zero; + long count = 0; + + foreach (var prim in mesh.GetProperty("primitives").EnumerateArray()) + { + if (!prim.TryGetProperty("attributes", out var attrs) || + !attrs.TryGetProperty("POSITION", out var posIdxElem)) + { + continue; + } + + var acc = accessors[posIdxElem.GetInt32()]; + int accCount = acc.GetProperty("count").GetInt32(); + int compType = acc.GetProperty("componentType").GetInt32(); + string accType = acc.GetProperty("type").GetString() ?? ""; + + if (binBlob.Length > 0 && + acc.TryGetProperty("bufferView", out var bvIdxElem) && + compType == 5126 && + accType == "VEC3") + { + var bv = bufferViews[bvIdxElem.GetInt32()]; + int bvOff = bv.TryGetProperty("byteOffset", out var bo) ? bo.GetInt32() : 0; + int accOff = acc.TryGetProperty("byteOffset", out var ao) ? ao.GetInt32() : 0; + int stride = bv.TryGetProperty("byteStride", out var bs) ? bs.GetInt32() : 12; + int offset = bvOff + accOff; + + for (int i = 0; i < accCount; i++) + { + int p = offset + i * stride; + float x = BinaryPrimitives.ReadSingleLittleEndian(binBlob.AsSpan(p, 4)); + float y = BinaryPrimitives.ReadSingleLittleEndian(binBlob.AsSpan(p + 4, 4)); + float z = BinaryPrimitives.ReadSingleLittleEndian(binBlob.AsSpan(p + 8, 4)); + sum += Vector3.Transform(new Vector3(x, y, z), world); + count++; + } + } + else if (acc.TryGetProperty("min", out var minElem) && acc.TryGetProperty("max", out var maxElem)) + { + float[] mn = minElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + float[] mx = maxElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); + var mid = new Vector3((mn[0] + mx[0]) * 0.5f, (mn[1] + mx[1]) * 0.5f, (mn[2] + mx[2]) * 0.5f); + sum += Vector3.Transform(mid, world); + count++; + } + } + + return count > 0 ? sum / count : world.Translation; + } + + private static (int X, int Y) FindNearestActiveCell(float targetX, float targetY, int gw, int gh, bool[] mask) + { + int bestX = 0; + int bestY = 0; + float bestDistSq = float.PositiveInfinity; + for (int y = 0; y < gh; y++) + { + for (int x = 0; x < gw; x++) + { + if (!mask[y * gw + x]) continue; + float dx = x - targetX; + float dy = y - targetY; + float d2 = dx * dx + dy * dy; + if (d2 < bestDistSq) + { + bestDistSq = d2; + bestX = x; + bestY = y; + } + } + } + return (bestX, bestY); + } + + private static string ClassifyPartKind(string nodeName) + { + string lower = nodeName.ToLowerInvariant(); + if (lower.StartsWith("shroud.", StringComparison.Ordinal) || lower.Contains("shroud")) + return "shroud"; + if (lower.Contains("armor") || lower.Contains("plate") || lower.Contains("glacis") || + lower.Contains("skirt") || lower.Contains("shield") || lower.Contains("fender") || + lower.Contains("bullbar") || lower.Contains("bumper") || lower.Contains("collar") || + lower.Contains("cheek") || lower.Contains("cowling") || lower.Contains("greave")) + return "armor"; + if (lower.Contains("wheel") || lower.Contains("tire") || lower.Contains("track") || + lower.Contains("rotor") || lower.Contains("blade") || lower.Contains("spinner") || + lower.Contains("nacelle")) + return "mobility"; + return "hull"; + } + + private static Dictionary BuildTunings() + { + return new Dictionary(StringComparer.Ordinal) + { + ["jackal"] = new( + Mobility: MobilityKind.Wheeled, + MassKg: 950f, MaxSpeed: 34f, TurnRate: 4.2f, ThrustNewtons: 14500f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 24f, Conductivity: 8.0f, BaseCellThermalMass: 10f, CargoCapacity: 4, + DefaultLoadout: new() { ["hp.weapon.roof"] = "mg_762", ["hp.engine.rear"] = "diesel_core", ["hp.radiator.rear"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.roof"] = new(5f, -15f, 45f), + ["hp.engine.rear"] = new(5f), + ["hp.radiator.rear"] = new(0f) + }), + + ["mule"] = new( + Mobility: MobilityKind.Wheeled, + MassKg: 1850f, MaxSpeed: 29f, TurnRate: 3.3f, ThrustNewtons: 23500f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 34f, Conductivity: 8.5f, BaseCellThermalMass: 13f, CargoCapacity: 6, + DefaultLoadout: new() { ["hp.weapon.cab"] = "mg_762", ["hp.weapon.bed_main"] = "autocannon", ["hp.engine.front"] = "turbo_core", ["hp.radiator.left"] = "copper_rad", ["hp.armor.front"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.front"] = new(12f), + ["hp.radiator.left"] = new(0f), + ["hp.engine.front"] = new(6f), + ["hp.radiator.right"] = new(0f), + ["hp.weapon.cab"] = new(6f, -15f, 45f), + ["hp.weapon.bed_main"] = new(8f, -12f, 35f) + }), + + ["ferret"] = new( + Mobility: MobilityKind.Tracked, + MassKg: 1450f, MaxSpeed: 28f, TurnRate: 3.8f, ThrustNewtons: 21000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 32f, Conductivity: 8.5f, BaseCellThermalMass: 12f, CargoCapacity: 5, + DefaultLoadout: new() { ["hp.weapon.turret"] = "autocannon", ["hp.weapon.pod"] = "mg_762", ["hp.engine.rear"] = "diesel_core", ["hp.radiator.deck"] = "copper_rad", ["hp.armor.glacis"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.glacis"] = new(14f), + ["hp.weapon.pod"] = new(6f, -15f, 45f), + ["hp.weapon.turret"] = new(10f, -10f, 32f), + ["hp.engine.rear"] = new(6f), + ["hp.radiator.deck"] = new(0f) + }), + + ["ironclad"] = new( + Mobility: MobilityKind.Tracked, + MassKg: 3600f, MaxSpeed: 22f, TurnRate: 2.4f, ThrustNewtons: 34000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 54f, Conductivity: 9.5f, BaseCellThermalMass: 17f, CargoCapacity: 8, + DefaultLoadout: new() { ["hp.weapon.main"] = "recoilless", ["hp.weapon.coax"] = "mg_762", ["hp.engine.rear"] = "turbo_core", ["hp.radiator.l"] = "copper_rad", ["hp.armor.front"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.front"] = new(22f), + ["hp.weapon.coax"] = new(10f, -10f, 40f), + ["hp.weapon.main"] = new(18f, -10f, 30f), + ["hp.armor.skirts"] = new(14f), + ["hp.radiator.l"] = new(0f), + ["hp.engine.rear"] = new(10f), + ["hp.radiator.r"] = new(0f) + }), + + ["mammoth"] = new( + Mobility: MobilityKind.Wheeled, + MassKg: 3900f, MaxSpeed: 24f, TurnRate: 2.3f, ThrustNewtons: 37000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 52f, Conductivity: 9.5f, BaseCellThermalMass: 16f, CargoCapacity: 8, + DefaultLoadout: new() { ["hp.weapon.turret_l"] = "autocannon", ["hp.weapon.turret_r"] = "autocannon", ["hp.weapon.bow"] = "mg_762", ["hp.engine.rear"] = "turbo_core", ["hp.radiator.l"] = "copper_rad", ["hp.armor.glacis"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.glacis"] = new(20f), + ["hp.weapon.bow"] = new(10f, -15f, 45f), + ["hp.weapon.turret_l"] = new(15f, -10f, 30f), + ["hp.weapon.turret_r"] = new(15f, -10f, 30f), + ["hp.armor.flanks"] = new(14f), + ["hp.engine.rear"] = new(10f), + ["hp.radiator.l"] = new(0f), + ["hp.radiator.r"] = new(0f) + }), + + ["anvil"] = new( + Mobility: MobilityKind.Tracked, + MassKg: 4800f, MaxSpeed: 19f, TurnRate: 2.0f, ThrustNewtons: 42000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 66f, Conductivity: 9.5f, BaseCellThermalMass: 19f, CargoCapacity: 9, + DefaultLoadout: new() { ["hp.weapon.siege_l"] = "autocannon", ["hp.weapon.siege_r"] = "autocannon", ["hp.weapon.sponson_l"] = "mg_762", ["hp.engine.rear"] = "turbo_core", ["hp.radiator.l"] = "copper_rad", ["hp.armor.front"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.front"] = new(26f), + ["hp.weapon.sponson_l"] = new(14f, -10f, 30f), + ["hp.weapon.siege_l"] = new(18f, -10f, 30f), + ["hp.armor.sides"] = new(18f), + ["hp.weapon.siege_r"] = new(18f, -10f, 30f), + ["hp.weapon.sponson_r"] = new(14f, -10f, 30f), + ["hp.engine.rear"] = new(12f), + ["hp.radiator.l"] = new(0f), + ["hp.radiator.r"] = new(0f) + }), + + ["hornet"] = new( + Mobility: MobilityKind.Vtol, + MassKg: 820f, MaxSpeed: 42f, TurnRate: 4.8f, ThrustNewtons: 18500f, HoverMaxAltitudeM: 42f, + ArmorPerCell: 14f, Conductivity: 9.0f, BaseCellThermalMass: 9f, CargoCapacity: 4, + DefaultLoadout: new() { ["hp.weapon.chin"] = "autocannon", ["hp.weapon.wing_l"] = "mg_762", ["hp.weapon.wing_r"] = "mg_762", ["hp.engine.core"] = "turbo_core", ["hp.radiator.nacelle_l"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.chin"] = new(2f, -55f, 20f), + ["hp.radiator.nacelle_l"] = new(0f), + ["hp.radiator.nacelle_r"] = new(0f), + ["hp.weapon.wing_l"] = new(2f, -55f, 20f), + ["hp.engine.core"] = new(4f), + ["hp.weapon.wing_r"] = new(2f, -55f, 20f) + }), + + ["condor"] = new( + Mobility: MobilityKind.Vtol, + MassKg: 1950f, MaxSpeed: 35f, TurnRate: 3.6f, ThrustNewtons: 32000f, HoverMaxAltitudeM: 36f, + ArmorPerCell: 22f, Conductivity: 10.0f, BaseCellThermalMass: 12f, CargoCapacity: 7, + DefaultLoadout: new() { ["hp.weapon.sponson_l"] = "autocannon", ["hp.weapon.sponson_r"] = "autocannon", ["hp.weapon.nose"] = "mg_762", ["hp.weapon.dorsal"] = "pd_flak", ["hp.engine.core"] = "turbo_core", ["hp.radiator.spine_l"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.nose"] = new(4f, -55f, 20f), + ["hp.armor.hull"] = new(8f), + ["hp.weapon.sponson_l"] = new(4f, -55f, 20f), + ["hp.weapon.dorsal"] = new(4f, -10f, 85f, IsWideArc: true), + ["hp.weapon.sponson_r"] = new(4f, -55f, 20f), + ["hp.engine.core"] = new(6f), + ["hp.radiator.spine_l"] = new(0f), + ["hp.radiator.spine_r"] = new(0f) + }), + + ["manticore"] = new( + Mobility: MobilityKind.Walker, + MassKg: 2800f, MaxSpeed: 26f, TurnRate: 3.6f, ThrustNewtons: 34500f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 46f, Conductivity: 11.0f, BaseCellThermalMass: 15f, CargoCapacity: 7, + DefaultLoadout: new() { ["hp.weapon.chin"] = "flak", ["hp.weapon.l"] = "mg_762", ["hp.weapon.r"] = "mg_762", ["hp.engine.core"] = "turbo_core", ["hp.radiator.flank_l"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.chin"] = new(10f, -15f, 45f), + ["hp.radiator.flank_l"] = new(4f), + ["hp.engine.core"] = new(12f), + ["hp.radiator.flank_r"] = new(4f), + ["hp.weapon.l"] = new(8f, -15f, 45f), + ["hp.weapon.r"] = new(8f, -15f, 45f), + ["hp.armor.prow"] = new(18f) + }), + + ["bastion"] = new( + Mobility: MobilityKind.Walker, + MassKg: 4600f, MaxSpeed: 20f, TurnRate: 2.4f, ThrustNewtons: 46000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 64f, Conductivity: 11.5f, BaseCellThermalMass: 19f, CargoCapacity: 9, + DefaultLoadout: new() { ["hp.weapon.turret_main"] = "recoilless", ["hp.weapon.turret_pd"] = "pd_flak", ["hp.weapon.flank_l"] = "autocannon", ["hp.engine.core"] = "turbo_core", ["hp.radiator.rear_l"] = "copper_rad", ["hp.armor.prow"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.armor.prow"] = new(24f), + ["hp.weapon.turret_pd"] = new(10f, -10f, 85f, IsWideArc: true), + ["hp.weapon.turret_main"] = new(20f, -10f, 30f), + ["hp.weapon.flank_l"] = new(12f, -10f, 35f), + ["hp.weapon.flank_r"] = new(12f, -10f, 35f), + ["hp.engine.core"] = new(14f), + ["hp.radiator.rear_l"] = new(0f), + ["hp.radiator.rear_r"] = new(0f) + }), + + ["kestrel"] = new( + Mobility: MobilityKind.Walker, + MassKg: 1650f, MaxSpeed: 34f, TurnRate: 4.6f, ThrustNewtons: 27500f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 32f, Conductivity: 10.0f, BaseCellThermalMass: 12f, CargoCapacity: 5, + DefaultLoadout: new() { ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.dorsal"] = "mg_762", ["hp.engine.core"] = "turbo_core", ["hp.radiator.back"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.dorsal"] = new(8f, -10f, 85f, IsWideArc: true), + ["hp.armor.chest"] = new(14f), + ["hp.radiator.back"] = new(4f), + ["hp.engine.core"] = new(10f), + ["hp.weapon.arm_r"] = new(8f, -15f, 45f) + }), + + ["raptor"] = new( + Mobility: MobilityKind.Walker, + MassKg: 2300f, MaxSpeed: 30f, TurnRate: 4.1f, ThrustNewtons: 33000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 42f, Conductivity: 10.5f, BaseCellThermalMass: 14f, CargoCapacity: 6, + DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "flak", ["hp.engine.chest"] = "turbo_core", ["hp.radiator.sh_l"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.radiator.sh_l"] = new(4f), + ["hp.radiator.sh_r"] = new(4f), + ["hp.weapon.arm_l"] = new(8f, -15f, 45f), + ["hp.engine.chest"] = new(12f), + ["hp.weapon.arm_r"] = new(8f, -15f, 45f) + }), + + ["spectre"] = new( + Mobility: MobilityKind.Walker, + MassKg: 2450f, MaxSpeed: 31f, TurnRate: 4.2f, ThrustNewtons: 35000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 44f, Conductivity: 10.5f, BaseCellThermalMass: 14f, CargoCapacity: 6, + DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.shoulder_l"] = "pd_flak", ["hp.engine.core"] = "turbo_core", ["hp.radiator.back_l"] = "copper_rad" }, + HardpointTuning: new() + { + ["hp.weapon.shoulder_l"] = new(8f, -10f, 85f, IsWideArc: true), + ["hp.armor.torso"] = new(16f), + ["hp.weapon.arm_l"] = new(10f, -15f, 45f), + ["hp.radiator.back_l"] = new(4f), + ["hp.engine.core"] = new(12f), + ["hp.radiator.back_r"] = new(4f), + ["hp.weapon.arm_r"] = new(10f, -15f, 45f) + }), + + ["breaker"] = new( + Mobility: MobilityKind.Walker, + MassKg: 3800f, MaxSpeed: 24f, TurnRate: 3.0f, ThrustNewtons: 41000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 56f, Conductivity: 11.0f, BaseCellThermalMass: 17f, CargoCapacity: 8, + DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.shoulder_l"] = "mg_762", ["hp.engine.chest"] = "turbo_core", ["hp.radiator.back_l"] = "copper_rad", ["hp.armor.torso"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.weapon.arm_l"] = new(12f, -15f, 45f), + ["hp.weapon.arm_r"] = new(12f, -15f, 45f), + ["hp.weapon.shoulder_l"] = new(10f, -10f, 85f, IsWideArc: true), + ["hp.armor.torso"] = new(20f), + ["hp.engine.chest"] = new(14f), + ["hp.radiator.back_l"] = new(6f), + ["hp.radiator.back_r"] = new(6f) + }), + + ["paladin"] = new( + Mobility: MobilityKind.Walker, + MassKg: 4100f, MaxSpeed: 22f, TurnRate: 2.7f, ThrustNewtons: 43000f, HoverMaxAltitudeM: 0f, + ArmorPerCell: 58f, Conductivity: 11.5f, BaseCellThermalMass: 18f, CargoCapacity: 9, + DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.sh_l"] = "pd_flak", ["hp.engine.chest"] = "turbo_core", ["hp.radiator.back_l"] = "copper_rad", ["hp.armor.torso"] = "welded_plate" }, + HardpointTuning: new() + { + ["hp.weapon.sh_l"] = new(12f, -10f, 85f, IsWideArc: true), + ["hp.armor.torso"] = new(22f), + ["hp.weapon.sh_r"] = new(12f, -10f, 85f, IsWideArc: true), + ["hp.weapon.arm_l"] = new(12f, -15f, 45f), + ["hp.engine.chest"] = new(16f), + ["hp.weapon.arm_r"] = new(12f, -15f, 45f), + ["hp.radiator.back_l"] = new(6f), + ["hp.armor.legs"] = new(20f), + ["hp.radiator.back_r"] = new(6f) + }), + }; + } + } +} diff --git a/tools/VehiclePacker/VehiclePacker.csproj b/tools/VehiclePacker/VehiclePacker.csproj new file mode 100644 index 0000000..a53a965 --- /dev/null +++ b/tools/VehiclePacker/VehiclePacker.csproj @@ -0,0 +1,14 @@ + + + + Exe + net10.0 + enable + disable + + + + + + + diff --git a/tools/decals/build_decal_atlas.py b/tools/decals/build_decal_atlas.py new file mode 100644 index 0000000..a2c1d40 --- /dev/null +++ b/tools/decals/build_decal_atlas.py @@ -0,0 +1,939 @@ +"""Procedural 4x4 hard-surface & combat POM decal trim-sheet atlas generator. + +Outputs three 1024x1024 RGBA/RGB PNG textures under assets/decals/: + - decal_atlas_albedo.png (RGBA: sRGB albedo + alpha mask, dilated into alpha=0) + - decal_atlas_normal.png (RGB: tangent-space normal map, OpenGL/Godot +X right, +Y down) + - decal_atlas_ormh.png (RGBA: R=AO, G=Roughness, B=Metallic, A=Height [1=surface, 0=deep recess]) + +4x4 tile layout (256x256 each, row 0 = top): + Row 0: (0) louvered armor vent, (1) recessed bolted maintenance hatch, + (2) 4-bolt recessed fastener strip, (3) slotted intake grille + Row 1: (4) rivet panel seam, (5) welded armor repair patch, + (6) recessed lift-lug pocket, (7) weathered hazard caution chevron strip + Row 2: (8) tactical stencil "03", (9) tactical stencil "07", + (10) radiation/heat warning stencil, (11) faction chevron emblem + Row 3: (12) deep AP autocannon penetration hole, (13) diagonal shrapnel/flak armor gouge, + (14) molten plasma burn crater, (15) radial blast scorch mark +""" +from __future__ import annotations + +from pathlib import Path +import numpy as np +from PIL import Image + +REPO_ROOT = Path(__file__).resolve().parents[2] +OUT_DIR = REPO_ROOT / "assets" / "decals" + +TILE_SIZE = 256 +GRID = 4 +ATLAS_SIZE = TILE_SIZE * GRID # 1024 + + +# --------------------------------------------------------------------------- +# Deterministic vectorized noise & SDF primitives (on normalized [-1, 1]^2 tile coords) +# --------------------------------------------------------------------------- + +def _hash2(ix: np.ndarray, iy: np.ndarray, seed: int) -> np.ndarray: + n = (ix.astype(np.int64) * 374761393 + + iy.astype(np.int64) * 668265263 + + np.int64(seed) * 1442695041) & 0xFFFFFFFF + n = ((n ^ (n >> 13)) * 1274126177) & 0xFFFFFFFF + n = n ^ (n >> 16) + return (n & 0xFFFFFF).astype(np.float32) / float(0x1000000) + + +def value_noise(x: np.ndarray, y: np.ndarray, freq: float, seed: int = 1) -> np.ndarray: + px = x * freq + py = y * freq + ix = np.floor(px).astype(np.int64) + iy = np.floor(py).astype(np.int64) + fx = px - ix + fy = py - iy + ux = fx * fx * (3.0 - 2.0 * fx) + uy = fy * fy * (3.0 - 2.0 * fy) + a = _hash2(ix, iy, seed) + b = _hash2(ix + 1, iy, seed) + c = _hash2(ix, iy + 1, seed) + d = _hash2(ix + 1, iy + 1, seed) + return (a * (1.0 - ux) + b * ux) * (1.0 - uy) + (c * (1.0 - ux) + d * ux) * uy + + +def fbm(x: np.ndarray, y: np.ndarray, base_freq: float, octaves: int = 4, seed: int = 1) -> np.ndarray: + acc = np.zeros_like(x, dtype=np.float32) + amp = 0.5 + norm = 0.0 + f = base_freq + for o in range(octaves): + acc += amp * value_noise(x, y, f, seed + o * 37) + norm += amp + amp *= 0.5 + f *= 2.03 + return acc / norm + + +def smoothstep(e0: float, e1: float, x: np.ndarray) -> np.ndarray: + t = np.clip((x - e0) / (e1 - e0), 0.0, 1.0) + return t * t * (3.0 - 2.0 * t) + + +def sd_box(x: np.ndarray, y: np.ndarray, cx: float, cy: float, hx: float, hy: float, r: float = 0.0) -> np.ndarray: + qx = np.abs(x - cx) - (hx - r) + qy = np.abs(y - cy) - (hy - r) + out = np.sqrt(np.maximum(qx, 0.0) ** 2 + np.maximum(qy, 0.0) ** 2) + ins = np.minimum(np.maximum(qx, qy), 0.0) + return out + ins - r + + +def sd_circle(x: np.ndarray, y: np.ndarray, cx: float, cy: float, r: float) -> np.ndarray: + return np.sqrt((x - cx) ** 2 + (y - cy) ** 2) - r + + +def sd_segment(x: np.ndarray, y: np.ndarray, ax: float, ay: float, bx: float, by: float) -> np.ndarray: + pax = x - ax + pay = y - ay + bax = bx - ax + bay = by - ay + denom = bax * bax + bay * bay + 1e-12 + h = np.clip((pax * bax + pay * bay) / denom, 0.0, 1.0) + return np.sqrt((pax - bax * h) ** 2 + (pay - bay * h) ** 2) + + +def sd_hexagon(x: np.ndarray, y: np.ndarray, cx: float, cy: float, r: float) -> np.ndarray: + px = np.abs(x - cx) + py = np.abs(y - cy) + # Regular hexagon with flat top/bottom + d = np.maximum(px * 0.8660254 + py * 0.5, py) - r + return d + + +def sd_triangle_eq(x: np.ndarray, y: np.ndarray, cx: float, cy: float, r: float) -> np.ndarray: + # Pointing up (-y in image space) + px = np.abs(x - cx) + py = -(y - cy) + r * 0.25 + px_k = np.sqrt(3.0) + # Standard IQ equilateral triangle SDF + px2 = px - r + py2 = py + r / px_k + cond = (px + px_k * py) > 0.0 + nx = np.where(cond, (px - px_k * py) * 0.5, px) + ny = np.where(cond, (-px_k * px - py) * 0.5, py) + nx -= np.clip(nx, -2.0 * r, 0.0) + return -np.sqrt(nx * nx + ny * ny) * np.sign(ny) + + +def tile_coords() -> tuple[np.ndarray, np.ndarray]: + lin = np.linspace(-1.0 + 1.0 / TILE_SIZE, 1.0 - 1.0 / TILE_SIZE, TILE_SIZE, dtype=np.float32) + yy, xx = np.meshgrid(lin, lin, indexing="ij") + return xx, yy + + +def new_tile() -> dict[str, np.ndarray]: + shape = (TILE_SIZE, TILE_SIZE) + return { + "rgb": np.full((*shape, 3), 0.18, dtype=np.float32), + "alpha": np.zeros(shape, dtype=np.float32), + "height": np.ones(shape, dtype=np.float32), + "rough": np.full(shape, 0.56, dtype=np.float32), + "metal": np.full(shape, 0.35, dtype=np.float32), + } + + +def add_hex_bolt( + t: dict[str, np.ndarray], + x: np.ndarray, + y: np.ndarray, + cx: float, + cy: float, + pocket_r: float = 0.095, + head_r: float = 0.064, + base_h: float = 0.85, +) -> None: + dp = sd_circle(x, y, cx, cy, pocket_r) + dh = sd_circle(x, y, cx, cy, head_r) + dhex = sd_hexagon(x, y, cx, cy, head_r * 0.48) + + in_pocket = smoothstep(0.015, -0.015, dp) + in_head = smoothstep(0.012, -0.012, dh) + in_socket = smoothstep(0.010, -0.010, dhex) + + # Countersunk floor + pocket_h = base_h - 0.52 * in_pocket + # Raised chamfered bolt head inside pocket + head_profile = np.clip(1.0 - np.maximum(dh / head_r + 1.0, 0.0) ** 4 * 0.15, 0.0, 1.0) + bolt_h = base_h - 0.06 + 0.04 * head_profile + bolt_h = bolt_h - 0.36 * in_socket + + t["height"] = np.where(in_head > 0.5, bolt_h, np.minimum(t["height"], pocket_h)) + # Colors & PBR + pocket_col = np.array([0.055, 0.058, 0.056], dtype=np.float32) + bolt_col = np.array([0.24, 0.25, 0.24], dtype=np.float32) + sock_col = np.array([0.035, 0.036, 0.036], dtype=np.float32) + + t["rgb"] = t["rgb"] * (1.0 - in_pocket[..., None]) + pocket_col * in_pocket[..., None] + t["rgb"] = t["rgb"] * (1.0 - in_head[..., None]) + bolt_col * in_head[..., None] + t["rgb"] = t["rgb"] * (1.0 - in_socket[..., None]) + sock_col * in_socket[..., None] + t["metal"] = np.where(in_head > 0.5, 0.88, np.where(in_pocket > 0.5, 0.65, t["metal"])) + t["rough"] = np.where(in_head > 0.5, 0.34, np.where(in_pocket > 0.5, 0.62, t["rough"])) + + +def add_domed_rivet( + t: dict[str, np.ndarray], + x: np.ndarray, + y: np.ndarray, + cx: float, + cy: float, + r: float = 0.052, + base_h: float = 0.88, +) -> None: + d = sd_circle(x, y, cx, cy, r) + mask = smoothstep(0.012, -0.012, d) + ring = smoothstep(0.018, 0.0, np.abs(d - 0.005)) + dist_norm = np.clip(np.sqrt((x - cx) ** 2 + (y - cy) ** 2) / r, 0.0, 1.0) + dome = np.sqrt(np.maximum(1.0 - dist_norm ** 2, 0.0)) + rivet_h = base_h - 0.08 * ring + 0.11 * dome * mask + t["height"] = t["height"] * (1.0 - mask) + np.clip(rivet_h, 0.0, 1.0) * mask + col = np.array([0.28, 0.29, 0.27], dtype=np.float32) + t["rgb"] = t["rgb"] * (1.0 - mask[..., None]) + col * mask[..., None] + t["metal"] = t["metal"] * (1.0 - mask) + 0.85 * mask + t["rough"] = t["rough"] * (1.0 - mask) + 0.32 * mask + + +# --------------------------------------------------------------------------- +# Individual tiles (0..15) +# --------------------------------------------------------------------------- + +def tile_00_louvered_vent(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(0) Louvered armor vent.""" + t = new_tile() + n1 = fbm(x, y, 10.0, 4, seed=101) + n2 = fbm(x, y, 36.0, 3, seed=102) + + d_outer = sd_box(x, y, 0.0, 0.0, 0.80, 0.72, r=0.06) + d_inner = sd_box(x, y, 0.0, 0.0, 0.65, 0.56, r=0.03) + d_seam = np.abs(d_outer) + + outer_m = smoothstep(0.025, -0.025, d_outer) + inner_m = smoothstep(0.02, -0.02, d_inner) + + # Frame plate + frame_h = 0.96 - 0.04 * smoothstep(0.0, 0.14, np.maximum(-d_outer, 0.0)) + frame_h -= 0.45 * smoothstep(0.03, 0.0, d_seam) + # Recessed bay behind louvers + h = np.where(inner_m > 0.5, 0.04, frame_h) + + # 5 angled louvers inside d_inner + slat_centers = np.linspace(-0.42, 0.42, 5) + slat_mask_all = np.zeros_like(x) + for sc in slat_centers: + # Each louver spans x=[-0.62, 0.62], y=[sc-0.065, sc+0.065] + ds = sd_box(x, y, 0.0, float(sc), 0.62, 0.068, r=0.015) + sm = smoothstep(0.015, -0.015, ds) + # Slope from top (high) down to bottom (low), exposing dark gap underneath + local_t = np.clip((y - (sc - 0.068)) / 0.136, 0.0, 1.0) + slat_h = 0.92 - 0.62 * local_t + h = np.maximum(h, sm * slat_h) + slat_mask_all = np.maximum(slat_mask_all, sm) + + # Paint + worn steel + soot inside vent + olive = np.array([0.16, 0.18, 0.14], dtype=np.float32) * (0.85 + 0.30 * n1[..., None]) + steel = np.array([0.26, 0.27, 0.26], dtype=np.float32) * (0.85 + 0.30 * n2[..., None]) + void = np.array([0.025, 0.025, 0.027], dtype=np.float32) + + edge_wear = smoothstep(0.05, 0.0, np.abs(d_inner)) * smoothstep(0.35, 0.65, n2) + slat_top_wear = slat_mask_all * smoothstep(0.70, 0.92, h) * smoothstep(0.35, 0.70, n2) + wear = np.clip(np.maximum(edge_wear, slat_top_wear), 0.0, 1.0) + + col = olive * (1.0 - wear[..., None]) + steel * wear[..., None] + # Darken recessed gap + in_void = inner_m * (1.0 - slat_mask_all) + col = col * (1.0 - in_void[..., None]) + void * in_void[..., None] + # Soot darkening on lower slope of slats + col *= (1.0 - 0.45 * slat_mask_all[..., None] * smoothstep(0.85, 0.30, h)[..., None]) + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = outer_m + t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.35 + 0.55 * wear + 0.25 * slat_mask_all, 0.0, 1.0) + t["rough"] = np.clip(0.58 - 0.26 * wear + 0.25 * in_void, 0.18, 0.95) + + for bx, by in [(-0.71, -0.63), (0.71, -0.63), (-0.71, 0.63), (0.71, 0.63)]: + add_hex_bolt(t, x, y, bx, by, pocket_r=0.055, head_r=0.036, base_h=0.95) + return t + + +def tile_01_bolted_hatch(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(1) Recessed bolted maintenance hatch.""" + t = new_tile() + n1 = fbm(x, y, 8.0, 4, seed=201) + n2 = fbm(x, y, 28.0, 3, seed=202) + + d_outer = sd_box(x, y, 0.0, 0.0, 0.80, 0.80, r=0.08) + d_groove = np.abs(sd_box(x, y, 0.0, 0.0, 0.66, 0.66, r=0.06)) + d_door = sd_box(x, y, 0.0, 0.0, 0.63, 0.63, r=0.05) + d_latch = sd_box(x, y, 0.32, 0.0, 0.13, 0.22, r=0.03) + d_bar = sd_box(x, y, 0.32, 0.0, 0.045, 0.16, r=0.02) + + outer_m = smoothstep(0.025, -0.025, d_outer) + groove_m = smoothstep(0.032, 0.0, d_groove) + latch_m = smoothstep(0.02, -0.02, d_latch) + bar_m = smoothstep(0.015, -0.015, d_bar) + + h = np.full_like(x, 0.96) + # Bevel down into perimeter seam + h = np.where(d_door < 0.0, 0.88, h) + h -= 0.72 * groove_m + # Recessed latch pocket with grab bar + h = np.where(latch_m > 0.5, 0.22, h) + h = np.where(bar_m > 0.5, 0.86, h) + + base_col = np.array([0.19, 0.21, 0.16], dtype=np.float32) * (0.86 + 0.28 * n1[..., None]) + door_col = np.array([0.22, 0.24, 0.19], dtype=np.float32) * (0.86 + 0.28 * n1[..., None]) + seam_col = np.array([0.04, 0.04, 0.038], dtype=np.float32) + bar_col = np.array([0.34, 0.34, 0.32], dtype=np.float32) + + in_door = smoothstep(0.02, -0.02, d_door) + col = base_col * (1.0 - in_door[..., None]) + door_col * in_door[..., None] + # Paint chip around door edge + chip = smoothstep(0.05, 0.0, np.abs(d_door)) * smoothstep(0.45, 0.68, n2) + col = col * (1.0 - chip[..., None]) + np.array([0.32, 0.33, 0.32], dtype=np.float32) * chip[..., None] + col = col * (1.0 - groove_m[..., None]) + seam_col * groove_m[..., None] + col = col * (1.0 - latch_m[..., None]) + np.array([0.05, 0.05, 0.05], dtype=np.float32) * latch_m[..., None] + col = col * (1.0 - bar_m[..., None]) + bar_col * bar_m[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = outer_m + t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.30 + 0.55 * chip + 0.60 * bar_m, 0.0, 1.0) + t["rough"] = np.clip(0.56 - 0.24 * chip + 0.25 * groove_m, 0.2, 0.95) + + for bx, by in [(-0.50, -0.50), (0.0, -0.52), (0.50, -0.50), + (-0.50, 0.50), (0.0, 0.52), (0.50, 0.50), + (-0.52, 0.0)]: + add_hex_bolt(t, x, y, bx, by, pocket_r=0.068, head_r=0.044, base_h=0.88) + return t + + +def tile_02_fastener_strip(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(2) 4-bolt recessed fastener strip.""" + t = new_tile() + n1 = fbm(x, y, 12.0, 4, seed=301) + n2 = fbm(x, y, 40.0, 3, seed=302) + + d_strip = sd_box(x, y, 0.0, 0.0, 0.84, 0.28, r=0.08) + d_bevel = sd_box(x, y, 0.0, 0.0, 0.78, 0.22, r=0.05) + mask = smoothstep(0.025, -0.025, d_strip) + + # Raised beveled plate with seam around edge + h = np.where(d_bevel < 0.0, 0.93, 0.82) + h -= 0.45 * smoothstep(0.03, 0.0, np.abs(d_strip)) + + col = np.array([0.21, 0.22, 0.19], dtype=np.float32) * (0.86 + 0.28 * n1[..., None]) + edge_wear = smoothstep(0.05, 0.0, np.abs(d_bevel)) * smoothstep(0.35, 0.70, n2) + col = col * (1.0 - edge_wear[..., None]) + np.array([0.36, 0.37, 0.36], dtype=np.float32) * edge_wear[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = mask + t["height"] = np.where(mask > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.45 + 0.45 * edge_wear, 0.0, 1.0) + t["rough"] = np.clip(0.48 - 0.18 * edge_wear, 0.22, 0.9) + + for bx in (-0.57, -0.19, 0.19, 0.57): + add_hex_bolt(t, x, y, bx, 0.0, pocket_r=0.115, head_r=0.075, base_h=0.93) + return t + + +def tile_03_intake_grille(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(3) Slotted intake grille.""" + t = new_tile() + n1 = fbm(x, y, 10.0, 4, seed=401) + n2 = fbm(x, y, 32.0, 3, seed=402) + + d_outer = sd_box(x, y, 0.0, 0.0, 0.80, 0.76, r=0.07) + d_inner = sd_box(x, y, 0.0, 0.0, 0.66, 0.60, r=0.04) + outer_m = smoothstep(0.025, -0.025, d_outer) + inner_m = smoothstep(0.02, -0.02, d_inner) + + h = np.where(inner_m > 0.5, 0.88, 0.96) + h -= 0.38 * smoothstep(0.03, 0.0, np.abs(d_inner)) + + # 6 vertical intake slots (2 rows of 6 or 6 tall slots) + slot_void = np.zeros_like(x) + for sx in np.linspace(-0.48, 0.48, 6): + for sy in (-0.27, 0.27): + ds = sd_box(x, y, float(sx), float(sy), 0.046, 0.21, r=0.038) + sm = smoothstep(0.015, -0.015, ds) + # Chamfered rim then deep void + rim = smoothstep(0.035, 0.0, np.abs(ds - 0.012)) + h = np.where(sm > 0.5, 0.02, h - 0.18 * rim) + slot_void = np.maximum(slot_void, sm) + + plate_col = np.array([0.16, 0.17, 0.16], dtype=np.float32) * (0.85 + 0.3 * n1[..., None]) + rib_wear = smoothstep(0.45, 0.75, n2) * inner_m * (1.0 - slot_void) * 0.45 + col = plate_col * (1.0 - rib_wear[..., None]) + np.array([0.30, 0.31, 0.30], dtype=np.float32) * rib_wear[..., None] + col = col * (1.0 - slot_void[..., None]) + np.array([0.02, 0.02, 0.022], dtype=np.float32) * slot_void[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = outer_m + t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.55 + 0.35 * rib_wear - 0.5 * slot_void, 0.0, 1.0) + t["rough"] = np.clip(0.46 - 0.15 * rib_wear + 0.4 * slot_void, 0.2, 0.95) + + for rx, ry in [(-0.72, -0.68), (0.72, -0.68), (-0.72, 0.68), (0.72, 0.68)]: + add_domed_rivet(t, x, y, rx, ry, r=0.042, base_h=0.95) + return t + + +def tile_04_rivet_seam(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(4) Rivet panel seam.""" + t = new_tile() + n1 = fbm(x, y, 10.0, 4, seed=501) + n2 = fbm(x, y, 36.0, 3, seed=502) + + d_strip = sd_box(x, y, 0.0, 0.0, 0.84, 0.32, r=0.04) + mask = smoothstep(0.025, -0.025, d_strip) + # Central recessed panel seam groove along y=0, clipped inside strip + groove = smoothstep(0.042, 0.0, np.abs(y)) * mask + h = 0.90 - 0.72 * groove + + col = np.array([0.20, 0.21, 0.17], dtype=np.float32) * (0.85 + 0.3 * n1[..., None]) + chip = smoothstep(0.08, 0.0, np.abs(y)) * smoothstep(0.48, 0.70, n2) * mask + col = col * (1.0 - chip[..., None]) + np.array([0.34, 0.35, 0.34], dtype=np.float32) * chip[..., None] + col = col * (1.0 - groove[..., None]) + np.array([0.04, 0.04, 0.036], dtype=np.float32) * groove[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = mask + t["height"] = np.where(mask > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.32 + 0.55 * chip, 0.0, 1.0) + t["rough"] = np.clip(0.56 - 0.24 * chip + 0.30 * groove, 0.2, 0.95) + + for rx in np.linspace(-0.70, 0.70, 6): + add_domed_rivet(t, x, y, float(rx), -0.15, r=0.046, base_h=0.90) + add_domed_rivet(t, x, y, float(rx), 0.15, r=0.046, base_h=0.90) + return t + + +def tile_05_welded_patch(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(5) Welded armor repair patch.""" + t = new_tile() + n1 = fbm(x, y, 9.0, 4, seed=601) + n2 = fbm(x, y, 42.0, 3, seed=602) + + # Slightly rotated/chamfered patch shape + ca, sa = np.cos(0.08), np.sin(0.08) + xr = x * ca - y * sa + yr = x * sa + y * ca + d_patch = sd_box(xr, yr, 0.0, 0.0, 0.64, 0.50, r=0.05) + # Irregular outer weld apron + d_outer = d_patch - 0.12 + outer_m = smoothstep(0.025, -0.025, d_outer) + patch_m = smoothstep(0.018, -0.018, d_patch) + + # Weld bead ripple along perimeter d_patch ~= 0 + bead_band = smoothstep(0.085, 0.0, np.abs(d_patch - 0.01)) + # Ripple along perimeter coordinate + ripple = 0.5 + 0.5 * np.sin((xr + yr) * 48.0 + n2 * 6.0) + bead_h = 0.72 + 0.27 * bead_band * (0.65 + 0.35 * ripple) + + h = np.where(patch_m > 0.5, 0.92 - 0.03 * n1, 0.68) + h = np.maximum(h, bead_h * bead_band) + + patch_col = np.array([0.23, 0.24, 0.21], dtype=np.float32) * (0.85 + 0.30 * n1[..., None]) + weld_col = np.array([0.38, 0.36, 0.33], dtype=np.float32) * (0.80 + 0.35 * ripple[..., None]) + # Heat-affected straw/blue oxide halo outside weld + haz = smoothstep(0.14, 0.02, np.abs(d_patch - 0.03)) * (1.0 - bead_band) + haz_col = np.array([0.14, 0.12, 0.14], dtype=np.float32) + + col = haz_col * haz[..., None] + patch_col * patch_m[..., None] + col = col * (1.0 - bead_band[..., None]) + weld_col * bead_band[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = np.clip(np.maximum(patch_m, bead_band * 0.95 + haz * 0.75) * outer_m, 0.0, 1.0) + t["height"] = np.where(t["alpha"] > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.35 + 0.58 * bead_band, 0.0, 1.0) + t["rough"] = np.clip(0.55 - 0.28 * bead_band, 0.18, 0.92) + return t + + +def tile_06_lift_lug(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(6) Recessed lift-lug pocket.""" + t = new_tile() + n1 = fbm(x, y, 11.0, 4, seed=701) + n2 = fbm(x, y, 34.0, 3, seed=702) + + d_outer = sd_box(x, y, 0.0, 0.0, 0.74, 0.74, r=0.10) + d_pocket = sd_box(x, y, 0.0, 0.0, 0.52, 0.52, r=0.09) + outer_m = smoothstep(0.025, -0.025, d_outer) + pocket_m = smoothstep(0.02, -0.02, d_pocket) + + # Chamfered pit wall + wall_t = np.clip(-d_pocket / 0.14, 0.0, 1.0) + pit_h = 0.94 - 0.84 * smoothstep(0.0, 1.0, wall_t) + h = np.where(pocket_m > 0.5, pit_h, 0.96) + + # Cylindrical steel crossbar along X (spanning the recessed pocket) + d_bar_y = np.abs(y) / 0.135 + d_bar_x = np.abs(x) - 0.50 + bar_m = smoothstep(1.06, 0.94, d_bar_y) * smoothstep(0.02, -0.02, d_bar_x) + cyl_z = np.sqrt(np.maximum(1.0 - np.clip(d_bar_y, 0.0, 1.0) ** 2, 0.0)) + bar_h = 0.45 + 0.50 * cyl_z + h = np.where(bar_m > 0.5, np.maximum(h, bar_h), h) + + flange_col = np.array([0.18, 0.19, 0.16], dtype=np.float32) * (0.85 + 0.30 * n1[..., None]) + pit_col = np.array([0.055, 0.056, 0.055], dtype=np.float32) * (0.8 + 0.3 * n1[..., None]) + bar_col = np.array([0.36, 0.37, 0.36], dtype=np.float32) * (0.85 + 0.25 * n2[..., None]) + + col = flange_col * (1.0 - pocket_m[..., None]) + pit_col * pocket_m[..., None] + col = col * (1.0 - bar_m[..., None]) + bar_col * bar_m[..., None] + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = outer_m + t["height"] = np.where(outer_m > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.35 + 0.58 * bar_m, 0.0, 1.0) + t["rough"] = np.clip(0.55 - 0.28 * bar_m + 0.20 * pocket_m * (1.0 - bar_m), 0.18, 0.95) + return t + + +def tile_07_hazard_chevron(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(7) Weathered hazard caution chevron strip.""" + t = new_tile() + n1 = fbm(x, y, 8.0, 4, seed=801) + n2 = fbm(x, y, 34.0, 4, seed=802) + + d_strip = sd_box(x, y, 0.0, 0.0, 0.84, 0.26, r=0.025) + d_inner = sd_box(x, y, 0.0, 0.0, 0.78, 0.20, r=0.015) + strip_m = smoothstep(0.02, -0.02, d_strip) + inner_m = smoothstep(0.015, -0.015, d_inner) + + # Diagonal stripes + stripe_wave = np.sin((x * 2.2 + y * 2.2) * np.pi * 2.4) + is_yellow = smoothstep(-0.08, 0.08, stripe_wave) + + yellow = np.array([0.68, 0.44, 0.06], dtype=np.float32) + black = np.array([0.055, 0.055, 0.052], dtype=np.float32) + steel = np.array([0.28, 0.29, 0.28], dtype=np.float32) + + col = black * (1.0 - is_yellow[..., None]) + yellow * is_yellow[..., None] + # Thin dark border frame + col = black * (1.0 - inner_m[..., None]) + col * inner_m[..., None] + # Grime + paint chips + chip = smoothstep(0.62, 0.69, n2) + col *= (0.78 + 0.35 * n1[..., None]) + col = col * (1.0 - chip[..., None] * 0.75) + steel * (chip[..., None] * 0.75) + + # Subtle paint film thickness + border recess + h = 0.98 - 0.08 * (1.0 - inner_m) - 0.04 * chip + edge_wear = smoothstep(0.06, 0.0, np.abs(d_strip)) * smoothstep(0.55, 0.72, n2) + alpha = np.clip(strip_m * (1.0 - 0.80 * edge_wear), 0.0, 1.0) + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = np.clip(alpha, 0.0, 1.0) + t["height"] = np.where(strip_m > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.15 + 0.65 * chip, 0.0, 1.0) + t["rough"] = np.clip(0.60 - 0.25 * chip, 0.25, 0.92) + return t + + +# --------------------------------------------------------------------------- +# Row 2: Stencils & Emblems +# --------------------------------------------------------------------------- + +def _sd_digit_0(x: np.ndarray, y: np.ndarray, cx: float, cy: float) -> np.ndarray: + d_out = sd_box(x, y, cx, cy, 0.28, 0.46, r=0.14) + d_in = sd_box(x, y, cx, cy, 0.11, 0.28, r=0.05) + d = np.maximum(d_out, -d_in) + # Stencil bridge gaps top/bottom + gap = np.abs(x - cx) - 0.032 + d_bridge = np.maximum(gap, 0.25 - np.abs(y - cy)) + return np.maximum(d, -d_bridge) + + +def _sd_digit_3(x: np.ndarray, y: np.ndarray, cx: float, cy: float) -> np.ndarray: + d_out = sd_box(x, y, cx, cy, 0.28, 0.46, r=0.14) + d_in_top = sd_box(x, y, cx - 0.04, cy - 0.20, 0.16, 0.11, r=0.03) + d_in_bot = sd_box(x, y, cx - 0.04, cy + 0.20, 0.16, 0.11, r=0.03) + d_open_l = sd_box(x, y, cx - 0.24, cy, 0.16, 0.15, r=0.0) + d = np.maximum(d_out, -np.minimum(np.minimum(d_in_top, d_in_bot), d_open_l)) + # Stencil bridge on right spine + gap = np.maximum(np.abs(y - cy) - 0.028, (cx - 0.05) - x) + return np.maximum(d, -gap) + + +def _sd_digit_7(x: np.ndarray, y: np.ndarray, cx: float, cy: float) -> np.ndarray: + d_top = sd_box(x, y, cx, cy - 0.37, 0.28, 0.09, r=0.02) + # Slanted leg from (cx+0.20, cy-0.36) to (cx-0.08, cy+0.39) + d_leg = sd_segment(x, y, cx + 0.18, cy - 0.34, cx - 0.07, cy + 0.38) - 0.088 + d = np.minimum(d_top, d_leg) + # Stencil gap between top bar & leg + gap = sd_box(x, y, cx + 0.12, cy - 0.25, 0.20, 0.025, r=0.0) + return np.maximum(d, -gap) + + +def _finish_stencil( + x: np.ndarray, + y: np.ndarray, + mask: np.ndarray, + paint_col: np.ndarray, + seed: int, +) -> dict[str, np.ndarray]: + t = new_tile() + n1 = fbm(x, y, 10.0, 4, seed=seed) + n2 = fbm(x, y, 40.0, 4, seed=seed + 1) + + # Flaking & scratching across stencil paint + flake = smoothstep(0.58, 0.72, n2) + scratches = smoothstep(0.68, 0.74, fbm(x * 0.4 + y * 1.8, y * 0.4, 24.0, 3, seed=seed + 2)) + wear = np.clip(flake * 0.85 + scratches * 0.7, 0.0, 1.0) + + alpha = np.clip(mask * (1.0 - wear * 0.85), 0.0, 1.0) + col = paint_col * (0.82 + 0.25 * n1[..., None]) + h = 1.0 - 0.02 * mask * (1.0 - wear) - 0.04 * (1.0 - mask) + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = alpha + t["height"] = np.where(alpha > 0.02, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.full_like(x, 0.08) + t["rough"] = np.clip(0.68 + 0.15 * n1, 0.4, 0.9) + return t + + +def tile_08_stencil_03(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(8) Tactical stencil '03'.""" + d = np.minimum(_sd_digit_0(x, y, -0.36, 0.0), _sd_digit_3(x, y, 0.36, 0.0)) + mask = smoothstep(0.02, -0.02, d) + return _finish_stencil(x, y, mask, np.array([0.74, 0.71, 0.62], dtype=np.float32), seed=901) + + +def tile_09_stencil_07(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(9) Tactical stencil '07'.""" + d = np.minimum(_sd_digit_0(x, y, -0.36, 0.0), _sd_digit_7(x, y, 0.36, 0.0)) + mask = smoothstep(0.02, -0.02, d) + return _finish_stencil(x, y, mask, np.array([0.74, 0.71, 0.62], dtype=np.float32), seed=1001) + + +def tile_10_radiation_warning(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(10) Radiation / thermal warning stencil.""" + r = np.sqrt(x * x + y * y) + ang = np.arctan2(y, x) + + # Outer dashed warning ring + d_ring = np.abs(r - 0.66) - 0.065 + ring_seg = np.abs(((ang + np.pi) / (np.pi / 3.0)) % 1.0 - 0.5) - 0.34 + d_ring = np.maximum(d_ring, ring_seg * 0.5) + + # Central dot + 3 trefoil blades + d_core = r - 0.11 + blade_annulus = np.maximum(0.18 - r, r - 0.52) + blade_ang = np.cos(3.0 * (ang + np.pi / 6.0)) + d_blades = np.maximum(blade_annulus, (0.45 - blade_ang) * 0.28) + + d = np.minimum(np.minimum(d_ring, d_core), d_blades) + mask = smoothstep(0.02, -0.02, d) + return _finish_stencil(x, y, mask, np.array([0.78, 0.36, 0.09], dtype=np.float32), seed=1101) + + +def tile_11_faction_emblem(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(11) Faction chevron emblem.""" + ax = np.abs(x) + # Double military chevron + diamond center + d1 = np.abs((y + 0.14) + ax * 0.85) - 0.085 + d1 = np.maximum(d1, ax - 0.68) + d2 = np.abs((y - 0.22) + ax * 0.85) - 0.065 + d2 = np.maximum(d2, ax - 0.52) + d_diamond = (ax * 0.9 + np.abs(y + 0.42)) - 0.18 + d_chev = np.minimum(d1, d2) + + m_chev = smoothstep(0.02, -0.02, d_chev) + m_dia = smoothstep(0.02, -0.02, d_diamond) + mask = np.maximum(m_chev, m_dia) + + t = _finish_stencil(x, y, mask, np.array([0.76, 0.72, 0.60], dtype=np.float32), seed=1201) + # Signal orange center diamond + orange = np.array([0.74, 0.27, 0.10], dtype=np.float32) + t["rgb"] = t["rgb"] * (1.0 - m_dia[..., None]) + orange * m_dia[..., None] + return t + + +# --------------------------------------------------------------------------- +# Row 3: Dynamic combat hits (12..15) +# --------------------------------------------------------------------------- + +def tile_12_ap_penetration(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(12) Deep AP autocannon penetration hole (rolled metallic rim + black bore + hot rim).""" + t = new_tile() + n1 = fbm(x, y, 7.0, 4, seed=1301) + n2 = fbm(x, y, 24.0, 4, seed=1302) + ang = np.arctan2(y, x) + # Jagged petal modulation around bore + jagged = 0.065 * np.sin(ang * 7.0 + 1.1) + 0.045 * np.cos(ang * 13.0 - 0.4) + 0.09 * (n2 - 0.5) + r = np.sqrt(x * x + y * y) + jagged + + bore_r = 0.28 + rim_r = 0.44 + scorch_r = 0.82 + + bore_m = smoothstep(bore_r + 0.03, bore_r - 0.02, r) + rim_m = smoothstep(0.10, 0.0, np.abs(r - (bore_r + 0.05))) + scorch_m = smoothstep(scorch_r, bore_r * 0.8, r) * (0.55 + 0.45 * n1) + + # Height: flush 1.0 outside -> raised/rolled rim at 0.96 -> sharp drop into 0.0 pitch-black bore + hole_wall = smoothstep(bore_r - 0.04, rim_r, r) + h = np.clip(hole_wall * 0.96 + 0.04 * smoothstep(rim_r + 0.12, rim_r, r), 0.0, 1.0) + h = np.where(r > rim_r + 0.12, 1.0, h) + + soot_col = np.array([0.04, 0.035, 0.032], dtype=np.float32) + steel_col = np.array([0.52, 0.54, 0.56], dtype=np.float32) * (0.75 + 0.45 * n2[..., None]) + bore_col = np.array([0.012, 0.010, 0.010], dtype=np.float32) + + col = soot_col * (1.0 - rim_m[..., None]) + steel_col * rim_m[..., None] + col = col * (1.0 - bore_m[..., None]) + bore_col * bore_m[..., None] + + # Alpha: opaque in bore + metal rim, softly feathered soot halo + alpha = np.clip(np.maximum(np.maximum(bore_m, rim_m), scorch_m * 0.88), 0.0, 1.0) + # Keep zero bleed at outer margin + border = smoothstep(0.92, 0.78, np.maximum(np.abs(x), np.abs(y))) + alpha *= border + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = alpha + t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(rim_m * 0.94 + bore_m * 0.10, 0.0, 1.0) + t["rough"] = np.clip(0.92 - rim_m * 0.66, 0.22, 0.96) + return t + + +def tile_13_shrapnel_gouge(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(13) Diagonal shrapnel/flak armor gouge.""" + t = new_tile() + n1 = fbm(x, y, 8.0, 4, seed=1401) + n2 = fbm(x, y, 28.0, 4, seed=1402) + + # Rotate -35 degrees for diagonal ricochet trench + ca, sa = np.cos(-0.62), np.sin(-0.62) + u = x * ca - y * sa + v = x * sa + y * ca + 0.04 * (n2 - 0.5) + + # Tapered V-trough from u=-0.62 to u=+0.62 + d_trench = sd_segment(u, v, -0.58, 0.0, 0.58, 0.0) + width = 0.13 + 0.05 * np.clip((u + 0.58) / 1.16, 0.0, 1.0) + trough_t = np.clip(1.0 - d_trench / width, 0.0, 1.0) + burr_m = smoothstep(0.06, 0.0, np.abs(d_trench - width)) + + h = 1.0 - 0.88 * smoothstep(0.0, 1.0, trough_t) + # Upturned burr ridge at edge + h = np.clip(h + 0.04 * burr_m, 0.0, 1.0) + + soot = np.array([0.045, 0.04, 0.036], dtype=np.float32) + torn_steel = np.array([0.50, 0.52, 0.54], dtype=np.float32) * (0.75 + 0.45 * n2[..., None]) + furrow_dark = np.array([0.09, 0.09, 0.095], dtype=np.float32) + + trench_m = smoothstep(0.05, 0.25, trough_t) + col = soot * (1.0 - trench_m[..., None]) + torn_steel * trench_m[..., None] + col = col * (1.0 - smoothstep(0.60, 0.95, trough_t)[..., None] * 0.7) + furrow_dark * (smoothstep(0.60, 0.95, trough_t)[..., None] * 0.7) + col = col * (1.0 - burr_m[..., None] * 0.65) + torn_steel * (burr_m[..., None] * 0.65) + + scorch_halo = smoothstep(0.42, 0.08, d_trench) * (0.5 + 0.5 * n1) + alpha = np.clip(np.maximum(trench_m, np.maximum(burr_m, scorch_halo * 0.85)), 0.0, 1.0) + border = smoothstep(0.92, 0.78, np.maximum(np.abs(x), np.abs(y))) + alpha *= border + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = alpha + t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(np.maximum(trench_m, burr_m) * 0.90, 0.0, 1.0) + t["rough"] = np.clip(0.90 - np.maximum(trench_m, burr_m) * 0.62, 0.24, 0.95) + return t + + +def tile_14_plasma_crater(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(14) Molten plasma burn crater.""" + t = new_tile() + n1 = fbm(x, y, 7.5, 4, seed=1501) + n2 = fbm(x, y, 22.0, 4, seed=1502) + r = np.sqrt(x * x + y * y) + 0.08 * (n2 - 0.5) + + crater_r = 0.44 + bowl_m = smoothstep(crater_r + 0.04, crater_r - 0.08, r) + rim_m = smoothstep(0.08, 0.0, np.abs(r - crater_r)) + scorch_m = smoothstep(0.84, 0.36, r) * (0.5 + 0.5 * n1) + + # Slag ripples in bowl + crisp crater rim + ripples = 0.5 + 0.5 * np.sin(r * 34.0 + n2 * 4.0) + bowl_depth = smoothstep(crater_r, 0.04, r) + h = 1.0 - 0.88 * bowl_depth + 0.08 * ripples * bowl_m + 0.06 * rim_m + + carbon = np.array([0.035, 0.030, 0.028], dtype=np.float32) + slag = np.array([0.22, 0.16, 0.14], dtype=np.float32) * (0.8 + 0.4 * ripples[..., None]) + molten_lip = np.array([0.46, 0.38, 0.32], dtype=np.float32) + + col = carbon * (1.0 - bowl_m[..., None]) + slag * bowl_m[..., None] + col = col * (1.0 - rim_m[..., None] * 0.7) + molten_lip * (rim_m[..., None] * 0.7) + + alpha = np.clip(np.maximum(bowl_m, np.maximum(rim_m, scorch_m * 0.90)), 0.0, 1.0) + border = smoothstep(0.92, 0.78, np.maximum(np.abs(x), np.abs(y))) + alpha *= border + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = alpha + t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(bowl_m * 0.78 + rim_m * 0.85, 0.0, 1.0) + t["rough"] = np.clip(0.92 - bowl_m * 0.50 - rim_m * 0.45, 0.28, 0.96) + return t + + +def tile_15_blast_scorch(x: np.ndarray, y: np.ndarray) -> dict[str, np.ndarray]: + """(15) Radial blast scorch mark.""" + t = new_tile() + n1 = fbm(x, y, 6.0, 4, seed=1601) + n2 = fbm(x, y, 20.0, 4, seed=1602) + ang = np.arctan2(y, x) + r = np.sqrt(x * x + y * y) + + # Radial blast rays + rays = 0.55 + 0.45 * value_noise(np.cos(ang) * 3.0, np.sin(ang) * 3.0, 3.5, seed=1603) + rays *= (0.7 + 0.3 * np.sin(ang * 11.0 + n2 * 3.0)) + r_eff = r / np.maximum(rays, 0.35) + + scorch = smoothstep(0.95, 0.08, r_eff) * (0.65 + 0.35 * n1) + pock = smoothstep(0.24, 0.05, r + 0.05 * (n2 - 0.5)) + h = 1.0 - 0.45 * pock - 0.04 * scorch + + soot = np.array([0.032, 0.028, 0.025], dtype=np.float32) + ash = np.array([0.11, 0.095, 0.082], dtype=np.float32) + col = soot * (1.0 - pock[..., None] * 0.35) + ash * (pock[..., None] * 0.35) + + border = smoothstep(0.93, 0.78, np.maximum(np.abs(x), np.abs(y))) + alpha = np.clip(scorch * 0.92 * border, 0.0, 1.0) + + t["rgb"] = np.clip(col, 0.0, 1.0) + t["alpha"] = alpha + t["height"] = np.where(alpha > 0.01, np.clip(h, 0.0, 1.0), 1.0) + t["metal"] = np.clip(0.05 + 0.25 * pock, 0.0, 1.0) + t["rough"] = np.clip(0.94 - 0.20 * pock, 0.65, 0.98) + return t + + +# --------------------------------------------------------------------------- +# Normal map, AO, color dilation, and atlas assembly +# --------------------------------------------------------------------------- + +def compute_normal_map(height: np.ndarray, strength: float = 5.5) -> np.ndarray: + """Sobel tangent-space normal map matching OpenGL/Godot (+X right, +Y down, +Z out).""" + h = np.pad(height, 1, mode="edge") + # Sobel X (+right) and Y (+down) + dx = ((h[:-2, 2:] + 2.0 * h[1:-1, 2:] + h[2:, 2:]) + - (h[:-2, :-2] + 2.0 * h[1:-1, :-2] + h[2:, :-2])) * 0.125 + dy = ((h[2:, :-2] + 2.0 * h[2:, 1:-1] + h[2:, 2:]) + - (h[:-2, :-2] + 2.0 * h[:-2, 1:-1] + h[:-2, 2:])) * 0.125 + nx = -dx * strength + ny = -dy * strength + nz = np.ones_like(nx) + inv_len = 1.0 / np.sqrt(nx * nx + ny * ny + nz * nz + 1e-12) + return np.stack([nx * inv_len * 0.5 + 0.5, + ny * inv_len * 0.5 + 0.5, + nz * inv_len * 0.5 + 0.5], axis=-1) + + +def compute_height_ao(height: np.ndarray) -> np.ndarray: + """Fast multi-radius horizon/cavity AO from the heightfield.""" + ao = np.ones_like(height, dtype=np.float32) + dirs = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)] + radii = (2, 5, 10) + occ_sum = np.zeros_like(height, dtype=np.float32) + count = 0 + h_pad = np.pad(height, 12, mode="edge") + H, W = height.shape + for r in radii: + for dx, dy in dirs: + ox = 12 + dx * r + oy = 12 + dy * r + sample_h = h_pad[oy : oy + H, ox : ox + W] + diff = np.maximum(sample_h - height, 0.0) + occ_sum += np.clip(diff * 2.8, 0.0, 1.0) + count += 1 + cavity = occ_sum / float(count) + # Also darken deep recesses naturally + ao = np.clip((1.0 - cavity * 1.35) * (0.30 + 0.70 * height), 0.08, 1.0) + return ao + + +def dilate_albedo(rgb: np.ndarray, alpha: np.ndarray, steps: int = 8) -> np.ndarray: + """Propagate opaque RGB into transparent pixels to eliminate bilinear dark fringes.""" + out = rgb.copy() + mask = alpha > 0.04 + for _ in range(steps): + if np.all(mask): + break + acc = np.zeros_like(out) + wsum = np.zeros(mask.shape, dtype=np.float32) + p_rgb = np.pad(out, ((1, 1), (1, 1), (0, 0)), mode="edge") + p_m = np.pad(mask.astype(np.float32), ((1, 1), (1, 1)), mode="edge") + H, W = mask.shape + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + if dx == 0 and dy == 0: + continue + m_nb = p_m[1 + dy : 1 + dy + H, 1 + dx : 1 + dx + W] + acc += p_rgb[1 + dy : 1 + dy + H, 1 + dx : 1 + dx + W] * m_nb[..., None] + wsum += m_nb + fill = (~mask) & (wsum > 0.0) + out[fill] = acc[fill] / wsum[fill, None] + mask = mask | fill + return out + + +def main() -> int: + OUT_DIR.mkdir(parents=True, exist_ok=True) + x, y = tile_coords() + + builders = [ + tile_00_louvered_vent, + tile_01_bolted_hatch, + tile_02_fastener_strip, + tile_03_intake_grille, + tile_04_rivet_seam, + tile_05_welded_patch, + tile_06_lift_lug, + tile_07_hazard_chevron, + tile_08_stencil_03, + tile_09_stencil_07, + tile_10_radiation_warning, + tile_11_faction_emblem, + tile_12_ap_penetration, + tile_13_shrapnel_gouge, + tile_14_plasma_crater, + tile_15_blast_scorch, + ] + + atlas_albedo = np.zeros((ATLAS_SIZE, ATLAS_SIZE, 4), dtype=np.uint8) + atlas_normal = np.zeros((ATLAS_SIZE, ATLAS_SIZE, 3), dtype=np.uint8) + atlas_ormh = np.zeros((ATLAS_SIZE, ATLAS_SIZE, 4), dtype=np.uint8) + + for idx, fn in enumerate(builders): + row = idx // GRID + col = idx % GRID + t = fn(x, y) + + rgb_dilated = dilate_albedo(t["rgb"], t["alpha"], steps=12) + nrm = compute_normal_map(t["height"], strength=6.0) + ao = compute_height_ao(t["height"]) + + y0, y1 = row * TILE_SIZE, (row + 1) * TILE_SIZE + x0, x1 = col * TILE_SIZE, (col + 1) * TILE_SIZE + + albedo_rgba = np.dstack([rgb_dilated, t["alpha"]]) + ormh_rgba = np.dstack([ao, t["rough"], t["metal"], t["height"]]) + + atlas_albedo[y0:y1, x0:x1] = np.clip(np.round(albedo_rgba * 255.0), 0, 255).astype(np.uint8) + atlas_normal[y0:y1, x0:x1] = np.clip(np.round(nrm * 255.0), 0, 255).astype(np.uint8) + atlas_ormh[y0:y1, x0:x1] = np.clip(np.round(ormh_rgba * 255.0), 0, 255).astype(np.uint8) + + Image.fromarray(atlas_albedo, mode="RGBA").save(OUT_DIR / "decal_atlas_albedo.png") + Image.fromarray(atlas_normal, mode="RGB").save(OUT_DIR / "decal_atlas_normal.png") + Image.fromarray(atlas_ormh, mode="RGBA").save(OUT_DIR / "decal_atlas_ormh.png") + + print(f"Wrote 1024x1024 decal atlas textures to {OUT_DIR}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/decals/previews/visual_substrate_preview.png b/tools/decals/previews/visual_substrate_preview.png new file mode 100644 index 0000000..5ded766 Binary files /dev/null and b/tools/decals/previews/visual_substrate_preview.png differ diff --git a/tools/vehicles/bake_vertex_weathering.py b/tools/vehicles/bake_vertex_weathering.py new file mode 100644 index 0000000..068c2f9 --- /dev/null +++ b/tools/vehicles/bake_vertex_weathering.py @@ -0,0 +1,556 @@ +"""Bake geometric weathering vertex attributes (COLOR_0) into Brokkr vehicle GLBs. + +Writes COLOR_0 (VEC4 normalized UNSIGNED_BYTE) onto every mesh primitive: + R = geometric cavity AO (0 = deep crevice, 1 = open exposed face) + G = convex dihedral edge curvature (0 = flat, 1 = sharp exposed edge) + B = connected-component per-island hash (0..1) + A = normalized rest-pose height above minY (meters / 6.0, clamped 0..1) + +Pure numpy + struct; runs in < 1s per vehicle and is idempotent on re-run. +Preserves all glTF nodes, transforms, materials, hardpoint anchors, joints, and bounds. + +Usage: + python tools/vehicles/bake_vertex_weathering.py paladin jackal + python tools/vehicles/bake_vertex_weathering.py --all +""" +from __future__ import annotations + +import argparse +import json +import math +import struct +import time +from pathlib import Path +from typing import Any + +import numpy as np + +REPO_ROOT = Path(__file__).resolve().parents[2] +VEHICLES_DIR = REPO_ROOT / "assets" / "vehicles" + +ALL_VEHICLES = ( + "jackal", "mule", "ferret", "hornet", "mammoth", "ironclad", "anvil", "condor", + "breaker", "paladin", "raptor", "manticore", "bastion", "spectre", "kestrel", +) + + +# --------------------------------------------------------------------------- +# glTF / GLB helpers +# --------------------------------------------------------------------------- + +def _node_local_matrix(node: dict[str, Any]) -> np.ndarray: + if "matrix" in node: + return np.array(node["matrix"], dtype=np.float64).reshape(4, 4).T + m = np.eye(4, dtype=np.float64) + if "scale" in node: + sx, sy, sz = node["scale"] + m = m @ np.diag([sx, sy, sz, 1.0]) + if "rotation" in node: + qx, qy, qz, qw = node["rotation"] + xx, yy, zz = qx * qx, qy * qy, qz * qz + xy, xz, yz = qx * qy, qx * qz, qy * qz + wx, wy, wz = qw * qx, qw * qy, qw * qz + r = np.array([ + [1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy), 0.0], + [2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx), 0.0], + [2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy), 0.0], + [0.0, 0.0, 0.0, 1.0], + ], dtype=np.float64) + m = r @ m + if "translation" in node: + tx, ty, tz = node["translation"] + m[:3, 3] = [tx, ty, tz] + return m + + +def _read_accessor( + accessors: list[dict[str, Any]], + buffer_views: list[dict[str, Any]], + bin_blob: bytes, + acc_idx: int, +) -> np.ndarray: + acc = accessors[acc_idx] + bv = buffer_views[acc["bufferView"]] + off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0) + count = acc["count"] + ct = acc["componentType"] + typ = acc["type"] + if typ == "VEC3" and ct == 5126: + stride = bv.get("byteStride", 12) + if stride == 12: + return np.frombuffer(bin_blob, dtype=" float: + x = (a * 0x9E3779B97F4A7C15 + b * 0xBF58476D1CE4E5B9 + c * 0x94D049BB133111EB) & 0xFFFFFFFFFFFFFFFF + x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & 0xFFFFFFFFFFFFFFFF + x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & 0xFFFFFFFFFFFFFFFF + x = x ^ (x >> 31) + return float((x >> 40) & 0xFFFFFF) / float(0x1000000) + + +# --------------------------------------------------------------------------- +# Fast geometric operators (pure numpy) +# --------------------------------------------------------------------------- + +def _weld_positions(pos: np.ndarray) -> tuple[np.ndarray, int]: + """Quantize positions to 0.1 mm and return (weld_id_per_vert, unique_count).""" + q = np.round(pos * 10000.0).astype(np.int64) + # View rows as structured void for fast single-pass np.unique + q_contig = np.ascontiguousarray(q) + view = q_contig.view([("x", np.int64), ("y", np.int64), ("z", np.int64)]).ravel() + _, inv = np.unique(view, return_inverse=True) + return inv.astype(np.int64), int(inv.max()) + 1 if len(inv) else 0 + + +def _connected_components(n_weld: int, tris_weld: np.ndarray) -> np.ndarray: + """Fast union-find connected components on welded vertex indices.""" + parent = list(range(n_weld)) + + def find(x: int) -> int: + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + + for a, b, c in tris_weld.tolist(): + ra, rb, rc = find(a), find(b), find(c) + if ra != rb: + parent[rb] = ra + if ra != rc: + parent[rc] = ra + + roots = np.empty(n_weld, dtype=np.int64) + root_map: dict[int, int] = {} + nxt = 0 + for i in range(n_weld): + r = find(i) + cid = root_map.get(r) + if cid is None: + cid = nxt + root_map[r] = cid + nxt += 1 + roots[i] = cid + return roots + + +def _dihedral_edge_and_crevice( + pos: np.ndarray, + nrm: np.ndarray, + tris: np.ndarray, + weld_id: np.ndarray, + n_weld: int, +) -> tuple[np.ndarray, np.ndarray]: + """Compute (convex_edge_curvature, local_concave_ao) per vertex.""" + edge_out = np.zeros(len(pos), dtype=np.float32) + conc_ao = np.ones(len(pos), dtype=np.float32) + if len(tris) == 0 or n_weld == 0: + return edge_out, conc_ao + + v0 = pos[tris[:, 0]] + v1 = pos[tris[:, 1]] + v2 = pos[tris[:, 2]] + fn_raw = np.cross(v1 - v0, v2 - v0) + fn_len = np.linalg.norm(fn_raw, axis=1, keepdims=True) + valid_tri = (fn_len[:, 0] > 1e-12) + fn = np.divide(fn_raw, np.maximum(fn_len, 1e-12)) + fc = (v0 + v1 + v2) / 3.0 + + wt = weld_id[tris] # (T, 3) + t_idx = np.arange(len(tris), dtype=np.int64) + + e0 = np.stack([np.minimum(wt[:, 0], wt[:, 1]), np.maximum(wt[:, 0], wt[:, 1]), t_idx], axis=1) + e1 = np.stack([np.minimum(wt[:, 1], wt[:, 2]), np.maximum(wt[:, 1], wt[:, 2]), t_idx], axis=1) + e2 = np.stack([np.minimum(wt[:, 2], wt[:, 0]), np.maximum(wt[:, 2], wt[:, 0]), t_idx], axis=1) + edges = np.concatenate([e0, e1, e2], axis=0) + # Remove degenerate edges + edges = edges[edges[:, 0] != edges[:, 1]] + if len(edges) == 0: + return edge_out, conc_ao + + order = np.lexsort((edges[:, 1], edges[:, 0])) + edges = edges[order] + + same = (edges[:-1, 0] == edges[1:, 0]) & (edges[:-1, 1] == edges[1:, 1]) + idx_a = edges[:-1, 2][same] + idx_b = edges[1:, 2][same] + eu = edges[:-1, 0][same] + ev = edges[:-1, 1][same] + + both_valid = valid_tri[idx_a] & valid_tri[idx_b] + idx_a, idx_b, eu, ev = idx_a[both_valid], idx_b[both_valid], eu[both_valid], ev[both_valid] + + weld_convex_sum = np.zeros(n_weld, dtype=np.float32) + weld_convex_cnt = np.zeros(n_weld, dtype=np.float32) + weld_convex_max = np.zeros(n_weld, dtype=np.float32) + weld_concave = np.zeros(n_weld, dtype=np.float32) + + if len(idx_a) > 0: + na = fn[idx_a] + nb = fn[idx_b] + dots = np.clip(np.sum(na * nb, axis=1), -1.0, 1.0) + angles = np.arccos(dots) # radians [0, pi] + delta_c = fc[idx_b] - fc[idx_a] + # Convex if triangle B center lies behind triangle A's front plane + proj_a = np.sum(na * delta_c, axis=1) + proj_b = np.sum(nb * (-delta_c), axis=1) + sign_val = 0.5 * (proj_a + proj_b) + + is_convex = (sign_val < -1e-5) & (angles > 0.55) + is_concave = (sign_val > 1e-5) & (angles > 0.28) + + convex_val = np.where(is_convex, np.clip((angles - 0.55) / 0.95, 0.0, 1.0), 0.0).astype(np.float32) + concave_val = np.where(is_concave, np.clip((angles - 0.28) / 1.20, 0.0, 1.0), 0.0).astype(np.float32) + + np.add.at(weld_convex_sum, eu, convex_val) + np.add.at(weld_convex_sum, ev, convex_val) + np.add.at(weld_convex_cnt, eu, 1.0) + np.add.at(weld_convex_cnt, ev, 1.0) + np.maximum.at(weld_convex_max, eu, convex_val) + np.maximum.at(weld_convex_max, ev, convex_val) + np.maximum.at(weld_concave, eu, concave_val) + np.maximum.at(weld_concave, ev, concave_val) + + weld_convex_mean = np.divide(weld_convex_sum, np.maximum(weld_convex_cnt, 1.0)) + weld_convex = 0.55 * weld_convex_mean + 0.45 * weld_convex_max + edge_out = weld_convex[weld_id] + conc_ao = np.clip(1.0 - 0.55 * weld_concave[weld_id], 0.35, 1.0).astype(np.float32) + return edge_out, conc_ao + + +def _compute_voxel_ao( + all_wpos: np.ndarray, + all_wnrm: np.ndarray, + sample_pts: np.ndarray, +) -> np.ndarray: + """Fast 3D spatial occupancy ray-marched AO across the whole rest-pose vehicle.""" + if len(all_wpos) == 0 or len(sample_pts) == 0: + return np.ones(len(all_wpos), dtype=np.float32) + + bmin = sample_pts.min(axis=0) + bmax = sample_pts.max(axis=0) + extent = np.maximum(bmax - bmin, 0.2) + max_ext = float(extent.max()) + voxel = max(0.075, max_ext / 84.0) + pad = voxel * 8.0 + origin = bmin - pad + dims = np.ceil((extent + 2.0 * pad) / voxel).astype(np.int64) + nx, ny, nz = int(dims[0]), int(dims[1]), int(dims[2]) + + grid = np.zeros((nx, ny, nz), dtype=np.uint8) + idx = np.floor((sample_pts - origin) / voxel).astype(np.int64) + idx[:, 0] = np.clip(idx[:, 0], 0, nx - 1) + idx[:, 1] = np.clip(idx[:, 1], 0, ny - 1) + idx[:, 2] = np.clip(idx[:, 2], 0, nz - 1) + grid[idx[:, 0], idx[:, 1], idx[:, 2]] = 1 + grid_flat = grid.ravel() + sy = nz + sx = ny * nz + + # 18 well-distributed unit ray directions (6 axial + 12 diagonal) + raw_dirs = [ + (1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1), + (1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0), + (1, 0, 1), (-1, 0, 1), (1, 0, -1), (-1, 0, -1), + (0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1), + ] + dirs = np.array(raw_dirs, dtype=np.float32) + dirs /= np.linalg.norm(dirs, axis=1, keepdims=True) + + # Start rays slightly outside the vertex surface to prevent self-hit + p0 = all_wpos.astype(np.float32) + all_wnrm.astype(np.float32) * (1.35 * voxel) + steps = np.array([0.14, 0.25, 0.38, 0.54, 0.72], dtype=np.float32) + step_weights = np.array([1.0, 0.85, 0.65, 0.45, 0.28], dtype=np.float32) + + nrm_f = all_wnrm.astype(np.float32) + inv_vox = np.float32(1.0 / voxel) + orig_f = origin.astype(np.float32) + + occ_acc = np.zeros(len(all_wpos), dtype=np.float32) + weight_acc = np.zeros(len(all_wpos), dtype=np.float32) + + for d in dirs: + cos_w = np.maximum(nrm_f @ d, 0.0) + active = cos_w > 0.08 + if not np.any(active): + continue + w_act = cos_w[active] + p_act = p0[active] + hit_max = np.zeros(len(p_act), dtype=np.float32) + + for st, sw in zip(steps, step_weights): + q = p_act + d * st + gx = np.floor((q[:, 0] - orig_f[0]) * inv_vox).astype(np.int64) + gy = np.floor((q[:, 1] - orig_f[1]) * inv_vox).astype(np.int64) + gz = np.floor((q[:, 2] - orig_f[2]) * inv_vox).astype(np.int64) + inside = (gx >= 0) & (gx < nx) & (gy >= 0) & (gy < ny) & (gz >= 0) & (gz < nz) + if not np.any(inside): + continue + flat_i = np.where(inside, gx * sx + gy * sy + gz, 0) + occ = grid_flat[flat_i] & inside + hit_max = np.maximum(hit_max, occ.astype(np.float32) * sw) + + occ_acc[active] += hit_max * w_act + weight_acc[active] += w_act + + raw_occ = np.divide(occ_acc, np.maximum(weight_acc, 1e-4)) + return np.clip(1.0 - raw_occ * 0.92, 0.06, 1.0).astype(np.float32) + + +# --------------------------------------------------------------------------- +# GLB baker +# --------------------------------------------------------------------------- + +def bake_glb(glb_path: Path) -> dict[str, Any]: + t0 = time.perf_counter() + data = glb_path.read_bytes() + magic, version, total_len = struct.unpack_from(" None: + node = nodes[node_idx] + world = parent_mat @ _node_local_matrix(node) + if "mesh" in node and node["mesh"] not in mesh_world: + mesh_world[node["mesh"]] = world + for c in node.get("children", []): + walk(c, world) + + ident = np.eye(4, dtype=np.float64) + for r_idx in root_indices: + walk(r_idx, ident) + + # Pass 1: Read all primitives, compute rest-pose world positions/normals, edges, islands, and surface samples + prim_records: list[dict[str, Any]] = [] + wpos_chunks: list[np.ndarray] = [] + wnrm_chunks: list[np.ndarray] = [] + sample_chunks: list[np.ndarray] = [] + global_min_y = math.inf + vert_cursor = 0 + + for m_idx, mesh in enumerate(meshes): + wmat = mesh_world.get(m_idx, ident) + rot_lin = wmat[:3, :3] + det = float(np.linalg.det(rot_lin)) + nrm_mat = np.linalg.inv(rot_lin).T if abs(det) > 1e-12 else rot_lin + + for p_idx, prim in enumerate(mesh.get("primitives", [])): + attrs = prim.get("attributes", {}) + if "POSITION" not in attrs: + continue + pos = _read_accessor(accessors, buffer_views, bin_blob, attrs["POSITION"]) + vcount = len(pos) + if vcount == 0: + continue + if "NORMAL" in attrs: + nrm = _read_accessor(accessors, buffer_views, bin_blob, attrs["NORMAL"]) + else: + nrm = np.tile(np.array([0.0, 1.0, 0.0]), (vcount, 1)) + + if prim.get("mode", 4) == 4: + if "indices" in prim: + tris = _read_accessor(accessors, buffer_views, bin_blob, prim["indices"]).reshape(-1, 3) + else: + tris = np.arange((vcount // 3) * 3, dtype=np.int64).reshape(-1, 3) + else: + tris = np.empty((0, 3), dtype=np.int64) + + wpos = pos @ rot_lin.T + wmat[:3, 3] + wnrm = nrm @ nrm_mat.T + wnrm_len = np.linalg.norm(wnrm, axis=1, keepdims=True) + wnrm = np.divide(wnrm, np.maximum(wnrm_len, 1e-12)) + + global_min_y = min(global_min_y, float(wpos[:, 1].min())) + + weld_id, n_weld = _weld_positions(pos) + if len(tris) > 0 and n_weld > 0: + comp_weld = _connected_components(n_weld, weld_id[tris]) + max_c = int(comp_weld.max()) + 1 + comp_hashes = np.array([_splitmix64_hash(m_idx, p_idx, c) for c in range(max_c)], dtype=np.float32) + island_hash = comp_hashes[comp_weld[weld_id]] + else: + island_hash = np.full(vcount, _splitmix64_hash(m_idx, p_idx, 0), dtype=np.float32) + + edge_curv, local_conc_ao = _dihedral_edge_and_crevice(pos, nrm, tris, weld_id, n_weld) + + # Surface samples for voxel AO (vertices + face centroids + edge midpoints) + sample_chunks.append(wpos) + if len(tris) > 0: + tv0, tv1, tv2 = wpos[tris[:, 0]], wpos[tris[:, 1]], wpos[tris[:, 2]] + sample_chunks.append((tv0 + tv1 + tv2) / 3.0) + sample_chunks.append((tv0 + tv1) * 0.5) + sample_chunks.append((tv1 + tv2) * 0.5) + sample_chunks.append((tv2 + tv0) * 0.5) + + wpos_chunks.append(wpos) + wnrm_chunks.append(wnrm) + prim_records.append({ + "prim": prim, + "vcount": vcount, + "vstart": vert_cursor, + "edge": edge_curv, + "local_ao": local_conc_ao, + "island": island_hash, + }) + vert_cursor += vcount + + if not prim_records: + raise RuntimeError(f"No mesh primitives found in {glb_path}") + + all_wpos = np.concatenate(wpos_chunks, axis=0) + all_wnrm = np.concatenate(wnrm_chunks, axis=0) + all_samples = np.concatenate(sample_chunks, axis=0) + + # Pass 2: Global 3D voxel ambient occlusion + voxel_ao = _compute_voxel_ao(all_wpos, all_wnrm, all_samples) + rest_height = np.clip((all_wpos[:, 1] - global_min_y) / 6.0, 0.0, 1.0).astype(np.float32) + + # Pass 3: Append COLOR_0 bufferViews & accessors cleanly + new_bin = bytearray(bin_blob) + if len(new_bin) % 4 != 0: + new_bin.extend(b"\x00" * (4 - (len(new_bin) % 4))) + + ao_vals = [] + edge_vals = [] + for rec in prim_records: + s, n = rec["vstart"], rec["vcount"] + ao = np.clip(voxel_ao[s : s + n] * rec["local_ao"], 0.0, 1.0) + edge = rec["edge"] + island = rec["island"] + h = rest_height[s : s + n] + ao_vals.append(ao) + edge_vals.append(edge) + + rgba = np.stack([ao, edge, island, h], axis=1) + rgba_u8 = np.clip(np.round(rgba * 255.0), 0, 255).astype(np.uint8) + raw_bytes = rgba_u8.tobytes() + + byte_off = len(new_bin) + new_bin.extend(raw_bytes) + if len(new_bin) % 4 != 0: + new_bin.extend(b"\x00" * (4 - (len(new_bin) % 4))) + + bv_idx = len(buffer_views) + buffer_views.append({ + "buffer": 0, + "byteOffset": byte_off, + "byteLength": len(raw_bytes), + "target": 34962, # ARRAY_BUFFER + }) + acc_idx = len(accessors) + accessors.append({ + "bufferView": bv_idx, + "byteOffset": 0, + "componentType": 5121, # UNSIGNED_BYTE + "normalized": True, + "count": n, + "type": "VEC4", + }) + rec["prim"]["attributes"]["COLOR_0"] = acc_idx + + gltf["buffers"][0]["byteLength"] = len(new_bin) + gltf.setdefault("extras", {}) + gltf["extras"]["rtd.color0_base_bin_len"] = base_bin_len + gltf["extras"]["rtd.color0_base_bv_count"] = base_bv_count + gltf["extras"]["rtd.color0_base_acc_count"] = base_acc_count + + json_bytes = json.dumps(gltf, separators=(",", ":")).encode("utf-8") + if len(json_bytes) % 4 != 0: + json_bytes += b" " * (4 - (len(json_bytes) % 4)) + if len(new_bin) % 4 != 0: + new_bin.extend(b"\x00" * (4 - (len(new_bin) % 4))) + + total_out = 12 + 8 + len(json_bytes) + 8 + len(new_bin) + out = bytearray() + out.extend(struct.pack(" 0.3).mean()), + "size_kib": len(out) / 1024.0, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description="Bake COLOR_0 weathering attributes onto vehicle GLBs.") + parser.add_argument("vehicles", nargs="*", help="Vehicle IDs to bake (e.g. paladin jackal).") + parser.add_argument("--all", action="store_true", help="Bake all 15 vehicles.") + args = parser.parse_args() + + targets = ALL_VEHICLES if args.all else (tuple(args.vehicles) if args.vehicles else ("paladin", "jackal")) + for vid in targets: + glb_path = VEHICLES_DIR / vid / f"{vid}.glb" + if not glb_path.is_file(): + raise FileNotFoundError(f"Missing vehicle GLB: {glb_path}") + stats = bake_glb(glb_path) + print( + f"Baked {vid:10s} | verts={stats['verts']:6d} | prims={stats['prims']:3d} " + f"| {stats['elapsed_s']:.3f}s | ao=[{stats['ao_min']:.2f}, mean={stats['ao_mean']:.2f}] " + f"| edge>0.3={stats['edge_gt_03']*100:.1f}% | {stats['size_kib']:.1f} KiB" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/vehicles/build_anvil.py b/tools/vehicles/build_anvil.py new file mode 100644 index 0000000..871f408 --- /dev/null +++ b/tools/vehicles/build_anvil.py @@ -0,0 +1,468 @@ +"""Build the Anvil (Heavy Quad-Track Siege Tank) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_quad_track_pod(name: str, side: float, y_center: float, is_front: bool, parent) -> None: + """Build one heavy articulated armored quad-track pod grounded at Z = 0.""" + pod_x = side * 1.56 + pod = vc.make_empty(name, parent=parent, location=(pod_x, y_center, 0.0)) + + rw_r = 0.27 + rw_z = rw_r + 0.045 + rw_ys = (-0.54, 0.0, 0.54) + front_y, front_z, front_r = -0.98, 0.54, 0.24 + rear_y, rear_z, rear_r = 0.98, 0.54, 0.24 + track_w = 0.62 + + # 3 roadwheels + front/rear sprockets + for i, ry in enumerate(rw_ys): + vc.make_tube_part( + f"{name}_rw_tire_{i}", rw_r, rw_r, track_w * 0.84, segments=14, + mat_name="rubber_dark", parent=pod, location=(-track_w * 0.42, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_rw_hub_{i}", rw_r * 0.64, rw_r * 0.64, track_w * 0.90, segments=10, + mat_name="olive_armor", parent=pod, location=(-track_w * 0.45, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_sproc_f", front_r, front_r, track_w * 0.80, segments=12, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.40, front_y, front_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_sproc_r", rear_r, rear_r, track_w * 0.80, segments=12, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.40, rear_y, rear_z), rotation_deg=(0.0, 90.0, 0.0), + ) + + # Track loop polyline in (y, z) + loop_yz: list[tuple[float, float]] = [] + for k in range(6): + ang = math.radians(100.0 + 135.0 * (k / 5.0)) + loop_yz.append((front_y + math.cos(ang) * (front_r + 0.03), front_z + math.sin(ang) * (front_r + 0.03))) + loop_yz.append((-0.54, 0.025)) + loop_yz.append((0.54, 0.025)) + for k in range(6): + ang = math.radians(-55.0 + 135.0 * (k / 5.0)) + loop_yz.append((rear_y + math.cos(ang) * (rear_r + 0.03), rear_z + math.sin(ang) * (rear_r + 0.03))) + loop_yz.append((0.46, 0.83)) + loop_yz.append((-0.46, 0.83)) + + path_3d = [[0.0, y, z] for (y, z) in loop_yz] + vc.make_swept_profile( + f"{name}_track_band", + "box", + 0.034, + track_w * 0.92, + 0.034, + path_3d, + up=[1.0, 0.0, 0.0], + mat_name="rubber_dark", + parent=pod, + closed=True, + ) + + pts = loop_yz + [loop_yz[0]] + segs = [math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]) for i in range(len(loop_yz))] + total_len = sum(segs) + n_shoes = 28 + + def build_shoes(bm: bmesh.types.BMesh) -> None: + for s_idx in range(n_shoes): + target_d = (s_idx / n_shoes) * total_len + acc = 0.0 + for i, sl in enumerate(segs): + if acc + sl >= target_d or i == len(segs) - 1: + t = (target_d - acc) / max(sl, 1e-6) + y0, z0 = pts[i] + y1, z1 = pts[i + 1] + py = y0 + (y1 - y0) * t + pz = z0 + (z1 - z0) * t + ang = math.atan2(z1 - z0, y1 - y0) + m = ( + Matrix.Translation((0.0, py, pz)) + @ Matrix.Rotation(ang, 4, "X") + @ Matrix.Diagonal((track_w, 0.11, 0.034, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + break + acc += sl + + vc.make_bmesh_object(f"{name}_shoes", build_shoes, "gunmetal", parent=pod) + + # Heavy sloped armored pod housing (top deck + chamfered nose/tail + outer bolted side skirts) + vc.make_box(f"{name}_cover_top", (track_w + 0.12, 1.98, 0.14), "olive_armor", parent=pod, location=(0.0, 0.0, 0.92), bevel=0.012) + vc.make_box(f"{name}_cover_f", (track_w + 0.12, 0.42, 0.14), "olive_armor", parent=pod, location=(0.0, -1.14, 0.80), rotation_deg=(36.0, 0.0, 0.0), bevel=0.01) + vc.make_box(f"{name}_cover_r", (track_w + 0.12, 0.42, 0.14), "olive_armor", parent=pod, location=(0.0, 1.14, 0.80), rotation_deg=(-36.0, 0.0, 0.0), bevel=0.01) + # Outer bolted track pod side skirt + skirt_pts = [ + [side * (track_w * 0.5 + 0.04), -1.12, 0.72], + [side * (track_w * 0.5 + 0.04), 1.12, 0.72], + [side * (track_w * 0.5 + 0.04), 0.98, 0.94], + [side * (track_w * 0.5 + 0.04), -0.98, 0.94], + [side * (track_w * 0.5 + 0.04), -0.74, 0.34], + [side * (track_w * 0.5 + 0.04), 0.74, 0.34], + [side * (track_w * 0.5 + 0.04), 1.12, 0.56], + [side * (track_w * 0.5 + 0.04), -1.12, 0.56], + ] + # Use clean trapezoidal slab for outer pod skirt with bolts + vc.make_plates( + { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": f"{name}_outer_skirt", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "slab": { + "at": [side * (track_w * 0.5 + 0.04), 0.0, 0.64], + "normal": [side, 0.0, 0.0], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -side, 0.0], + "outline": [[-1.08, -0.08], [-0.74, -0.32], [0.74, -0.32], [1.08, -0.08], [0.96, 0.28], [-0.96, 0.28]], + "thick": 0.055, + "taper": 0.012, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.025, "spacing": 0.34, "mat": "gunmetal", "params": "r=0.014"}, + ], + } + ], + }, + parent=pod, + ) + # Inner pod cheek & front headlight block + vc.make_box(f"{name}_inner_cheek", (0.06, 1.84, 0.48), "gunmetal", parent=pod, location=(-side * (track_w * 0.5 + 0.02), 0.0, 0.64), bevel=0.008) + if is_front: + vc.make_box(f"{name}_headlight_pod", (0.28, 0.20, 0.14), "gunmetal", parent=pod, location=(0.0, -1.04, 1.00), bevel=0.008) + vc.make_box(f"{name}_headlight_lens", (0.20, 0.05, 0.08), "smoked_glass", parent=pod, location=(0.0, -1.14, 1.00), bevel=0.004) + + +def build_anvil() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("AnvilRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. Central Lower Belly Tub, Ribbed Prow & Pod Outrigger Beams --- + vc.make_box("lower_tub", (2.14, 4.78, 0.64), "gunmetal", parent=chassis, location=(0.0, 0.04, 0.74), bevel=0.016) + # Corrugated lower prow armor ribs + vc.make_box("lower_prow_plate", (2.06, 0.44, 0.52), "olive_armor", parent=chassis, location=(0.0, -2.32, 0.74), rotation_deg=(24.0, 0.0, 0.0), bevel=0.012) + for rx in (-0.84, -0.56, -0.28, 0.0, 0.28, 0.56, 0.84): + vc.make_box(f"prow_rib_{rx:.2f}", (0.08, 0.14, 0.48), "gunmetal", parent=chassis, location=(rx, -2.50, 0.72), rotation_deg=(24.0, 0.0, 0.0), bevel=0.006) + # Outrigger pod axle beams + suspension rams + for p_tag, py in (("f", -1.48), ("r", 1.48)): + vc.make_box(f"pod_crossbeam_{p_tag}", (3.08, 0.58, 0.32), "gunmetal", parent=chassis, location=(0.0, py, 0.62), bevel=0.012) + for side in (-1.0, 1.0): + s_tag = "L" if side > 0 else "R" + vc.make_ram_span( + f"pod_strut_{p_tag}_{s_tag}", + [side * 1.04, py, 1.02], + [side * 1.38, py, 0.74], + body_r=0.048, + rod_r=0.026, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + + # --- 2. Wide Sloped Composite Hull & Tall Casemate Superstructure (Brokkr plate.v0) --- + hull_pts = [ + # Lower hull belt above track pods + [-1.18, -2.38, 0.96], [1.18, -2.38, 0.96], + [-1.22, -0.50, 1.02], [1.22, -0.50, 1.02], + [-1.22, 2.58, 1.02], [1.22, 2.58, 1.02], + # Tall casemate roof (y = -0.48 .. +1.28, z = 1.98) + [-1.16, -0.48, 1.98], [1.16, -0.48, 1.98], + [-1.18, 1.28, 1.98], [1.18, 1.28, 1.98], + # Stepped rear engine deck (y = +1.30 .. +2.64, z = 1.70) + [-1.18, 1.32, 1.70], [1.18, 1.32, 1.70], + [-1.14, 2.64, 1.68], [1.14, 2.64, 1.68], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "anvil_hull", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": hull_pts, + "clad": { + "mat": "olive_armor", + "facets": [{"n": [0.0, -0.45, 0.89], "cos": 0.86}], + "min_area": 0.22, + "lifts": [0.008, 0.015], + "inset": 0.07, + "gap": 0.020, + "split": 0.88, + "seed": 901, + "bolt_r": 0.014, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + }, + # Heavy bolted forward superstructure cheek plates + { + "name": "anvil_casemate_cheek", + "mat": "olive_armor", + "bevel": 0.010, + "sides": "both", + "mirror": False, + "slab": { + "at": [1.20, 0.42, 1.54], + "normal": [1.0, 0.0, 0.0], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.86, -0.34], [0.86, -0.34], [0.78, 0.36], [-0.52, 0.36]], + "thick": 0.055, + "taper": 0.014, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.03, "spacing": 0.34, "mat": "gunmetal", "params": "r=0.014"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Sponson weapon shelves (left/right forward flanks) + rear radiator housing + driver periscope + vc.make_box("driver_periscope", (0.58, 0.18, 0.11), "smoked_glass", parent=chassis, location=(0.0, -0.78, 1.84), rotation_deg=(-24.0, 0.0, 0.0), bevel=0.006) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"sponson_shelf_{tag}", (0.48, 0.72, 0.24), "gunmetal", parent=chassis, location=(side * 1.24, -0.76, 1.42), bevel=0.01) + vc.make_box(f"rad_housing_{tag}", (0.16, 1.18, 0.62), "olive_armor", parent=chassis, location=(side * 1.20, 1.50, 1.42), bevel=0.01) + vc.make_box(f"tow_shackle_{tag}", (0.09, 0.16, 0.16), "signal_orange", parent=chassis, location=(side * 0.68, -2.54, 0.64), bevel=0.006) + + # --- 3. 4 Articulated Quad-Track Pods --- + _build_quad_track_pod("pod_fl", 1.0, -1.48, True, chassis) + _build_quad_track_pod("pod_fr", -1.0, -1.48, True, chassis) + _build_quad_track_pod("pod_rl", 1.0, 1.48, False, chassis) + _build_quad_track_pod("pod_rr", -1.0, 1.48, False, chassis) + + # --- 4. Towering Rear Exhaust Stacks --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + for s_idx, sy in enumerate((2.40, 2.62)): + vc.make_swept_tube( + f"exhaust_stack_{tag}_{s_idx}", + [ + [side * 0.96, sy - 0.14, 1.48], + [side * 1.04, sy, 1.66], + [side * 1.04, sy, 2.86], + [side * 1.04, sy + 0.14, 2.98], + ], + 0.072, + segments=12, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.06, + ) + vc.make_tube_part( + f"exhaust_shroud_{tag}_{s_idx}", + 0.105, + 0.105, + 0.68, + segments=10, + inner0=0.09, + inner1=0.09, + mat_name="olive_armor", + parent=chassis, + location=(side * 1.04, sy, 1.76), + ) + + # --- 5. Broad Reinforced Siege Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, 0.04, 1.98)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest = [{"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}] + + vc.make_tube_part("turret_race", 0.88, 0.94, 0.10, segments=24, mat_name="gunmetal", parent=turret_pivot) + + turret_pts = [ + [-0.76, -0.92, 0.10], [0.76, -0.92, 0.10], + [0.98, -0.22, 0.10], [0.88, 1.04, 0.10], + [-0.88, 1.04, 0.10], [-0.98, -0.22, 0.10], + [-0.58, -0.70, 0.62], [0.58, -0.70, 0.62], + [0.76, -0.14, 0.62], [0.68, 0.86, 0.62], + [-0.68, 0.86, 0.62], [-0.76, -0.14, 0.62], + ] + turret_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "anvil_turret_shell", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": turret_pts, + }, + { + "name": "anvil_turret_cheek", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.86, 0.16, 0.34], + "normal": [0.94, 0.0, 0.34], + "up": [-0.34, 0.0, 0.94], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.58, -0.18], [0.58, -0.18], [0.46, 0.18], [-0.46, 0.18]], + "thick": 0.055, + "taper": 0.014, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.025, "spacing": 0.26, "mat": "gunmetal", "params": "r=0.013"}, + ], + }, + ], + } + vc.make_plates(turret_doc, parent=turret_pivot) + + vc.make_box("turret_mantlet_bar", (1.12, 0.22, 0.24), "gunmetal", parent=turret_pivot, location=(0.0, -0.84, 0.34), bevel=0.012) + vc.make_box("turret_bustle", (1.28, 0.46, 0.38), "olive_armor", parent=turret_pivot, location=(0.0, 1.10, 0.38), bevel=0.012) + vc.make_tube_part("commander_cupola", 0.22, 0.24, 0.11, segments=14, mat_name="olive_armor", parent=turret_pivot, location=(0.0, 0.48, 0.62)) + vc.make_box("turret_optic", (0.20, 0.22, 0.16), "smoked_glass", parent=turret_pivot, location=(0.0, -0.46, 0.68), bevel=0.008) + + # --- 6. Visible Exterior Hardpoints (5x6 Dorsal Grid) --- + # 1) hp.armor.front (0,0, 5x1) on steep front glacis + vc.add_hardpoint_slot( + "hp.armor.front", + "armor", + parent=chassis, + location=(0.0, -1.48, 1.46), + rotation_deg=(62.0, 0.0, 0.0), + size=(1.88, 0.42, 0.10), + plinth_depth=0.04, + ) + # 2 & 3) hp.weapon.sponson_l (0,1, 1x2) & hp.weapon.sponson_r (4,1, 1x2) + vc.add_hardpoint_slot( + "hp.weapon.sponson_l", + "weapon", + parent=chassis, + location=(1.26, -0.76, 1.54), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.50, 0.50, 0.09), + ) + vc.add_hardpoint_slot( + "hp.weapon.sponson_r", + "weapon", + parent=chassis, + location=(-1.26, -0.76, 1.54), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.50, 0.50, 0.09), + ) + # 4 & 5) hp.weapon.siege_l (1,1, 1x2) & hp.weapon.siege_r (3,1, 1x2) on turret roof + vc.add_hardpoint_slot( + "hp.weapon.siege_l", + "weapon", + parent=turret_pivot, + location=(0.42, -0.04, 0.63), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.62, 0.11), + ) + vc.add_hardpoint_slot( + "hp.weapon.siege_r", + "weapon", + parent=turret_pivot, + location=(-0.42, -0.04, 0.63), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.62, 0.11), + ) + # 6) hp.armor.sides (2,1, 1x2) on right (-X) casemate cheek + vc.add_hardpoint_slot( + "hp.armor.sides", + "armor", + parent=chassis, + location=(-1.20, 0.42, 1.54), + rotation_deg=(90.0, 0.0, -90.0), + size=(1.12, 0.34, 0.10), + plinth_depth=0.03, + ) + # 7) hp.engine.rear (1,3, 3x2) on sloped rear engine deck (y=1.98 -> hull surface z=1.825) + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 1.98, 1.815), + rotation_deg=(-12.5, 0.0, 0.0), + size=(1.42, 0.96, 0.15), + plinth_depth=0.04, + ) + # 8 & 9) hp.radiator.l (0,4, 1x2) & hp.radiator.r (4,4, 1x2) + vc.add_hardpoint_slot( + "hp.radiator.l", + "radiator", + parent=chassis, + location=(1.28, 1.50, 1.42), + rotation_deg=(90.0, 0.0, 90.0), + size=(1.04, 0.52, 0.13), + ) + vc.add_hardpoint_slot( + "hp.radiator.r", + "radiator", + parent=chassis, + location=(-1.28, 1.50, 1.42), + rotation_deg=(90.0, 0.0, -90.0), + size=(1.04, 0.52, 0.13), + ) + + # --- 7. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "anvil" / "anvil.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "anvil" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "anvil_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="anvil", + name="Anvil", + vehicle_class="Heavy Quad-Track Siege Tank", + grid_width=5, + grid_height=6, + mask=[ + "#####", + "#####", + "#####", + "#####", + "#####", + "#####", + ], + hardpoints=[ + {"id": "hp.armor.front", "kind": "armor", "x": 0, "y": 0, "w": 5, "h": 1, "modelNodeId": "hp.armor.front"}, + {"id": "hp.weapon.sponson_l", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.sponson_l"}, + {"id": "hp.weapon.siege_l", "kind": "weapon", "x": 1, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.siege_l"}, + {"id": "hp.armor.sides", "kind": "armor", "x": 2, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.armor.sides"}, + {"id": "hp.weapon.siege_r", "kind": "weapon", "x": 3, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.siege_r"}, + {"id": "hp.weapon.sponson_r", "kind": "weapon", "x": 4, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.sponson_r"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 1, "y": 3, "w": 3, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.l", "kind": "radiator", "x": 0, "y": 4, "w": 1, "h": 2, "modelNodeId": "hp.radiator.l"}, + {"id": "hp.radiator.r", "kind": "radiator", "x": 4, "y": 4, "w": 1, "h": 2, "modelNodeId": "hp.radiator.r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[anvil] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "anvil", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_anvil() diff --git a/tools/vehicles/build_condor.py b/tools/vehicles/build_condor.py new file mode 100644 index 0000000..b6d3e67 --- /dev/null +++ b/tools/vehicles/build_condor.py @@ -0,0 +1,508 @@ +"""Build the Condor (Heavy Quad-Thruster Assault VTOL) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_jet_nacelle( + name: str, + joint_id: str, + rotor_id: str, + side: float, + location: tuple[float, float, float], + scale: float, + tilt_deg: float, + parent, + joints_manifest: list[dict], +) -> None: + """Build a pivoting vectored-thrust armored jet nacelle with copper exhaust skirt and spinning turbine.""" + nacelle_pivot = vc.make_empty( + joint_id, + parent=parent, + location=location, + rotation_deg=(tilt_deg, 0.0, 0.0), + ) + vc.tag_joint(nacelle_pivot, joint_id, [1.0, 0.0, 0.0], -45.0, 75.0) + joints_manifest.append({"id": joint_id, "axis": [1.0, 0.0, 0.0], "min": -45.0, "max": 75.0}) + + r_in = 0.31 * scale + r_out = 0.43 * scale + # Armored olive intake shroud + jet housing + shroud_prof = [ + [r_in, -0.18 * scale], + [r_out * 0.96, -0.18 * scale], + [r_out * 1.05, 0.02 * scale], + [r_out * 1.05, 0.34 * scale], + [r_out * 0.92, 0.44 * scale], + [r_in * 1.02, 0.44 * scale], + [r_in * 0.96, 0.26 * scale], + [r_in, -0.18 * scale], + ] + vc.make_lathe_part( + f"{name}_shroud", + shroud_prof[:-1], + segments=20, + loop=True, + smooth=True, + mat_name="olive_armor", + parent=nacelle_pivot, + ) + # Vectored copper thermal exhaust nozzle petals + nozzle_prof = [ + [r_in * 0.92, -0.44 * scale], + [r_out * 0.86, -0.44 * scale], + [r_out * 0.96, -0.18 * scale], + [r_in, -0.18 * scale], + ] + vc.make_lathe_part( + f"{name}_nozzle", + nozzle_prof, + segments=20, + loop=True, + smooth=True, + mat_name="copper_rad", + parent=nacelle_pivot, + ) + # Inner gunmetal stator vanes + outer hinge trunnion lug + for ang_deg in (0.0, 90.0): + vc.make_box( + f"{name}_stator_{int(ang_deg)}", + (r_in * 1.92, 0.04 * scale, 0.06 * scale), + "gunmetal", + parent=nacelle_pivot, + location=(0.0, 0.0, -0.16 * scale), + rotation_deg=(0.0, 0.0, ang_deg), + bevel=0.004, + ) + vc.make_box( + f"{name}_trunnion_lug", + (0.18 * scale, 0.28 * scale, 0.20 * scale), + "gunmetal", + parent=nacelle_pivot, + location=(-side * (r_out * 0.98), 0.0, 0.12 * scale), + bevel=0.008, + ) + + # Spinning axial turbine rotor + rotor_pivot = vc.make_empty(rotor_id, parent=nacelle_pivot, location=(0.0, 0.0, 0.14 * scale)) + vc.tag_joint(rotor_pivot, rotor_id, [0.0, 1.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": rotor_id, "axis": [0.0, 1.0, 0.0], "min": -360.0, "max": 360.0}) + + spinner_prof = [ + [0.0, -0.06 * scale], + [0.11 * scale, -0.06 * scale], + [0.11 * scale, 0.08 * scale], + [0.06 * scale, 0.22 * scale], + [0.0, 0.30 * scale], + ] + vc.make_lathe_part(f"{name}_spinner", spinner_prof, segments=12, loop=False, smooth=True, mat_name="gunmetal", parent=rotor_pivot) + + def build_blades(bm: bmesh.types.BMesh) -> None: + for i in range(6): + a = i * math.pi / 3.0 + m = ( + Matrix.Rotation(a, 4, "Z") + @ Matrix.Translation((0.19 * scale, 0.0, 0.02 * scale)) + @ Matrix.Rotation(math.radians(26.0), 4, "X") + @ Matrix.Diagonal((0.20 * scale, 0.072 * scale, 0.014 * scale, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + + vc.make_bmesh_object(f"{name}_blades", build_blades, "gunmetal", parent=rotor_pivot) + + +def build_condor() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("CondorRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. 4 Stubby Hydraulic Landing Legs (grounded at Z = 0) --- + # Front twin nose/cheek wheel-legs at y = -1.56, x = +/- 0.42 + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_ram_span( + f"gear_front_strut_{tag}", + [side * 0.34, -1.52, 0.64], + [side * 0.44, -1.60, 0.16], + body_r=0.052, + rod_r=0.030, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + vc.make_ram_span( + f"gear_front_drag_{tag}", + [side * 0.30, -1.16, 0.58], + [side * 0.44, -1.58, 0.18], + body_r=0.030, + rod_r=0.018, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="gunmetal", + ) + vc.make_knobby_wheel( + f"gear_front_wheel_{tag}", + radius=0.16, + width=0.14, + parent=chassis, + location=(side * 0.46, -1.60, 0.16), + tread_lugs=10, + rim_segments=12, + side_sign=int(side), + ) + # Rear splayed outrigger hydraulic legs with armored ski-pads at y = +1.08 + vc.make_box(f"gear_rear_sponson_{tag}", (0.26, 0.46, 0.24), "olive_armor", parent=chassis, location=(side * 0.78, 1.06, 0.68), bevel=0.01) + vc.make_ram_span( + f"gear_rear_strut_{tag}", + [side * 0.78, 1.06, 0.64], + [side * 1.04, 1.08, 0.08], + body_r=0.058, + rod_r=0.032, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + vc.make_ram_span( + f"gear_rear_brace_{tag}", + [side * 0.62, 0.68, 0.56], + [side * 1.02, 1.06, 0.10], + body_r=0.032, + rod_r=0.020, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="gunmetal", + ) + # Articulated ski-pad foot + small bogie wheel grounded at Z = 0 + vc.make_box(f"gear_rear_ski_{tag}", (0.26, 0.66, 0.055), "gunmetal", parent=chassis, location=(side * 1.04, 1.08, 0.028), bevel=0.008) + vc.make_box(f"gear_rear_ski_tip_{tag}", (0.26, 0.16, 0.055), "gunmetal", parent=chassis, location=(side * 1.04, 0.72, 0.065), rotation_deg=(28.0, 0.0, 0.0), bevel=0.006) + + # --- 2. Brutalist Angular Bolted Fuselage & Canopy (Brokkr plate.v0) --- + hull_pts = [ + # Nose prow (y = -2.78) + [-0.38, -2.78, 0.84], [0.38, -2.78, 0.84], + [-0.44, -2.72, 1.06], [0.44, -2.72, 1.06], + # Forward cabin shoulder (y = -1.54) + [-0.78, -1.54, 0.56], [0.78, -1.54, 0.56], + [-0.86, -1.42, 1.24], [0.86, -1.42, 1.24], + [-0.58, -1.24, 1.62], [0.58, -1.24, 1.62], + # Mid troop bay (y = +1.12) + [-0.78, 1.12, 0.56], [0.78, 1.12, 0.56], + [-0.88, 1.12, 1.28], [0.88, 1.12, 1.28], + [-0.64, 1.12, 1.66], [0.64, 1.12, 1.66], + # Tapered rear tail boom (y = +2.78) + [-0.36, 2.78, 1.08], [0.36, 2.78, 1.08], + [-0.38, 2.78, 1.48], [0.38, 2.78, 1.48], + ] + canopy_pts = [ + [-0.42, -2.42, 1.06], [0.42, -2.42, 1.06], + [-0.56, -1.36, 1.26], [0.56, -1.36, 1.26], + [-0.48, -1.20, 1.66], [0.48, -1.20, 1.66], + [-0.40, -1.86, 1.62], [0.40, -1.86, 1.62], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "condor_fuselage", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": hull_pts, + }, + { + "name": "condor_canopy", + "mat": "smoked_glass", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "points": canopy_pts, + }, + # Bolted side troop-bay armor plates + crew doors + { + "name": "condor_flank_armor", + "mat": "olive_armor", + "bevel": 0.010, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.86, -0.14, 0.94], + "normal": [0.98, 0.0, -0.18], + "up": [0.18, 0.0, 0.98], + "right": [0.0, -1.0, 0.0], + "outline": [[-1.18, -0.32], [1.18, -0.32], [1.08, 0.34], [-1.08, 0.34]], + "thick": 0.05, + "taper": 0.014, + "back": 0.92, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.14, + "lifts": [0.008, 0.014], + "inset": 0.05, + "gap": 0.016, + "split": 0.72, + "seed": 1001, + "bolt_r": 0.013, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.025, "spacing": 0.34, "mat": "gunmetal", "params": "r=0.013"}, + {"kind": "part", "part": "handle", "at": [0.32, 0.02], "roll": 0.0, "mat": "gunmetal", "params": "length=0.22;lift=0.045;r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Canopy structural armor ribs + dorsal radiator spine housing + rear APU jet nozzle + V-tail stabilizers + vc.make_swept_tube( + "canopy_spine", + [[0.0, -2.44, 1.06], [0.0, -1.86, 1.64], [0.0, -1.18, 1.68]], + 0.028, segments=6, mat_name="olive_armor", parent=chassis, fillet_r=0.04, + ) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_swept_tube( + f"canopy_rib_{tag}", + [[side * 0.40, -2.40, 1.06], [side * 0.42, -1.84, 1.62], [side * 0.48, -1.20, 1.66]], + 0.022, segments=6, mat_name="olive_armor", parent=chassis, fillet_r=0.04, + ) + # Side weapon sponson boxes on forward cheek flanks + vc.make_box(f"weapon_sponson_box_{tag}", (0.24, 0.76, 0.36), "olive_armor", parent=chassis, location=(side * 0.92, -1.16, 0.96), bevel=0.01) + # Fore nacelle shoulder sponsons (y = -0.86) + vc.make_box(f"fore_wing_{tag}", (0.64, 0.44, 0.22), "olive_armor", parent=chassis, location=(side * 0.86, -0.86, 1.48), rotation_deg=(0.0, side * -6.0, 0.0), bevel=0.012) + # Aft main high-mounted swept wings (y = +0.74) + vc.make_box(f"aft_wing_{tag}", (1.06, 0.72, 0.22), "olive_armor", parent=chassis, location=(side * 1.18, 0.74, 1.60), rotation_deg=(0.0, side * -5.0, side * -8.0), bevel=0.014) + # Tilt actuator rams for fore & aft nacelles + vc.make_ram_span( + f"tilt_ram_f_{tag}", + [side * 0.68, -1.04, 1.54], + [side * 1.06, -0.86, 1.50], + body_r=0.032, + rod_r=0.018, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + vc.make_ram_span( + f"tilt_ram_r_{tag}", + [side * 1.18, 0.50, 1.68], + [side * 1.56, 0.74, 1.66], + body_r=0.038, + rod_r=0.020, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + # Canted twin tail stabilizers + ventral strakes + vc.make_box( + f"tail_fin_{tag}", + (0.06, 0.66, 0.94), + "olive_armor", + parent=chassis, + location=(side * 0.56, 2.58, 1.72), + rotation_deg=(24.0, side * -32.0, 0.0), + bevel=0.01, + ) + vc.make_box( + f"tail_horiz_{tag}", + (0.46, 0.54, 0.07), + "olive_armor", + parent=chassis, + location=(side * 0.44, 2.54, 1.34), + rotation_deg=(0.0, side * 10.0, side * -12.0), + bevel=0.008, + ) + + # Dorsal radiator spine ridge (runs behind canopy to tail root) + vc.make_box("dorsal_spine_core", (0.78, 2.48, 0.26), "olive_armor", parent=chassis, location=(0.0, 0.28, 1.70), bevel=0.014) + vc.make_box("dorsal_spine_cap", (0.48, 2.38, 0.14), "gunmetal", parent=chassis, location=(0.0, 0.28, 1.84), bevel=0.01) + + # Rear tail APU / main jet exhaust cone + rear_nozzle_prof = [ + [0.18, 0.0], + [0.27, 0.0], + [0.29, 0.18], + [0.24, 0.36], + [0.16, 0.36], + [0.18, 0.0], + ] + vc.make_lathe_part( + "rear_jet_nozzle", + rear_nozzle_prof[:-1], + segments=18, + loop=True, + smooth=True, + mat_name="copper_rad", + parent=chassis, + location=(0.0, 2.74, 1.28), + rotation_deg=(-90.0, 0.0, 0.0), + ) + + # --- 3. 4 Pivoting Vectored-Thrust Jet Nacelles (joint.nacelle_fl/fr/rl/rr) --- + joints_manifest: list[dict] = [] + # Fore nacelles + for side, j_tag in ((1.0, "fl"), (-1.0, "fr")): + _build_jet_nacelle( + f"nacelle_{j_tag}", + f"joint.nacelle_{j_tag}", + f"joint.rotor_{j_tag}", + side, + location=(side * 1.42, -0.86, 1.48), + scale=0.82, + tilt_deg=-16.0, + parent=chassis, + joints_manifest=joints_manifest, + ) + # Aft main nacelles (larger vectored jet pods) + for side, j_tag in ((1.0, "rl"), (-1.0, "rr")): + _build_jet_nacelle( + f"nacelle_{j_tag}", + f"joint.nacelle_{j_tag}", + f"joint.rotor_{j_tag}", + side, + location=(side * 1.88, 0.74, 1.62), + scale=1.06, + tilt_deg=-14.0, + parent=chassis, + joints_manifest=joints_manifest, + ) + + # --- 4. Heavy Nose Chin Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, -2.26, 0.74)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest.append({"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}) + + vc.make_tube_part("chin_turret_ring", 0.28, 0.30, 0.10, segments=16, mat_name="gunmetal", parent=turret_pivot, location=(0.0, 0.0, -0.04)) + vc.make_box("chin_turret_housing", (0.44, 0.48, 0.22), "olive_armor", parent=turret_pivot, location=(0.0, 0.0, -0.14), bevel=0.012) + vc.make_box("chin_optics", (0.20, 0.10, 0.10), "smoked_glass", parent=turret_pivot, location=(0.0, -0.24, -0.10), bevel=0.005) + + # --- 5. Visible Exterior Hardpoints (5x6 Masked Dorsal Grid) --- + # 1) hp.weapon.nose (1,0, 2x1) under chin turret + vc.add_hardpoint_slot( + "hp.weapon.nose", + "weapon", + parent=turret_pivot, + location=(0.0, 0.0, -0.25), + rotation_deg=(0.0, 180.0, 0.0), + size=(0.46, 0.46, 0.08), + ) + # 2) hp.armor.hull (3,0, 1x1) on sloped upper nose glacis in front of canopy + vc.add_hardpoint_slot( + "hp.armor.hull", + "armor", + parent=chassis, + location=(0.0, -2.56, 1.13), + rotation_deg=(69.0, 0.0, 0.0), + size=(0.64, 0.26, 0.09), + plinth_depth=0.04, + ) + # 3 & 4) hp.weapon.sponson_l (0,1, 1x2) & hp.weapon.sponson_r (4,1, 1x2) on cheek weapon sponsons + vc.add_hardpoint_slot( + "hp.weapon.sponson_l", + "weapon", + parent=chassis, + location=(1.04, -1.16, 0.96), + rotation_deg=(0.0, 90.0, 0.0), + size=(0.44, 0.44, 0.08), + ) + vc.add_hardpoint_slot( + "hp.weapon.sponson_r", + "weapon", + parent=chassis, + location=(-1.04, -1.16, 0.96), + rotation_deg=(0.0, -90.0, 0.0), + size=(0.44, 0.44, 0.08), + ) + # 5) hp.weapon.dorsal (2,1, 1x1) on forward dorsal spine behind cockpit + vc.add_hardpoint_slot( + "hp.weapon.dorsal", + "weapon", + parent=chassis, + location=(0.0, -0.78, 1.91), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.54, 0.54, 0.09), + ) + # 6) hp.engine.core (1,2, 3x2) central dorsal turbine bay (dorsal_spine_core width 0.78, cap top at z=1.91) + vc.add_hardpoint_slot( + "hp.engine.core", + "engine", + parent=chassis, + location=(0.0, 0.36, 1.89), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.74, 1.14, 0.14), + plinth_depth=0.05, + ) + # 7 & 8) hp.radiator.spine_l (0,3, 1x2) & hp.radiator.spine_r (4,3, 1x2) along canted dorsal spine flanks + vc.add_hardpoint_slot( + "hp.radiator.spine_l", + "radiator", + parent=chassis, + location=(0.56, 1.02, 1.68), + rotation_deg=(0.0, 56.0, 0.0), + size=(0.40, 1.04, 0.11), + ) + vc.add_hardpoint_slot( + "hp.radiator.spine_r", + "radiator", + parent=chassis, + location=(-0.56, 1.02, 1.68), + rotation_deg=(0.0, -56.0, 0.0), + size=(0.40, 1.04, 0.11), + ) + + # --- 6. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "condor" / "condor.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "condor" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "condor_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="condor", + name="Condor", + vehicle_class="Heavy Quad-Thruster Assault VTOL", + grid_width=5, + grid_height=6, + mask=[ + ".###.", + "#####", + "#####", + "#####", + "#####", + "..#..", + ], + hardpoints=[ + {"id": "hp.weapon.nose", "kind": "weapon", "x": 1, "y": 0, "w": 2, "h": 1, "modelNodeId": "hp.weapon.nose"}, + {"id": "hp.armor.hull", "kind": "armor", "x": 3, "y": 0, "w": 1, "h": 1, "modelNodeId": "hp.armor.hull"}, + {"id": "hp.weapon.sponson_l", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.sponson_l"}, + {"id": "hp.weapon.dorsal", "kind": "weapon", "x": 2, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.weapon.dorsal"}, + {"id": "hp.weapon.sponson_r", "kind": "weapon", "x": 4, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.sponson_r"}, + {"id": "hp.engine.core", "kind": "engine", "x": 1, "y": 2, "w": 3, "h": 2, "modelNodeId": "hp.engine.core"}, + {"id": "hp.radiator.spine_l", "kind": "radiator", "x": 0, "y": 3, "w": 1, "h": 2, "modelNodeId": "hp.radiator.spine_l"}, + {"id": "hp.radiator.spine_r", "kind": "radiator", "x": 4, "y": 3, "w": 1, "h": 2, "modelNodeId": "hp.radiator.spine_r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[condor] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "condor", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_condor() diff --git a/tools/vehicles/build_ferret.py b/tools/vehicles/build_ferret.py new file mode 100644 index 0000000..1c17c8f --- /dev/null +++ b/tools/vehicles/build_ferret.py @@ -0,0 +1,344 @@ +"""Build the Ferret (Light Tracked Scout Tankette) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_track_pod(name: str, side: float, parent) -> None: + """Build one wide articulated steel track pod with roadwheels, drive sprockets, and track shoes.""" + pod_x = side * 0.86 + pod = vc.make_empty(name, parent=parent, location=(pod_x, 0.0, 0.0)) + + # Track loop keypoints in (y, z): front idler -> bottom roadwheels -> rear sprocket -> top return + # Ground at z = 0.0 (track shoe thickness ~0.04 -> wheel bottom at z = 0.04) + rw_r = 0.25 + rw_z = rw_r + 0.04 + rw_ys = (-0.90, -0.30, 0.30, 0.90) + idler_y, idler_z, idler_r = -1.48, 0.46, 0.22 + sproc_y, sproc_z, sproc_r = 1.46, 0.48, 0.23 + track_w = 0.40 + + # Roadwheels (4) + Front Idler + Rear Drive Sprocket + for i, ry in enumerate(rw_ys): + vc.make_tube_part( + f"{name}_rw_tire_{i}", rw_r, rw_r, track_w * 0.82, segments=16, + mat_name="rubber_dark", parent=pod, location=(-track_w * 0.41, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_rw_hub_{i}", rw_r * 0.66, rw_r * 0.66, track_w * 0.88, segments=12, + mat_name="olive_armor", parent=pod, location=(-track_w * 0.44, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_idler", idler_r, idler_r, track_w * 0.78, segments=14, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.39, idler_y, idler_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_sprocket", sproc_r, sproc_r, track_w * 0.82, segments=14, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.41, sproc_y, sproc_z), rotation_deg=(0.0, 90.0, 0.0), + ) + + # Track belt loop + articulated grouser shoes sampled evenly around closed perimeter + # Build loop path points in (y, z) + loop_yz: list[tuple[float, float]] = [] + # Front idler arc (from top-front down to bottom-front) + for k in range(7): + ang = math.radians(95.0 + 145.0 * (k / 6.0)) + loop_yz.append((idler_y + math.cos(ang) * (idler_r + 0.025), idler_z + math.sin(ang) * (idler_r + 0.025))) + # Bottom run across roadwheels + loop_yz.append((-0.90, 0.02)) + loop_yz.append((0.90, 0.02)) + # Rear sprocket arc (from bottom-rear up to top-rear) + for k in range(7): + ang = math.radians(-65.0 + 145.0 * (k / 6.0)) + loop_yz.append((sproc_y + math.cos(ang) * (sproc_r + 0.025), sproc_z + math.sin(ang) * (sproc_r + 0.025))) + # Top return run + loop_yz.append((0.40, 0.73)) + loop_yz.append((-0.40, 0.73)) + + # Continuous inner track band via core.sweep (with up=+X, outline's h spans X and w spans thickness) + path_3d = [[0.0, y, z] for (y, z) in loop_yz] + vc.make_swept_profile( + f"{name}_track_band", + "box", + 0.030, + track_w * 0.92, + 0.030, + path_3d, + up=[1.0, 0.0, 0.0], + mat_name="rubber_dark", + parent=pod, + closed=True, + ) + + # Articulated steel grouser shoes along loop + # Compute cumulative arc length + pts = loop_yz + [loop_yz[0]] + segs = [math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]) for i in range(len(loop_yz))] + total_len = sum(segs) + n_shoes = 38 + + def build_shoes(bm: bmesh.types.BMesh) -> None: + for s_idx in range(n_shoes): + target_d = total_d = (s_idx / n_shoes) * total_len + acc = 0.0 + for i, sl in enumerate(segs): + if acc + sl >= target_d or i == len(segs) - 1: + t = (target_d - acc) / max(sl, 1e-6) + y0, z0 = pts[i] + y1, z1 = pts[i + 1] + py = y0 + (y1 - y0) * t + pz = z0 + (z1 - z0) * t + ang = math.atan2(z1 - z0, y1 - y0) + # Normal pointing outward from loop (y, z) + m = ( + Matrix.Translation((0.0, py, pz)) + @ Matrix.Rotation(ang, 4, "X") + @ Matrix.Diagonal((track_w, 0.085, 0.026, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + break + acc += sl + + vc.make_bmesh_object(f"{name}_shoes", build_shoes, "gunmetal", parent=pod) + + # Armored track fender & upper side skirt (Brokkr plate.v0 slab) + vc.make_box(f"{name}_fender_top", (track_w + 0.06, 3.24, 0.055), "olive_armor", parent=pod, location=(0.0, -0.02, 0.79), bevel=0.008) + vc.make_box(f"{name}_fender_front", (track_w + 0.06, 0.34, 0.055), "olive_armor", parent=pod, location=(0.0, -1.72, 0.68), rotation_deg=(36.0, 0.0, 0.0), bevel=0.008) + vc.make_box(f"{name}_fender_rear", (track_w + 0.06, 0.32, 0.055), "olive_armor", parent=pod, location=(0.0, 1.66, 0.68), rotation_deg=(-36.0, 0.0, 0.0), bevel=0.008) + + # Outer bolted track skirt covering upper roadwheels + skirt_pts = [ + [side * 0.22, -1.36, 0.78], + [side * 0.22, 1.36, 0.78], + [side * 0.22, 1.18, 0.36], + [side * 0.22, -1.16, 0.36], + ] + vc.make_box( + f"{name}_skirt", + (0.045, 2.52, 0.40), + "olive_armor", + parent=pod, + location=(side * (track_w * 0.5 + 0.025), 0.0, 0.58), + bevel=0.008, + ) + + +def build_ferret() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("FerretRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. Lower Tub & Wedge Glacis Hull (Brokkr plate.v0 convex hull) --- + vc.make_box("lower_tub", (1.28, 3.06, 0.44), "gunmetal", parent=chassis, location=(0.0, -0.04, 0.46), bevel=0.012) + + hull_pts = [ + [-0.64, -1.68, 0.46], [0.64, -1.68, 0.46], + [0.68, -1.68, 0.64], [-0.68, -1.68, 0.64], + [-0.68, -0.78, 1.04], [0.68, -0.78, 1.04], + [-0.68, 0.66, 1.04], [0.68, 0.66, 1.04], + [-0.64, 1.66, 0.80], [0.64, 1.66, 0.80], + [-0.64, 1.66, 0.50], [0.64, 1.66, 0.50], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "ferret_hull", + "mat": "olive_armor", + "bevel": 0.014, + "sides": "one", + "mirror": False, + "points": hull_pts, + "clad": { + "mat": "olive_armor", + "facets": [{"n": [0.0, -0.45, 0.89], "cos": 0.90}], + "min_area": 0.12, + "lifts": [0.008, 0.014], + "inset": 0.05, + "gap": 0.016, + "split": 0.90, + "seed": 601, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + }, + # Sloped upper hull sponson cheek plates + { + "name": "ferret_sponson", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.76, 0.14, 0.90], + "normal": [0.85, 0.0, 0.52], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.94, -0.14], [0.94, -0.14], [0.76, 0.14], [-0.78, 0.14]], + "thick": 0.05, + "taper": 0.014, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.30, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Headlights, tow shackles, and flank cylindrical mufflers + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"headlight_{tag}", (0.12, 0.12, 0.10), "gunmetal", parent=chassis, location=(side * 0.82, -1.52, 0.88), bevel=0.008) + vc.make_box(f"tow_shackle_{tag}", (0.06, 0.10, 0.10), "signal_orange", parent=chassis, location=(side * 0.42, -1.72, 0.56), bevel=0.005) + # Side exhaust muffler + copper pipes + vc.make_tube_part( + f"muffler_{tag}", 0.085, 0.085, 0.62, segments=12, + mat_name="gunmetal", parent=chassis, location=(side * 0.80, 0.72, 0.92), rotation_deg=(-90.0, 0.0, 0.0), + ) + vc.make_swept_tube( + f"muffler_pipe_{tag}", + [[side * 0.62, 0.64, 0.92], [side * 0.80, 0.72, 0.92], [side * 0.80, 1.44, 0.90]], + 0.032, segments=8, mat_name="copper_rad", parent=chassis, fillet_r=0.03, + ) + + # --- 2. Wide Articulated Track Pods --- + _build_track_pod("track_pod_L", 1.0, chassis) + _build_track_pod("track_pod_R", -1.0, chassis) + + # --- 3. Low Octagonal Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, -0.18, 1.04)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest = [{"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}] + + # Turret ring race + vc.make_tube_part("turret_race", 0.54, 0.58, 0.07, segments=20, mat_name="gunmetal", parent=turret_pivot, location=(0.0, 0.0, 0.0)) + + turret_pts = [ + [-0.46, -0.52, 0.06], [0.46, -0.52, 0.06], + [0.54, -0.10, 0.06], [0.48, 0.56, 0.06], + [-0.48, 0.56, 0.06], [-0.54, -0.10, 0.06], + [-0.36, -0.40, 0.42], [0.36, -0.40, 0.42], + [0.42, -0.06, 0.42], [0.38, 0.46, 0.42], + [-0.38, 0.46, 0.42], [-0.42, -0.06, 0.42], + ] + turret_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "ferret_turret_shell", + "mat": "olive_armor", + "bevel": 0.012, + "sides": "one", + "mirror": False, + "points": turret_pts, + }, + ], + } + vc.make_plates(turret_doc, parent=turret_pivot) + + # Commander hatch & front optic prism + cheek pylon shelf + vc.make_tube_part("commander_cupola", 0.17, 0.18, 0.08, segments=12, mat_name="olive_armor", parent=turret_pivot, location=(-0.16, 0.14, 0.42)) + vc.make_box("turret_optic", (0.14, 0.16, 0.10), "smoked_glass", parent=turret_pivot, location=(0.18, -0.26, 0.45), bevel=0.006) + vc.make_box("turret_mantlet_collar", (0.28, 0.16, 0.22), "gunmetal", parent=turret_pivot, location=(0.0, -0.50, 0.24), bevel=0.008) + vc.make_box("cheek_pylon_shelf", (0.24, 0.34, 0.08), "gunmetal", parent=turret_pivot, location=(0.56, 0.02, 0.22), bevel=0.006) + + # --- 4. Visible Exterior Hardpoints (3x4 Dorsal Grid) --- + # 1) Front wedge glacis armor stud rail + vc.add_hardpoint_slot( + "hp.armor.glacis", + "armor", + parent=chassis, + location=(0.0, -1.24, 0.85), + rotation_deg=(66.0, 0.0, 0.0), + size=(1.12, 0.34, 0.08), + plinth_depth=0.03, + ) + # 2) Main turret weapon collar + vc.add_hardpoint_slot( + "hp.weapon.turret", + "weapon", + parent=turret_pivot, + location=(0.0, -0.02, 0.43), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.62, 0.10), + ) + # 3) Turret cheek pod weapon collar (on left +X cheek pylon shelf) + vc.add_hardpoint_slot( + "hp.weapon.pod", + "weapon", + parent=turret_pivot, + location=(0.58, 0.02, 0.27), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.34, 0.34, 0.07), + ) + # 4) Rear engine bay frame (sloped deck surface at y=0.82 is z=1.00) + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 0.82, 0.99), + rotation_deg=(-13.5, 0.0, 0.0), + size=(0.86, 0.66, 0.13), + plinth_depth=0.04, + ) + # 5) Rear deck copper radiator louver bay (sloped deck surface at y=1.42 is z=0.858) + vc.add_hardpoint_slot( + "hp.radiator.deck", + "radiator", + parent=chassis, + location=(0.0, 1.42, 0.845), + rotation_deg=(-13.5, 0.0, 0.0), + size=(0.88, 0.44, 0.09), + plinth_depth=0.04, + ) + + # --- 5. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "ferret" / "ferret.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "ferret" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "ferret_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="ferret", + name="Ferret", + vehicle_class="Light Tracked Scout Tankette", + grid_width=3, + grid_height=4, + mask=[ + "###", + "###", + "###", + "###", + ], + hardpoints=[ + {"id": "hp.armor.glacis", "kind": "armor", "x": 0, "y": 0, "w": 3, "h": 1, "modelNodeId": "hp.armor.glacis"}, + {"id": "hp.weapon.pod", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.weapon.pod"}, + {"id": "hp.weapon.turret", "kind": "weapon", "x": 1, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.turret"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 2, "y": 2, "w": 1, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.deck", "kind": "radiator", "x": 1, "y": 3, "w": 1, "h": 1, "modelNodeId": "hp.radiator.deck"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[ferret] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "ferret", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_ferret() diff --git a/tools/vehicles/build_gear.py b/tools/vehicles/build_gear.py new file mode 100644 index 0000000..60b095d --- /dev/null +++ b/tools/vehicles/build_gear.py @@ -0,0 +1,144 @@ +"""Build the 6 modular starter gear GLBs into assets/gear/.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _export_gear(name: str, root) -> tuple[int, dict]: + glb_path = vc.ASSETS_GEAR_DIR / f"{name}.glb" + tris, bounds = vc.export_vehicle_glb(glb_path, root=root) + print(f"[gear:{name}] tris={tris} bounds={bounds} glb={glb_path}") + return tris, bounds + + +def build_mg_762() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Pintle base + yoke + receiver + perforated barrel shroud + side ammo box + spade grips + vc.make_tube_part("pintle_base", 0.14, 0.12, 0.06, segments=12, mat_name="gunmetal", parent=root) + vc.make_box("cradle_yoke", (0.14, 0.18, 0.18), "gunmetal", parent=root, location=(0.0, 0.0, 0.15), bevel=0.006) + vc.make_box("receiver", (0.12, 0.44, 0.14), "olive_armor", parent=root, location=(0.0, -0.04, 0.28), bevel=0.006) + vc.make_tube_part("barrel_shroud", 0.032, 0.028, 0.48, segments=10, mat_name="gunmetal", parent=root, location=(0.0, -0.24, 0.29), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part("barrel_inner", 0.014, 0.014, 0.68, segments=8, mat_name="gunmetal", parent=root, location=(0.0, -0.24, 0.29), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_box("ammo_box", (0.14, 0.22, 0.16), "olive_armor", parent=root, location=(0.14, -0.02, 0.25), bevel=0.006) + vc.make_box("ammo_latch", (0.04, 0.10, 0.04), "signal_orange", parent=root, location=(0.14, -0.02, 0.34), bevel=0.003) + for side in (-1.0, 1.0): + vc.make_tube_part(f"grip_{'L' if side > 0 else 'R'}", 0.012, 0.012, 0.10, segments=6, mat_name="rubber_dark", parent=root, location=(side * 0.06, 0.22, 0.23)) + _export_gear("mg_762", root) + + +def build_autocannon() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Turret base ring + twin armored trunnion cheeks + dual 20mm barrels + twin ammo drums + vc.make_tube_part("turret_collar", 0.26, 0.24, 0.08, segments=16, mat_name="gunmetal", parent=root) + vc.make_box("gun_housing", (0.30, 0.46, 0.24), "olive_armor", parent=root, location=(0.0, 0.04, 0.20), bevel=0.010) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_tube_part(f"barrel_jacket_{tag}", 0.036, 0.030, 0.42, segments=10, mat_name="gunmetal", parent=root, location=(side * 0.085, -0.18, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part(f"barrel_tube_{tag}", 0.018, 0.018, 0.88, segments=8, mat_name="gunmetal", parent=root, location=(side * 0.085, -0.18, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part(f"muzzle_brake_{tag}", 0.028, 0.028, 0.09, segments=8, mat_name="copper_rad", parent=root, location=(side * 0.085, -1.00, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part(f"ammo_drum_{tag}", 0.13, 0.13, 0.16, segments=14, mat_name="olive_armor", parent=root, location=(side * 0.22, 0.14, 0.24), rotation_deg=(0.0, 90.0 * side, 0.0)) + vc.make_box("optic_pod", (0.10, 0.14, 0.09), "smoked_glass", parent=root, location=(0.0, -0.08, 0.36), bevel=0.005) + _export_gear("autocannon", root) + + +def build_recoilless() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Pedestal + heavy long recoilless tube + flared rear venturi + top optic rail + vc.make_tube_part("base_flange", 0.20, 0.18, 0.07, segments=14, mat_name="gunmetal", parent=root) + vc.make_box("trunnion_post", (0.14, 0.20, 0.20), "gunmetal", parent=root, location=(0.0, 0.02, 0.16), bevel=0.008) + tube_prof = [ + [0.055, -0.58], + [0.085, -0.58], + [0.095, -0.35], + [0.095, 0.42], + [0.072, 0.46], + [0.072, 0.78], + [0.088, 0.82], + [0.062, 0.82], + [0.055, 0.44], + ] + vc.make_lathe_part("launcher_tube", tube_prof, segments=16, loop=True, smooth=True, mat_name="olive_armor", parent=root, location=(0.0, 0.0, 0.32), rotation_deg=(-90.0, 0.0, 0.0)) + vc.make_box("breech_band", (0.20, 0.12, 0.20), "signal_orange", parent=root, location=(0.0, 0.26, 0.32), bevel=0.006) + vc.make_tube_part("sight_tube", 0.028, 0.032, 0.22, segments=10, mat_name="gunmetal", parent=root, location=(0.11, -0.02, 0.36), rotation_deg=(90.0, 0.0, 0.0)) + _export_gear("recoilless", root) + + +def build_copper_rad() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Industrial copper finned radiator bank + armored end tanks + coolant pipes + base flange + vc.make_box("base_flange", (0.48, 0.42, 0.045), "gunmetal", parent=root, location=(0.0, 0.0, 0.0225), bevel=0.006) + vc.make_kit_part( + "copper_fins", + "mechanical", + "radiator_stack", + {"fins": 10, "fin_w": 0.36, "fin_h": 0.24, "fin_t": 0.008, "pitch": 0.032, "segments": 10}, + mat_name="copper_rad", + parent=root, + location=(0.0, -0.145, 0.18), + rotation_deg=(-90.0, 0.0, 0.0), + ) + for side in (-1.0, 1.0): + vc.make_box(f"end_tank_{'L' if side > 0 else 'R'}", (0.06, 0.38, 0.26), "gunmetal", parent=root, location=(side * 0.21, 0.0, 0.18), bevel=0.008) + vc.make_swept_tube(f"coolant_pipe_{'L' if side > 0 else 'R'}", [[side * 0.21, 0.14, 0.26], [side * 0.21, 0.24, 0.18], [side * 0.16, 0.24, 0.06]], 0.018, segments=8, mat_name="copper_rad", parent=root, fillet_r=0.02) + vc.make_box("top_cap_bar", (0.44, 0.06, 0.04), "signal_orange", parent=root, location=(0.0, -0.15, 0.31), bevel=0.004) + _export_gear("copper_rad", root) + + +def build_gilded_lance() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Imperial Tourist ornate gilded thermal lance with ivory cowl, gold flutes, and cyan condenser rings + vc.make_tube_part("imperial_base", 0.24, 0.21, 0.08, segments=18, mat_name="imperial_gold", parent=root) + vc.make_box("ivory_cowl", (0.28, 0.52, 0.22), "imperial_ivory", parent=root, location=(0.0, 0.02, 0.20), bevel=0.014) + vc.make_box("gold_crest", (0.10, 0.44, 0.08), "imperial_gold", parent=root, location=(0.0, 0.02, 0.32), bevel=0.008) + vc.make_tube_part("lance_core", 0.042, 0.026, 0.96, segments=14, mat_name="imperial_gold", parent=root, location=(0.0, -0.20, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + for i, dy in enumerate((-0.42, -0.64, -0.86)): + vc.make_tube_part(f"condenser_ring_{i}", 0.062 - i * 0.006, 0.062 - i * 0.006, 0.04, segments=14, mat_name="cyan_coil", parent=root, location=(0.0, dy, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + _export_gear("gilded_lance", root) + + +def build_gold_radiator() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Imperial Tourist ornate gilded louver array with ivory housing & cyan thermal core + vc.make_box("imperial_flange", (0.48, 0.42, 0.045), "imperial_gold", parent=root, location=(0.0, 0.0, 0.0225), bevel=0.006) + vc.make_box("ivory_shroud", (0.44, 0.38, 0.22), "imperial_ivory", parent=root, location=(0.0, 0.0, 0.155), bevel=0.012) + vc.make_box("cyan_core", (0.34, 0.28, 0.16), "cyan_coil", parent=root, location=(0.0, 0.0, 0.16), bevel=0.004) + def build_gold_vanes(bm: bmesh.types.BMesh) -> None: + for i in range(7): + y = -0.14 + 0.28 * (i / 6.0) + m = Matrix.Translation((0.0, y, 0.265)) @ Matrix.Rotation(math.radians(20.0), 4, "X") @ Matrix.Diagonal((0.38, 0.022, 0.055, 1.0)) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + vc.make_bmesh_object("gold_vanes", build_gold_vanes, "imperial_gold", parent=root) + _export_gear("gold_radiator", root) + + +def build_all_gear() -> None: + build_mg_762() + build_autocannon() + build_recoilless() + build_copper_rad() + build_gilded_lance() + build_gold_radiator() + + +if __name__ == "__main__": + build_all_gear() diff --git a/tools/vehicles/build_hornet.py b/tools/vehicles/build_hornet.py new file mode 100644 index 0000000..bb073e1 --- /dev/null +++ b/tools/vehicles/build_hornet.py @@ -0,0 +1,400 @@ +"""Build the Hornet (Light Ducted-Fan VTOL Gunship) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_ducted_nacelle(name: str, side: float, parent, joints_manifest: list[dict]) -> None: + """Build a pivoting armored ducted-fan nacelle with inner copper thrust collar and spinning rotor.""" + nacelle_id = f"joint.nacelle_{'l' if side > 0 else 'r'}" + nacelle_pivot = vc.make_empty( + nacelle_id, + parent=parent, + location=(side * 1.18, 0.10, 1.32), + rotation_deg=(-18.0, 0.0, 0.0), + ) + vc.tag_joint(nacelle_pivot, nacelle_id, [1.0, 0.0, 0.0], -45.0, 75.0) + joints_manifest.append({"id": nacelle_id, "axis": [1.0, 0.0, 0.0], "min": -45.0, "max": 75.0}) + + # Upper olive-drab armored duct shroud (CCW in (r, z) for core.lathe) + shroud_prof = [ + [0.34, -0.06], + [0.44, -0.06], + [0.47, 0.02], + [0.47, 0.22], + [0.43, 0.28], + [0.35, 0.28], + [0.33, 0.20], + [0.34, -0.06], + ] + vc.make_lathe_part( + f"{name}_shroud", + shroud_prof[:-1], + segments=22, + loop=True, + smooth=True, + mat_name="olive_armor", + parent=nacelle_pivot, + ) + # Lower copper thermal exhaust skirt + skirt_prof = [ + [0.33, -0.20], + [0.41, -0.20], + [0.44, -0.06], + [0.34, -0.06], + ] + vc.make_lathe_part( + f"{name}_skirt", + skirt_prof, + segments=22, + loop=True, + smooth=True, + mat_name="copper_rad", + parent=nacelle_pivot, + ) + # Stator cross vanes + hinge yoke collar + for ang_deg in (0.0, 90.0): + vc.make_box( + f"{name}_stator_{int(ang_deg)}", + (0.68, 0.04, 0.06), + "gunmetal", + parent=nacelle_pivot, + location=(0.0, 0.0, -0.08), + rotation_deg=(0.0, 0.0, ang_deg), + bevel=0.004, + ) + vc.make_box( + f"{name}_hinge_lug", + (0.16, 0.22, 0.16), + "gunmetal", + parent=nacelle_pivot, + location=(-side * 0.44, 0.0, 0.08), + bevel=0.008, + ) + + # Spinning rotor hub + 4 pitched fan blades (about glTF +Y = Blender +Z) + rotor_id = f"joint.rotor_{'l' if side > 0 else 'r'}" + rotor_pivot = vc.make_empty(rotor_id, parent=nacelle_pivot, location=(0.0, 0.0, 0.04)) + vc.tag_joint(rotor_pivot, rotor_id, [0.0, 1.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": rotor_id, "axis": [0.0, 1.0, 0.0], "min": -360.0, "max": 360.0}) + + spinner_prof = [ + [0.0, -0.04], + [0.10, -0.04], + [0.10, 0.06], + [0.06, 0.16], + [0.0, 0.22], + ] + vc.make_lathe_part(f"{name}_spinner", spinner_prof, segments=14, loop=False, smooth=True, mat_name="gunmetal", parent=rotor_pivot) + + def build_blades(bm: bmesh.types.BMesh) -> None: + for i in range(4): + a = i * math.pi * 0.5 + m = ( + Matrix.Rotation(a, 4, "Z") + @ Matrix.Translation((0.20, 0.0, 0.02)) + @ Matrix.Rotation(math.radians(22.0), 4, "X") + @ Matrix.Diagonal((0.24, 0.085, 0.014, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + + vc.make_bmesh_object(f"{name}_blades", build_blades, "gunmetal", parent=rotor_pivot) + + +def build_hornet() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("HornetRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. Rugged Steel Landing Skids (grounded at Z = 0) --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_swept_tube( + f"skid_runner_{tag}", + [ + [side * 0.72, -1.56, 0.16], + [side * 0.72, -1.24, 0.032], + [side * 0.72, 1.06, 0.032], + ], + 0.032, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.08, + ) + # Front & rear diagonal skid struts up to fuselage belly + for s_tag, sy_lo, sy_hi in (("f", -0.82, -0.68), ("r", 0.52, 0.44)): + vc.make_swept_tube( + f"skid_strut_{tag}_{s_tag}", + [[side * 0.72, sy_lo, 0.04], [side * 0.40, sy_hi, 0.54]], + 0.026, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + + # --- 2. Faceted Armored Cockpit & Fuselage Hull (Brokkr plate.v0) --- + hull_pts = [ + [-0.28, -1.86, 0.56], [0.28, -1.86, 0.56], + [-0.36, -1.78, 0.78], [0.36, -1.78, 0.78], + [-0.58, -0.86, 0.46], [0.58, -0.86, 0.46], + [-0.64, -0.64, 1.02], [0.64, -0.64, 1.02], + [-0.64, 0.76, 1.02], [0.64, 0.76, 1.02], + [-0.56, 0.88, 0.54], [0.56, 0.88, 0.54], + [-0.44, 0.64, 1.44], [0.44, 0.64, 1.44], + [-0.44, -0.26, 1.44], [0.44, -0.26, 1.44], + ] + canopy_pts = [ + [-0.34, -1.66, 0.78], [0.34, -1.66, 0.78], + [-0.52, -0.88, 1.02], [0.52, -0.88, 1.02], + [-0.42, -0.28, 1.40], [0.42, -0.28, 1.40], + [-0.36, -0.88, 1.38], [0.36, -0.88, 1.38], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "hornet_fuselage", + "mat": "olive_armor", + "bevel": 0.014, + "sides": "one", + "mirror": False, + "points": hull_pts, + }, + { + "name": "hornet_canopy", + "mat": "smoked_glass", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "points": canopy_pts, + }, + # Cheek armor skirts with bolts + { + "name": "hornet_cheek", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.58, -0.62, 0.76], + "normal": [0.92, -0.28, 0.26], + "up": [0.0, 0.0, 1.0], + "right": [-0.28, -0.96, 0.0], + "outline": [[-0.56, -0.14], [0.52, -0.18], [0.48, 0.16], [-0.46, 0.14]], + "thick": 0.04, + "taper": 0.012, + "back": 0.90, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.24, "mat": "gunmetal", "params": "r=0.011"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Canopy structural armor ribs + nose EO/IR optics pod + vc.make_swept_tube( + "canopy_spine", + [[0.0, -1.68, 0.78], [0.0, -0.90, 1.40], [0.0, -0.26, 1.44]], + 0.024, segments=6, mat_name="olive_armor", parent=chassis, fillet_r=0.04, + ) + for side in (-1.0, 1.0): + vc.make_swept_tube( + f"canopy_rib_{'L' if side > 0 else 'R'}", + [[side * 0.33, -1.65, 0.78], [side * 0.37, -0.89, 1.38], [side * 0.43, -0.28, 1.42]], + 0.020, segments=6, mat_name="olive_armor", parent=chassis, fillet_r=0.04, + ) + vc.make_box("nose_optics_housing", (0.24, 0.20, 0.18), "gunmetal", parent=chassis, location=(0.0, -1.86, 0.66), bevel=0.01) + vc.make_tube_part("nose_optics_lens", 0.065, 0.065, 0.06, segments=12, mat_name="smoked_glass", parent=chassis, location=(0.0, -1.94, 0.66), rotation_deg=(90.0, 0.0, 0.0)) + + # Stub wings + nacelle outrigger arms + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box( + f"stub_wing_{tag}", + (0.68, 0.56, 0.09), + "olive_armor", + parent=chassis, + location=(side * 0.74, 0.14, 0.74), + rotation_deg=(0.0, side * 8.0, side * -10.0), + bevel=0.01, + ) + vc.make_box( + f"nacelle_arm_{tag}", + (0.46, 0.30, 0.18), + "gunmetal", + parent=chassis, + location=(side * 0.62, 0.10, 1.32), + bevel=0.01, + ) + + # --- 3. Pivoting Ducted-Fan Nacelles + Hydraulic Tilt Actuators --- + joints_manifest: list[dict] = [] + for side in (1.0, -1.0): + tag = "L" if side > 0 else "R" + _build_ducted_nacelle(f"nacelle_{tag}", side, chassis, joints_manifest) + # Dual hydraulic tilt actuator from dorsal shoulder clevis out to nacelle hinge lug + vc.make_box(f"tilt_clevis_{tag}", (0.10, 0.14, 0.10), "gunmetal", parent=chassis, location=(side * 0.44, -0.10, 1.38), bevel=0.005) + vc.make_ram_span( + f"tilt_actuator_{tag}", + [side * 0.44, -0.10, 1.38], + [side * 0.78, 0.08, 1.38], + body_r=0.028, + rod_r=0.015, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + + # --- 4. Skeletal Truss Tail Boom & V/T Tailfins --- + # Rear boom mounting bulkhead + 3-chord space-frame tail boom anchored inside fuselage + vc.make_box("tail_boom_collar", (0.44, 0.28, 0.42), "gunmetal", parent=chassis, location=(0.0, 0.74, 1.10), bevel=0.01) + boom_top_l = [0.16, 0.62, 1.24] + boom_top_r = [-0.16, 0.62, 1.24] + boom_bot = [0.0, 0.62, 0.94] + tail_top_l = [0.07, 2.38, 1.34] + tail_top_r = [-0.07, 2.38, 1.34] + tail_bot = [0.0, 2.38, 1.16] + for cname, p0, p1 in [ + ("boom_tl", boom_top_l, tail_top_l), + ("boom_tr", boom_top_r, tail_top_r), + ("boom_bt", boom_bot, tail_bot), + ]: + vc.make_swept_tube(cname, [p0, p1], 0.020, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + + # Truss bay diagonals along the tail boom + n_bays = 5 + def lerp3(a, b, t): + return [a[k] + (b[k] - a[k]) * t for k in range(3)] + + for i in range(n_bays): + t0 = i / n_bays + t1 = (i + 1) / n_bays + p_tl0, p_tr0, p_b0 = lerp3(boom_top_l, tail_top_l, t0), lerp3(boom_top_r, tail_top_r, t0), lerp3(boom_bot, tail_bot, t0) + p_tl1, p_tr1, p_b1 = lerp3(boom_top_l, tail_top_l, t1), lerp3(boom_top_r, tail_top_r, t1), lerp3(boom_bot, tail_bot, t1) + vc.make_swept_tube(f"boom_cross_{i}", [p_tl1, p_tr1, p_b1, p_tl1], 0.012, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + vc.make_swept_tube(f"boom_diag_l_{i}", [p_tl0, p_b1], 0.011, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + vc.make_swept_tube(f"boom_diag_r_{i}", [p_tr0, p_b1], 0.011, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + + # Swept-back V-tail stabilizers + ventral fin + tail hub + vc.make_box("tail_fin_hub", (0.16, 0.24, 0.20), "gunmetal", parent=chassis, location=(0.0, 2.36, 1.26), bevel=0.008) + for side in (-1.0, 1.0): + vc.make_box( + f"vtail_{'L' if side > 0 else 'R'}", + (0.04, 0.34, 0.62), + "olive_armor", + parent=chassis, + location=(side * 0.24, 2.40, 1.54), + rotation_deg=(22.0, side * -38.0, 0.0), + bevel=0.006, + ) + vc.make_box("ventral_fin", (0.035, 0.26, 0.24), "olive_armor", parent=chassis, location=(0.0, 2.36, 1.04), rotation_deg=(22.0, 0.0, 0.0), bevel=0.006) + + # --- 5. Visible Exterior Hardpoints (4x4 Dorsal Grid) --- + # 1) Chin gimbal collar (under nose, pointing +Z forward and -Y downward) + vc.add_hardpoint_slot( + "hp.weapon.chin", + "weapon", + parent=chassis, + location=(0.0, -1.46, 0.525), + rotation_deg=(5.7, 180.0, 0.0), + size=(0.42, 0.42, 0.08), + plinth_depth=0.04, + ) + # 2 & 3) Stub-wing weapon pylons (under left/right wings) + vc.add_hardpoint_slot( + "hp.weapon.wing_l", + "weapon", + parent=chassis, + location=(0.88, 0.14, 0.69), + rotation_deg=(0.0, 180.0, 0.0), + size=(0.34, 0.34, 0.07), + ) + vc.add_hardpoint_slot( + "hp.weapon.wing_r", + "weapon", + parent=chassis, + location=(-0.88, 0.14, 0.69), + rotation_deg=(0.0, 180.0, 0.0), + size=(0.34, 0.34, 0.07), + ) + # 4) Dorsal turbine core engine bay + vc.add_hardpoint_slot( + "hp.engine.core", + "engine", + parent=chassis, + location=(0.0, 0.26, 1.44), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.74, 0.80, 0.13), + ) + # 5 & 6) Twin copper-louvered nacelle root exhaust radiator bays + vc.add_hardpoint_slot( + "hp.radiator.nacelle_l", + "radiator", + parent=chassis, + location=(0.54, -0.32, 1.23), + rotation_deg=(72.0, 0.0, 34.0), + size=(0.36, 0.32, 0.09), + plinth_depth=0.04, + ) + vc.add_hardpoint_slot( + "hp.radiator.nacelle_r", + "radiator", + parent=chassis, + location=(-0.54, -0.32, 1.23), + rotation_deg=(72.0, 0.0, -34.0), + size=(0.36, 0.32, 0.09), + plinth_depth=0.04, + ) + + # --- 6. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "hornet" / "hornet.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "hornet" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "hornet_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="hornet", + name="Hornet", + vehicle_class="Light Ducted-Fan VTOL Gunship", + grid_width=4, + grid_height=4, + mask=[ + ".##.", + "####", + "####", + ".##.", + ], + hardpoints=[ + {"id": "hp.weapon.chin", "kind": "weapon", "x": 1, "y": 0, "w": 1, "h": 2, "modelNodeId": "hp.weapon.chin"}, + {"id": "hp.radiator.nacelle_l", "kind": "radiator", "x": 0, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.radiator.nacelle_l"}, + {"id": "hp.radiator.nacelle_r", "kind": "radiator", "x": 3, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.radiator.nacelle_r"}, + {"id": "hp.weapon.wing_l", "kind": "weapon", "x": 0, "y": 2, "w": 1, "h": 1, "modelNodeId": "hp.weapon.wing_l"}, + {"id": "hp.engine.core", "kind": "engine", "x": 1, "y": 2, "w": 2, "h": 2, "modelNodeId": "hp.engine.core"}, + {"id": "hp.weapon.wing_r", "kind": "weapon", "x": 3, "y": 2, "w": 1, "h": 1, "modelNodeId": "hp.weapon.wing_r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[hornet] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "hornet", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_hornet() diff --git a/tools/vehicles/build_ironclad.py b/tools/vehicles/build_ironclad.py new file mode 100644 index 0000000..a20dfeb --- /dev/null +++ b/tools/vehicles/build_ironclad.py @@ -0,0 +1,423 @@ +"""Build the Ironclad (Medium Tracked Battle Tank) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_mbt_track_pod(name: str, side: float, parent) -> None: + """Build one wide MBT track assembly with 5 double roadwheels, idler, sprocket, shoes, and bolted side skirt.""" + pod_x = side * 1.12 + pod = vc.make_empty(name, parent=parent, location=(pod_x, 0.0, 0.0)) + + rw_r = 0.28 + rw_z = rw_r + 0.045 + rw_ys = (-1.28, -0.64, 0.0, 0.64, 1.28) + idler_y, idler_z, idler_r = -1.94, 0.56, 0.25 + sproc_y, sproc_z, sproc_r = 1.92, 0.58, 0.26 + track_w = 0.48 + + # Roadwheels (5) + 3 return rollers + Front Idler + Rear Drive Sprocket + for i, ry in enumerate(rw_ys): + vc.make_tube_part( + f"{name}_rw_tire_{i}", rw_r, rw_r, track_w * 0.84, segments=16, + mat_name="rubber_dark", parent=pod, location=(-track_w * 0.42, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_rw_dish_{i}", rw_r * 0.68, rw_r * 0.68, track_w * 0.90, segments=12, + mat_name="olive_armor", parent=pod, location=(-track_w * 0.45, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_rw_cap_{i}", rw_r * 0.28, rw_r * 0.28, track_w * 0.94, segments=10, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.47, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + for j, rry in enumerate((-0.96, 0.0, 0.96)): + vc.make_tube_part( + f"{name}_ret_{j}", 0.09, 0.09, track_w * 0.68, segments=10, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.34, rry, 0.78), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_idler", idler_r, idler_r, track_w * 0.80, segments=14, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.40, idler_y, idler_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_sprocket", sproc_r, sproc_r, track_w * 0.84, segments=14, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.42, sproc_y, sproc_z), rotation_deg=(0.0, 90.0, 0.0), + ) + + # Track loop polyline in (y, z) + loop_yz: list[tuple[float, float]] = [] + for k in range(7): + ang = math.radians(95.0 + 145.0 * (k / 6.0)) + loop_yz.append((idler_y + math.cos(ang) * (idler_r + 0.03), idler_z + math.sin(ang) * (idler_r + 0.03))) + loop_yz.append((-1.28, 0.025)) + loop_yz.append((1.28, 0.025)) + for k in range(7): + ang = math.radians(-65.0 + 145.0 * (k / 6.0)) + loop_yz.append((sproc_y + math.cos(ang) * (sproc_r + 0.03), sproc_z + math.sin(ang) * (sproc_r + 0.03))) + loop_yz.append((0.60, 0.89)) + loop_yz.append((-0.60, 0.89)) + + path_3d = [[0.0, y, z] for (y, z) in loop_yz] + vc.make_swept_profile( + f"{name}_track_band", + "box", + 0.034, + track_w * 0.92, + 0.034, + path_3d, + up=[1.0, 0.0, 0.0], + mat_name="rubber_dark", + parent=pod, + closed=True, + ) + + # Articulated steel grouser shoes + pts = loop_yz + [loop_yz[0]] + segs = [math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]) for i in range(len(loop_yz))] + total_len = sum(segs) + n_shoes = 46 + + def build_shoes(bm: bmesh.types.BMesh) -> None: + for s_idx in range(n_shoes): + target_d = (s_idx / n_shoes) * total_len + acc = 0.0 + for i, sl in enumerate(segs): + if acc + sl >= target_d or i == len(segs) - 1: + t = (target_d - acc) / max(sl, 1e-6) + y0, z0 = pts[i] + y1, z1 = pts[i + 1] + py = y0 + (y1 - y0) * t + pz = z0 + (z1 - z0) * t + ang = math.atan2(z1 - z0, y1 - y0) + m = ( + Matrix.Translation((0.0, py, pz)) + @ Matrix.Rotation(ang, 4, "X") + @ Matrix.Diagonal((track_w, 0.095, 0.030, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + break + acc += sl + + vc.make_bmesh_object(f"{name}_shoes", build_shoes, "gunmetal", parent=pod) + + # Full-length top track fender + front/rear mudflaps + vc.make_box(f"{name}_fender_top", (track_w + 0.08, 4.18, 0.065), "olive_armor", parent=pod, location=(0.0, -0.02, 0.96), bevel=0.01) + vc.make_box(f"{name}_fender_front", (track_w + 0.08, 0.36, 0.06), "olive_armor", parent=pod, location=(0.0, -2.20, 0.84), rotation_deg=(38.0, 0.0, 0.0), bevel=0.008) + vc.make_box(f"{name}_fender_rear", (track_w + 0.08, 0.34, 0.06), "olive_armor", parent=pod, location=(0.0, 2.16, 0.84), rotation_deg=(-38.0, 0.0, 0.0), bevel=0.008) + + +def build_ironclad() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("IroncladRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. Lower Armored Tub & Welded Angular MBT Hull (Brokkr plate.v0) --- + vc.make_box("lower_tub", (1.74, 4.10, 0.52), "gunmetal", parent=chassis, location=(0.0, -0.02, 0.56), bevel=0.014) + + hull_pts = [ + [-0.87, -2.26, 0.52], [0.87, -2.26, 0.52], + [-0.90, -2.24, 0.74], [0.90, -2.24, 0.74], + [-0.92, -1.16, 1.16], [0.92, -1.16, 1.16], + [-0.92, 0.96, 1.16], [0.92, 0.96, 1.16], + [-0.88, 2.18, 0.96], [0.88, 2.18, 0.96], + [-0.86, 2.16, 0.54], [0.86, 2.16, 0.54], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "ironclad_hull", + "mat": "olive_armor", + "bevel": 0.015, + "sides": "one", + "mirror": False, + "points": hull_pts, + "clad": { + "mat": "olive_armor", + "facets": [{"n": [0.0, -0.36, 0.93], "cos": 0.88}], + "min_area": 0.16, + "lifts": [0.008, 0.014], + "inset": 0.06, + "gap": 0.018, + "split": 0.88, + "seed": 701, + "bolt_r": 0.013, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + }, + # Heavy bolted forward/mid track skirts (leaves rear flank clear for radiator bays) + { + "name": "ironclad_track_skirt", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [1.39, -0.44, 0.68], + "normal": [1.0, 0.0, 0.0], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-1.34, -0.26], [1.44, -0.26], [1.26, 0.28], [-1.34, 0.28]], + "thick": 0.048, + "taper": 0.010, + "back": 0.92, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.10, + "lifts": [0.008, 0.014], + "inset": 0.04, + "gap": 0.016, + "split": 0.72, + "seed": 702, + "bolt_r": 0.013, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.025, "spacing": 0.34, "mat": "gunmetal", "params": "r=0.013"}, + ], + }, + # Sloped upper hull sponson shoulders + { + "name": "ironclad_sponson", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [1.08, 0.16, 1.04], + "normal": [0.76, 0.0, 0.65], + "up": [-0.65, 0.0, 0.76], + "right": [0.0, -1.0, 0.0], + "outline": [[-1.72, -0.18], [1.72, -0.18], [1.56, 0.18], [-1.56, 0.18]], + "thick": 0.05, + "taper": 0.014, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.36, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Rear flank armored housings for radiator bays + driver periscope + headlights + tow shackles + vc.make_box("driver_periscope", (0.42, 0.14, 0.09), "smoked_glass", parent=chassis, location=(-0.30, -1.32, 1.18), bevel=0.005) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"headlight_box_{tag}", (0.18, 0.14, 0.12), "gunmetal", parent=chassis, location=(side * 1.08, -2.06, 1.04), bevel=0.008) + vc.make_box(f"headlight_lens_{tag}", (0.12, 0.04, 0.07), "smoked_glass", parent=chassis, location=(side * 1.08, -2.13, 1.04), bevel=0.003) + vc.make_box(f"tow_shackle_{tag}", (0.07, 0.12, 0.12), "signal_orange", parent=chassis, location=(side * 0.56, -2.28, 0.62), bevel=0.006) + # Rear flank radiator mounting box + exhaust armor box + vc.make_box(f"rear_rad_housing_{tag}", (0.18, 1.04, 0.50), "olive_armor", parent=chassis, location=(side * 1.28, 1.36, 0.78), bevel=0.01) + vc.make_box(f"rear_exhaust_box_{tag}", (0.42, 0.34, 0.24), "gunmetal", parent=chassis, location=(side * 0.62, 2.08, 0.86), bevel=0.01) + vc.make_swept_tube( + f"exhaust_pipe_{tag}", + [[side * 0.62, 2.12, 0.86], [side * 0.72, 2.26, 0.88], [side * 0.72, 2.34, 0.78]], + 0.042, + segments=10, + mat_name="copper_rad", + parent=chassis, + fillet_r=0.03, + ) + # External cylindrical stern fuel drums (signature Ironclad silhouette; tank extends along local +Z) + vc.make_kit_part( + f"stern_fuel_drum_{tag}", + "mechanical", + "tank", + {"radius": 0.17, "length": 0.76, "segments": 14}, + mat_name="olive_armor", + parent=chassis, + location=(side * 0.06, 2.24, 1.04), + rotation_deg=(0.0, side * 90.0, 0.0), + ) + + # --- 2. Wide Articulated MBT Track Pods --- + _build_mbt_track_pod("track_pod_L", 1.0, chassis) + _build_mbt_track_pod("track_pod_R", -1.0, chassis) + + # --- 3. Faceted Central MBT Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, -0.18, 1.16)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest = [{"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}] + + vc.make_tube_part("turret_race", 0.76, 0.82, 0.08, segments=24, mat_name="gunmetal", parent=turret_pivot) + + turret_pts = [ + [-0.58, -0.84, 0.08], [0.58, -0.84, 0.08], + [0.86, -0.20, 0.08], [0.76, 0.88, 0.08], + [-0.76, 0.88, 0.08], [-0.86, -0.20, 0.08], + [-0.46, -0.60, 0.50], [0.46, -0.60, 0.50], + [0.64, -0.10, 0.50], [0.58, 0.76, 0.50], + [-0.58, 0.76, 0.50], [-0.64, -0.10, 0.50], + ] + turret_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "ironclad_turret_shell", + "mat": "olive_armor", + "bevel": 0.014, + "sides": "one", + "mirror": False, + "points": turret_pts, + }, + { + "name": "ironclad_turret_cheek", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.62, -0.52, 0.28], + "normal": [0.64, -0.68, 0.35], + "up": [-0.24, 0.25, 0.94], + "right": [-0.73, -0.68, 0.0], + "outline": [[-0.28, -0.16], [0.28, -0.16], [0.22, 0.16], [-0.22, 0.16]], + "thick": 0.05, + "taper": 0.012, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.20, "mat": "gunmetal", "params": "r=0.011"}, + ], + }, + ], + } + vc.make_plates(turret_doc, parent=turret_pivot) + + # Turret mantlet, bustle rack, commander cupola, CITV optic, smoke dischargers & coax bracket + vc.make_box("turret_mantlet", (0.52, 0.24, 0.26), "gunmetal", parent=turret_pivot, location=(0.0, -0.82, 0.28), bevel=0.01) + vc.make_box("turret_bustle", (1.10, 0.44, 0.32), "olive_armor", parent=turret_pivot, location=(0.0, 0.98, 0.32), bevel=0.01) + vc.make_tube_part("commander_cupola", 0.17, 0.19, 0.09, segments=14, mat_name="olive_armor", parent=turret_pivot, location=(-0.36, 0.46, 0.50)) + vc.make_box("turret_citv_pod", (0.18, 0.20, 0.16), "gunmetal", parent=turret_pivot, location=(0.34, -0.32, 0.56), bevel=0.008) + vc.make_box("turret_citv_lens", (0.12, 0.05, 0.09), "smoked_glass", parent=turret_pivot, location=(0.34, -0.42, 0.57), bevel=0.004) + vc.make_box("coax_bracket", (0.36, 0.42, 0.10), "gunmetal", parent=turret_pivot, location=(0.64, -0.22, 0.34), bevel=0.008) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + for k in range(3): + vc.make_tube_part( + f"smoke_tube_{tag}_{k}", 0.030, 0.030, 0.17, segments=8, + mat_name="gunmetal", parent=turret_pivot, + location=(side * 0.80, 0.36 + k * 0.10, 0.30), rotation_deg=(-58.0, 0.0, side * 22.0), + ) + + # --- 4. Visible Exterior Hardpoints (4x5 Dorsal Grid) --- + # 1) hp.armor.front (0,0, 4x1) + vc.add_hardpoint_slot( + "hp.armor.front", + "armor", + parent=chassis, + location=(0.0, -1.72, 0.94), + rotation_deg=(68.0, 0.0, 0.0), + size=(1.46, 0.36, 0.09), + plinth_depth=0.04, + ) + # 2) hp.weapon.main (1,1, 2x2) + vc.add_hardpoint_slot( + "hp.weapon.main", + "weapon", + parent=turret_pivot, + location=(0.0, -0.02, 0.51), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.82, 0.82, 0.11), + ) + # 3) hp.weapon.coax (0,1, 1x1) on left turret cheek bracket + vc.add_hardpoint_slot( + "hp.weapon.coax", + "weapon", + parent=turret_pivot, + location=(0.66, -0.22, 0.39), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.38, 0.38, 0.08), + ) + # 4) hp.armor.skirts (3,1, 1x2) on right (-X) track skirt + vc.add_hardpoint_slot( + "hp.armor.skirts", + "armor", + parent=chassis, + location=(-1.42, -0.38, 0.68), + rotation_deg=(90.0, 0.0, -90.0), + size=(1.28, 0.32, 0.09), + ) + # 5) hp.engine.rear (1,3, 2x2) + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 1.48, 1.08), + rotation_deg=(-9.0, 0.0, 0.0), + size=(1.08, 0.92, 0.13), + ) + # 6 & 7) hp.radiator.l (0,3, 1x2) & hp.radiator.r (3,3, 1x2) + vc.add_hardpoint_slot( + "hp.radiator.l", + "radiator", + parent=chassis, + location=(1.36, 1.36, 0.78), + rotation_deg=(90.0, 0.0, 90.0), + size=(0.94, 0.44, 0.12), + ) + vc.add_hardpoint_slot( + "hp.radiator.r", + "radiator", + parent=chassis, + location=(-1.36, 1.36, 0.78), + rotation_deg=(90.0, 0.0, -90.0), + size=(0.94, 0.44, 0.12), + ) + + # --- 5. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "ironclad" / "ironclad.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "ironclad" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "ironclad_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="ironclad", + name="Ironclad", + vehicle_class="Medium Tracked Battle Tank", + grid_width=4, + grid_height=5, + mask=[ + "####", + "####", + "####", + "####", + "####", + ], + hardpoints=[ + {"id": "hp.armor.front", "kind": "armor", "x": 0, "y": 0, "w": 4, "h": 1, "modelNodeId": "hp.armor.front"}, + {"id": "hp.weapon.coax", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.weapon.coax"}, + {"id": "hp.weapon.main", "kind": "weapon", "x": 1, "y": 1, "w": 2, "h": 2, "modelNodeId": "hp.weapon.main"}, + {"id": "hp.armor.skirts", "kind": "armor", "x": 3, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.armor.skirts"}, + {"id": "hp.radiator.l", "kind": "radiator", "x": 0, "y": 3, "w": 1, "h": 2, "modelNodeId": "hp.radiator.l"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 1, "y": 3, "w": 2, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.r", "kind": "radiator", "x": 3, "y": 3, "w": 1, "h": 2, "modelNodeId": "hp.radiator.r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[ironclad] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "ironclad", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_ironclad() diff --git a/tools/vehicles/build_jackal.py b/tools/vehicles/build_jackal.py new file mode 100644 index 0000000..97bd932 --- /dev/null +++ b/tools/vehicles/build_jackal.py @@ -0,0 +1,405 @@ +"""Build the Jackal (Light Wheeled Dune Buggy) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def build_jackal() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("JackalRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # Dimensions & key coordinates (Blender: -Y forward, +Z up, +X left) + front_y = -1.12 + rear_y = 1.08 + track_x = 0.84 + wheel_r = 0.41 + wheel_w = 0.29 + axle_z = wheel_r + + # --- 1. Belly pan & central backbone --- + vc.make_box("belly_pan", (0.76, 2.24, 0.08), "gunmetal", parent=chassis, location=(0.0, 0.0, 0.34), bevel=0.01) + vc.make_box("front_diff", (0.28, 0.28, 0.20), "gunmetal", parent=chassis, location=(0.0, front_y, 0.42), bevel=0.01) + vc.make_box("rear_transaxle", (0.34, 0.36, 0.24), "gunmetal", parent=chassis, location=(0.0, rear_y, 0.44), bevel=0.01) + + # --- 2. Tubular Chromoly Rollcage & Bullbar (Brokkr core.sweep) --- + r_main = 0.025 + r_brace = 0.020 + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + # Lower sill rail + vc.make_swept_tube( + f"cage_sill_{tag}", + [ + [side * 0.30, -1.42, 0.48], + [side * 0.48, -0.78, 0.36], + [side * 0.48, 0.56, 0.36], + [side * 0.42, 1.38, 0.56], + ], + r_main, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + # Main A-pillar -> roof rail -> fastback B/C-pillar + vc.make_swept_tube( + f"cage_arch_{tag}", + [ + [side * 0.34, -1.24, 0.62], + [side * 0.44, -0.70, 0.82], + [side * 0.39, -0.14, 1.44], + [side * 0.39, 0.44, 1.44], + [side * 0.42, 1.38, 0.82], + [side * 0.42, 1.38, 0.56], + ], + r_main, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + # Mid beltline side bar + diagonal door brace + vc.make_swept_tube( + f"cage_belt_{tag}", + [ + [side * 0.45, -0.70, 0.78], + [side * 0.48, 0.52, 0.78], + [side * 0.42, 1.36, 0.80], + ], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + vc.make_swept_tube( + f"cage_diag_{tag}", + [[side * 0.46, -0.45, 0.42], [side * 0.41, 0.42, 1.42]], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + # Shock tower hoop + vc.make_swept_tube( + f"shock_hoop_{tag}", + [ + [side * 0.32, -1.28, 0.54], + [side * 0.38, -1.04, 0.80], + [side * 0.38, -0.78, 0.74], + ], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + + # Transverse rollcage crossbars & front tubular bullbar + for idx, (y_pos, z_pos, half_w) in enumerate([ + (-0.70, 0.82, 0.44), + (-0.14, 1.44, 0.39), + (0.44, 1.44, 0.39), + (0.54, 0.78, 0.46), + (1.38, 0.82, 0.42), + (1.38, 0.56, 0.42), + ]): + vc.make_swept_tube( + f"cage_cross_{idx}", + [[-half_w, y_pos, z_pos], [half_w, y_pos, z_pos]], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + + # Front stinger bullbar + twin headlights + vc.make_swept_tube( + "front_bullbar", + [ + [-0.32, -1.40, 0.48], + [-0.24, -1.64, 0.56], + [-0.16, -1.68, 0.68], + [0.16, -1.68, 0.68], + [0.24, -1.64, 0.56], + [0.32, -1.40, 0.48], + ], + r_main, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + for side in (-1.0, 1.0): + vc.make_tube_part( + f"headlight_{'L' if side > 0 else 'R'}", + r0=0.045, + r1=0.055, + length=0.08, + segments=12, + mat_name="gunmetal", + parent=chassis, + location=(side * 0.28, -1.46, 0.66), + rotation_deg=(90.0, 0.0, 0.0), + ) + + # --- 3. Hard Armour Plates (Brokkr plate.v0) --- + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "jackal_side", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.47, -0.05, 0.58], + "normal": [1.0, 0.0, 0.14], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.58, -0.16], [0.58, -0.14], [0.68, 0.16], [-0.42, 0.22]], + "thick": 0.04, + "taper": 0.015, + "back": 0.92, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.04, + "lifts": [0.008, 0.012], + "inset": 0.04, + "gap": 0.015, + "split": 0.55, + "seed": 401, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.26, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + { + "name": "jackal_hood", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "slab": { + "at": [0.0, -0.98, 0.73], + "normal": [0.0, -0.32, 0.95], + "up": [0.0, -0.95, -0.32], + "right": [1.0, 0.0, 0.0], + "outline": [[-0.28, 0.30], [0.28, 0.30], [0.38, -0.28], [-0.38, -0.28]], + "thick": 0.045, + "taper": 0.018, + "back": 0.90, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.05, + "lifts": [0.008, 0.014], + "inset": 0.04, + "gap": 0.014, + "split": 0.60, + "seed": 402, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.24, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + { + "name": "jackal_roof", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "slab": { + "at": [0.0, 0.14, 1.455], + "normal": [0.0, 0.0, 1.0], + "up": [0.0, -1.0, 0.0], + "right": [1.0, 0.0, 0.0], + "outline": {"w": 0.74, "h": 0.62, "clip": 0.08}, + "thick": 0.036, + "taper": 0.012, + "back": 0.94, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.22, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # --- 4. Cockpit Seats & Firewall --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"seat_base_{tag}", (0.32, 0.34, 0.08), "rubber_dark", parent=chassis, location=(side * 0.20, 0.08, 0.42), bevel=0.01) + vc.make_box(f"seat_back_{tag}", (0.30, 0.08, 0.48), "rubber_dark", parent=chassis, location=(side * 0.20, 0.24, 0.68), rotation_deg=(14.0, 0.0, 0.0), bevel=0.01) + vc.make_box("rear_firewall", (0.76, 0.04, 0.42), "gunmetal", parent=chassis, location=(0.0, 0.46, 0.60), bevel=0.005) + vc.make_swept_tube("steer_col", [[0.18, -0.58, 0.80], [0.18, -0.34, 0.92]], 0.018, segments=8, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + + # --- 5. Double-Wishbone Suspension, Coilovers & 4 Knobby Wheels --- + joints_manifest: list[dict] = [] + + for is_front, y_ax, prefix in [(True, front_y, "f"), (False, rear_y, "r")]: + for side, s_tag in [(1.0, "l"), (-1.0, "r")]: + j_suffix = f"{prefix}{s_tag}" + in_x = side * 0.24 + out_x = side * 0.68 + # Upper & lower A-arms (two separate wishbone legs meeting at the ball joint) + for leg_tag, dy in (("a", -0.16), ("b", 0.16)): + vc.make_swept_tube( + f"wishbone_lo_{j_suffix}_{leg_tag}", + [[in_x, y_ax + dy, 0.36], [out_x, y_ax, axle_z - 0.06]], + 0.018, + segments=6, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + for leg_tag, dy in (("a", -0.14), ("b", 0.14)): + vc.make_swept_tube( + f"wishbone_hi_{j_suffix}_{leg_tag}", + [[in_x, y_ax + dy, 0.52], [out_x, y_ax, axle_z + 0.08]], + 0.016, + segments=6, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + # Coilover shock strut from knuckle up to shock tower + tower_z = 0.80 if is_front else 0.86 + tower_y = y_ax + (0.04 if is_front else -0.06) + vc.make_ram_span( + f"coilover_{j_suffix}", + [side * 0.40, tower_y, tower_z], + [side * 0.62, y_ax, axle_z - 0.02], + body_r=0.028, + rod_r=0.016, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="gunmetal", + coil_rings=6, + ) + + # Steering knuckle (front only) + wheel hub spin joint + knuckle_loc = (side * track_x, y_ax, axle_z) + if is_front: + steer_id = f"joint.steer_{j_suffix}" + steer_node = vc.make_empty(steer_id, parent=chassis, location=(side * 0.68, y_ax, axle_z)) + vc.tag_joint(steer_node, steer_id, [0.0, 1.0, 0.0], -32.0, 32.0) + joints_manifest.append({"id": steer_id, "axis": [0.0, 1.0, 0.0], "min": -32.0, "max": 32.0}) + vc.make_box(f"knuckle_{j_suffix}", (0.08, 0.11, 0.18), "gunmetal", parent=steer_node, bevel=0.005) + wheel_parent = steer_node + wheel_loc = (side * (track_x - 0.68), 0.0, 0.0) + else: + vc.make_box(f"hub_carrier_{j_suffix}", (0.10, 0.12, 0.18), "gunmetal", parent=chassis, location=(side * 0.68, y_ax, axle_z), bevel=0.005) + wheel_parent = chassis + wheel_loc = knuckle_loc + + wheel_id = f"joint.wheel_{j_suffix}" + wheel_pivot = vc.make_knobby_wheel( + wheel_id, + radius=wheel_r, + width=wheel_w, + parent=wheel_parent, + location=wheel_loc, + tread_lugs=16, + rim_segments=18, + side_sign=int(side), + ) + wheel_pivot.name = wheel_id + vc.tag_joint(wheel_pivot, wheel_id, [1.0, 0.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": wheel_id, "axis": [1.0, 0.0, 0.0], "min": -360.0, "max": 360.0}) + + # --- 6. Visible Exterior Hardpoint Slots --- + # 1) Roof weapon collar ring + vc.add_hardpoint_slot( + "hp.weapon.roof", + "weapon", + parent=chassis, + location=(0.0, 0.14, 1.47), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.62, 0.10), + ) + # 2) Open rear engine bay frame + mounting tray + twin exhaust sweeps + vc.make_box("rear_engine_tray", (0.64, 0.74, 0.06), "gunmetal", parent=chassis, location=(0.0, 0.90, 0.51), bevel=0.006) + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 0.90, 0.53), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.72, 0.16), + ) + for side in (-1.0, 1.0): + vc.make_swept_tube( + f"exhaust_{'L' if side > 0 else 'R'}", + [ + [side * 0.24, 0.78, 0.68], + [side * 0.36, 1.12, 0.66], + [side * 0.38, 1.48, 0.74], + ], + 0.028, + segments=8, + mat_name="copper_rad", + parent=chassis, + ) + # 3) Upright rear copper radiator louver bay seated on rear cage shroud + vc.make_box("rear_rad_shroud", (0.60, 0.06, 0.36), "gunmetal", parent=chassis, location=(0.0, 1.36, 0.74), rotation_deg=(28.0, 0.0, 0.0), bevel=0.006) + vc.add_hardpoint_slot( + "hp.radiator.rear", + "radiator", + parent=chassis, + location=(0.0, 1.34, 0.75), + rotation_deg=(-62.0, 0.0, 0.0), + size=(0.58, 0.44, 0.11), + ) + vc.make_box("rad_header_tank", (0.58, 0.09, 0.08), "copper_rad", parent=chassis, location=(0.0, 1.44, 0.95), bevel=0.008) + + # --- 7. Export GLB, Manifest & 4-Panel Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "jackal" / "jackal.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "jackal" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "jackal_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="jackal", + name="Jackal", + vehicle_class="Light Wheeled Dune Buggy", + grid_width=3, + grid_height=4, + mask=[ + "###", + "###", + "###", + "###", + ], + hardpoints=[ + {"id": "hp.weapon.roof", "kind": "weapon", "x": 1, "y": 0, "w": 1, "h": 2, "modelNodeId": "hp.weapon.roof"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 1, "y": 2, "w": 1, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.rear", "kind": "radiator", "x": 2, "y": 3, "w": 1, "h": 1, "modelNodeId": "hp.radiator.rear"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[jackal] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "jackal", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_jackal() diff --git a/tools/vehicles/build_mammoth.py b/tools/vehicles/build_mammoth.py new file mode 100644 index 0000000..e4292ff --- /dev/null +++ b/tools/vehicles/build_mammoth.py @@ -0,0 +1,460 @@ +"""Build the Mammoth (Heavy 8x8 Armored Fire Support Rig) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def build_mammoth() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("MammothRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # Dimensions (Blender: -Y forward, +Z up, +X left) + axle_ys = [ + ("f1", -1.90, True), + ("f2", -0.74, True), + ("r1", 0.74, False), + ("r2", 1.90, False), + ] + track_x = 1.24 + wheel_r = 0.52 + wheel_w = 0.38 + axle_z = wheel_r + + # --- 1. Heavy Armored Lower Tub, Frame Rails, Axles & Suspension --- + vc.make_box("lower_tub", (1.64, 4.94, 0.62), "gunmetal", parent=chassis, location=(0.0, -0.02, 0.82), bevel=0.015) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"frame_rail_{tag}", (0.14, 5.10, 0.20), "gunmetal", parent=chassis, location=(side * 0.68, -0.04, 0.62), bevel=0.01) + # Side fuel tank / battery box tucked between front and rear tandem wheel pairs + vc.make_box(f"side_stowage_{tag}", (0.42, 0.72, 0.44), "olive_armor", parent=chassis, location=(side * 1.08, 0.0, 0.86), bevel=0.01) + # Crew entry door + boarding ladder step on mid-hull flank + vc.make_box(f"crew_step_{tag}", (0.16, 0.44, 0.06), "gunmetal", parent=chassis, location=(side * 1.32, 0.0, 0.62), bevel=0.006) + vc.make_box(f"crew_door_{tag}", (0.06, 0.56, 0.78), "olive_armor", parent=chassis, location=(side * 1.28, 0.0, 1.24), bevel=0.008) + + for idx, (a_tag, y_ax, _) in enumerate(axle_ys): + vc.make_tube_part( + f"axle_tube_{a_tag}", + 0.075, + 0.075, + track_x * 1.68, + segments=10, + mat_name="gunmetal", + parent=chassis, + location=(-track_x * 0.84, y_ax, axle_z), + rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_box(f"diff_{a_tag}", (0.34, 0.34, 0.28), "gunmetal", parent=chassis, location=(0.0, y_ax, axle_z), bevel=0.012) + for side in (-1.0, 1.0): + s_tag = "L" if side > 0 else "R" + vc.make_ram_span( + f"strut_{a_tag}_{s_tag}", + [side * 0.74, y_ax, 1.02], + [side * 0.98, y_ax, axle_z + 0.02], + body_r=0.040, + rod_r=0.022, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + coil_rings=0, + ) + + # --- 2. Faceted 8x8 Armored Hull & Bolted Sponson Plates (Brokkr plate.v0) --- + hull_pts = [ + # Lower hull belt above wheel arches (z = 1.14) + [-1.34, -2.26, 1.14], [1.34, -2.26, 1.14], + [-1.36, 2.26, 1.14], [1.36, 2.26, 1.14], + # Lower nose & lower tail bevel + [-1.08, -2.62, 1.02], [1.08, -2.62, 1.02], + [-1.12, 2.64, 1.12], [1.12, 2.64, 1.12], + # Roof deck (z = 1.66) + [-1.14, -1.78, 1.66], [1.14, -1.78, 1.66], + [-1.16, 1.88, 1.66], [1.16, 1.88, 1.66], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "mammoth_hull", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": hull_pts, + "clad": { + "mat": "olive_armor", + "facets": [{"n": [0.0, -0.55, 0.83], "cos": 0.85}, {"n": [0.0, 0.0, 1.0], "cos": 0.95}], + "min_area": 0.18, + "lifts": [0.008, 0.014], + "inset": 0.06, + "gap": 0.018, + "split": 0.88, + "seed": 801, + "bolt_r": 0.014, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + }, + # Sloped upper side cheek armor with bolted applique panels + { + "name": "mammoth_side_cheek", + "mat": "olive_armor", + "bevel": 0.010, + "sides": "both", + "mirror": False, + "slab": { + "at": [1.26, -0.04, 1.40], + "normal": [0.92, 0.0, 0.38], + "up": [-0.38, 0.0, 0.92], + "right": [0.0, -1.0, 0.0], + "outline": [[-1.92, -0.24], [1.92, -0.24], [1.72, 0.24], [-1.72, 0.24]], + "thick": 0.055, + "taper": 0.015, + "back": 0.92, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.14, + "lifts": [0.008, 0.014], + "inset": 0.05, + "gap": 0.016, + "split": 0.72, + "seed": 802, + "bolt_r": 0.013, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.025, "spacing": 0.36, "mat": "gunmetal", "params": "r=0.013"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Heavy flared wheel arches over all 4 wheel stations on each side + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + for a_tag, y_ax, _ in axle_ys: + # Top arch cap + angled front/rear lip flaps + vc.make_box(f"arch_top_{tag}_{a_tag}", (0.44, 0.68, 0.07), "olive_armor", parent=chassis, location=(side * 1.24, y_ax, 1.14), bevel=0.008) + vc.make_box(f"arch_f_{tag}_{a_tag}", (0.44, 0.32, 0.07), "olive_armor", parent=chassis, location=(side * 1.24, y_ax - 0.44, 1.02), rotation_deg=(36.0, 0.0, 0.0), bevel=0.008) + vc.make_box(f"arch_r_{tag}_{a_tag}", (0.44, 0.32, 0.07), "olive_armor", parent=chassis, location=(side * 1.24, y_ax + 0.44, 1.02), rotation_deg=(-36.0, 0.0, 0.0), bevel=0.008) + + # Front nose recessed grille, armored headlights, driver slit & rearview mirrors + vc.make_box("front_grille", (1.22, 0.14, 0.34), "socket_bay", parent=chassis, location=(0.0, -2.58, 0.96), bevel=0.008) + for k in range(4): + vc.make_box(f"grille_slat_{k}", (1.16, 0.06, 0.03), "gunmetal", parent=chassis, location=(0.0, -2.64, 0.86 + k * 0.07), bevel=0.003) + vc.make_box("driver_periscope", (0.56, 0.16, 0.10), "smoked_glass", parent=chassis, location=(-0.38, -1.96, 1.60), rotation_deg=(-22.0, 0.0, 0.0), bevel=0.005) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"headlight_box_{tag}", (0.24, 0.16, 0.16), "gunmetal", parent=chassis, location=(side * 0.88, -2.54, 1.06), bevel=0.008) + vc.make_box(f"headlight_lens_{tag}", (0.16, 0.04, 0.09), "smoked_glass", parent=chassis, location=(side * 0.88, -2.62, 1.06), bevel=0.003) + vc.make_box(f"tow_shackle_{tag}", (0.08, 0.14, 0.14), "signal_orange", parent=chassis, location=(side * 0.48, -2.66, 0.72), bevel=0.006) + # Rear corner tail light housing + vc.make_box(f"taillight_{tag}", (0.18, 0.12, 0.14), "gunmetal", parent=chassis, location=(side * 1.04, 2.58, 1.12), bevel=0.006) + + # --- 3. Reinforced Front Dozer Ram Plow --- + plow_root = vc.make_empty("dozer_plow", parent=chassis, location=(0.0, -2.86, 0.56)) + def build_plow_blade(bm: bmesh.types.BMesh) -> None: + # Curved multi-segment scoop profile extruded across width X = [-1.34, +1.34] + prof = [ + (-0.34, -0.34), # bottom cutting lip + (-0.22, -0.14), + (-0.04, 0.06), + (0.02, 0.26), + (-0.14, 0.42), # upper curved spill lip + (0.04, 0.42), + (0.14, 0.22), + (0.08, -0.12), + (-0.18, -0.34), + ] + hw = 1.34 + verts_l = [bm.verts.new((hw, y, z)) for (y, z) in prof] + verts_r = [bm.verts.new((-hw, y, z)) for (y, z) in prof] + n = len(prof) + for i in range(n): + j = (i + 1) % n + bm.faces.new([verts_l[i], verts_l[j], verts_r[j], verts_r[i]]) + bm.faces.new(verts_l) + bm.faces.new(list(reversed(verts_r))) + + vc.make_bmesh_object("plow_moldboard", build_plow_blade, "olive_armor", parent=plow_root, bevel=0.012) + vc.make_box("plow_cutting_edge", (2.72, 0.16, 0.07), "gunmetal", parent=plow_root, location=(0.0, -0.28, -0.32), rotation_deg=(16.0, 0.0, 0.0), bevel=0.006) + for gx in (-0.98, -0.48, 0.0, 0.48, 0.98): + vc.make_box(f"plow_rib_{gx:.2f}", (0.07, 0.18, 0.62), "gunmetal", parent=plow_root, location=(gx, 0.12, 0.06), bevel=0.006) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"plow_wing_{tag}", (0.12, 0.48, 0.68), "olive_armor", parent=plow_root, location=(side * 1.36, -0.10, 0.04), bevel=0.008) + # Hydraulic push arms + tilt rams + vc.make_box(f"plow_pusharm_{tag}", (0.12, 0.72, 0.14), "gunmetal", parent=chassis, location=(side * 0.66, -2.56, 0.56), bevel=0.008) + vc.make_ram_span( + f"plow_ram_{tag}", + [side * 0.66, -2.42, 0.90], + [side * 0.66, -2.80, 0.76], + body_r=0.042, + rod_r=0.024, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + + # --- 4. Rear Diesel Exhaust Stacks --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_swept_tube( + f"exhaust_stack_{tag}", + [ + [side * 1.02, 2.24, 1.36], + [side * 1.06, 2.46, 1.56], + [side * 1.06, 2.46, 2.18], + [side * 1.06, 2.60, 2.30], + ], + 0.062, + segments=12, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.06, + ) + vc.make_tube_part( + f"exhaust_shield_{tag}", + 0.09, + 0.09, + 0.52, + segments=10, + inner0=0.078, + inner1=0.078, + mat_name="copper_rad", + parent=chassis, + location=(side * 1.06, 2.46, 1.62), + ) + + # --- 5. 8x8 Wheels & Front 4 Steering Knuckles --- + joints_manifest: list[dict] = [] + for a_tag, y_ax, steerable in axle_ys: + for side, s_tag in ((1.0, "l"), (-1.0, "r")): + j_suffix = f"{a_tag[0]}{s_tag}{a_tag[1]}" # fl1, fr1, fl2, fr2, rl1, rr1, rl2, rr2 + if steerable: + steer_id = f"joint.steer_{j_suffix}" + steer_node = vc.make_empty(steer_id, parent=chassis, location=(side * 0.98, y_ax, axle_z)) + vc.tag_joint(steer_node, steer_id, [0.0, 1.0, 0.0], -28.0, 28.0) + joints_manifest.append({"id": steer_id, "axis": [0.0, 1.0, 0.0], "min": -28.0, "max": 28.0}) + vc.make_box(f"knuckle_{j_suffix}", (0.10, 0.14, 0.22), "gunmetal", parent=steer_node, bevel=0.006) + wheel_parent = steer_node + wheel_loc = (side * (track_x - 0.98), 0.0, 0.0) + else: + vc.make_box(f"hub_carrier_{j_suffix}", (0.12, 0.16, 0.22), "gunmetal", parent=chassis, location=(side * 0.98, y_ax, axle_z), bevel=0.006) + wheel_parent = chassis + wheel_loc = (side * track_x, y_ax, axle_z) + + wheel_id = f"joint.wheel_{j_suffix}" + wheel_pivot = vc.make_knobby_wheel( + wheel_id, + radius=wheel_r, + width=wheel_w, + parent=wheel_parent, + location=wheel_loc, + tread_lugs=14, + rim_segments=16, + side_sign=int(side), + ) + wheel_pivot.name = wheel_id + vc.tag_joint(wheel_pivot, wheel_id, [1.0, 0.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": wheel_id, "axis": [1.0, 0.0, 0.0], "min": -360.0, "max": 360.0}) + + # --- 6. Broad Angular Central Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, -0.18, 1.66)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest.append({"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}) + + vc.make_tube_part("turret_race", 0.74, 0.80, 0.08, segments=24, mat_name="gunmetal", parent=turret_pivot) + turret_pts = [ + [-0.64, -0.78, 0.08], [0.64, -0.78, 0.08], + [0.84, -0.22, 0.08], [0.76, 0.94, 0.08], + [-0.76, 0.94, 0.08], [-0.84, -0.22, 0.08], + [-0.50, -0.60, 0.56], [0.50, -0.60, 0.56], + [0.64, -0.14, 0.56], [0.58, 0.78, 0.56], + [-0.58, 0.78, 0.56], [-0.64, -0.14, 0.56], + ] + turret_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "mammoth_turret_shell", + "mat": "olive_armor", + "bevel": 0.015, + "sides": "one", + "mirror": False, + "points": turret_pts, + }, + { + "name": "mammoth_turret_cheek", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.74, 0.14, 0.30], + "normal": [0.94, 0.0, 0.34], + "up": [-0.34, 0.0, 0.94], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.52, -0.16], [0.52, -0.16], [0.42, 0.16], [-0.42, 0.16]], + "thick": 0.045, + "taper": 0.012, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.24, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + ], + } + vc.make_plates(turret_doc, parent=turret_pivot) + + # Turret bustle stowage rack, commander hatch, optics & smoke launchers + vc.make_box("turret_bustle", (1.08, 0.42, 0.34), "gunmetal", parent=turret_pivot, location=(0.0, 0.98, 0.34), bevel=0.01) + vc.make_tube_part("commander_cupola", 0.22, 0.24, 0.10, segments=14, mat_name="olive_armor", parent=turret_pivot, location=(-0.28, 0.34, 0.56)) + vc.make_box("turret_sight", (0.20, 0.22, 0.14), "smoked_glass", parent=turret_pivot, location=(0.24, -0.38, 0.62), bevel=0.008) + vc.make_box("turret_mantlet_bar", (0.94, 0.18, 0.18), "gunmetal", parent=turret_pivot, location=(0.0, -0.70, 0.30), bevel=0.01) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + for k in range(3): + vc.make_tube_part( + f"smoke_tube_{tag}_{k}", + 0.032, + 0.032, + 0.18, + segments=8, + mat_name="gunmetal", + parent=turret_pivot, + location=(side * 0.78, 0.42 + k * 0.10, 0.34), + rotation_deg=(-58.0, 0.0, side * 22.0), + ) + + # --- 7. Visible Exterior Hardpoints (4x6 Dorsal Grid) --- + # 1) hp.armor.glacis (0,0, 4x1) + vc.add_hardpoint_slot( + "hp.armor.glacis", + "armor", + parent=chassis, + location=(0.0, -2.20, 1.36), + rotation_deg=(53.0, 0.0, 0.0), + size=(1.54, 0.38, 0.10), + plinth_depth=0.03, + ) + # 2) hp.weapon.bow (0,1, 1x1) on front-left bow deck + vc.make_box("bow_weapon_plinth", (0.48, 0.50, 0.12), "gunmetal", parent=chassis, location=(0.88, -1.48, 1.62), bevel=0.008) + vc.add_hardpoint_slot( + "hp.weapon.bow", + "weapon", + parent=chassis, + location=(0.88, -1.48, 1.68), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.46, 0.46, 0.09), + ) + # 3) hp.weapon.turret_l (1,1, 1x2) & 4) hp.weapon.turret_r (2,1, 1x2) on turret roof + vc.add_hardpoint_slot( + "hp.weapon.turret_l", + "weapon", + parent=turret_pivot, + location=(0.36, -0.10, 0.57), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.56, 0.56, 0.10), + ) + vc.add_hardpoint_slot( + "hp.weapon.turret_r", + "weapon", + parent=turret_pivot, + location=(-0.36, -0.10, 0.57), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.56, 0.56, 0.10), + ) + # 5) hp.armor.flanks (3,1, 1x2) on right (-X) upper cheek + vc.add_hardpoint_slot( + "hp.armor.flanks", + "armor", + parent=chassis, + location=(-1.32, -0.16, 1.38), + rotation_deg=(90.0, 0.0, -90.0), + size=(1.12, 0.32, 0.10), + ) + # 6) hp.engine.rear (1,3, 2x2) + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 1.34, 1.66), + rotation_deg=(0.0, 0.0, 0.0), + size=(1.14, 1.04, 0.14), + ) + # 7 & 8) hp.radiator.l (0,4, 1x2) & hp.radiator.r (3,4, 1x2) + vc.add_hardpoint_slot( + "hp.radiator.l", + "radiator", + parent=chassis, + location=(1.28, 1.40, 1.38), + rotation_deg=(90.0, 0.0, 90.0), + size=(0.98, 0.44, 0.12), + ) + vc.add_hardpoint_slot( + "hp.radiator.r", + "radiator", + parent=chassis, + location=(-1.28, 1.40, 1.38), + rotation_deg=(90.0, 0.0, -90.0), + size=(0.98, 0.44, 0.12), + ) + + # --- 8. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "mammoth" / "mammoth.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "mammoth" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "mammoth_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="mammoth", + name="Mammoth", + vehicle_class="Heavy 8x8 Armored Fire Support Rig", + grid_width=4, + grid_height=6, + mask=[ + "####", + "####", + "####", + "####", + "####", + "####", + ], + hardpoints=[ + {"id": "hp.armor.glacis", "kind": "armor", "x": 0, "y": 0, "w": 4, "h": 1, "modelNodeId": "hp.armor.glacis"}, + {"id": "hp.weapon.bow", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.weapon.bow"}, + {"id": "hp.weapon.turret_l", "kind": "weapon", "x": 1, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.turret_l"}, + {"id": "hp.weapon.turret_r", "kind": "weapon", "x": 2, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.turret_r"}, + {"id": "hp.armor.flanks", "kind": "armor", "x": 3, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.armor.flanks"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 1, "y": 3, "w": 2, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.l", "kind": "radiator", "x": 0, "y": 4, "w": 1, "h": 2, "modelNodeId": "hp.radiator.l"}, + {"id": "hp.radiator.r", "kind": "radiator", "x": 3, "y": 4, "w": 1, "h": 2, "modelNodeId": "hp.radiator.r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[mammoth] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "mammoth", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_mammoth() diff --git a/tools/vehicles/build_mule.py b/tools/vehicles/build_mule.py new file mode 100644 index 0000000..b5223dd --- /dev/null +++ b/tools/vehicles/build_mule.py @@ -0,0 +1,299 @@ +"""Build the Mule (Medium 6x6 Armored Gun Truck) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def build_mule() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("MuleRoot") + chassis = vc.make_empty("Chassis", parent=root) + + front_y = -1.52 + mid_y = 0.88 + rear_y = 1.92 + track_x = 0.98 + wheel_r = 0.49 + wheel_w = 0.34 + axle_z = wheel_r + + # --- 1. Ladder Frame Rails, Axles, Bumper & Fuel Tanks --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"frame_rail_{tag}", (0.12, 4.54, 0.18), "gunmetal", parent=chassis, location=(side * 0.46, 0.0, 0.62), bevel=0.008) + # Side cylindrical fuel tanks (Brokkr mechanical kit tank) + vc.make_kit_part( + f"fuel_tank_{tag}", + "mechanical", + "tank", + {"radius": 0.19, "length": 0.86, "segments": 14}, + mat_name="gunmetal", + parent=chassis, + location=(side * 0.78, -0.35, 0.56), + rotation_deg=(90.0, 0.0, 0.0), + ) + + for idx, y_ax in enumerate((front_y, mid_y, rear_y)): + vc.make_tube_part( + f"axle_tube_{idx}", + 0.065, + 0.065, + track_x * 1.66, + segments=10, + mat_name="gunmetal", + parent=chassis, + location=(-track_x * 0.83, y_ax, axle_z), + rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_box(f"diff_{idx}", (0.28, 0.28, 0.24), "gunmetal", parent=chassis, location=(0.0, y_ax, axle_z), bevel=0.01) + + # Heavy front steel bumper + tow shackles + vc.make_box("front_bumper", (2.16, 0.24, 0.24), "gunmetal", parent=chassis, location=(0.0, -2.26, 0.66), bevel=0.014) + for side in (-1.0, 1.0): + vc.make_box(f"bumper_shackle_{'L' if side > 0 else 'R'}", (0.07, 0.12, 0.14), "signal_orange", parent=chassis, location=(side * 0.52, -2.40, 0.62), bevel=0.006) + vc.make_box(f"headlight_box_{'L' if side > 0 else 'R'}", (0.16, 0.12, 0.14), "gunmetal", parent=chassis, location=(side * 0.78, -2.18, 0.92), bevel=0.008) + + # --- 2. Armored Hood & Sloped Armored Cab (Brokkr plate.v0 + faceted cab) --- + # Hood core + front grille frame + vc.make_box("hood_core", (1.36, 1.06, 0.60), "olive_armor", parent=chassis, location=(0.0, -1.66, 1.04), bevel=0.015) + vc.make_box("cab_lower", (1.84, 1.18, 0.68), "olive_armor", parent=chassis, location=(0.0, -0.54, 1.06), bevel=0.015) + + # Sloped upper armored cab via plate.v0 convex hull ("faces" / "points") + cab_pts = [ + [-0.90, -1.12, 1.34], [0.90, -1.12, 1.34], + [0.90, 0.04, 1.34], [-0.90, 0.04, 1.34], + [-0.78, -0.82, 2.02], [0.78, -0.82, 2.02], + [0.80, 0.02, 2.02], [-0.80, 0.02, 2.02], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "mule_cab_upper", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": cab_pts, + }, + # Flared front wheel fenders + { + "name": "mule_fender_front", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.92, -1.52, 1.08], + "normal": [0.18, 0.0, 0.98], + "up": [0.0, -1.0, 0.0], + "right": [0.98, 0.0, -0.18], + "outline": [[-0.24, 0.54], [0.24, 0.54], [0.24, -0.54], [-0.24, -0.54]], + "thick": 0.06, + "taper": 0.015, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.28, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + # Armored cab doors with stepped clad panels + { + "name": "mule_door", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.93, -0.54, 1.18], + "normal": [1.0, 0.0, 0.0], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.44, -0.34], [0.44, -0.34], [0.40, 0.36], [-0.44, 0.36]], + "thick": 0.04, + "taper": 0.012, + "back": 0.94, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.06, + "lifts": [0.008, 0.012], + "inset": 0.04, + "gap": 0.014, + "split": 0.65, + "seed": 501, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "part", "part": "handle", "at": [0.24, -0.04], "roll": 0.0, "mat": "gunmetal", "params": "length=0.20;lift=0.045;r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Armored smoked glass windshield slit & side viewports + vc.make_box("windshield_slit", (1.28, 0.08, 0.16), "smoked_glass", parent=chassis, location=(0.0, -0.98, 1.68), rotation_deg=(-22.0, 0.0, 0.0), bevel=0.004) + for side in (-1.0, 1.0): + vc.make_box(f"side_glass_{'L' if side > 0 else 'R'}", (0.06, 0.46, 0.22), "smoked_glass", parent=chassis, location=(side * 0.86, -0.46, 1.66), rotation_deg=(0.0, side * -12.0, 0.0), bevel=0.004) + + # --- 3. Open Armored Cargo Bed + Rear Mudguards --- + vc.make_box("bed_floor", (2.06, 2.26, 0.12), "gunmetal", parent=chassis, location=(0.0, 1.24, 0.92), bevel=0.01) + # Bed side walls (stepped armor with ribs & tubular top grab rail) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"bed_wall_{tag}", (0.10, 2.22, 0.68), "olive_armor", parent=chassis, location=(side * 0.98, 1.24, 1.32), bevel=0.01) + for ry in (0.35, 0.95, 1.55, 2.15): + vc.make_box(f"bed_rib_{tag}_{ry:.2f}", (0.05, 0.08, 0.64), "olive_armor", parent=chassis, location=(side * 1.04, ry, 1.32), bevel=0.004) + vc.make_swept_tube( + f"bed_rail_{tag}", + [[side * 0.98, 0.16, 1.68], [side * 0.98, 0.16, 1.82], [side * 0.98, 2.32, 1.82], [side * 0.98, 2.32, 1.68]], + 0.022, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.03, + ) + # Rear tandem fender flare + vc.make_box(f"rear_fender_{tag}", (0.38, 1.98, 0.08), "olive_armor", parent=chassis, location=(side * 0.94, 1.40, 1.06), bevel=0.008) + + # Tailgate + vc.make_box("bed_tailgate", (1.92, 0.10, 0.62), "olive_armor", parent=chassis, location=(0.0, 2.32, 1.29), bevel=0.01) + # Central turret pedestal drum in cargo bed + vc.make_tube_part("bed_pedestal", 0.44, 0.48, 0.58, segments=16, mat_name="gunmetal", parent=chassis, location=(0.0, 1.36, 0.98)) + + # --- 4. 6x6 Off-Road Wheels & Front Steering Knuckles --- + joints_manifest: list[dict] = [] + for axle_tag, y_ax, steerable in (("f", front_y, True), ("m", mid_y, False), ("r", rear_y, False)): + for side, s_tag in ((1.0, "l"), (-1.0, "r")): + j_suffix = f"{axle_tag}{s_tag}" + if steerable: + steer_id = f"joint.steer_{j_suffix}" + steer_node = vc.make_empty(steer_id, parent=chassis, location=(side * 0.80, y_ax, axle_z)) + vc.tag_joint(steer_node, steer_id, [0.0, 1.0, 0.0], -30.0, 30.0) + joints_manifest.append({"id": steer_id, "axis": [0.0, 1.0, 0.0], "min": -30.0, "max": 30.0}) + wheel_parent = steer_node + wheel_loc = (side * (track_x - 0.80), 0.0, 0.0) + else: + wheel_parent = chassis + wheel_loc = (side * track_x, y_ax, axle_z) + + wheel_id = f"joint.wheel_{j_suffix}" + wheel_pivot = vc.make_knobby_wheel( + wheel_id, + radius=wheel_r, + width=wheel_w, + parent=wheel_parent, + location=wheel_loc, + tread_lugs=16, + rim_segments=18, + side_sign=int(side), + ) + wheel_pivot.name = wheel_id + vc.tag_joint(wheel_pivot, wheel_id, [1.0, 0.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": wheel_id, "axis": [1.0, 0.0, 0.0], "min": -360.0, "max": 360.0}) + + # --- 5. Visible Exterior Hardpoints (3x5 Dorsal Grid) --- + # Front bumper/grille armor rail + vc.add_hardpoint_slot( + "hp.armor.front", + "armor", + parent=chassis, + location=(0.0, -2.18, 1.00), + rotation_deg=(90.0, 0.0, 0.0), + size=(1.32, 0.36, 0.09), + plinth_depth=0.03, + ) + # Hood engine bay frame + vc.add_hardpoint_slot( + "hp.engine.front", + "engine", + parent=chassis, + location=(0.0, -1.66, 1.32), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.88, 0.86, 0.14), + ) + # Cab roof weapon pintle ring + vc.add_hardpoint_slot( + "hp.weapon.cab", + "weapon", + parent=chassis, + location=(0.0, -0.44, 2.02), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.56, 0.56, 0.09), + ) + # Main cargo-bed turret ring + vc.add_hardpoint_slot( + "hp.weapon.bed_main", + "weapon", + parent=chassis, + location=(0.0, 1.36, 1.56), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.98, 0.98, 0.12), + ) + # Twin flank radiator louver pods behind cab (horizontal louvers: local +Y = +Z up) + vc.add_hardpoint_slot( + "hp.radiator.left", + "radiator", + parent=chassis, + location=(1.04, 0.56, 1.40), + rotation_deg=(90.0, 0.0, 90.0), + size=(0.78, 0.72, 0.14), + ) + vc.add_hardpoint_slot( + "hp.radiator.right", + "radiator", + parent=chassis, + location=(-1.04, 0.56, 1.40), + rotation_deg=(90.0, 0.0, -90.0), + size=(0.78, 0.72, 0.14), + ) + + # --- 6. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "mule" / "mule.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "mule" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "mule_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="mule", + name="Mule", + vehicle_class="Medium 6x6 Armored Gun Truck", + grid_width=3, + grid_height=5, + mask=[ + "###", + "###", + "###", + "###", + "###", + ], + hardpoints=[ + {"id": "hp.armor.front", "kind": "armor", "x": 0, "y": 0, "w": 3, "h": 1, "modelNodeId": "hp.armor.front"}, + {"id": "hp.radiator.left", "kind": "radiator", "x": 0, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.radiator.left"}, + {"id": "hp.engine.front", "kind": "engine", "x": 1, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.engine.front"}, + {"id": "hp.radiator.right", "kind": "radiator", "x": 2, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.radiator.right"}, + {"id": "hp.weapon.cab", "kind": "weapon", "x": 0, "y": 3, "w": 1, "h": 1, "modelNodeId": "hp.weapon.cab"}, + {"id": "hp.weapon.bed_main", "kind": "weapon", "x": 1, "y": 3, "w": 2, "h": 2, "modelNodeId": "hp.weapon.bed_main"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[mule] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "mule", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_mule() diff --git a/tools/vehicles/previews/anvil_preview.png b/tools/vehicles/previews/anvil_preview.png new file mode 100644 index 0000000..4e5fc09 Binary files /dev/null and b/tools/vehicles/previews/anvil_preview.png differ diff --git a/tools/vehicles/previews/bastion_preview.png b/tools/vehicles/previews/bastion_preview.png new file mode 100644 index 0000000..96022c9 Binary files /dev/null and b/tools/vehicles/previews/bastion_preview.png differ diff --git a/tools/vehicles/previews/breaker_preview.png b/tools/vehicles/previews/breaker_preview.png new file mode 100644 index 0000000..2a62be9 Binary files /dev/null and b/tools/vehicles/previews/breaker_preview.png differ diff --git a/tools/vehicles/previews/condor_preview.png b/tools/vehicles/previews/condor_preview.png new file mode 100644 index 0000000..c8ef101 Binary files /dev/null and b/tools/vehicles/previews/condor_preview.png differ diff --git a/tools/vehicles/previews/ferret_preview.png b/tools/vehicles/previews/ferret_preview.png new file mode 100644 index 0000000..a6fe46e Binary files /dev/null and b/tools/vehicles/previews/ferret_preview.png differ diff --git a/tools/vehicles/previews/hornet_preview.png b/tools/vehicles/previews/hornet_preview.png new file mode 100644 index 0000000..dbdf035 Binary files /dev/null and b/tools/vehicles/previews/hornet_preview.png differ diff --git a/tools/vehicles/previews/ironclad_preview.png b/tools/vehicles/previews/ironclad_preview.png new file mode 100644 index 0000000..2c217db Binary files /dev/null and b/tools/vehicles/previews/ironclad_preview.png differ diff --git a/tools/vehicles/previews/jackal_preview.png b/tools/vehicles/previews/jackal_preview.png new file mode 100644 index 0000000..7cf2b1a Binary files /dev/null and b/tools/vehicles/previews/jackal_preview.png differ diff --git a/tools/vehicles/previews/kestrel_preview.png b/tools/vehicles/previews/kestrel_preview.png new file mode 100644 index 0000000..3e03632 Binary files /dev/null and b/tools/vehicles/previews/kestrel_preview.png differ diff --git a/tools/vehicles/previews/mammoth_preview.png b/tools/vehicles/previews/mammoth_preview.png new file mode 100644 index 0000000..ce921ce Binary files /dev/null and b/tools/vehicles/previews/mammoth_preview.png differ diff --git a/tools/vehicles/previews/manticore_preview.png b/tools/vehicles/previews/manticore_preview.png new file mode 100644 index 0000000..e90a2bb Binary files /dev/null and b/tools/vehicles/previews/manticore_preview.png differ diff --git a/tools/vehicles/previews/mule_preview.png b/tools/vehicles/previews/mule_preview.png new file mode 100644 index 0000000..5180720 Binary files /dev/null and b/tools/vehicles/previews/mule_preview.png differ diff --git a/tools/vehicles/previews/paladin_preview.png b/tools/vehicles/previews/paladin_preview.png new file mode 100644 index 0000000..8cebb84 Binary files /dev/null and b/tools/vehicles/previews/paladin_preview.png differ diff --git a/tools/vehicles/previews/raptor_preview.png b/tools/vehicles/previews/raptor_preview.png new file mode 100644 index 0000000..6e662e4 Binary files /dev/null and b/tools/vehicles/previews/raptor_preview.png differ diff --git a/tools/vehicles/previews/spectre_preview.png b/tools/vehicles/previews/spectre_preview.png new file mode 100644 index 0000000..9506ebb Binary files /dev/null and b/tools/vehicles/previews/spectre_preview.png differ diff --git a/tools/vehicles/retrofit_mechs.py b/tools/vehicles/retrofit_mechs.py new file mode 100644 index 0000000..85b5ea2 --- /dev/null +++ b/tools/vehicles/retrofit_mechs.py @@ -0,0 +1,2398 @@ +"""Retrofit Brokkr kit-built mechs for Rust to Dust: +- Strip built-in weapon loadouts and studio backdrop/rig helpers (read-only on source .blend/.json). +- Normalize procedural Brokkr shaders to clean glTF 2.0 Principled BSDF PBR materials. +- Apply skinning-preserving / silhouette-preserving LOD decimation (target ~26k-32k tris). +- Reorient from Brokkr (+Y forward, -X left) to RTD (+Z forward glTF / -Y Blender, +X left), grounded at minY = 0. +- Attach visible exterior hardpoint collars/bays (`add_hardpoint_slot`) and joint tags (`tag_joint`). +- Emit `.glb`, `manifest.json` (including `mechanisms` when model JSON has rams/scissors/struts), and 4-panel preview PNG. + +Adding a future Brokkr mech (e.g. `bastion`, `seraph`): add a `MechRetrofitSpec` entry in `SPECS`. +""" +from __future__ import annotations + +import argparse +import json +import math +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import bmesh +import bpy +from mathutils import Euler, Matrix, Vector +from mathutils.bvhtree import BVHTree + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +@dataclass(frozen=True) +class HardpointMount: + hp_id: str + kind: str + x: int + y: int + w: int + h: int + parent_name: str + parent_bone: str | None + world_pos: tuple[float, float, float] + world_normal: tuple[float, float, float] + size: tuple[float, float, float] + + +@dataclass(frozen=True) +class JointTagSpec: + joint_id: str + target_name: str + parent_bone: str | None + axis_gltf: tuple[float, float, float] + min_val: float + max_val: float + + +@dataclass(frozen=True) +class MechRetrofitSpec: + mech_id: str + name: str + vehicle_class: str + plane: str + grid_width: int + grid_height: int + mask: tuple[str, ...] + blend_path: Path + model_json_path: Path | None + target_mech_tris: int + drop_collections: tuple[str, ...] = () + strip_prefixes: tuple[str, ...] = () + strip_vertex_groups: tuple[str, ...] = () + strip_islands: tuple[tuple[str, str, float], ...] = () + armature_name: str | None = None + hardpoints: tuple[HardpointMount, ...] = () + joints: tuple[JointTagSpec, ...] = () + extra_notes: str = "" + + +SPECS: dict[str, MechRetrofitSpec] = { + "breaker": MechRetrofitSpec( + mech_id="breaker", + name="Breaker", + vehicle_class="Heavy Assault Biped", + plane="Coronal", + grid_width=5, + grid_height=6, + mask=( + ".###.", + "#####", + "#####", + "#####", + ".#.#.", + ".#.#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-breaker-3\out\breaker\breaker_walk.blend"), + model_json_path=None, + target_mech_tris=32000, + drop_collections=(), + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "CannonL", "CannonR"), + strip_vertex_groups=(), + armature_name=None, + hardpoints=( + HardpointMount("hp.weapon.arm_l", "weapon", 0, 1, 1, 2, "ForearmL", None, (-2.18, 0.45, 3.52), (-1.0, 0.0, 0.0), (0.54, 0.54, 0.11)), + HardpointMount("hp.weapon.arm_r", "weapon", 4, 1, 1, 2, "ForearmR", None, (2.14, 0.65, 3.55), (1.0, 0.0, 0.0), (0.54, 0.54, 0.11)), + HardpointMount("hp.weapon.shoulder_l", "weapon", 1, 0, 1, 1, "Core", None, (-1.48, 0.12, 5.99), (0.0, 0.0, 1.0), (0.72, 0.72, 0.12)), + HardpointMount("hp.armor.torso", "armor", 2, 1, 1, 1, "Core", None, (0.0, 1.32, 5.05), (0.0, 0.82, 0.57), (1.02, 0.40, 0.11)), + HardpointMount("hp.engine.chest", "engine", 2, 2, 1, 2, "Core", None, (0.0, 1.76, 4.48), (0.0, 1.0, 0.0), (0.78, 0.56, 0.13)), + HardpointMount("hp.radiator.back_l", "radiator", 1, 1, 1, 1, "Core", None, (-1.50, -1.14, 5.22), (0.0, -1.0, 0.0), (0.68, 0.92, 0.12)), + HardpointMount("hp.radiator.back_r", "radiator", 3, 1, 1, 1, "Core", None, (1.50, -1.14, 5.22), (0.0, -1.0, 0.0), (0.68, 0.92, 0.12)), + ), + joints=( + JointTagSpec("joint.torso_yaw", "Core", None, (0.0, 1.0, 0.0), -90.0, 90.0), + JointTagSpec("joint.arm_l_pitch", "ShoulderYokeL", None, (1.0, 0.0, 0.0), -45.0, 60.0), + JointTagSpec("joint.arm_r_pitch", "ShoulderYokeR", None, (1.0, 0.0, 0.0), -45.0, 60.0), + ), + ), + "paladin": MechRetrofitSpec( + mech_id="paladin", + name="Paladin", + vehicle_class="Heavy Assault Biped", + plane="Coronal", + grid_width=6, + grid_height=7, + mask=( + "..##..", + ".####.", + "######", + "######", + ".####.", + ".#..#.", + ".#..#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-paladin-3\out\paladin\paladin.blend"), + model_json_path=None, + target_mech_tris=29000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Battery.", "EW.", "EWLow.", "Gatling.", "Emitter."), + hardpoints=( + HardpointMount("hp.weapon.sh_l", "weapon", 1, 1, 1, 1, "Trunk", None, (-2.88, 0.35, 9.82), (0.0, 0.0, 1.0), (0.94, 0.94, 0.15)), + HardpointMount("hp.armor.torso", "armor", 2, 1, 2, 1, "Trunk", None, (0.0, 1.80, 8.75), (0.0, 0.60, 0.80), (1.22, 0.40, 0.12)), + HardpointMount("hp.weapon.sh_r", "weapon", 4, 1, 1, 1, "Trunk", None, (2.88, 0.35, 9.82), (0.0, 0.0, 1.0), (0.94, 0.94, 0.15)), + HardpointMount("hp.weapon.arm_l", "weapon", 0, 2, 1, 2, "ArmL.Lower", None, (-3.44, 0.85, 5.75), (-1.0, 0.0, 0.0), (0.74, 0.74, 0.13)), + HardpointMount("hp.engine.chest", "engine", 2, 2, 2, 2, "Trunk", None, (0.0, 2.22, 8.05), (0.0, 0.94, 0.34), (0.82, 0.54, 0.14)), + HardpointMount("hp.weapon.arm_r", "weapon", 5, 2, 1, 2, "ArmR.Lower", None, (3.52, 1.05, 6.22), (1.0, 0.0, 0.0), (0.72, 0.72, 0.13)), + HardpointMount("hp.radiator.back_l", "radiator", 1, 4, 1, 1, "Trunk", None, (-0.92, -1.44, 8.65), (0.0, -1.0, 0.0), (0.82, 1.35, 0.14)), + HardpointMount("hp.armor.legs", "armor", 2, 4, 2, 1, "Pelvis", None, (0.0, 1.18, 5.55), (0.0, 1.0, 0.0), (0.95, 0.38, 0.11)), + HardpointMount("hp.radiator.back_r", "radiator", 4, 4, 1, 1, "Trunk", None, (0.92, -1.44, 8.65), (0.0, -1.0, 0.0), (0.82, 1.35, 0.14)), + ), + joints=( + JointTagSpec("joint.torso_yaw", "Trunk", None, (0.0, 1.0, 0.0), -90.0, 90.0), + JointTagSpec("joint.arm_l_pitch", "ArmL.Upper", None, (1.0, 0.0, 0.0), -40.0, 70.0), + JointTagSpec("joint.arm_r_pitch", "ArmR.Upper", None, (1.0, 0.0, 0.0), -40.0, 70.0), + ), + ), + "raptor": MechRetrofitSpec( + mech_id="raptor", + name="Raptor", + vehicle_class="Medium Theropod Biped", + plane="Coronal", + grid_width=5, + grid_height=6, + mask=( + "..#..", + ".###.", + "#####", + "#.#.#", + ".#.#.", + ".#.#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-raptor-4\out\raptor\raptor.blend"), + model_json_path=None, + target_mech_tris=28000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Bank0.", "Bank1.", "LaserL.", "LaserR."), + hardpoints=( + HardpointMount("hp.radiator.sh_l", "radiator", 1, 1, 1, 1, "_ROOT_", None, (-0.56, 0.05, 6.26), (-0.25, 0.0, 0.97), (0.64, 1.00, 0.12)), + HardpointMount("hp.radiator.sh_r", "radiator", 3, 1, 1, 1, "_ROOT_", None, (0.56, 0.05, 6.26), (0.25, 0.0, 0.97), (0.64, 1.00, 0.12)), + HardpointMount("hp.weapon.arm_l", "weapon", 0, 2, 1, 2, "ArmL.Fore", None, (-1.32, 2.14, 3.86), (-1.0, 0.0, 0.0), (0.48, 0.48, 0.11)), + HardpointMount("hp.engine.chest", "engine", 2, 2, 1, 2, "_ROOT_", None, (0.0, -2.02, 6.78), (0.0, 0.0, 1.0), (0.82, 1.06, 0.14)), + HardpointMount("hp.weapon.arm_r", "weapon", 4, 2, 1, 2, "ArmR.Fore", None, (1.32, 2.14, 3.86), (1.0, 0.0, 0.0), (0.48, 0.48, 0.11)), + ), + joints=( + JointTagSpec("joint.arm_l_pitch", "ArmL.Upper", None, (1.0, 0.0, 0.0), -45.0, 45.0), + JointTagSpec("joint.arm_r_pitch", "ArmR.Upper", None, (1.0, 0.0, 0.0), -45.0, 45.0), + ), + ), + "manticore": MechRetrofitSpec( + mech_id="manticore", + name="Manticore", + vehicle_class="Heavy Quadruped Scorpion", + plane="Dorsal", + grid_width=5, + grid_height=5, + mask=( + "#####", + ".###.", + "#####", + ".###.", + "#.#.#", + ), + blend_path=Path(r"F:\aeth-wt\fable-manticore-3\out\manticore\manticore.blend"), + model_json_path=None, + target_mech_tris=28000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Laser.light", "Launcher.", "ArmGunL.", "ArmGunR."), + hardpoints=( + HardpointMount("hp.weapon.chin", "weapon", 2, 0, 1, 1, "Hull", None, (0.0, 3.34, 1.38), (0.0, 0.94, -0.34), (0.64, 0.64, 0.12)), + HardpointMount("hp.radiator.flank_l", "radiator", 1, 1, 1, 1, "Hull", None, (-1.18, -0.35, 2.76), (-0.22, 0.0, 0.97), (0.56, 0.98, 0.12)), + HardpointMount("hp.engine.core", "engine", 2, 1, 1, 2, "Hull", None, (0.0, -0.25, 2.94), (0.0, 0.14, 0.99), (0.86, 1.20, 0.14)), + HardpointMount("hp.radiator.flank_r", "radiator", 3, 1, 1, 1, "Hull", None, (1.18, -0.35, 2.76), (0.22, 0.0, 0.97), (0.56, 0.98, 0.12)), + HardpointMount("hp.weapon.l", "weapon", 0, 2, 1, 1, "ArmL.Upper", None, (-0.96, 2.75, 0.72), (-0.65, 0.76, 0.0), (0.56, 0.56, 0.11)), + HardpointMount("hp.weapon.r", "weapon", 4, 2, 1, 1, "ArmR.Upper", None, (0.96, 2.75, 0.72), (0.65, 0.76, 0.0), (0.56, 0.56, 0.11)), + HardpointMount("hp.armor.prow", "armor", 2, 3, 1, 1, "Hull", None, (0.0, 3.14, 1.94), (0.0, 0.85, 0.53), (0.88, 0.34, 0.11)), + ), + joints=( + JointTagSpec("joint.tail_yaw", "Tail.Coxa", None, (0.0, 1.0, 0.0), -75.0, 75.0), + JointTagSpec("joint.tail_s1", "Tail.S1", None, (1.0, 0.0, 0.0), -60.0, 60.0), + JointTagSpec("joint.tail_s2", "Tail.S2", None, (1.0, 0.0, 0.0), -75.0, 15.0), + JointTagSpec("joint.tail_s3", "Tail.S3", None, (1.0, 0.0, 0.0), -80.0, 10.0), + JointTagSpec("joint.tail_elev", "Tail.Elev", None, (1.0, 0.0, 0.0), -40.0, 30.0), + ), + ), + "bastion": MechRetrofitSpec( + mech_id="bastion", + name="Bastion", + vehicle_class="Heavy Siege Quadruped", + plane="Dorsal", + grid_width=6, + grid_height=6, + mask=( + "..##..", + ".####.", + "######", + "######", + ".####.", + ".#..#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-bastion-2\out\bastion\bastion.blend"), + model_json_path=None, + target_mech_tris=32000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Aim.Gun", "Gun.", "Magazine.", "Interceptor."), + hardpoints=( + HardpointMount("hp.armor.prow", "armor", 2, 0, 2, 1, "Trunk", None, (0.0, 5.16, 6.50), (0.0, 0.29, 0.96), (1.35, 0.42, 0.12)), + HardpointMount("hp.weapon.turret_pd", "weapon", 1, 1, 1, 1, "Aim.Turret", None, (0.0, -1.80, 9.11), (0.0, 0.0, 1.0), (0.68, 0.68, 0.12)), + HardpointMount("hp.weapon.turret_main", "weapon", 2, 1, 2, 2, "Aim.Turret", None, (0.0, 0.45, 9.07), (0.0, 0.03, 1.0), (1.30, 1.30, 0.16)), + HardpointMount("hp.weapon.flank_l", "weapon", 0, 2, 1, 2, "Trunk", None, (-3.70, -0.22, 6.18), (-1.0, 0.0, 0.0), (0.85, 0.85, 0.14)), + HardpointMount("hp.weapon.flank_r", "weapon", 5, 2, 1, 2, "Trunk", None, (3.70, -0.22, 6.18), (1.0, 0.0, 0.0), (0.85, 0.85, 0.14)), + HardpointMount("hp.engine.core", "engine", 2, 3, 2, 2, "Trunk", None, (0.0, -5.70, 7.34), (0.0, 0.0, 1.0), (1.50, 1.35, 0.16)), + HardpointMount("hp.radiator.rear_l", "radiator", 1, 4, 1, 2, "Trunk", None, (-2.55, -5.75, 7.38), (0.0, 0.0, 1.0), (0.98, 1.38, 0.14)), + HardpointMount("hp.radiator.rear_r", "radiator", 4, 4, 1, 2, "Trunk", None, (2.55, -5.75, 7.38), (0.0, 0.0, 1.0), (0.98, 1.38, 0.14)), + ), + joints=( + JointTagSpec("joint.turret_yaw", "Aim.Turret", None, (0.0, 1.0, 0.0), -180.0, 180.0), + ), + ), + "spectre": MechRetrofitSpec( + mech_id="spectre", + name="Spectre", + vehicle_class="Medium Recon/Skirmisher Biped", + plane="Coronal", + grid_width=5, + grid_height=6, + mask=( + ".#...", + ".###.", + "#####", + "#####", + ".#.#.", + ".#.#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-spectre-3\out\spectre\spectre.blend"), + model_json_path=None, + target_mech_tris=27000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "Rack.", "RackTail.", "GunL.lamp", "GunR.lamp", "GunR.glass"), + strip_islands=( + ("GunL.gunmetal", "max_y>", 2.0), + ("GunR.gunmetal", "max_y>", 3.15), + ("GunR.khaki", "max_y>", 3.15), + ), + hardpoints=( + HardpointMount("hp.weapon.shoulder_l", "weapon", 1, 0, 1, 1, "Waist", None, (-2.22, 0.15, 7.48), (-0.17, 0.23, 0.96), (0.78, 0.78, 0.13)), + HardpointMount("hp.armor.torso", "armor", 2, 1, 1, 1, "Waist", None, (0.0, 3.10, 5.68), (0.0, 0.11, -0.99), (0.74, 0.28, 0.10)), + HardpointMount("hp.weapon.arm_l", "weapon", 0, 2, 1, 2, "ShoulderL", None, (-2.81, 1.75, 5.15), (-1.0, 0.0, 0.0), (0.52, 0.52, 0.11)), + HardpointMount("hp.radiator.back_l", "radiator", 1, 2, 1, 1, "Waist", None, (-2.20, -0.79, 7.00), (0.0, -1.0, 0.0), (0.76, 0.96, 0.12)), + HardpointMount("hp.engine.core", "engine", 2, 2, 1, 2, "Waist", None, (0.0, -2.30, 7.00), (0.0, -1.0, 0.0), (0.86, 1.18, 0.14)), + HardpointMount("hp.radiator.back_r", "radiator", 3, 2, 1, 1, "Waist", None, (2.20, -0.79, 7.00), (0.0, -1.0, 0.0), (0.76, 0.96, 0.12)), + HardpointMount("hp.weapon.arm_r", "weapon", 4, 2, 1, 2, "ShoulderR", None, (2.66, 1.75, 5.05), (1.0, 0.0, 0.0), (0.52, 0.52, 0.11)), + ), + joints=( + JointTagSpec("joint.torso_yaw", "Waist", None, (0.0, 1.0, 0.0), -90.0, 90.0), + JointTagSpec("joint.arm_l_pitch", "ShoulderL", None, (1.0, 0.0, 0.0), -45.0, 60.0), + JointTagSpec("joint.arm_r_pitch", "ShoulderR", None, (1.0, 0.0, 0.0), -45.0, 60.0), + ), + ), + "kestrel": MechRetrofitSpec( + mech_id="kestrel", + name="Kestrel", + vehicle_class="Light Scout Biped", + plane="Coronal", + grid_width=5, + grid_height=5, + mask=( + "..#..", + ".###.", + ".####", + ".####", + ".#.#.", + ), + blend_path=Path(r"F:\aeth-wt\fable-kestrel-2\out\kestrel\kestrel.blend"), + model_json_path=None, + target_mech_tris=27000, + strip_prefixes=("Rig", "Cam", "Sun", "Back", "Bounce", "Ground", "Horizon", "WeaponArm.accent_yellow"), + strip_islands=( + ("WeaponArm.gunmetal", "max_y>", 2.30), + ), + hardpoints=( + HardpointMount("hp.weapon.dorsal", "weapon", 2, 0, 1, 1, "Torso.pose", None, (0.0, 0.23, 9.25), (0.0, 0.38, 0.92), (0.56, 0.56, 0.11)), + HardpointMount("hp.armor.chest", "armor", 2, 1, 1, 1, "Torso.pose", None, (0.0, 2.28, 6.87), (0.0, 0.88, -0.47), (0.72, 0.32, 0.10)), + HardpointMount("hp.radiator.back", "radiator", 1, 2, 1, 1, "Torso.pose", None, (-1.02, -1.86, 8.35), (0.0, -0.97, 0.26), (0.58, 0.78, 0.11)), + HardpointMount("hp.engine.core", "engine", 2, 2, 1, 2, "Torso.pose", None, (0.0, -1.72, 8.20), (0.0, -0.93, 0.36), (0.76, 1.02, 0.13)), + HardpointMount("hp.weapon.arm_r", "weapon", 4, 2, 1, 2, "ArmR", None, (2.29, 1.15, 5.95), (1.0, 0.0, 0.0), (0.46, 0.46, 0.10)), + ), + joints=( + JointTagSpec("joint.torso_yaw", "Torso.pose", None, (0.0, 1.0, 0.0), -90.0, 90.0), + JointTagSpec("joint.arm_l_pitch", "ArmL", None, (1.0, 0.0, 0.0), -45.0, 60.0), + JointTagSpec("joint.arm_r_pitch", "ArmR", None, (1.0, 0.0, 0.0), -45.0, 60.0), + ), + ), +} + + +def _should_strip(name: str, prefixes: tuple[str, ...]) -> bool: + return any(name == p or name.startswith(p) or name.startswith(p.rstrip(".")) and name == p.rstrip(".") for p in prefixes) + + +def _remove_object_recursive(obj: bpy.types.Object) -> None: + for ch in list(obj.children): + _remove_object_recursive(ch) + if obj.name in bpy.data.objects: + bpy.data.objects.remove(obj, do_unlink=True) + + +def _strip_scene_objects(spec: MechRetrofitSpec) -> list[str]: + stripped: list[str] = [] + + # 1. Drop excluded build collections (e.g. breaker.build) + for col_name in spec.drop_collections: + col = bpy.data.collections.get(col_name) + if col is not None: + for obj_name in [o.name for o in col.objects]: + stripped.append(obj_name) + obj = bpy.data.objects.get(obj_name) + if obj is not None: + bpy.data.objects.remove(obj, do_unlink=True) + bpy.data.collections.remove(col) + + # 2. Strip matching prefixes, studio lights/cameras/fonts, and hidden boolean cutters + for obj_name in [o.name for o in bpy.data.objects]: + obj = bpy.data.objects.get(obj_name) + if obj is None: + continue + if obj.type in ("LIGHT", "CAMERA", "FONT"): + stripped.append(obj_name) + bpy.data.objects.remove(obj, do_unlink=True) + continue + is_skeleton_pivot = obj.get("kit_part") in ("bone", "trunk") + if not is_skeleton_pivot and (obj.hide_viewport or obj.hide_render or obj.display_type in ("WIRE", "BOUNDS")): + stripped.append(obj_name) + bpy.data.objects.remove(obj, do_unlink=True) + continue + if _should_strip(obj_name, spec.strip_prefixes): + stripped.append(obj_name) + _remove_object_recursive(obj) + continue + if not spec.armature_name and ".bolts" in obj_name: + stripped.append(obj_name) + bpy.data.objects.remove(obj, do_unlink=True) + + return sorted(set(stripped)) + + +def _strip_vertex_groups_from_mesh(obj: bpy.types.Object, vg_names: tuple[str, ...]) -> int: + if not vg_names or obj.type != "MESH": + return 0 + target_indices = { + obj.vertex_groups[name].index + for name in vg_names + if name in obj.vertex_groups + } + if not target_indices: + return 0 + bm = bmesh.new() + bm.from_mesh(obj.data) + dlayer = bm.verts.layers.deform.active + removed_verts = 0 + if dlayer is not None: + to_delete = [] + for v in bm.verts: + dw = v[dlayer] + if any(dw.get(idx, 0.0) > 0.5 for idx in target_indices): + to_delete.append(v) + removed_verts = len(to_delete) + if to_delete: + bmesh.ops.delete(bm, geom=to_delete, context="VERTS") + bm.to_mesh(obj.data) + bm.free() + obj.data.validate(verbose=False) + obj.data.update() + return removed_verts + + +def _strip_mesh_islands(strip_islands: tuple[tuple[str, str, float], ...]) -> dict[str, int]: + """Remove disconnected mesh islands matching world-space predicates (e.g. protruding gun barrels).""" + removed: dict[str, int] = {} + for obj_name, op, thresh in strip_islands: + obj = bpy.data.objects.get(obj_name) + if obj is None or obj.type != "MESH" or obj.data is None: + continue + bm = bmesh.new() + bm.from_mesh(obj.data) + bm.verts.ensure_lookup_table() + mw = obj.matrix_world + visited: set[int] = set() + del_verts: list[bmesh.types.BMVert] = [] + for v in bm.verts: + if v.index in visited: + continue + comp: list[bmesh.types.BMVert] = [] + stack = [v] + visited.add(v.index) + while stack: + cur = stack.pop() + comp.append(cur) + for e in cur.link_edges: + ov = e.other_vert(cur) + if ov.index not in visited: + visited.add(ov.index) + stack.append(ov) + pts = [mw @ c.co for c in comp] + hit = False + if op == "max_y>": + hit = max(p.y for p in pts) > thresh + elif op == "min_y<": + hit = min(p.y for p in pts) < thresh + elif op == "max_z>": + hit = max(p.z for p in pts) > thresh + if hit: + del_verts.extend(comp) + if del_verts: + bmesh.ops.delete(bm, geom=del_verts, context="VERTS") + bm.to_mesh(obj.data) + obj.data.validate(verbose=False) + obj.data.update() + removed[obj_name] = len(del_verts) + bm.free() + return removed + + +def _assemble_kestrel_hierarchy() -> None: + """Group Kestrel's flat root parts under Pelvis, Torso.pose, ArmL, and ArmR pivots.""" + torso_pose = bpy.data.objects.get("Torso.pose") + if torso_pose is None: + return + + def reparent_keep_world(obj: bpy.types.Object, parent: bpy.types.Object) -> None: + mw = obj.matrix_world.copy() + obj.parent = parent + obj.matrix_parent_inverse = Matrix.Identity(4) + obj.matrix_local = parent.matrix_world.inverted() @ mw + + pelvis = vc.make_empty("Pelvis", parent=None, location=(0.0, 0.0, 0.0)) + arm_l = vc.make_empty("ArmL", parent=torso_pose, location=(-1.62, 0.65, 1.50)) + arm_r = vc.make_empty("ArmR", parent=torso_pose, location=(1.62, 0.65, 1.50)) + bpy.context.view_layer.update() + + for obj in list(bpy.data.objects): + if obj in (pelvis, torso_pose, arm_l, arm_r): + continue + name = obj.name + if obj.parent is None and ( + name.startswith("Pelvis.") + or name.startswith("LegJoints") + or name.startswith("Thigh") + or name.startswith("Shin") + or name.startswith("Ankle") + or name.startswith("Foot") + ): + reparent_keep_world(obj, pelvis) + elif obj.parent is None and (name.startswith("Neck.") or name.startswith("Shoulder")): + reparent_keep_world(obj, torso_pose) + elif name.startswith("UpperArmL.") or name.startswith("ElbowL.") or name.startswith("ForearmL.") or name.startswith("HandL."): + reparent_keep_world(obj, arm_l) + elif name.startswith("UpperArmR.") or name.startswith("ElbowR.") or name.startswith("WeaponArm."): + reparent_keep_world(obj, arm_r) + bpy.context.view_layer.update() + + +def _apply_existing_modifiers() -> None: + """Drop BEVEL (which causes decimate spikes) and bake SOLIDIFY/BOOLEAN before stripping cutters.""" + for obj_name in [o.name for o in bpy.data.objects]: + obj = bpy.data.objects.get(obj_name) + if obj is None or obj.type != "MESH" or not obj.modifiers: + continue + for mod in list(obj.modifiers): + if mod.type == "BEVEL": + obj.modifiers.remove(mod) + depsgraph = bpy.context.evaluated_depsgraph_get() + for obj_name in [o.name for o in bpy.data.objects]: + obj = bpy.data.objects.get(obj_name) + if obj is None or obj.type != "MESH" or not obj.modifiers: + continue + if any(m.type == "ARMATURE" for m in obj.modifiers): + continue + ev = obj.evaluated_get(depsgraph) + new_mesh = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph) + new_mesh.name = f"{obj.name}_baked" + obj.modifiers.clear() + obj.data = new_mesh + + +def _convert_surviving_curves() -> None: + """Convert surviving CURVE hydraulic hoses to MESH.""" + view_layer = bpy.context.view_layer + curves = [o for o in bpy.data.objects if o.type == "CURVE"] + if curves: + bpy.ops.object.select_all(action="DESELECT") + for c in curves: + c.select_set(True) + view_layer.objects.active = curves[0] + bpy.ops.object.convert(target="MESH") + + +def _normalize_materials_for_gltf() -> None: + """Replace linked procedural shader trees with clean flat Principled BSDF PBR values.""" + vc.ensure_materials() + pal_map = { + "armour": "olive_armor", + "armor": "olive_armor", + "olive": "olive_armor", + "khaki": "olive_armor", + "metal": "gunmetal", + "gunmetal": "gunmetal", + "machine": "gunmetal", + "rubber": "rubber_dark", + "hazard": "signal_orange", + "brass": "copper_rad", + "copper": "copper_rad", + "glass": "smoked_glass", + "optic": "smoked_glass", + "pit": "socket_bay", + } + for mat in list(bpy.data.materials): + if mat.name in vc.PALETTE or not mat.use_nodes or not mat.node_tree: + continue + nt = mat.node_tree + bsdf = next((n for n in nt.nodes if n.type == "BSDF_PRINCIPLED"), None) + if bsdf is None: + continue + lname = mat.name.lower() + + # Extract Group node overrides if authored by Brokkr paint_pinned + grp = next((n for n in nt.nodes if n.type == "GROUP"), None) + base_col = None + cover_col = None + cover_amt = 0.0 + metallic = None + roughness = None + if grp is not None: + if "Base Color" in grp.inputs and hasattr(grp.inputs["Base Color"], "default_value"): + base_col = tuple(grp.inputs["Base Color"].default_value) + if "Cover Color" in grp.inputs and hasattr(grp.inputs["Cover Color"], "default_value"): + cover_col = tuple(grp.inputs["Cover Color"].default_value) + if "Cover" in grp.inputs and hasattr(grp.inputs["Cover"], "default_value"): + cover_amt = float(grp.inputs["Cover"].default_value) + if "Metallic" in grp.inputs and hasattr(grp.inputs["Metallic"], "default_value"): + metallic = float(grp.inputs["Metallic"].default_value) + if "Roughness" in grp.inputs and hasattr(grp.inputs["Roughness"], "default_value"): + roughness = float(grp.inputs["Roughness"].default_value) + + # Fallback to matching shared RTD palette entry for linked/procedural mats + matched_pal = None + for key, pal_name in pal_map.items(): + if key in lname: + matched_pal = vc.PALETTE[pal_name] + break + + # Clear links on Principled BSDF and reset overrides (e.g. Emission/Transmission) + for inp in bsdf.inputs: + for lk in list(inp.links): + nt.links.remove(lk) + if "Emission Strength" in bsdf.inputs: + bsdf.inputs["Emission Strength"].default_value = 0.0 + if "Emission Color" in bsdf.inputs: + bsdf.inputs["Emission Color"].default_value = (0.0, 0.0, 0.0, 1.0) + if "Transmission Weight" in bsdf.inputs: + bsdf.inputs["Transmission Weight"].default_value = 0.0 + if "Coat Weight" in bsdf.inputs: + bsdf.inputs["Coat Weight"].default_value = 0.0 + + if "glow_blue" in lname: + bsdf.inputs["Base Color"].default_value = vc.srgb_hex_to_linear("#38c9d8") + bsdf.inputs["Roughness"].default_value = 0.20 + bsdf.inputs["Emission Color"].default_value = vc.srgb_hex_to_linear("#38c9d8") + bsdf.inputs["Emission Strength"].default_value = 2.4 + elif any(k in lname for k in ("lamp", "glow", "amber")): + col = vc.srgb_hex_to_linear("#ff9f2e") + bsdf.inputs["Base Color"].default_value = col + bsdf.inputs["Roughness"].default_value = 0.20 + bsdf.inputs["Emission Color"].default_value = col + bsdf.inputs["Emission Strength"].default_value = 2.2 + elif "steel" in lname: + bsdf.inputs["Base Color"].default_value = (0.58, 0.60, 0.62, 1.0) + bsdf.inputs["Metallic"].default_value = 0.94 + bsdf.inputs["Roughness"].default_value = 0.22 + elif "optic_red" in lname: + bsdf.inputs["Base Color"].default_value = (0.14, 0.02, 0.015, 1.0) + bsdf.inputs["Metallic"].default_value = 0.0 + bsdf.inputs["Roughness"].default_value = 0.15 + if "Emission Color" in bsdf.inputs: + bsdf.inputs["Emission Color"].default_value = (1.0, 0.08, 0.03, 1.0) + if "Emission Strength" in bsdf.inputs: + bsdf.inputs["Emission Strength"].default_value = 1.6 + elif "warhead" in lname: + bsdf.inputs["Base Color"].default_value = (0.28, 0.10, 0.06, 1.0) + bsdf.inputs["Metallic"].default_value = 0.35 + bsdf.inputs["Roughness"].default_value = 0.45 + elif "mark" in lname: + bsdf.inputs["Base Color"].default_value = cover_col if (cover_col is not None and cover_amt >= 0.5) else (0.48, 0.46, 0.42, 1.0) + bsdf.inputs["Metallic"].default_value = 0.0 + bsdf.inputs["Roughness"].default_value = roughness if roughness is not None else 0.72 + elif matched_pal is not None: + bsdf.inputs["Base Color"].default_value = vc.srgb_hex_to_linear(matched_pal["hex"]) + bsdf.inputs["Metallic"].default_value = float(matched_pal["metallic"]) + bsdf.inputs["Roughness"].default_value = float(matched_pal["roughness"]) + if "alpha" in matched_pal: + bsdf.inputs["Alpha"].default_value = float(matched_pal["alpha"]) + if hasattr(mat, "blend_method"): + mat.blend_method = "BLEND" + elif base_col is not None: + bsdf.inputs["Base Color"].default_value = base_col + if metallic is not None: + bsdf.inputs["Metallic"].default_value = metallic + if roughness is not None: + bsdf.inputs["Roughness"].default_value = roughness + + +def _mesh_tri_count(obj: bpy.types.Object) -> int: + obj.data.calc_loop_triangles() + return len(obj.data.loop_triangles) + + +def _apply_crisp_normals_and_decimate(obj: bpy.types.Object, ratio: float) -> int: + view_layer = bpy.context.view_layer + if obj.data.users > 1: + obj.data = obj.data.copy() + bpy.ops.object.select_all(action="DESELECT") + obj.select_set(True) + view_layer.objects.active = obj + + if ratio < 0.99: + mod = obj.modifiers.new("LOD_Decimate", "DECIMATE") + mod.decimate_type = "COLLAPSE" + mod.ratio = ratio + mod.use_collapse_triangulate = True + if len(obj.modifiers) > 1: + bpy.ops.object.modifier_move_to_index(modifier=mod.name, index=0) + bpy.ops.object.modifier_apply(modifier=mod.name) + + # Split sharp armor edges (>36 deg) so decimated bevel corners never look pillowed + es = obj.modifiers.new("LOD_EdgeSplit", "EDGE_SPLIT") + es.use_edge_angle = True + es.split_angle = math.radians(36.0) + es.use_edge_sharp = True + if len(obj.modifiers) > 1: + bpy.ops.object.modifier_move_to_index(modifier=es.name, index=0) + bpy.ops.object.modifier_apply(modifier=es.name) + obj.data.validate(verbose=False) + obj.data.update() + return _mesh_tri_count(obj) + + +def _decimate_mech_meshes(meshes: list[bpy.types.Object], target_tris: int, min_keep_tris: int = 48) -> tuple[int, int]: + """Decimate mech meshes adaptively to target_tris while keeping armor plates crisp and spike-free.""" + tri_counts = [_mesh_tri_count(o) for o in meshes] + raw_total = sum(tri_counts) + if raw_total == 0: + return 0, 0 + + # Single-mesh rigged path (e.g. breaker.mesh) -> modifier_apply preserves armature + skinning + if len(meshes) == 1: + obj = meshes[0] + ratio = max(0.02, min(1.0, target_tris / raw_total)) + after = _apply_crisp_normals_and_decimate(obj, ratio) + return raw_total, after + + min_main_ratio = 0.125 if raw_total > 150000 else 0.20 + + def _target_for(obj: bpy.types.Object, t: int, k_val: float) -> int: + if t <= min_keep_tris: + return t + is_detail = ( + obj.name.startswith("Foot") + or ".Foot" in obj.name + or ".fit." in obj.name + or ".ferrules" in obj.name + or ".panels" in obj.name + ) + if is_detail: + return max(24, int(round(t * max(k_val * 0.50, 0.06)))) + if t <= 220: + return max(min(t, 44), int(round(t * max(k_val, 0.28)))) + return max(84, int(round(t * max(k_val, min_main_ratio)))) + + if raw_total <= target_tris: + k = 1.0 + else: + lo, hi = 0.10, 1.0 + for _ in range(28): + mid = 0.5 * (lo + hi) + est = sum(_target_for(obj, t, mid) for obj, t in zip(meshes, tri_counts)) + if est > target_tris: + hi = mid + else: + lo = mid + k = 0.5 * (lo + hi) + + # Queue DECIMATE + EDGE_SPLIT on all objects, then evaluate in one depsgraph pass + for obj, t in zip(meshes, tri_counts): + tgt = _target_for(obj, t, k) + if tgt < t: + ratio = max(0.08, min(1.0, tgt / t)) + if ratio < 0.99: + mod = obj.modifiers.new("LOD_Decimate", "DECIMATE") + mod.decimate_type = "COLLAPSE" + mod.ratio = ratio + mod.use_collapse_triangulate = True + es = obj.modifiers.new("LOD_EdgeSplit", "EDGE_SPLIT") + es.use_edge_angle = True + es.split_angle = math.radians(36.0) + es.use_edge_sharp = True + + depsgraph = bpy.context.evaluated_depsgraph_get() + after_total = 0 + for obj in meshes: + ev = obj.evaluated_get(depsgraph) + new_mesh = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph) + new_mesh.name = f"{obj.name}_lod" + new_mesh.validate(verbose=False) + obj.modifiers.clear() + obj.data = new_mesh + after_total += _mesh_tri_count(obj) + + return raw_total, after_total + + +def _collect_subtree_meshes(root_obj: bpy.types.Object) -> list[bpy.types.Object]: + out: list[bpy.types.Object] = [] + def walk(obj: bpy.types.Object) -> None: + if obj.name.startswith("slot_frame."): + return + if obj.type == "MESH" and obj.data is not None and len(obj.data.polygons) > 0: + out.append(obj) + for ch in obj.children: + walk(ch) + walk(root_obj) + return out + + +def _build_hull_bvh(mesh_objs: list[bpy.types.Object]) -> BVHTree | None: + if not mesh_objs: + return None + depsgraph = bpy.context.evaluated_depsgraph_get() + bm = bmesh.new() + for obj in mesh_objs: + ev = obj.evaluated_get(depsgraph) + me = ev.to_mesh() + if me is not None and len(me.polygons) > 0: + me.transform(obj.matrix_world) + bm.from_mesh(me) + ev.to_mesh_clear() + if len(bm.verts) == 0 or len(bm.faces) == 0: + bm.free() + return None + bvh = BVHTree.FromBMesh(bm) + bm.free() + return bvh + + +def _snap_hardpoint_bvh( + hp: HardpointMount, + parent_obj: bpy.types.Object, + root_obj: bpy.types.Object, + full_bvh: BVHTree, + bvh_cache: dict[str, BVHTree], +) -> tuple[Vector, float, tuple[float, float, float]]: + """Snap hardpoint anchor onto actual hull surface via 5-point BVH raycast + recessed plinth.""" + bvh = full_bvh + if parent_obj != root_obj and hp.parent_bone is None: + if parent_obj.name not in bvh_cache: + sub_meshes = _collect_subtree_meshes(parent_obj) + sub_bvh = _build_hull_bvh(sub_meshes) + if sub_bvh is not None: + bvh_cache[parent_obj.name] = sub_bvh + bvh = bvh_cache.get(parent_obj.name, full_bvh) + + p0 = Vector(hp.world_pos) + n = Vector(hp.world_normal).normalized() + q = Vector((0.0, 0.0, 1.0)).rotation_difference(n) + tu = q @ Vector((1.0, 0.0, 0.0)) + tv = q @ Vector((0.0, 1.0, 0.0)) + + sx, sy, sz = hp.size + if hp.kind == "weapon": + r = min(sx, sy) * 0.48 * 0.78 + rx, ry = r, r + elif hp.kind == "armor": + rx, ry = sx * 0.38, sy * 0.14 + else: + rx, ry = sx * 0.38, sy * 0.38 + + offsets = [(0.0, 0.0), (-rx, -ry), (rx, -ry), (rx, ry), (-rx, ry)] + raw_hits: list[float | None] = [] + for ox, oy in offsets: + pt = p0 + tu * ox + tv * oy + # Cast from +1.5m along +normal toward -normal; guard against far overhang hits by also trying +0.55m + loc, _, _, _ = bvh.ray_cast(pt + n * 0.65, -n, 1.35) + if loc is None: + loc, _, _, _ = bvh.ray_cast(pt + n * 1.5, -n, 3.0) + raw_hits.append((loc - p0).dot(n) if loc is not None else None) + + h_center = raw_hits[0] + if h_center is None: + near_loc, _, _, _ = bvh.find_nearest(p0) + if near_loc is not None: + h_center = (near_loc - p0).dot(n) + else: + h_center = 0.0 + # Guard against thin lifting-eye/antenna spikes lifting the entire base off the armor roof + corner_vals = sorted(h for h in raw_hits[1:] if h is not None) + if len(corner_vals) >= 3: + c_med = corner_vals[len(corner_vals) // 2] + if h_center - c_med > 0.08: + tight_hits: list[float] = [] + for tx, ty in ((-0.07, 0.0), (0.07, 0.0), (0.0, -0.07), (0.0, 0.07)): + t_loc, _, _, _ = bvh.ray_cast(p0 + tu * tx + tv * ty + n * 0.65, -n, 1.35) + if t_loc is not None: + tight_hits.append((t_loc - p0).dot(n)) + t_med = sorted(tight_hits)[len(tight_hits) // 2] if tight_hits else h_center + if h_center - t_med > 0.06: + h_center = c_med + + # Keep corner hits near the local surface patch; replace misses/cliffs with nearest or conservative drop + valid_corners: list[float] = [h_center] + misses = 0 + for idx, h in enumerate(raw_hits[1:], start=1): + if h is None or abs(h - h_center) > 0.18: + misses += 1 + ox, oy = offsets[idx] + near_loc, _, _, _ = bvh.find_nearest(p0 + tu * ox + tv * oy + n * h_center) + if near_loc is not None: + hn = (near_loc - p0).dot(n) + if abs(hn - h_center) <= 0.18: + valid_corners.append(hn) + continue + valid_corners.append(h_center - 0.035) + else: + valid_corners.append(h) + + h_min = min(valid_corners) + h_max = max(valid_corners) + # Seat bay origin recessed into surface at center (<= 0.022m from surface so verify_glbs passes) + # while extending plinth down past h_min and keeping rim proud above h_max + h_seat = h_center - 0.020 + if h_max - h_seat > sz * 0.55: + sz_out = max(sz, (h_max - h_seat) + 0.055) + else: + sz_out = sz + plinth_depth = max(0.050, min(0.18, (h_seat - h_min) + 0.045)) + snapped_pos = p0 + n * h_seat + print( + f" [snap] {hp.hp_id:22s} | dh_c={h_center:+.3f} span=[{h_min:+.3f},{h_max:+.3f}] " + f"seat={h_seat:+.3f} plinth={plinth_depth:.3f} miss={misses}" + ) + return snapped_pos, plinth_depth, (sx, sy, sz_out) + + +def _attach_hardpoint_world( + hp: HardpointMount, + root_obj: bpy.types.Object, + full_bvh: BVHTree, + bvh_cache: dict[str, BVHTree], +) -> None: + parent_obj = root_obj if hp.parent_name == "_ROOT_" else bpy.data.objects[hp.parent_name] + snapped_pos, plinth_depth, adj_size = _snap_hardpoint_bvh(hp, parent_obj, root_obj, full_bvh, bvh_cache) + anchor = vc.add_hardpoint_slot( + hp.hp_id, + hp.kind, + parent=parent_obj, + location=(0.0, 0.0, 0.0), + rotation_deg=(0.0, 0.0, 0.0), + size=adj_size, + plinth_depth=plinth_depth, + ) + bay_root = anchor.parent + if hp.parent_bone is not None: + bay_root.parent_type = "BONE" + bay_root.parent_bone = hp.parent_bone + + bpy.context.view_layer.update() + n = Vector(hp.world_normal).normalized() + q = Vector((0.0, 0.0, 1.0)).rotation_difference(n) + m_world = Matrix.Translation(snapped_pos) @ q.to_matrix().to_4x4() + + if hp.parent_bone is not None and parent_obj.type == "ARMATURE": + pb = parent_obj.pose.bones[hp.parent_bone] + # Blender bone parenting attaches at the pose bone tail with bone axes + bone_tail_mat = parent_obj.matrix_world @ pb.matrix @ Matrix.Translation((0.0, pb.length, 0.0)) + m_local = bone_tail_mat.inverted() @ m_world + else: + m_local = parent_obj.matrix_world.inverted() @ m_world + + loc, rot, _ = m_local.decompose() + bay_root.location = loc + bay_root.rotation_mode = "XYZ" + bay_root.rotation_euler = rot.to_euler("XYZ") + + +def _apply_joint_tags(spec: MechRetrofitSpec) -> list[dict[str, Any]]: + joints_manifest: list[dict[str, Any]] = [] + for j in spec.joints: + target = bpy.data.objects[j.target_name] + if j.parent_bone is not None and target.type == "ARMATURE": + node = vc.make_empty(j.joint_id, parent=target, display_size=0.16) + node.parent_type = "BONE" + node.parent_bone = j.parent_bone + bpy.context.view_layer.update() + pb = target.pose.bones[j.parent_bone] + bone_head_w = target.matrix_world @ pb.head + bone_tail_mat = target.matrix_world @ pb.matrix @ Matrix.Translation((0.0, pb.length, 0.0)) + m_local = bone_tail_mat.inverted() @ Matrix.Translation(bone_head_w) + node.location = m_local.to_translation() + else: + node = target + vc.tag_joint(node, j.joint_id, j.axis_gltf, j.min_val, j.max_val) + joints_manifest.append({ + "id": j.joint_id, + "axis": [float(v) for v in j.axis_gltf], + "min": float(j.min_val), + "max": float(j.max_val), + }) + return joints_manifest + + +def _brokkr_vec_to_gltf(v: list[float], ground_z_shift: float = 0.0) -> list[float]: + """Convert raw Brokkr Blender (+Y fwd, -X left, +Z up) after 180 deg Z rot to glTF (+Z fwd, +X left, +Y up).""" + return [round(-float(v[0]), 6), round(float(v[2]) + ground_z_shift, 6), round(float(v[1]), 6)] + + +def _brokkr_dir_to_gltf(v: list[float]) -> list[float]: + return [round(-float(v[0]), 6), round(float(v[2]), 6), round(float(v[1]), 6)] + + +def _extract_mechanisms(model_json_path: Path, ground_z_shift: float = 0.0) -> dict[str, Any]: + raw = json.loads(model_json_path.read_text(encoding="utf-8")) + dofs_out = [] + for d in raw.get("dofs", []): + entry = { + "name": d["name"], + "parent": d["parent"], + "kind": d["kind"], + "mechanism": d.get("mechanism"), + "side": d.get("side"), + "origin": _brokkr_vec_to_gltf(d["origin"], ground_z_shift), + "axis": _brokkr_dir_to_gltf(d["axis"]), + "lo": d["lo"], + "hi": d["hi"], + "depth": d["depth"], + } + if "compliance" in d: + entry["compliance"] = d["compliance"] + if "stopped_by" in d: + entry["stopped_by"] = d["stopped_by"] + dofs_out.append(entry) + + points_raw = raw.get("points", {}) + dirs_raw = raw.get("dirs", {}) + rams_out = [] + for r in raw.get("rams", []): + pt_a = points_raw.get(r["a"]) + pt_b = points_raw.get(r["b"]) + dir_pin = dirs_raw.get(r["pin"]) + rams_out.append({ + "name": r["name"], + "barrel_bone": r["barrel_bone"], + "rod_bone": r["rod_bone"], + "spans": r.get("spans", []), + "bore": r.get("bore"), + "body": r.get("body"), + "inner": r.get("inner"), + "extension": r.get("extension"), + "rest": r.get("rest"), + "stroke": r.get("stroke"), + "a_parent_dof": pt_a[0] if pt_a else None, + "a_pos": _brokkr_vec_to_gltf(pt_a[1], ground_z_shift) if pt_a else None, + "b_parent_dof": pt_b[0] if pt_b else None, + "b_pos": _brokkr_vec_to_gltf(pt_b[1], ground_z_shift) if pt_b else None, + "pin_dir": _brokkr_dir_to_gltf(dir_pin[1]) if dir_pin else None, + }) + + scissors_out = [] + for s in raw.get("scissors", []): + pt_a = points_raw.get(s["a"]) + pt_b = points_raw.get(s["b"]) + dir_out = dirs_raw.get(s["out"]) + scissors_out.append({ + "name": s["name"], + "upper_bone": s["upper_bone"], + "lower_bone": s["lower_bone"], + "arm": s.get("arm"), + "a_parent_dof": pt_a[0] if pt_a else None, + "a_pos": _brokkr_vec_to_gltf(pt_a[1], ground_z_shift) if pt_a else None, + "b_parent_dof": pt_b[0] if pt_b else None, + "b_pos": _brokkr_vec_to_gltf(pt_b[1], ground_z_shift) if pt_b else None, + "out_dir": _brokkr_dir_to_gltf(dir_out[1]) if dir_out else None, + }) + + struts_out = [ + { + "name": st["name"], + "side": st.get("side"), + "dof": st["dof"], + "travel": st["travel"], + "hertz": st["hertz"], + "damping_ratio": st["damping_ratio"], + } + for st in raw.get("struts", []) + ] + + return { + "frame": "gltf (+Y up, +Z forward, +X left, meters)", + "rootOrigin": _brokkr_vec_to_gltf(raw.get("root", [0.0, 0.0, 0.0]), ground_z_shift), + "dofs": dofs_out, + "rams": rams_out, + "scissors": scissors_out, + "struts": struts_out, + } + + +def _extract_mechanisms_from_blend_raw(root_name: str = "Pelvis") -> dict[str, Any] | None: + """Extract raw Brokkr-frame DOFs, hydraulic rams, torque scissors, and oleo struts from kit_* props.""" + root_obj = bpy.data.objects.get(root_name) + if root_obj is None or "kit_part" not in root_obj: + return None + bpy.context.view_layer.update() + + def _side_of(name: str) -> str: + for tag, s in (("LegL", "L"), ("LegR", "R")): + if name.startswith(tag): + return s + base = name.split(".")[0] + if base.endswith("L"): + return "L" + if base.endswith("R"): + return "R" + return "" + + limits_deg = { + "hip": (-60.0, 60.0), "hip yaw": (-35.0, 35.0), "knee": (-100.0, 100.0), + "ankle": (-40.0, 40.0), "waist": (-110.0, 110.0), "shoulder slew": (-100.0, 100.0), + "shoulder hinge": (-45.0, 45.0), "arm twist": (-90.0, 90.0), "elbow": (-100.0, 100.0), + "hinge": (-60.0, 60.0), "slew": (-90.0, 90.0), + } + + dofs_raw: list[dict[str, Any]] = [] + obj_to_dof: dict[str, int] = {} + + def walk(obj: bpy.types.Object, parent_dof: int, depth: int) -> None: + here = parent_dof + here_depth = depth + if obj != root_obj and "kit_socket" in obj and obj.get("kit_part") != "ram" and obj.parent is not None and "kit_part" in obj.parent: + part = str(obj["kit_part"]) + ppart = str(obj.parent["kit_part"]) + psock = str(obj.get("kit_parent_socket", "")) + kind: str | None = None + if ppart == "slew_ring" and psock == "top": + kind = "slew" + elif str(obj.get("kit_mechanism", "")) == "oleo": + kind = "slide" + elif psock == "clevis": + kind = "hinge" + if kind is not None: + if kind == "slew": + # Slew axis is the parent slew_ring's Z axis at the top socket + origin_v = obj.parent.matrix_world.translation.copy() + axis_v = obj.parent.matrix_world.to_3x3().col[2].normalized() + else: + origin_v = obj.matrix_world.translation.copy() + axis_v = obj.matrix_world.to_3x3().col[2].normalized() + + grand = obj.parent.parent.get("kit_part", "") if obj.parent.parent else "" + if kind == "slide": + mech = str(obj.get("kit_mechanism", "oleo")) + val = float(obj.get("kit_slide", 0.0)) + lo = float(obj.get("kit_min", 0.0)) - val + hi = float(obj.get("kit_max", 0.2)) - val + elif kind == "slew": + mech = ( + "hip" if part in ("thigh", "hip_stub") + else "hip yaw" if part == "shank" + else "waist" if part == "chassis" + else ("shoulder slew" if grand == "chassis" else "arm twist") if part == "yoke" + else "slew" + ) + lo, hi = (math.radians(v) for v in limits_deg[mech]) + else: + if "kit_min" in obj and obj.get("kit_mechanism"): + mech = str(obj["kit_mechanism"]).replace("_", " ") + roll = float(obj.get("kit_roll", 0.0)) + lo = math.radians(float(obj["kit_min"]) - roll) + hi = math.radians(float(obj["kit_max"]) - roll) + else: + if part in ("foot", "foot_core"): + mech = "ankle" + elif part in ("link", "strut_shin"): + mech = "knee" + elif part == "wrist": + up_m = dofs_raw[parent_dof]["mechanism"] if parent_dof >= 0 else "" + mech = "shoulder hinge" if up_m == "shoulder slew" else "elbow" if up_m == "arm twist" else "hinge" + else: + mech = "hinge" + lo, hi = (math.radians(v) for v in limits_deg[mech]) + + entry: dict[str, Any] = { + "name": obj.name, + "parent": parent_dof, + "kind": kind, + "mechanism": mech, + "side": _side_of(obj.name), + "origin": [float(origin_v.x), float(origin_v.y), float(origin_v.z)], + "axis": [float(axis_v.x), float(axis_v.y), float(axis_v.z)], + "lo": float(lo), + "hi": float(hi), + "depth": depth, + } + if obj.get("kit_compliance"): + entry["compliance"] = json.loads(str(obj["kit_compliance"])) + if mech == "ankle": + entry["stopped_by"] = "ram" + here = len(dofs_raw) + here_depth = depth + 1 + dofs_raw.append(entry) + obj_to_dof[obj.name] = here + for ch in obj.children: + walk(ch, here, here_depth) + + walk(root_obj, -1, 0) + + rams_raw: list[dict[str, Any]] = [] + for obj in sorted(bpy.data.objects, key=lambda o: o.name): + if obj.get("kit_part") != "ram" or obj.parent is None: + continue + raw_close = obj.get("kit_close_to") + if raw_close is None: + continue + close_to = ( + raw_close + if isinstance(raw_close, bpy.types.Object) + else bpy.data.objects.get(raw_close.name if hasattr(raw_close, "name") else str(raw_close)) + ) + if close_to is None: + continue + params = json.loads(str(obj.get("kit_params", "{}"))) + lug_b_params = json.loads(str(close_to.get("kit_params", "{}"))) + a_pos = obj.matrix_world.translation.copy() + # Lug pivot sits at local (0, 0, height) + b_h = float(lug_b_params.get("height", 0.234)) + b_pos = close_to.matrix_world @ Vector((0.0, 0.0, b_h)) + rest = float((b_pos - a_pos).length) + pin_dir = obj.parent.matrix_world.to_3x3().col[0].normalized() + body = float(params.get("body_len", 0.68)) + ext = float(params.get("extension", 0.40)) + a_dof = obj_to_dof.get(obj.parent.name, -1) + b_dof = obj_to_dof.get(close_to.name, -1) + rams_raw.append({ + "name": obj.name, + "barrel_bone": f"{obj.name}.barrel", + "rod_bone": f"{obj.name}.rod", + "spans": [dofs_raw[i]["name"] for i in (a_dof + 1, b_dof) if 0 <= i < len(dofs_raw)], + "bore": float(params.get("bore_r", 0.09)), + "body": body, + "inner": rest - body * 0.85, + "extension": ext, + "rest": rest, + "stroke": [-ext, max(0.2, body - 0.15)], + "a_parent_dof": a_dof, + "a_pos": [float(a_pos.x), float(a_pos.y), float(a_pos.z)], + "b_parent_dof": b_dof, + "b_pos": [float(b_pos.x), float(b_pos.y), float(b_pos.z)], + "pin_dir": [float(pin_dir.x), float(pin_dir.y), float(pin_dir.z)], + }) + + scissors_raw: list[dict[str, Any]] = [] + for sc in json.loads(str(bpy.context.scene.get("mech_scissors", "[]"))): + oa = bpy.data.objects.get(sc["a"][0]) + ob = bpy.data.objects.get(sc["b"][0]) + oo = bpy.data.objects.get(sc["out"][0]) + if oa is None or ob is None or oo is None: + continue + pa = oa.matrix_world @ Vector(sc["a"][1]) + pb = ob.matrix_world @ Vector(sc["b"][1]) + dout = (oo.matrix_world.to_3x3() @ Vector(sc["out"][1])).normalized() + scissors_raw.append({ + "name": sc["name"], + "upper_bone": f"{sc['name']}.upper", + "lower_bone": f"{sc['name']}.lower", + "arm": float(sc["arm"]), + "a_parent_dof": obj_to_dof.get(oa.name, -1), + "a_pos": [float(pa.x), float(pa.y), float(pa.z)], + "b_parent_dof": obj_to_dof.get(ob.name, -1), + "b_pos": [float(pb.x), float(pb.y), float(pb.z)], + "out_dir": [float(dout.x), float(dout.y), float(dout.z)], + }) + + struts_raw = [ + { + "name": d["name"], + "side": d["side"], + "dof": d["name"], + "travel": round(abs(d["hi"] - d["lo"]), 6), + "hertz": float(d["compliance"]["hertz"]), + "damping_ratio": float(d["compliance"]["damping_ratio"]), + } + for d in dofs_raw + if d.get("mechanism") == "oleo" and "compliance" in d + ] + + r_pos = root_obj.matrix_world.translation + return { + "root": [float(r_pos.x), float(r_pos.y), float(r_pos.z)], + "dofs": dofs_raw, + "rams": rams_raw, + "scissors": scissors_raw, + "struts": struts_raw, + } + + +def _finalize_mechanisms_gltf(raw: dict[str, Any], ground_z_shift: float) -> dict[str, Any]: + dofs_out = [] + for d in raw["dofs"]: + entry = { + **d, + "origin": _brokkr_vec_to_gltf(d["origin"], ground_z_shift), + "axis": _brokkr_dir_to_gltf(d["axis"]), + } + dofs_out.append(entry) + rams_out = [ + { + **r, + "a_pos": _brokkr_vec_to_gltf(r["a_pos"], ground_z_shift), + "b_pos": _brokkr_vec_to_gltf(r["b_pos"], ground_z_shift), + "pin_dir": _brokkr_dir_to_gltf(r["pin_dir"]), + } + for r in raw["rams"] + ] + scissors_out = [ + { + **s, + "a_pos": _brokkr_vec_to_gltf(s["a_pos"], ground_z_shift), + "b_pos": _brokkr_vec_to_gltf(s["b_pos"], ground_z_shift), + "out_dir": _brokkr_dir_to_gltf(s["out_dir"]), + } + for s in raw["scissors"] + ] + return { + "frame": "gltf (+Y up, +Z forward, +X left, meters)", + "rootOrigin": _brokkr_vec_to_gltf(raw["root"], ground_z_shift), + "dofs": dofs_out, + "rams": rams_out, + "scissors": scissors_out, + "struts": raw["struts"], + } + + +def _finalize_shroud_obj(obj: bpy.types.Object, bevel: float = 0.010) -> bpy.types.Object: + """Apply crisp hard-surface bevel + 36-deg edge split and bake to clean mesh.""" + if bevel > 0.0: + bv = obj.modifiers.new("Shroud_Bevel", "BEVEL") + bv.width = float(bevel) + bv.segments = 1 + bv.limit_method = "ANGLE" + bv.angle_limit = math.radians(30.0) + bv.harden_normals = False + es = obj.modifiers.new("Shroud_EdgeSplit", "EDGE_SPLIT") + es.use_edge_angle = True + es.split_angle = math.radians(36.0) + es.use_edge_sharp = True + depsgraph = bpy.context.evaluated_depsgraph_get() + ev = obj.evaluated_get(depsgraph) + new_mesh = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph) + new_mesh.name = f"{obj.name}_mesh" + new_mesh.validate(verbose=False) + obj.modifiers.clear() + obj.data = new_mesh + return obj + + +def _make_loft_shroud( + name: str, + rings: list[list[Vector]], + parent: bpy.types.Object, + mat_name: str = "olive_armor", + bevel: float = 0.010, +) -> bpy.types.Object: + """Loft a closed manifold hard-surface armor shell across multi-station 3D rings in parent local space.""" + assert len(rings) >= 2 and all(len(r) == len(rings[0]) for r in rings) + m = len(rings[0]) + bm = bmesh.new() + bm_rings: list[list[bmesh.types.BMVert]] = [ + [bm.verts.new(tuple(float(c) for c in pt)) for pt in ring] + for ring in rings + ] + bm.verts.ensure_lookup_table() + for i in range(len(bm_rings) - 1): + r0, r1 = bm_rings[i], bm_rings[i + 1] + for j in range(m): + jn = (j + 1) % m + bm.faces.new((r0[j], r0[jn], r1[jn], r1[j])) + bm.faces.new(list(reversed(bm_rings[0]))) + bm.faces.new(bm_rings[-1]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + mesh = bpy.data.meshes.new(name) + bm.to_mesh(mesh) + bm.free() + obj = bpy.data.objects.new(name, mesh) + vc._assign_material(obj, mat_name) + vc._link_object(obj, parent=parent, location=(0.0, 0.0, 0.0), rotation_deg=(0.0, 0.0, 0.0)) + return _finalize_shroud_obj(obj, bevel=bevel) + + +def _make_chamfer_box_shroud( + name: str, + x0: float, + x1: float, + y0: float, + y1: float, + z0: float, + z1: float, + parent: bpy.types.Object, + mat_name: str = "olive_armor", + chamfer: float = 0.035, + top_taper_xy: tuple[float, float] = (1.0, 1.0), + bevel: float = 0.010, +) -> bpy.types.Object: + """Create a tapered octagonal-section armor plate spanning [x0..x1] x [y0..y1] x [z0..z1].""" + cx, cy = 0.5 * (x0 + x1), 0.5 * (y0 + y1) + hx, hy = 0.5 * abs(x1 - x0), 0.5 * abs(y1 - y0) + c = min(chamfer, hx * 0.42, hy * 0.42) + + def _ring(z_val: float, sx: float, sy: float) -> list[Vector]: + rx, ry = hx * sx, hy * sy + cc = min(c, rx * 0.45, ry * 0.45) + pts = [ + (cx - rx + cc, cy - ry), + (cx + rx - cc, cy - ry), + (cx + rx, cy - ry + cc), + (cx + rx, cy + ry - cc), + (cx + rx - cc, cy + ry), + (cx - rx + cc, cy + ry), + (cx - rx, cy + ry - cc), + (cx - rx, cy - ry + cc), + ] + return [Vector((px, py, z_val)) for px, py in pts] + + tx, ty = top_taper_xy + rings = [_ring(z0, 1.0, 1.0), _ring(z1, tx, ty)] + return _make_loft_shroud(name, rings, parent=parent, mat_name=mat_name, bevel=bevel) + + +def _make_arc_fender( + name: str, + center: Vector, + axis: Vector, + fwd_dir: Vector, + up_dir: Vector, + r_in: float, + r_out: float, + half_w: float, + ang_start_deg: float, + ang_end_deg: float, + steps: int, + parent: bpy.types.Object, + mat_name: str = "olive_armor", + end_taper_w: float = 0.84, + bevel: float = 0.010, +) -> bpy.types.Object: + """Sweep a beveled armored fender arch around a cylindrical drum (0 deg = fwd_dir, 90 deg = up_dir).""" + ax = axis.normalized() + fd = fwd_dir.normalized() + ud = up_dir.normalized() + rings: list[list[Vector]] = [] + for k in range(steps + 1): + u = k / steps + ang = math.radians(ang_start_deg + (ang_end_deg - ang_start_deg) * u) + radial = fd * math.cos(ang) + ud * math.sin(ang) + # Slightly pinch width and thickness at the very ends for Brokkr fender silhouette + edge_fac = 1.0 - (1.0 - end_taper_w) * (abs(2.0 * u - 1.0) ** 2) + hw = half_w * edge_fac + hw_outer = hw * 0.86 + r_mid = r_in + (r_out - r_in) * 0.65 + pts = [ + center + radial * r_in - ax * hw, + center + radial * r_in + ax * hw, + center + radial * r_mid + ax * hw, + center + radial * r_out + ax * hw_outer, + center + radial * r_out - ax * hw_outer, + center + radial * r_mid - ax * hw, + ] + rings.append(pts) + return _make_loft_shroud(name, rings, parent=parent, mat_name=mat_name, bevel=bevel) + + +def _obj_bounds_in_ref(obj_names: list[str], ref_obj: bpy.types.Object, z_filter: tuple[float, float] | None = None) -> tuple[Vector, Vector] | None: + """Measure combined world vertices of named objects transformed into ref_obj local space.""" + inv_ref = ref_obj.matrix_world.inverted() + pts: list[Vector] = [] + for nm in obj_names: + o = bpy.data.objects.get(nm) + if o is None or o.type != "MESH" or o.data is None: + continue + mw = o.matrix_world + for v in o.data.vertices: + pw = mw @ v.co + if z_filter is not None and not (z_filter[0] <= pw.z <= z_filter[1]): + continue + pts.append(inv_ref @ pw) + if not pts: + return None + bmin = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts))) + bmax = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts))) + return bmin, bmax + + +def _add_kestrel_shrouds() -> list[bpy.types.Object]: + created: list[bpy.types.Object] = [] + torso = bpy.data.objects.get("Torso.pose") + pelvis = bpy.data.objects.get("Pelvis") + if torso is None or pelvis is None: + return created + + # 1. Sloped hooded shoulder pauldrons over exposed ribbed shoulder drums (parented to Torso.pose) + # Linearly tapered stations keep top/flank quads planar for crisp panel shading. + for side, sx in (("L", -1.0), ("R", 1.0)): + stations_spec = [ + # (|x|, y_rear, y_front, z_low_rear, z_low_front, z_top_rear, z_top_front) + (1.20, 0.00, 1.24, 1.54, 1.54, 2.26, 2.18), + (1.52, 0.02, 1.22, 1.36, 1.42, 2.18, 2.10), + (1.86, 0.04, 1.19, 1.22, 1.30, 2.07, 2.00), + (2.16, 0.06, 1.16, 1.16, 1.24, 1.92, 1.86), + (2.30, 0.10, 1.10, 1.24, 1.30, 1.74, 1.69), + ] + rings: list[list[Vector]] = [] + for ax, yr, yf, zlr, zlf, ztr, ztf in stations_spec: + px = sx * ax + yc = 0.5 * (yr + yf) + pts = [ + Vector((px, yr, zlr)), + Vector((px, yr + 0.14, zlr)), + Vector((px, yr + 0.16, ztr - 0.18)), + Vector((px, yc, min(ztr, ztf) - 0.12)), + Vector((px, yf - 0.16, ztf - 0.18)), + Vector((px, yf - 0.14, zlf)), + Vector((px, yf, zlf)), + Vector((px, yf - 0.08, ztf)), + Vector((px, yc, max(ztr, ztf) + 0.04)), + Vector((px, yr + 0.08, ztr)), + ] + if sx < 0: + pts = list(reversed(pts)) + rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Kestrel.Pauldron{side}", rings, torso, "olive_armor", bevel=0.012)) + + # Gunmetal mounting flange bracket bridging inner shoulder cowl to drum core + created.append( + _make_arc_fender( + f"Shroud.Kestrel.PauldronFlange{side}", + center=Vector((sx * 1.38, 0.65, 1.50)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.49, + r_out=0.56, + half_w=0.10, + ang_start_deg=15.0, + ang_end_deg=165.0, + steps=6, + parent=torso, + mat_name="gunmetal", + end_taper_w=0.92, + bevel=0.008, + ) + ) + + # 2. Compact sloped hip-fender guards + outer drum caps over bare hip cylinders (parented to Pelvis) + created.append( + _make_arc_fender( + f"Shroud.Kestrel.HipFender{side}", + center=Vector((sx * 1.28, 0.0, 6.20)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.515, + r_out=0.60, + half_w=0.38, + ang_start_deg=-10.0, + ang_end_deg=158.0, + steps=8, + parent=pelvis, + mat_name="olive_armor", + end_taper_w=0.80, + bevel=0.010, + ) + ) + # Outer hip drum shield cap + hip_cap_rings: list[list[Vector]] = [] + for x_off, r in ((1.46, 0.36), (1.58, 0.36), (1.64, 0.25)): + px = sx * x_off + pts = [ + Vector((px, r * math.cos(math.radians(a)), 6.20 + r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if sx < 0: + pts = list(reversed(pts)) + hip_cap_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Kestrel.HipCap{side}", hip_cap_rings, pelvis, "olive_armor", bevel=0.008)) + created.append( + _make_arc_fender( + f"Shroud.Kestrel.HipFlange{side}", + center=Vector((sx * 1.02, 0.0, 6.20)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.49, + r_out=0.54, + half_w=0.07, + ang_start_deg=-5.0, + ang_end_deg=162.0, + steps=7, + parent=pelvis, + mat_name="gunmetal", + end_taper_w=0.95, + bevel=0.006, + ) + ) + + # 4. Faceted knee caps + outer cheek shields over bare black knee drums (parented to Pelvis) + knee_bounds = _obj_bounds_in_ref([f"LegJoints{side}.gunmetal"], pelvis, z_filter=(3.0, 4.4)) + if knee_bounds is not None: + kmin, kmax = knee_bounds + kcx = 0.5 * (kmin.x + kmax.x) + kcy = 0.5 * (kmin.y + kmax.y) + kcz = 0.5 * (kmin.z + kmax.z) + created.append( + _make_arc_fender( + f"Shroud.Kestrel.KneeCap{side}", + center=Vector((kcx, kcy, kcz)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.37, + r_out=0.465, + half_w=0.37, + ang_start_deg=-42.0, + ang_end_deg=72.0, + steps=6, + parent=pelvis, + mat_name="olive_armor", + end_taper_w=0.78, + bevel=0.010, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Kestrel.KneeCapFront{side}", + kcx - 0.25, + kcx + 0.25, + kcy + 0.36, + kcy + 0.49, + kcz - 0.24, + kcz + 0.28, + parent=pelvis, + mat_name="olive_armor", + chamfer=0.06, + top_taper_xy=(0.86, 0.85), + bevel=0.009, + ) + ) + knee_side_rings: list[list[Vector]] = [] + for x_off, r in ((0.28, 0.28), (0.37, 0.28), (0.42, 0.19)): + px = kcx + sx * x_off + pts = [ + Vector((px, kcy + r * math.cos(math.radians(a)), kcz + r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if sx < 0: + pts = list(reversed(pts)) + knee_side_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Kestrel.KneeCheek{side}", knee_side_rings, pelvis, "olive_armor", bevel=0.008)) + + # 5. Armored calf/shin shrouds wrapping rear twin ankle hydraulic pistons (parented to Pelvis) + ram_objs = [f"Ankle{side}.root.machine.ram", f"Ankle{side}.root.steel.ram", f"Ankle{side}.root.steel.eye"] + top_b = _obj_bounds_in_ref(ram_objs, pelvis, z_filter=(2.05, 2.75)) + bot_b = _obj_bounds_in_ref(ram_objs, pelvis, z_filter=(0.95, 1.65)) + if top_b is not None and bot_b is not None: + t_cx = 0.5 * (top_b[0].x + top_b[1].x) + t_cy = 0.5 * (top_b[0].y + top_b[1].y) + b_cx = 0.5 * (bot_b[0].x + bot_b[1].x) + b_cy = 0.5 * (bot_b[0].y + bot_b[1].y) + z_bot, z_top = 1.16, 2.74 + # Interpolate exact piston spine centerline from z_bot..z_top and wrap a U-channel rear/flank greave + greave_rings: list[list[Vector]] = [] + for frac, hw, y_back, y_front in ( + (0.00, 0.145, -0.145, 0.13), + (0.22, 0.165, -0.165, 0.17), + (0.75, 0.180, -0.175, 0.22), + (1.00, 0.160, -0.145, 0.19), + ): + zz = z_bot + (z_top - z_bot) * frac + # top_b centroid is ~z=2.40, bot_b centroid is ~z=1.30 + t_u = (zz - 1.30) / 1.10 + px = b_cx + (t_cx - b_cx) * t_u + py = b_cy + (t_cy - b_cy) * t_u + c_in = hw * 0.58 + pts = [ + Vector((px - hw, py + y_front, zz)), + Vector((px - c_in, py + y_front, zz)), + Vector((px - c_in, py + y_back + 0.08, zz)), + Vector((px + c_in, py + y_back + 0.08, zz)), + Vector((px + c_in, py + y_front, zz)), + Vector((px + hw, py + y_front, zz)), + Vector((px + hw, py + y_back + 0.05, zz)), + Vector((px + hw * 0.62, py + y_back, zz)), + Vector((px - hw * 0.62, py + y_back, zz)), + Vector((px - hw, py + y_back + 0.05, zz)), + ] + greave_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Kestrel.AnkleGreave{side}", greave_rings, pelvis, "olive_armor", bevel=0.010)) + for idx_band, zb in enumerate((1.38, 2.38)): + t_u = (zb - 1.30) / 1.10 + px = b_cx + (t_cx - b_cx) * t_u + py = b_cy + (t_cy - b_cy) * t_u + created.append( + _make_chamfer_box_shroud( + f"Shroud.Kestrel.AnkleBand{side}{idx_band}", + px - 0.18, + px + 0.18, + py - 0.175, + py + 0.16, + zb - 0.045, + zb + 0.045, + parent=pelvis, + mat_name="gunmetal", + chamfer=0.03, + bevel=0.006, + ) + ) + + # 3. Segmented armored spine shroud over exposed rear waist hydraulic rods (parented to Torso.pose) + # In Torso.pose local space (offset 0, -0.15, 6.75), neck rings step forward in Y as Z rises from -0.05 to +0.88 + for idx_seg, (z0, z1, y_back, hx) in enumerate(( + (-0.04, 0.27, -0.66, 0.58), + (0.24, 0.56, -0.58, 0.54), + (0.53, 0.86, -0.49, 0.49), + )): + created.append( + _make_chamfer_box_shroud( + f"Shroud.Kestrel.WaistSpine{idx_seg}", + -hx, + hx, + y_back, + y_back + 0.34, + z0, + z1, + parent=torso, + mat_name="olive_armor", + chamfer=0.07, + top_taper_xy=(0.92, 0.90), + bevel=0.010, + ) + ) + created.append( + _make_chamfer_box_shroud( + "Shroud.Kestrel.WaistSpineRib", + -0.16, + 0.16, + -0.69, + -0.42, + 0.00, + 0.82, + parent=torso, + mat_name="gunmetal", + chamfer=0.03, + top_taper_xy=(0.88, 0.85), + bevel=0.008, + ) + ) + return created + + +def _add_spectre_shrouds() -> list[bpy.types.Object]: + created: list[bpy.types.Object] = [] + + # 1. Angled shin/hock hydraulic ram deflector greaves (parented to LegL.Cannon / LegR.Cannon) + for leg in ("LegL", "LegR"): + cannon = bpy.data.objects.get(f"{leg}.Cannon") + if cannon is None: + continue + inv_can = cannon.matrix_world.inverted() + ram_objs = [bpy.data.objects.get(f"{leg}.Hock.ram.barrel"), bpy.data.objects.get(f"{leg}.Hock.ram.rod")] + for side_tag, x_sign in (("Out", -1.0 if leg == "LegL" else 1.0), ("In", 1.0 if leg == "LegL" else -1.0)): + pts: list[Vector] = [] + for ro in ram_objs: + if ro is None or ro.type != "MESH" or ro.data is None: + continue + mw = ro.matrix_world + for v in ro.data.vertices: + pl = inv_can @ (mw @ v.co) + if pl.x * x_sign > 0.10: + pts.append(pl) + if not pts: + continue + xmin = min(p.x for p in pts) + xmax = max(p.x for p in pts) + ymax = max(p.y for p in pts) + ymin = min(p.y for p in pts) + # Deflector greave wrapping the front (+Y) and outer/side face of each exposed silver ram + x_in = (xmin - 0.02) if x_sign > 0 else (xmin - 0.055) + x_out = (xmax + 0.055) if x_sign > 0 else (xmax + 0.02) + y_f = ymax + 0.055 + y_b = max(ymin - 0.02, ymax - 0.24) + z_top = 0.28 + z_bot = 1.46 + # Loft from top bevel cap -> mid shield -> lower tapered deflector lip + rings: list[list[Vector]] = [] + for zz, x_pad, y_pad in ( + (z_top, -0.02, -0.03), + (z_top + 0.14, 0.0, 0.0), + (z_bot - 0.18, 0.0, 0.0), + (z_bot, -0.025, -0.04), + ): + xa, xb = x_in - x_pad * x_sign, x_out + x_pad * x_sign + if xa > xb: + xa, xb = xb, xa + yf = y_f + y_pad + yb = y_b + xm = 0.5 * (xa + xb) + ym = 0.5 * (yb + yf) + rings.append([ + Vector((xa, yb, zz)), + Vector((xb, yb, zz)), + Vector((xb, ym + 0.03, zz)), + Vector((xm + 0.04 * (xb - xa), yf, zz)), + Vector((xm - 0.04 * (xb - xa), yf, zz)), + Vector((xa, ym + 0.03, zz)), + ]) + created.append(_make_loft_shroud(f"Shroud.Spectre.{leg}RamGuard{side_tag}", rings, cannon, "olive_armor", bevel=0.009)) + # Gunmetal mounting bracket tying greave into Leg*.Shank + bx0 = min(x_in, x_out) - (0.06 if x_sign > 0 else 0.0) + bx1 = max(x_in, x_out) + (0.06 if x_sign < 0 else 0.0) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Spectre.{leg}RamBracket{side_tag}", + bx0, + bx1, + y_b - 0.08, + y_b + 0.04, + 0.55, + 0.78, + parent=cannon, + mat_name="gunmetal", + chamfer=0.025, + bevel=0.006, + ) + ) + + # 2. Compact armored waist collar / hip skirt around vertical waist spindle (parented to Waist) + waist = bpy.data.objects.get("Waist") + if waist is not None: + # Waist wloc=(0,0,5.30), WaistLug extends z_local=-0.35..0.14, WaistColumn z_local=0..0.81 + skirt_rings: list[list[Vector]] = [] + for zz, sx, sy in ( + (-0.28, 0.72, 0.62), + (-0.04, 0.74, 0.64), + (0.24, 0.64, 0.56), + (0.42, 0.55, 0.49), + ): + c = 0.16 + skirt_rings.append([ + Vector((-sx + c, -sy, zz)), + Vector((sx - c, -sy, zz)), + Vector((sx, -sy + c, zz)), + Vector((sx, sy - c, zz)), + Vector((sx - c, sy, zz)), + Vector((-sx + c, sy, zz)), + Vector((-sx, sy - c, zz)), + Vector((-sx, -sy + c, zz)), + ]) + created.append(_make_loft_shroud("Shroud.Spectre.WaistSkirt", skirt_rings, waist, "olive_armor", bevel=0.010)) + created.append( + _make_chamfer_box_shroud( + "Shroud.Spectre.WaistCollar", + -0.56, + 0.56, + -0.51, + 0.51, + 0.32, + 0.48, + parent=waist, + mat_name="gunmetal", + chamfer=0.10, + bevel=0.008, + ) + ) + + # 3. Outer shoulder-hinge axle caps (parented to ShoulderL / ShoulderR) + for side, sx in (("L", -1.0), ("R", 1.0)): + sh = bpy.data.objects.get(f"Shoulder{side}") + if sh is None: + continue + cap_rings: list[list[Vector]] = [] + for x_off, r in ((0.24, 0.305), (0.44, 0.305), (0.52, 0.225)): + px = sx * x_off + pts = [ + Vector((px, r * math.cos(math.radians(a)), r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if sx < 0: + pts = list(reversed(pts)) + cap_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Spectre.ShoulderCap{side}", cap_rings, sh, "olive_armor", bevel=0.008)) + + return created + + +def _add_raptor_shrouds() -> list[bpy.types.Object]: + created: list[bpy.types.Object] = [] + pelvis = bpy.data.objects.get("Pelvis") + + for side, sx in (("L", -1.0), ("R", 1.0)): + # 1. Angled olive hip-fender cowl over protruding black hip drum (parented to Pelvis) + if pelvis is not None: + created.append( + _make_arc_fender( + f"Shroud.Raptor.HipFender{side}", + center=Vector((sx * 1.44, 0.0, 0.0)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.535, + r_out=0.615, + half_w=0.45, + ang_start_deg=18.0, + ang_end_deg=165.0, + steps=7, + parent=pelvis, + mat_name="olive_armor", + end_taper_w=0.82, + bevel=0.010, + ) + ) + created.append( + _make_arc_fender( + f"Shroud.Raptor.HipFlange{side}", + center=Vector((sx * 1.02, 0.0, 0.0)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.50, + r_out=0.555, + half_w=0.07, + ang_start_deg=15.0, + ang_end_deg=168.0, + steps=6, + parent=pelvis, + mat_name="gunmetal", + end_taper_w=0.95, + bevel=0.006, + ) + ) + + # 2. Outer hip drum cap + knee-cap shield + rear thigh actuator guard (parented to Leg*.Thigh) + thigh = bpy.data.objects.get(f"Leg{side}.Thigh") + if thigh is not None: + # In LegL.Thigh local space +X is outer left; in LegR.Thigh local space -X is outer right + x_out_sign = -sx + hip_cap_rings: list[list[Vector]] = [] + for x_off, r in ((0.48, 0.35), (0.60, 0.35), (0.66, 0.25)): + px = x_out_sign * x_off + pts = [ + Vector((px, r * math.cos(math.radians(a)), r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if x_out_sign < 0: + pts = list(reversed(pts)) + hip_cap_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Raptor.HipCap{side}", hip_cap_rings, thigh, "olive_armor", bevel=0.008)) + + # KneeBearing*.gunmetal sits at z_local=[1.52..2.28], y_local=[-0.38..+0.38] (center 0.0, 1.90) + created.append( + _make_arc_fender( + f"Shroud.Raptor.KneeCap{side}", + center=Vector((x_out_sign * 0.06, 0.0, 1.90)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, -1.0)), + r_in=0.385, + r_out=0.475, + half_w=0.46, + ang_start_deg=-62.0, + ang_end_deg=62.0, + steps=7, + parent=thigh, + mat_name="olive_armor", + end_taper_w=0.78, + bevel=0.010, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.KneeCapFront{side}", + x_out_sign * 0.06 - 0.30, + x_out_sign * 0.06 + 0.30, + 0.37, + 0.50, + 1.64, + 2.16, + parent=thigh, + mat_name="olive_armor", + chamfer=0.06, + top_taper_xy=(0.86, 0.85), + bevel=0.009, + ) + ) + # Outer circular knee-drum cap + knee_cap_rings: list[list[Vector]] = [] + for x_off, r in ((0.46, 0.28), (0.58, 0.28), (0.64, 0.19)): + px = x_out_sign * x_off + pts = [ + Vector((px, r * math.cos(math.radians(a)), 1.90 + r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if x_out_sign < 0: + pts = list(reversed(pts)) + knee_cap_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Raptor.KneeOuterCap{side}", knee_cap_rings, thigh, "olive_armor", bevel=0.008)) + + # Rear thigh actuator guard over Actuators*.steel (y_local=[-0.62..-0.42], z_local=[1.14..1.71]) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.ThighRam{side}", + -0.37, + 0.37, + -0.66, + -0.36, + 1.08, + 1.72, + parent=thigh, + mat_name="olive_armor", + chamfer=0.06, + top_taper_xy=(0.90, 0.88), + bevel=0.009, + ) + ) + + # 3. Shin upper rod shroud (parented to Leg*.Shin) + shin = bpy.data.objects.get(f"Leg{side}.Shin") + if shin is not None: + # HydraulicsShin*.gunmetal/steel: x=[-0.23..0.23], y=[0.46..0.66], z=[0.18..1.48] + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.ShinRod{side}", + -0.27, + 0.27, + 0.36, + 0.71, + 0.20, + 1.32, + parent=shin, + mat_name="olive_armor", + chamfer=0.06, + top_taper_xy=(0.82, 0.80), + bevel=0.009, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.ShinRodCollar{side}", + -0.29, + 0.29, + 0.34, + 0.72, + 0.82, + 0.98, + parent=shin, + mat_name="gunmetal", + chamfer=0.04, + bevel=0.006, + ) + ) + + # 4. Protruding rear calf hydraulic rod shroud (parented to Leg*.Cannon) + cannon = bpy.data.objects.get(f"Leg{side}.Cannon") + if cannon is not None: + # Hydraulics*.gunmetal/steel: x=[-0.23..0.23], y=[-0.57..-0.37], z=[0.18..1.61] + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.CalfRod{side}", + -0.28, + 0.28, + -0.63, + -0.27, + 0.20, + 1.40, + parent=cannon, + mat_name="olive_armor", + chamfer=0.07, + top_taper_xy=(0.80, 0.78), + bevel=0.009, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Raptor.CalfRodCollar{side}", + -0.30, + 0.30, + -0.64, + -0.26, + 0.88, + 1.04, + parent=cannon, + mat_name="gunmetal", + chamfer=0.04, + bevel=0.006, + ) + ) + + return created + + +def _add_manticore_shrouds() -> list[bpy.types.Object]: + created: list[bpy.types.Object] = [] + for leg in ("LegBL", "LegBR"): + # In LegBL local space -X is outward-left; in LegBR local space +X is outward-right + x_out_sign = -1.0 if leg == "LegBL" else 1.0 + + # 1. Rear hip armor cap over bare gunmetal coxa drum (parented to LegB*.Coxa) + coxa = bpy.data.objects.get(f"{leg}.Coxa") + if coxa is not None: + # coxa.dress.machine: x=[-0.446..0.446], y=[-0.30..0.30], z=[0.16..0.76]; +Y_local is outer-rear + created.append( + _make_chamfer_box_shroud( + f"Shroud.Manticore.{leg}HipCap", + -0.48, + 0.48, + -0.12, + 0.40, + -0.02, + 0.54, + parent=coxa, + mat_name="olive_armor", + chamfer=0.08, + top_taper_xy=(0.90, 0.86), + bevel=0.010, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Manticore.{leg}HipFlange", + -0.50, + 0.50, + -0.14, + 0.28, + -0.04, + 0.12, + parent=coxa, + mat_name="gunmetal", + chamfer=0.06, + bevel=0.006, + ) + ) + + # 2. Rear knee armor cap arching over bare gunmetal knee drum + outer drum cap (parented to LegB*.S1) + s1 = bpy.data.objects.get(f"{leg}.S1") + if s1 is not None: + # knee.dress.machine: x=[-0.44..0.44], y=[-0.34..0.34], z=[1.242..1.922]; femur.plate ends at z=1.25, y=[0.30..0.42] + created.append( + _make_arc_fender( + f"Shroud.Manticore.{leg}KneeCap", + center=Vector((0.0, 0.0, 1.58)), + axis=Vector((1.0, 0.0, 0.0)), + fwd_dir=Vector((0.0, 1.0, 0.0)), + up_dir=Vector((0.0, 0.0, 1.0)), + r_in=0.345, + r_out=0.445, + half_w=0.48, + ang_start_deg=-38.0, + ang_end_deg=132.0, + steps=8, + parent=s1, + mat_name="olive_armor", + end_taper_w=0.84, + bevel=0.010, + ) + ) + created.append( + _make_chamfer_box_shroud( + f"Shroud.Manticore.{leg}KneeCapTop", + -0.34, + 0.34, + 0.24, + 0.45, + 1.26, + 1.80, + parent=s1, + mat_name="olive_armor", + chamfer=0.06, + top_taper_xy=(0.88, 0.85), + bevel=0.009, + ) + ) + knee_side_rings: list[list[Vector]] = [] + for x_off, r in ((0.38, 0.28), (0.48, 0.28), (0.53, 0.19)): + px = x_out_sign * x_off + pts = [ + Vector((px, r * math.cos(math.radians(a)), 1.58 + r * math.sin(math.radians(a)))) + for a in range(0, 360, 45) + ] + if x_out_sign < 0: + pts = list(reversed(pts)) + knee_side_rings.append(pts) + created.append(_make_loft_shroud(f"Shroud.Manticore.{leg}KneeSideCap", knee_side_rings, s1, "olive_armor", bevel=0.008)) + + return created + + +def _add_paladin_shrouds() -> list[bpy.types.Object]: + created: list[bpy.types.Object] = [] + arm_r = bpy.data.objects.get("ArmR.Lower") + if arm_r is None: + return created + + # ArmR.Lower local box is [-0.297, -0.25, -0.144]..[0.297, 0.25, 1.55]. + # hp.weapon.arm_r sits on -X_local face at (-0.311, -0.124, 0.697) with 0.72x0.72 footprint -> keep -X_local z=[0.26..1.16] clear! + # Inner (+X), Front (+Y), and Rear (-Y) forearm plates: + created.append( + _make_chamfer_box_shroud( + "Shroud.Paladin.ArmRInner", + 0.28, + 0.42, + -0.27, + 0.27, + 0.14, + 1.44, + parent=arm_r, + mat_name="olive_armor", + chamfer=0.04, + top_taper_xy=(0.90, 0.88), + bevel=0.009, + ) + ) + created.append( + _make_chamfer_box_shroud( + "Shroud.Paladin.ArmRFront", + -0.31, + 0.36, + 0.23, + 0.39, + 0.14, + 1.44, + parent=arm_r, + mat_name="olive_armor", + chamfer=0.05, + top_taper_xy=(0.86, 0.86), + bevel=0.009, + ) + ) + created.append( + _make_chamfer_box_shroud( + "Shroud.Paladin.ArmRRear", + -0.31, + 0.36, + -0.39, + -0.23, + 0.14, + 1.44, + parent=arm_r, + mat_name="olive_armor", + chamfer=0.05, + top_taper_xy=(0.86, 0.86), + bevel=0.009, + ) + ) + # Upper elbow cuff & lower wrist cuff collar (staying clear of hp.weapon.arm_r around z=0.26..1.16 on -X) + created.append( + _make_chamfer_box_shroud( + "Shroud.Paladin.ArmRElbowCuff", + -0.38, + 0.38, + -0.33, + 0.33, + -0.02, + 0.22, + parent=arm_r, + mat_name="olive_armor", + chamfer=0.06, + bevel=0.009, + ) + ) + created.append( + _make_chamfer_box_shroud( + "Shroud.Paladin.ArmRWristBand", + -0.34, + 0.36, + -0.30, + 0.30, + 1.36, + 1.50, + parent=arm_r, + mat_name="gunmetal", + chamfer=0.04, + bevel=0.006, + ) + ) + return created + + +def _add_actuator_armor_shrouds(mech_id: str) -> list[bpy.types.Object]: + builders = { + "kestrel": _add_kestrel_shrouds, + "spectre": _add_spectre_shrouds, + "raptor": _add_raptor_shrouds, + "manticore": _add_manticore_shrouds, + "paladin": _add_paladin_shrouds, + } + fn = builders.get(mech_id) + if fn is None: + return [] + return fn() + + +def retrofit_mech(spec: MechRetrofitSpec) -> dict[str, Any]: + bpy.ops.wm.open_mainfile(filepath=str(spec.blend_path)) + scene = bpy.context.scene + scene.unit_settings.system = "METRIC" + scene.unit_settings.scale_length = 1.0 + + # 1. Apply SOLIDIFY/BOOLEAN/BEVEL BEFORE stripping hidden boolean cutters + if not spec.armature_name: + _apply_existing_modifiers() + + # 2. Strip studio rig/backdrop & built-in weapons + stripped = _strip_scene_objects(spec) + + if not spec.armature_name: + _convert_surviving_curves() + + # Square Breaker-3 torso yaw (-5 deg walk offset -> 0 deg neutral symmetric forward) + if spec.mech_id == "breaker" and "Core" in bpy.data.objects: + bpy.data.objects["Core"].rotation_euler.z = 0.0 + bpy.context.view_layer.update() + + raw_blend_mechs = ( + _extract_mechanisms_from_blend_raw("Pelvis") + if spec.model_json_path is None and spec.mech_id == "breaker" + else None + ) + + # 3. For rigged meshes, strip weapon vertex groups cleanly; strip protruding weapon islands + stripped_vgs: dict[str, int] = {} + if spec.strip_vertex_groups: + for obj in bpy.data.objects: + if obj.type == "MESH": + cnt = _strip_vertex_groups_from_mesh(obj, spec.strip_vertex_groups) + if cnt > 0: + stripped_vgs[obj.name] = cnt + if spec.strip_islands: + _strip_mesh_islands(spec.strip_islands) + if spec.mech_id == "kestrel": + _assemble_kestrel_hierarchy() + + # 4. Normalize procedural materials -> clean glTF PBR + _normalize_materials_for_gltf() + + # 5. Collect surviving mech meshes & decimate to game-ready LOD budget + mech_meshes = [o for o in bpy.data.objects if o.type == "MESH"] + raw_tris, lod_tris = _decimate_mech_meshes(mech_meshes, spec.target_mech_tris) + + # 5b. Add Brokkr-style olive-drab armor shrouds over exposed joints/actuators + shroud_objs = _add_actuator_armor_shrouds(spec.mech_id) + if shroud_objs: + shroud_tris = sum(_mesh_tri_count(o) for o in shroud_objs) + lod_tris += shroud_tris + print(f" [shroud] {spec.mech_id}: +{len(shroud_objs)} shrouds (+{shroud_tris} tris)") + + # 6. Parent everything cleanly under a root Empty (in raw Brokkr orientation first) + chassis_root = vc.make_empty(spec.mech_id, parent=None, location=(0.0, 0.0, 0.0)) + for obj in list(bpy.data.objects): + if obj == chassis_root or obj.parent is not None: + continue + mw = obj.matrix_world.copy() + obj.parent = chassis_root + obj.matrix_parent_inverse = Matrix.Identity(4) + obj.matrix_local = mw + bpy.context.view_layer.update() + + # 7. Build hull BVH over final LOD meshes, snap & recess every hardpoint bay, tag joints + full_bvh = _build_hull_bvh([o for o in bpy.data.objects if o.type == "MESH"]) + assert full_bvh is not None, f"{spec.mech_id}: empty hull BVH" + bvh_cache: dict[str, BVHTree] = {} + for hp in spec.hardpoints: + _attach_hardpoint_world(hp, chassis_root, full_bvh, bvh_cache) + joints_manifest = _apply_joint_tags(spec) + + # 8. Rotate chassis_root 180 deg around Z so Brokkr +Y forward -> RTD -Y forward (+Z glTF), -X left -> +X left + chassis_root.rotation_mode = "XYZ" + chassis_root.rotation_euler = Euler((0.0, 0.0, math.pi), "XYZ") + bpy.context.view_layer.update() + + # 9. Export GLB (grounding minZ=0.0), write manifest.json, render 4-panel preview + glb_path = vc.ASSETS_VEHICLES_DIR / spec.mech_id / f"{spec.mech_id}.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / spec.mech_id / "manifest.json" + preview_path = vc.PREVIEWS_DIR / f"{spec.mech_id}_preview.png" + + z_shift_before = chassis_root.location.z + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=chassis_root) + ground_z_shift = chassis_root.location.z - z_shift_before + + if spec.model_json_path is not None: + mechanisms = _extract_mechanisms(spec.model_json_path, ground_z_shift=ground_z_shift) + elif raw_blend_mechs is not None: + mechanisms = _finalize_mechanisms_gltf(raw_blend_mechs, ground_z_shift=ground_z_shift) + else: + mechanisms = None + + hp_manifest = [ + { + "id": hp.hp_id, + "kind": hp.kind, + "x": hp.x, + "y": hp.y, + "w": hp.w, + "h": hp.h, + "modelNodeId": hp.hp_id, + } + for hp in spec.hardpoints + ] + + vc.write_manifest( + manifest_path, + vehicle_id=spec.mech_id, + name=spec.name, + vehicle_class=spec.vehicle_class, + plane=spec.plane, + grid_width=spec.grid_width, + grid_height=spec.grid_height, + mask=spec.mask, + hardpoints=hp_manifest, + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + mechanisms=mechanisms, + ) + + vc.render_four_panel_preview(preview_path) + glb_bytes = glb_path.stat().st_size + summary = { + "id": spec.mech_id, + "raw_tris_after_strip": raw_tris, + "lod_mech_tris": lod_tris, + "exported_total_tris": tri_count, + "glb_bytes": glb_bytes, + "bounds": bounds, + "stripped_count": len(stripped), + "stripped_vgs": stripped_vgs, + } + print(f"[{spec.mech_id}] {json.dumps(summary)}") + return summary + + +def main() -> int: + argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else [] + parser = argparse.ArgumentParser(description="Retrofit Brokkr mechs for Rust to Dust.") + parser.add_argument("--mech", choices=sorted(SPECS.keys()), help="Single mech ID to retrofit.") + parser.add_argument("--all", action="store_true", help="Retrofit all configured mechs sequentially.") + args = parser.parse_args(argv) + + targets = list(SPECS.keys()) if (args.all or not args.mech) else [args.mech] + for mid in targets: + retrofit_mech(SPECS[mid]) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/vehicles/vehicle_common.py b/tools/vehicles/vehicle_common.py new file mode 100644 index 0000000..0077681 --- /dev/null +++ b/tools/vehicles/vehicle_common.py @@ -0,0 +1,1160 @@ +"""Shared Brokkr-powered vehicle construction, hardpoint sockets, joint tagging, +GLB export, manifest emission, and 4-panel preview rendering for Rust to Dust. + +All Blender geometry is authored in Blender right-handed Z-up coordinates with: + -Y = vehicle forward (+Z in exported glTF) + +Y = vehicle rear (-Z in exported glTF) + +Z = vehicle up (+Y in exported glTF, grounded at Z = 0) + +X = vehicle left (+X in exported glTF) + -X = vehicle right (-X in exported glTF) + +Export uses bpy.ops.export_scene.gltf(..., export_yup=True, export_extras=True) +so Godot receives +Z forward, +Y up, minY ~ 0.0, and rtd.* custom properties. +""" +from __future__ import annotations + +import json +import math +import sys +from pathlib import Path +from typing import Any, Callable, Sequence + +import bmesh +import bpy +import numpy as np +from mathutils import Euler, Matrix, Vector + +BROKKR_BLENDER_DIR = Path(r"F:\Projects\Brokkr\surfaces\blender") +if str(BROKKR_BLENDER_DIR) not in sys.path: + sys.path.insert(0, str(BROKKR_BLENDER_DIR)) + +import brokkr_mesh_polish # noqa: E402, F401 +import brokkr_kitbash # noqa: E402 +from brokkr_kitbash import core, plate, ram # noqa: E402, F401 + +REPO_ROOT = Path(__file__).resolve().parents[2] +ASSETS_VEHICLES_DIR = REPO_ROOT / "assets" / "vehicles" +ASSETS_GEAR_DIR = REPO_ROOT / "assets" / "gear" +PREVIEWS_DIR = Path(__file__).resolve().parent / "previews" + +# Shared industrial PBR palette (sRGB hex -> linear PBR base color) +PALETTE: dict[str, dict[str, Any]] = { + "olive_armor": {"hex": "#4e5740", "metallic": 0.28, "roughness": 0.58}, + "gunmetal": {"hex": "#2c302e", "metallic": 0.78, "roughness": 0.40}, + "rubber_dark": {"hex": "#191a19", "metallic": 0.04, "roughness": 0.86}, + "copper_rad": {"hex": "#9c5a34", "metallic": 0.86, "roughness": 0.34}, + "socket_bay": {"hex": "#151816", "metallic": 0.55, "roughness": 0.72}, + "signal_orange": {"hex": "#d96c27", "metallic": 0.18, "roughness": 0.44}, + "smoked_glass": {"hex": "#1e2a2d", "metallic": 0.12, "roughness": 0.10, "alpha": 0.82}, + # Imperial Tourist & salvage gear accents + "imperial_gold": {"hex": "#d4a634", "metallic": 0.90, "roughness": 0.26}, + "imperial_ivory": {"hex": "#ebe4d1", "metallic": 0.16, "roughness": 0.38}, + "cyan_coil": {"hex": "#38c9d8", "metallic": 0.20, "roughness": 0.25, "emission": "#38c9d8", "emission_strength": 1.8}, +} + +_KITS_CACHE: dict[str, dict] = {} + + +def srgb_hex_to_linear(hex_str: str) -> tuple[float, float, float, float]: + h = hex_str.lstrip("#") + vals = [int(h[i : i + 2], 16) / 255.0 for i in (0, 2, 4)] + + def to_lin(c: float) -> float: + return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 + + return (to_lin(vals[0]), to_lin(vals[1]), to_lin(vals[2]), 1.0) + + +def reset_scene() -> bpy.types.Scene: + """Clear all objects, meshes, materials, cameras, lights, and orphan data.""" + bpy.ops.wm.read_factory_settings(use_empty=True) + scene = bpy.context.scene + scene.unit_settings.system = "METRIC" + scene.unit_settings.scale_length = 1.0 + return scene + + +def ensure_materials() -> dict[str, bpy.types.Material]: + """Create shared industrial PBR materials cleanly on Principled BSDF.""" + mats: dict[str, bpy.types.Material] = {} + for name, spec in PALETTE.items(): + mat = bpy.data.materials.get(name) + if mat is None: + mat = bpy.data.materials.new(name=name) + mat.use_nodes = True + nt = mat.node_tree + nt.nodes.clear() + out = nt.nodes.new("ShaderNodeOutputMaterial") + bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + nt.links.new(bsdf.outputs["BSDF"], out.inputs["Surface"]) + bsdf.inputs["Base Color"].default_value = srgb_hex_to_linear(spec["hex"]) + bsdf.inputs["Metallic"].default_value = float(spec["metallic"]) + bsdf.inputs["Roughness"].default_value = float(spec["roughness"]) + if "alpha" in spec: + bsdf.inputs["Alpha"].default_value = float(spec["alpha"]) + mat.blend_method = "BLEND" if hasattr(mat, "blend_method") else "HASHED" + if "emission" in spec: + bsdf.inputs["Emission Color"].default_value = srgb_hex_to_linear(spec["emission"]) + bsdf.inputs["Emission Strength"].default_value = float(spec.get("emission_strength", 1.0)) + mats[name] = mat + return mats + + +def load_kit(name: str) -> dict: + if name not in _KITS_CACHE: + _KITS_CACHE[name] = core.load_kit(name) + return _KITS_CACHE[name] + + +def _assign_material(obj: bpy.types.Object, mat_name: str) -> None: + mat = bpy.data.materials.get(mat_name) + if mat is None: + ensure_materials() + mat = bpy.data.materials[mat_name] + if len(obj.data.materials): + obj.data.materials[0] = mat + else: + obj.data.materials.append(mat) + + +def _link_object( + obj: bpy.types.Object, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), +) -> bpy.types.Object: + scene = bpy.context.scene + if obj.name not in scene.collection.objects: + scene.collection.objects.link(obj) + if parent is not None: + obj.parent = parent + obj.matrix_parent_inverse = Matrix.Identity(4) + obj.location = Vector(location) + obj.rotation_mode = "XYZ" + obj.rotation_euler = Euler([math.radians(a) for a in rotation_deg], "XYZ") + return obj + + +def _add_bevel(obj: bpy.types.Object, width: float, segments: int = 1, angle_deg: float = 30.0) -> None: + if width <= 0.0: + return + mod = obj.modifiers.new("Bevel", "BEVEL") + mod.width = width + mod.segments = segments + mod.limit_method = "ANGLE" + mod.angle_limit = math.radians(angle_deg) + mod.harden_normals = False + + +def make_empty( + name: str, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + display_type: str = "PLAIN_AXES", + display_size: float = 0.12, +) -> bpy.types.Object: + obj = bpy.data.objects.new(name, None) + obj.empty_display_type = display_type + obj.empty_display_size = display_size + return _link_object(obj, parent=parent, location=location, rotation_deg=rotation_deg) + + +def make_mesh_from_swept( + name: str, + swept: Any, + mat_name: str, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + mesh = bpy.data.meshes.new(name) + brokkr_kitbash.write_mesh(mesh, swept) + obj = bpy.data.objects.new(name, mesh) + _assign_material(obj, mat_name) + _link_object(obj, parent=parent, location=location, rotation_deg=rotation_deg) + if bevel > 0.0: + _add_bevel(obj, bevel, segments=1) + return obj + + +def _build_inline_shape(name: str, shape_dict: dict[str, Any]) -> core.Built: + doc = { + "schema": core.SCHEMA, + "kit": "inline", + "doc": "inline part", + "socketTypes": {}, + "parts": [{ + "name": "p", + "doc": name, + "params": [], + "shapes": [shape_dict], + "sockets": [], + }], + } + checked = core.check_kit(doc) + return core.build(checked["parts"]["p"], {}) + + +def make_tube_part( + name: str, + r0: float, + r1: float, + length: float, + segments: int = 12, + inner0: float = 0.0, + inner1: float = 0.0, + smooth: bool = True, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + shape_dict: dict[str, Any] = { + "shape": "tube", + "r0": float(r0), + "r1": float(r1), + "length": float(length), + "segments": int(segments), + "smooth": bool(smooth), + } + if inner0 > 0.0 or inner1 > 0.0: + shape_dict["inner0"] = float(inner0) + shape_dict["inner1"] = float(inner1) + return make_mesh_from_swept( + name, + _build_inline_shape(name, shape_dict), + mat_name, + parent=parent, + location=location, + rotation_deg=rotation_deg, + bevel=bevel, + ) + + +def make_lathe_part( + name: str, + profile: Sequence[Sequence[float]], + segments: int = 16, + loop: bool = False, + smooth: bool = True, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + shape_dict = { + "shape": "lathe", + "segments": int(segments), + "loop": bool(loop), + "smooth": bool(smooth), + "profile": [[float(p[0]), float(p[1])] for p in profile], + } + return make_mesh_from_swept( + name, + _build_inline_shape(name, shape_dict), + mat_name, + parent=parent, + location=location, + rotation_deg=rotation_deg, + bevel=bevel, + ) + + +def make_kit_part( + name: str, + kit_name: str, + part_name: str, + params: dict[str, Any] | None = None, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + kit = load_kit(kit_name) + part_def = core.part(kit, part_name) + built = core.build(part_def, params or {}) + return make_mesh_from_swept( + name=name, + swept=built, + mat_name=mat_name, + parent=parent, + location=location, + rotation_deg=rotation_deg, + bevel=bevel, + ) + + +def _auto_ups(path: np.ndarray, closed: bool = False) -> np.ndarray: + """Compute smooth non-collinear up vectors along any 3D polyline for core.sweep.""" + n = len(path) + steps = (np.roll(path, -1, axis=0) - path)[: n if closed else n - 1] + lengths = np.linalg.norm(steps, axis=1, keepdims=True) + tangents = steps / np.maximum(lengths, 1e-9) + if closed: + vert_tan = tangents + np.roll(tangents, 1, axis=0) + else: + vert_tan = np.vstack([tangents[:1], tangents[:-1] + tangents[1:], tangents[-1:]]) + vert_tan /= np.maximum(np.linalg.norm(vert_tan, axis=1, keepdims=True), 1e-9) + ups = np.zeros_like(vert_tan) + ref = np.array([0.0, 0.0, 1.0]) if abs(vert_tan[0, 2]) < 0.85 else np.array([1.0, 0.0, 0.0]) + u0 = ref - vert_tan[0] * float(ref @ vert_tan[0]) + ups[0] = u0 / np.linalg.norm(u0) + for i in range(1, n): + u = ups[i - 1] - vert_tan[i] * float(ups[i - 1] @ vert_tan[i]) + norm = float(np.linalg.norm(u)) + if norm < 1e-5: + alt = np.array([1.0, 0.0, 0.0]) if abs(vert_tan[i, 0]) < 0.85 else np.array([0.0, 1.0, 0.0]) + u = alt - vert_tan[i] * float(alt @ vert_tan[i]) + norm = float(np.linalg.norm(u)) + ups[i] = u / norm + return ups + + +def fillet_polyline(points: Sequence[Sequence[float]], radius: float = 0.05, subdivs: int = 2, closed: bool = False) -> np.ndarray: + """Round interior corners of a 3D polyline so core.sweep stays well below TURN_LIMIT.""" + pts = np.asarray(points, dtype=np.float64) + if len(pts) < 3 or radius <= 0.0: + return pts + out: list[np.ndarray] = [] + n = len(pts) + indices = range(n) if closed else range(1, n - 1) + if not closed: + out.append(pts[0]) + for i in indices: + p_prev = pts[(i - 1) % n] + p_curr = pts[i] + p_next = pts[(i + 1) % n] + v_in = p_curr - p_prev + v_out = p_next - p_curr + l_in = float(np.linalg.norm(v_in)) + l_out = float(np.linalg.norm(v_out)) + if l_in < 1e-6 or l_out < 1e-6: + out.append(p_curr) + continue + d_in = v_in / l_in + d_out = v_out / l_out + if float(d_in @ d_out) > 0.995: + out.append(p_curr) + continue + trim = min(radius, 0.35 * l_in, 0.35 * l_out) + a = p_curr - d_in * trim + b = p_curr + d_out * trim + for k in range(subdivs + 1): + t = k / subdivs + # Quadratic Bezier corner blend + pt = (1 - t) ** 2 * a + 2 * (1 - t) * t * p_curr + t ** 2 * b + out.append(pt) + if not closed: + out.append(pts[-1]) + return np.array(out, dtype=np.float64) + + +def make_swept_tube( + name: str, + points: Sequence[Sequence[float]], + radius: float, + segments: int = 8, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + closed: bool = False, + fillet_r: float = 0.04, +) -> bpy.types.Object: + path = fillet_polyline(points, radius=fillet_r, subdivs=2, closed=closed) if fillet_r > 0 else np.asarray(points, dtype=np.float64) + ups = _auto_ups(path, closed=closed) + swept = core.sweep(path, core.circle(radius, segments), ups, closed=closed) + return make_mesh_from_swept(name, swept, mat_name, parent=parent, location=location, rotation_deg=rotation_deg) + + +def make_swept_profile( + name: str, + section: str, + w: float, + h: float, + t: float, + points: Sequence[Sequence[float]], + up: Sequence[float] | None = None, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + closed: bool = False, +) -> bpy.types.Object: + path = np.asarray(points, dtype=np.float64) + ups = np.asarray(up, dtype=np.float64) if up is not None else _auto_ups(path, closed=closed) + swept = core.sweep(path, core.profile(section, w, h, t), ups, closed=closed) + return make_mesh_from_swept(name, swept, mat_name, parent=parent, location=location, rotation_deg=rotation_deg) + + +def make_box( + name: str, + size: Sequence[float], + mat_name: str = "olive_armor", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.008, +) -> bpy.types.Object: + sx, sy, sz = (float(v) for v in size) + V = core.BOX_SIGNS * np.array([sx, sy, sz], dtype=np.float64) + swept = core.Swept( + V=V, + faces=core.BOX_FACES.ravel().astype(np.int32), + counts=np.full(6, 4, dtype=np.int32), + smooth=np.zeros(6, dtype=bool), + sharp=core.NO_SHARP.astype(np.int32), + ) + return make_mesh_from_swept(name, swept, mat_name, parent=parent, location=location, rotation_deg=rotation_deg, bevel=bevel) + + +def make_bmesh_object( + name: str, + builder: Callable[[bmesh.types.BMesh], None], + mat_name: str = "olive_armor", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, + smooth: bool = False, +) -> bpy.types.Object: + bm = bmesh.new() + builder(bm) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + mesh = bpy.data.meshes.new(name) + bm.to_mesh(mesh) + bm.free() + if smooth: + for poly in mesh.polygons: + poly.use_smooth = True + obj = bpy.data.objects.new(name, mesh) + _assign_material(obj, mat_name) + _link_object(obj, parent=parent, location=location, rotation_deg=rotation_deg) + if bevel > 0.0: + _add_bevel(obj, bevel, segments=1) + return obj + + +def _write_vf_mesh(name: str, V: np.ndarray, faces: list[list[int]], mat_name: str, parent: bpy.types.Object | None = None, bevel: float = 0.0) -> bpy.types.Object: + mesh = bpy.data.meshes.new(name) + mesh.from_pydata(np.asarray(V, dtype=np.float64).tolist(), [], [[int(k) for k in f] for f in faces]) + sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE") + sharp.data.foreach_set("value", np.ones(len(mesh.polygons), dtype=bool)) + mesh.update() + obj = bpy.data.objects.new(name, mesh) + _assign_material(obj, mat_name) + _link_object(obj, parent=parent) + if bevel > 0.0: + _add_bevel(obj, bevel, segments=1, angle_deg=15.0) + return obj + + +def make_plates( + table_doc: dict[str, Any], + parent: bpy.types.Object | None = None, + prefix: str = "", + side: int = 1, +) -> list[bpy.types.Object]: + """Build Brokkr hard armour plates (brokkr.plates.v0) directly into Blender objects.""" + checked = plate.check(table_doc) + entries = plate.build(checked, side=side) + created: list[bpy.types.Object] = [] + for entry in entries: + row = checked["plates"][entry["row"]] + pname = f"{prefix}{entry['name']}" + solid_obj = _write_vf_mesh(pname, entry["solid"][0], entry["solid"][1], row["mat"], parent=parent, bevel=row["bevel"]) + created.append(solid_obj) + clad = row["clad"] + if clad: + if len(entry["panels"][1]): + p_obj = _write_vf_mesh(f"{pname}.panels", entry["panels"][0], entry["panels"][1], clad["mat"], parent=solid_obj, bevel=clad["bevel"]) + created.append(p_obj) + if len(entry["bolts"][1]): + b_obj = _write_vf_mesh(f"{pname}.bolts", entry["bolts"][0], entry["bolts"][1], clad["bolt_mat"], parent=solid_obj, bevel=0.0) + created.append(b_obj) + for fit_mat, fit_mesh in entry["fits"].items(): + if len(fit_mesh[1]): + f_obj = _write_vf_mesh(f"{pname}.fit.{fit_mat}", fit_mesh[0], fit_mesh[1], fit_mat, parent=solid_obj, bevel=0.0) + created.append(f_obj) + return created + + +def make_knobby_wheel( + name: str, + radius: float, + width: float, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + tread_lugs: int = 18, + rim_segments: int = 20, + side_sign: int = 1, +) -> bpy.types.Object: + """Build a crisp game-ready off-road wheel centered at (0,0,0) spinning about local X. + + side_sign = +1 for left (+X) wheel (hub faces +X), -1 for right (-X) wheel (hub faces -X). + """ + hub_pivot = make_empty(f"{name}_hub", parent=parent, location=location) + # Tire carcass via lathe rotated onto X axis (tube/lathe builds along +Z, so rot_y = 90) + r_rim = radius * 0.56 + r_side = radius * 0.92 + hw = width * 0.5 + tire_profile = [ + [r_rim * 0.96, -hw * 0.85], + [r_side, -hw * 0.95], + [radius * 0.96, -hw * 0.72], + [radius * 0.96, hw * 0.72], + [r_side, hw * 0.95], + [r_rim * 0.96, hw * 0.85], + ] + make_lathe_part( + f"{name}_tire", + tire_profile, + segments=rim_segments, + loop=True, + smooth=True, + mat_name="rubber_dark", + parent=hub_pivot, + rotation_deg=(0.0, 90.0, 0.0), + ) + + # Staggered knobby tread lugs around circumference (compact, low poly, high visual read) + def build_tread(bm: bmesh.types.BMesh) -> None: + lug_w = width * 0.38 + lug_h = radius * 0.055 + lug_len = (2.0 * math.pi * radius / tread_lugs) * 0.52 + for i in range(tread_lugs): + ang = 2.0 * math.pi * i / tread_lugs + for row_s in (-1.0, 1.0): + a = ang + (0.5 if row_s > 0 else 0.0) * (2.0 * math.pi / tread_lugs) + cy = math.cos(a) * (radius * 0.965) + cz = math.sin(a) * (radius * 0.965) + cx = row_s * hw * 0.42 + mat = ( + Matrix.Translation((cx, cy, cz)) + @ Matrix.Rotation(a, 4, "X") + @ Matrix.Scale(lug_w, 4, (1, 0, 0)) + @ Matrix.Scale(lug_h, 4, (0, 1, 0)) + @ Matrix.Scale(lug_len, 4, (0, 0, 1)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=mat) + + make_bmesh_object(f"{name}_treads", build_tread, "rubber_dark", parent=hub_pivot) + + # Steel wheel dish rim + hub cap (CCW in (r, z); +Z points outward via rot_y = 90 * side_sign) + rim_profile = [ + [0.0, -hw * 0.45], + [r_rim * 0.98, -hw * 0.45], + [r_rim * 0.98, hw * 0.86], + [r_rim * 0.82, hw * 0.86], + [r_rim * 0.72, hw * 0.48], + [r_rim * 0.30, hw * 0.48], + [r_rim * 0.25, hw * 0.82], + [0.0, hw * 0.82], + ] + make_lathe_part( + f"{name}_rim", + rim_profile, + segments=16, + loop=False, + smooth=True, + mat_name="gunmetal", + parent=hub_pivot, + rotation_deg=(0.0, 90.0 * side_sign, 0.0), + ) + + # Hub lug ring + def build_lugs(bm: bmesh.types.BMesh) -> None: + hx = side_sign * hw * 0.62 + for i in range(6): + a = 2.0 * math.pi * i / 6.0 + r_b = r_rim * 0.50 + m = Matrix.Translation((hx, math.cos(a) * r_b, math.sin(a) * r_b)) @ Matrix.Rotation(math.pi * 0.5, 4, "Y") + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=6, radius1=radius * 0.042, radius2=radius * 0.042, depth=width * 0.14, matrix=m) + + make_bmesh_object(f"{name}_hubbolts", build_lugs, "signal_orange", parent=hub_pivot) + return hub_pivot + + +def make_ram_span( + name: str, + p_base: Sequence[float], + p_tip: Sequence[float], + body_r: float = 0.036, + rod_r: float = 0.020, + parent: bpy.types.Object | None = None, + mat_barrel: str = "gunmetal", + mat_rod: str = "copper_rad", + coil_rings: int = 0, +) -> bpy.types.Object: + """Create a realistic hydraulic actuator or coilover strut spanning p_base -> p_tip.""" + a = np.asarray(p_base, dtype=np.float64) + b = np.asarray(p_tip, dtype=np.float64) + vec = b - a + total = float(np.linalg.norm(vec)) + if total < 1e-4: + raise ValueError(f"Ram {name} has zero span") + z_dir = Vector((vec / total).tolist()) + quat = Vector((0.0, 0.0, 1.0)).rotation_difference(z_dir) + rot_deg = tuple(math.degrees(v) for v in quat.to_euler("XYZ")) + root = make_empty(name, parent=parent, location=a.tolist(), rotation_deg=rot_deg) + + body_len = max(0.05, total * 0.54) + rod_len = max(0.05, total * 0.56) + if 0.05 <= body_r <= 0.12 and 0.2 <= body_len <= 1.0 and 0.2 <= rod_len <= 2.0 and 0.01 <= rod_r <= 0.02: + make_kit_part( + f"{name}_barrel", + "mechanical", + "ram_barrel", + {"body_r": body_r, "body_len": body_len, "rod_r": rod_r, "segments": 10}, + mat_name=mat_barrel, + parent=root, + ) + make_kit_part( + f"{name}_rod", + "mechanical", + "ram_rod", + {"body_r": body_r, "rod_r": rod_r, "length": rod_len, "segments": 10}, + mat_name=mat_rod, + parent=root, + location=(0.0, 0.0, total), + rotation_deg=(180.0, 0.0, 0.0), + ) + else: + make_tube_part(f"{name}_barrel", body_r, body_r, body_len, segments=10, mat_name=mat_barrel, parent=root) + make_tube_part( + f"{name}_rod", + rod_r, + rod_r, + rod_len, + segments=8, + mat_name=mat_rod, + parent=root, + location=(0.0, 0.0, total - rod_len), + ) + if coil_rings > 0: + def build_coils(bm: bmesh.types.BMesh) -> None: + z0 = total * 0.16 + z1 = total * 0.78 + for k in range(coil_rings): + z = z0 + (z1 - z0) * (k / max(1, coil_rings - 1)) + # Octagonal spring ring + pts = [] + rc = body_r * 1.48 + for s in range(10): + ang = 2.0 * math.pi * s / 10.0 + pts.append((rc * math.cos(ang), rc * math.sin(ang), z)) + # Build small torus-like faceted collar ring + for s in range(10): + p0 = Vector(pts[s]) + p1 = Vector(pts[(s + 1) % 10]) + mid = (p0 + p1) * 0.5 + seg_dir = (p1 - p0).normalized() + q_seg = Vector((0, 0, 1)).rotation_difference(seg_dir) + m = Matrix.Translation(mid) @ q_seg.to_matrix().to_4x4() + bmesh.ops.create_cone( + bm, cap_ends=True, cap_tris=False, segments=6, + radius1=body_r * 0.24, radius2=body_r * 0.24, + depth=(p1 - p0).length * 1.08, matrix=m, + ) + + make_bmesh_object(f"{name}_coil", build_coils, "signal_orange", parent=root) + return root + + +def add_hardpoint_slot( + hp_id: str, + kind: str, + parent: bpy.types.Object, + location: Sequence[float], + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + size: Sequence[float] = (0.55, 0.55, 0.12), + plinth_depth: float = 0.0, +) -> bpy.types.Object: + """Create standardized VISIBLE exterior hardpoint socket geometry + tagged rtd.id anchor Empty. + + The anchor Empty is named `hp_id`, carries custom properties `rtd.id` and `rtd.kind`, + and sits at the mounting plane origin with local +Z normal (+Y in glTF) pointing outward. + When `plinth_depth > 0`, a solid recessed base flange extends down to `z = -plinth_depth` + so sloped/curved armor corners physically intersect the hull with zero air gap. + """ + if kind not in ("weapon", "radiator", "engine", "armor"): + raise ValueError(f"Unsupported hardpoint kind {kind!r}") + + sx, sy, sz = (float(v) for v in size) + p_depth = max(0.0, float(plinth_depth)) + # Visual frame parented alongside the anchor + bay_root = make_empty(f"slot_frame.{hp_id}", parent=parent, location=location, rotation_deg=rotation_deg) + + if kind == "weapon": + r_outer = min(sx, sy) * 0.48 + r_inner = r_outer * 0.72 + collar_h = max(0.055, sz * 0.65) + if p_depth > 0.0: + make_tube_part( + f"{hp_id}.plinth", + r_outer * 0.96, + r_outer * 0.96, + p_depth + 0.025, + segments=12, + smooth=False, + mat_name="gunmetal", + parent=bay_root, + location=(0.0, 0.0, -p_depth), + ) + # Octagonal bolted collar ring via Brokkr lathe + collar_prof = [ + [r_inner, 0.0], + [r_outer, 0.0], + [r_outer, collar_h * 0.65], + [r_outer * 0.92, collar_h], + [r_inner * 1.04, collar_h], + [r_inner, collar_h * 0.35], + ] + make_lathe_part( + f"{hp_id}.collar", + collar_prof, + segments=12, + loop=True, + smooth=False, + mat_name="gunmetal", + parent=bay_root, + ) + # Recessed dark weapon socket floor + make_box(f"{hp_id}.well", (r_inner * 1.65, r_inner * 1.65, 0.024), "socket_bay", parent=bay_root, location=(0.0, 0.0, 0.012), bevel=0.0) + # Twin mounting rails + 4 signal-orange lock lugs + 8 perimeter bolts + rail_sep = r_inner * 0.52 + for side in (-1.0, 1.0): + make_box( + f"{hp_id}.rail_{'l' if side > 0 else 'r'}", + (0.04, r_inner * 1.45, collar_h * 0.72), + "gunmetal", + parent=bay_root, + location=(side * rail_sep, 0.0, collar_h * 0.38), + bevel=0.004, + ) + def build_lugs_and_bolts(bm: bmesh.types.BMesh) -> None: + for ang_deg in (45.0, 135.0, 225.0, 315.0): + a = math.radians(ang_deg) + rl = r_outer * 0.88 + m = Matrix.Translation((rl * math.cos(a), rl * math.sin(a), collar_h * 0.96)) @ Matrix.Rotation(a, 4, "Z") + bmesh.ops.create_cube(bm, size=1.0, matrix=m @ Matrix.Diagonal((0.065, 0.042, 0.032, 1.0))) + + make_bmesh_object(f"{hp_id}.lugs", build_lugs_and_bolts, "signal_orange", parent=bay_root) + + def build_bolts(bm: bmesh.types.BMesh) -> None: + for k in range(8): + a = 2.0 * math.pi * k / 8.0 + rb = r_outer * 0.84 + m = Matrix.Translation((rb * math.cos(a), rb * math.sin(a), collar_h * 0.85)) + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=6, radius1=0.016, radius2=0.014, depth=0.02, matrix=m) + + make_bmesh_object(f"{hp_id}.bolts", build_bolts, "gunmetal", parent=bay_root) + anchor_z = collar_h * 0.82 + + elif kind == "radiator": + frame_t = max(0.035, min(sx, sy) * 0.09) + depth = max(0.07, sz) + if p_depth > 0.0: + make_box( + f"{hp_id}.plinth", + (sx * 0.98, sy * 0.98, p_depth + 0.025), + "gunmetal", + parent=bay_root, + location=(0.0, 0.0, (-p_depth + 0.025) * 0.5), + bevel=0.0, + ) + # Recessed dark bay floor + make_box(f"{hp_id}.well", (sx * 0.92, sy * 0.92, depth * 0.4), "socket_bay", parent=bay_root, location=(0.0, 0.0, depth * 0.2), bevel=0.0) + # Outer armored louver frame (4 bars) + make_box(f"{hp_id}.frame_top", (sx, frame_t, depth), "gunmetal", parent=bay_root, location=(0.0, sy * 0.5 - frame_t * 0.5, depth * 0.5), bevel=0.005) + make_box(f"{hp_id}.frame_bot", (sx, frame_t, depth), "gunmetal", parent=bay_root, location=(0.0, -sy * 0.5 + frame_t * 0.5, depth * 0.5), bevel=0.005) + make_box(f"{hp_id}.frame_l", (frame_t, sy - frame_t * 2, depth), "gunmetal", parent=bay_root, location=(sx * 0.5 - frame_t * 0.5, 0.0, depth * 0.5), bevel=0.005) + make_box(f"{hp_id}.frame_r", (frame_t, sy - frame_t * 2, depth), "gunmetal", parent=bay_root, location=(-sx * 0.5 + frame_t * 0.5, 0.0, depth * 0.5), bevel=0.005) + # Copper radiator core louvers inside the bay + n_fins = max(5, min(11, int(sy / 0.065))) + def build_louvers(bm: bmesh.types.BMesh) -> None: + inner_w = sx - frame_t * 2.2 + inner_h = sy - frame_t * 2.2 + for i in range(n_fins): + y = -inner_h * 0.44 + inner_h * 0.88 * (i / max(1, n_fins - 1)) + m = ( + Matrix.Translation((0.0, y, depth * 0.58)) + @ Matrix.Rotation(math.radians(24.0), 4, "X") + @ Matrix.Diagonal((inner_w, 0.018, depth * 0.42, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + + make_bmesh_object(f"{hp_id}.louvers", build_louvers, "copper_rad", parent=bay_root) + # Corner flange bolts + signal-orange lock tabs + def build_tabs(bm: bmesh.types.BMesh) -> None: + for xs in (-1.0, 1.0): + for ys in (-1.0, 1.0): + m = Matrix.Translation((xs * (sx * 0.42), ys * (sy * 0.42), depth * 1.02)) + bmesh.ops.create_cube(bm, size=1.0, matrix=m @ Matrix.Diagonal((0.045, 0.045, 0.022, 1.0))) + + make_bmesh_object(f"{hp_id}.locktabs", build_tabs, "signal_orange", parent=bay_root) + anchor_z = depth * 0.55 + + elif kind == "engine": + wall_t = max(0.045, min(sx, sy) * 0.10) + depth = max(0.11, sz) + if p_depth > 0.0: + make_box( + f"{hp_id}.plinth", + (sx * 0.98, sy * 0.98, p_depth + 0.025), + "gunmetal", + parent=bay_root, + location=(0.0, 0.0, (-p_depth + 0.025) * 0.5), + bevel=0.0, + ) + # Deep dark engine bay recess + make_box(f"{hp_id}.well", (sx * 0.90, sy * 0.90, depth * 0.35), "socket_bay", parent=bay_root, location=(0.0, 0.0, depth * 0.18), bevel=0.0) + # Armored coaming rails + for xs in (-1.0, 1.0): + make_box(f"{hp_id}.coam_{'l' if xs > 0 else 'r'}", (wall_t, sy, depth), "gunmetal", parent=bay_root, location=(xs * (sx * 0.5 - wall_t * 0.5), 0.0, depth * 0.5), bevel=0.006) + for ys in (-1.0, 1.0): + make_box(f"{hp_id}.coam_{'b' if ys > 0 else 'f'}", (sx - wall_t * 2, wall_t, depth * 0.85), "gunmetal", parent=bay_root, location=(0.0, ys * (sy * 0.5 - wall_t * 0.5), depth * 0.42), bevel=0.006) + # Twin internal engine mount cradle rails + exhaust manifold stubs + for xs in (-1.0, 1.0): + make_box(f"{hp_id}.cradle_{'l' if xs > 0 else 'r'}", (0.05, sy * 0.72, depth * 0.45), "gunmetal", parent=bay_root, location=(xs * sx * 0.22, 0.0, depth * 0.45), bevel=0.004) + make_swept_tube( + f"{hp_id}.manifold_{'l' if xs > 0 else 'r'}", + [ + [xs * sx * 0.16, -sy * 0.26, depth * 0.55], + [xs * sx * 0.30, -sy * 0.12, depth * 0.74], + [xs * sx * 0.30, sy * 0.20, depth * 0.74], + ], + 0.022, + segments=8, + mat_name="copper_rad", + parent=bay_root, + fillet_r=0.03, + ) + # Signal-orange lock pins at corners + def build_pins(bm: bmesh.types.BMesh) -> None: + for xs in (-1.0, 1.0): + for ys in (-1.0, 1.0): + m = Matrix.Translation((xs * (sx * 0.40), ys * (sy * 0.40), depth * 1.02)) + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=8, radius1=0.022, radius2=0.018, depth=0.036, matrix=m) + + make_bmesh_object(f"{hp_id}.lockpins", build_pins, "signal_orange", parent=bay_root) + anchor_z = depth * 0.45 + + else: # "armor" + rail_h = max(0.05, sz) + if p_depth > 0.0: + make_box( + f"{hp_id}.plinth", + (sx * 0.90, sy * 0.44, p_depth + 0.025), + "gunmetal", + parent=bay_root, + location=(0.0, 0.0, (-p_depth + 0.025) * 0.5), + bevel=0.0, + ) + # Backing plate & stud rails across the glacis / flank + make_box(f"{hp_id}.rail", (sx * 0.92, sy * 0.32, rail_h * 0.55), "gunmetal", parent=bay_root, location=(0.0, 0.0, rail_h * 0.28), bevel=0.006) + n_boss = max(3, min(5, int(sx / 0.32) + 1)) + def build_bosses(bm: bmesh.types.BMesh) -> None: + for i in range(n_boss): + x = -sx * 0.38 + sx * 0.76 * (i / max(1, n_boss - 1)) + m = Matrix.Translation((x, 0.0, rail_h * 0.65)) + bmesh.ops.create_cube(bm, size=1.0, matrix=m @ Matrix.Diagonal((0.09, sy * 0.48, rail_h * 0.45, 1.0))) + + make_bmesh_object(f"{hp_id}.bosses", build_bosses, "gunmetal", parent=bay_root) + + def build_studs(bm: bmesh.types.BMesh) -> None: + for i in range(n_boss): + x = -sx * 0.38 + sx * 0.76 * (i / max(1, n_boss - 1)) + m = Matrix.Translation((x, 0.0, rail_h * 0.98)) + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=8, radius1=0.024, radius2=0.018, depth=0.038, matrix=m) + + make_bmesh_object(f"{hp_id}.studs", build_studs, "signal_orange", parent=bay_root) + anchor_z = rail_h * 0.75 + + # Authoritative glTF Empty anchor + anchor = make_empty( + hp_id, + parent=bay_root, + location=(0.0, 0.0, anchor_z), + rotation_deg=(0.0, 0.0, 0.0), + display_type="ARROWS", + display_size=0.18, + ) + anchor["rtd.id"] = hp_id + anchor["rtd.kind"] = kind + anchor["rtd.size"] = [float(sx), float(sy), float(sz)] + return anchor + + +def tag_joint( + node: bpy.types.Object, + joint_id: str, + axis_gltf: Sequence[float], + min_val: float, + max_val: float, +) -> bpy.types.Object: + """Tag a pivot/mechanism node with rtd.joint metadata exported in glTF extras.""" + node["rtd.joint"] = joint_id + node["rtd.axis"] = [float(axis_gltf[0]), float(axis_gltf[1]), float(axis_gltf[2])] + node["rtd.min"] = float(min_val) + node["rtd.max"] = float(max_val) + return node + + +def scene_triangle_count(context: bpy.types.Context | None = None) -> int: + ctx = context or bpy.context + depsgraph = ctx.evaluated_depsgraph_get() + total = 0 + for obj in ctx.scene.objects: + if obj.type != "MESH" or obj.name.startswith("_preview_"): + continue + ev = obj.evaluated_get(depsgraph) + me = ev.to_mesh() + me.calc_loop_triangles() + total += len(me.loop_triangles) + ev.to_mesh_clear() + return total + + +def scene_bounds_blender(context: bpy.types.Context | None = None) -> tuple[Vector, Vector]: + ctx = context or bpy.context + depsgraph = ctx.evaluated_depsgraph_get() + mins = [math.inf, math.inf, math.inf] + maxs = [-math.inf, -math.inf, -math.inf] + for obj in ctx.scene.objects: + if obj.type != "MESH" or obj.name.startswith("_preview_"): + continue + ev = obj.evaluated_get(depsgraph) + me = ev.to_mesh() + mw = obj.matrix_world + for v in me.vertices: + w = mw @ v.co + for i in range(3): + mins[i] = min(mins[i], w[i]) + maxs[i] = max(maxs[i], w[i]) + ev.to_mesh_clear() + return Vector(mins), Vector(maxs) + + +def ground_root_to_z0(root: bpy.types.Object) -> float: + """Shift root along Z so the lowest evaluated mesh vertex sits at Z = 0.""" + bpy.context.view_layer.update() + b_min, _ = scene_bounds_blender() + if math.isfinite(b_min.z) and abs(b_min.z) > 1e-5: + root.location.z -= b_min.z + bpy.context.view_layer.update() + return -b_min.z + return 0.0 + + +def bounds_gltf_from_blender(b_min: Vector, b_max: Vector) -> dict[str, list[float]]: + """Convert Blender Z-up bounds to glTF Y-up bounds: (x, y, z)_gltf = (x, z, -y)_blender.""" + g_min = [round(b_min.x, 4), round(b_min.z, 4), round(-b_max.y, 4)] + g_max = [round(b_max.x, 4), round(b_max.z, 4), round(-b_min.y, 4)] + size = [round(g_max[i] - g_min[i], 4) for i in range(3)] + return {"min": g_min, "max": g_max, "size": size} + + +def export_vehicle_glb(glb_path: Path, root: bpy.types.Object | None = None) -> tuple[int, dict[str, list[float]]]: + """Ground scene (if root given), measure evaluated tris & glTF bounds, and export .glb.""" + if root is not None: + ground_root_to_z0(root) + bpy.context.view_layer.update() + tri_count = scene_triangle_count() + b_min, b_max = scene_bounds_blender() + bounds_gltf = bounds_gltf_from_blender(b_min, b_max) + + glb_path.parent.mkdir(parents=True, exist_ok=True) + # Hide any preview helper objects if present + bpy.ops.export_scene.gltf( + filepath=str(glb_path), + export_format="GLB", + export_yup=True, + export_extras=True, + export_apply=True, + export_materials="EXPORT", + export_normals=True, + export_texcoords=True, + use_visible=True, + ) + return tri_count, bounds_gltf + + +def write_manifest( + manifest_path: Path, + *, + vehicle_id: str, + name: str, + vehicle_class: str, + grid_width: int, + grid_height: int, + mask: Sequence[str] | Sequence[bool], + hardpoints: list[dict[str, Any]], + joints: list[dict[str, Any]], + bounds: dict[str, list[float]], + tri_count: int, + plane: str = "Dorsal", + mechanisms: dict[str, Any] | None = None, +) -> None: + if len(mask) == grid_height and isinstance(mask[0], str): + mask_bools = [ch == "#" for row in mask for ch in row] + else: + mask_bools = [bool(v) for v in mask] + doc = { + "schema": "rtd.vehicle.manifest.v1", + "id": vehicle_id, + "name": name, + "class": vehicle_class, + "plane": plane, + "gridWidth": grid_width, + "gridHeight": grid_height, + "mask": mask_bools, + "hardpoints": hardpoints, + "joints": joints, + "bounds": bounds, + "triCount": int(tri_count), + } + if mechanisms is not None: + doc["mechanisms"] = mechanisms + manifest_path.parent.mkdir(parents=True, exist_ok=True) + manifest_path.write_text(json.dumps(doc, indent=2) + "\n", encoding="utf-8") + + +def _aim_camera_at(cam_obj: bpy.types.Object, eye: Vector, target: Vector) -> None: + cam_obj.location = eye + direction = (target - eye).normalized() + cam_obj.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler() + + +def render_four_panel_preview(preview_path: Path, panel_w: int = 640, panel_h: int = 480) -> Path: + """Render 3/4 Hero, Front (-Y), Side (+X), and Top Dorsal (+Z) views via EEVEE into one 2x2 PNG.""" + scene = bpy.context.scene + bpy.context.view_layer.update() + b_min, b_max = scene_bounds_blender() + center = (b_min + b_max) * 0.5 + extent = max((b_max - b_min).length, 1.5) + + # Setup world + studio lighting + ground plinth + world = bpy.data.worlds.new("_preview_world") + scene.world = world + world.use_nodes = True + bg = world.node_tree.nodes.get("Background") + if bg: + bg.inputs["Color"].default_value = (0.045, 0.050, 0.048, 1.0) + bg.inputs["Strength"].default_value = 1.1 + + # Ground disc (dark slate) + floor_mat = bpy.data.materials.new("_preview_floor_mat") + floor_mat.use_nodes = True + f_bsdf = floor_mat.node_tree.nodes.get("Principled BSDF") + if f_bsdf: + f_bsdf.inputs["Base Color"].default_value = (0.08, 0.085, 0.082, 1.0) + f_bsdf.inputs["Roughness"].default_value = 0.88 + bpy.ops.mesh.primitive_cylinder_add(vertices=48, radius=extent * 1.4, depth=0.04, location=(center.x, center.y, b_min.z - 0.021)) + floor_obj = bpy.context.active_object + floor_obj.name = "_preview_floor" + floor_obj.data.materials.append(floor_mat) + + def add_sun(name: str, rot_deg: Sequence[float], energy: float, color: Sequence[float]) -> bpy.types.Object: + ldata = bpy.data.lights.new(name, type="SUN") + ldata.energy = energy + ldata.color = color + lobj = bpy.data.objects.new(name, ldata) + scene.collection.objects.link(lobj) + lobj.rotation_euler = Euler([math.radians(a) for a in rot_deg], "XYZ") + return lobj + + lights = [ + add_sun("_preview_key", (48.0, 12.0, -35.0), 3.4, (1.0, 0.96, 0.90)), + add_sun("_preview_fill", (55.0, -15.0, 135.0), 1.4, (0.78, 0.86, 0.98)), + add_sun("_preview_rim", (25.0, 0.0, 175.0), 1.6, (1.0, 0.90, 0.78)), + ] + + cam_data = bpy.data.cameras.new("_preview_cam") + cam_data.lens = 42.0 + cam_obj = bpy.data.objects.new("_preview_cam", cam_data) + scene.collection.objects.link(cam_obj) + scene.camera = cam_obj + + scene.render.engine = "BLENDER_EEVEE" + scene.render.resolution_x = panel_w + scene.render.resolution_y = panel_h + scene.render.resolution_percentage = 100 + scene.render.image_settings.file_format = "PNG" + scene.render.image_settings.color_mode = "RGBA" + if hasattr(scene, "eevee"): + scene.eevee.taa_render_samples = 16 + + size_vec = b_max - b_min + d_hero = extent * 1.18 + d_ortho = max(size_vec.x, size_vec.y, size_vec.z) * 1.25 + + views = [ + ("hero", "PERSP", center + Vector((d_hero * 0.72, -d_hero * 0.85, d_hero * 0.46)), center), + ("front", "ORTHO", center + Vector((0.0, -d_ortho * 2.0, size_vec.z * 0.04)), center), + ("side", "ORTHO", center + Vector((d_ortho * 2.0, 0.0, size_vec.z * 0.04)), center), + ("top", "ORTHO", center + Vector((0.0, 0.0, d_ortho * 2.0)), center), + ] + + preview_path.parent.mkdir(parents=True, exist_ok=True) + tmp_files: list[Path] = [] + panels: list[np.ndarray] = [] + + for idx, (tag, proj, eye, tgt) in enumerate(views): + cam_data.type = proj + if proj == "ORTHO": + aspect = panel_w / max(1, panel_h) + if tag == "front": + cam_data.ortho_scale = max(size_vec.x * 1.32, size_vec.z * aspect * 1.38) + elif tag == "side": + cam_data.ortho_scale = max(size_vec.y * 1.24, size_vec.z * aspect * 1.35) + else: + cam_data.ortho_scale = max(size_vec.x * 1.30, size_vec.y * aspect * 1.22) + _aim_camera_at(cam_obj, eye, tgt) + # Keep top view upright with nose (-Y) pointing up in image + if tag == "top": + cam_obj.rotation_euler = Euler((0.0, 0.0, math.radians(180.0)), "XYZ") + + tmp_png = preview_path.with_name(f".tmp_{preview_path.stem}_{tag}.png") + tmp_files.append(tmp_png) + scene.render.filepath = str(tmp_png) + bpy.ops.render.render(write_still=True) + + img = bpy.data.images.load(str(tmp_png), check_existing=False) + arr = np.empty(panel_w * panel_h * 4, dtype=np.float32) + img.pixels.foreach_get(arr) + bpy.data.images.remove(img) + panels.append(arr.reshape((panel_h, panel_w, 4))) + + # Stitch 2x2 grid (note Blender image pixel row 0 is bottom): + # Top row in final PNG = [hero (TL), front (TR)] -> higher Y in Blender image space + # Bottom row in final PNG = [side (BL), top (BR)] -> lower Y in Blender image space + top_row = np.concatenate([panels[0], panels[1]], axis=1) + bot_row = np.concatenate([panels[2], panels[3]], axis=1) + # 4px dark divider lines + grid = np.concatenate([bot_row, top_row], axis=0) + grid[:, panel_w - 2 : panel_w + 2, :3] = 0.25 + grid[panel_h - 2 : panel_h + 2, :, :3] = 0.25 + + out_img = bpy.data.images.new("_preview_composite", width=panel_w * 2, height=panel_h * 2, alpha=True) + out_img.pixels.foreach_set(grid.ravel().tolist()) + out_img.filepath_raw = str(preview_path) + out_img.file_format = "PNG" + out_img.save() + bpy.data.images.remove(out_img) + + # Cleanup temp renders and preview objects + for tmp in tmp_files: + if tmp.exists(): + tmp.unlink() + for obj in [floor_obj, cam_obj, *lights]: + bpy.data.objects.remove(obj, do_unlink=True) + bpy.data.materials.remove(floor_mat) + bpy.data.worlds.remove(world) + + return preview_path diff --git a/tools/vehicles/verify_glbs.py b/tools/vehicles/verify_glbs.py new file mode 100644 index 0000000..bc7694d --- /dev/null +++ b/tools/vehicles/verify_glbs.py @@ -0,0 +1,463 @@ +"""Validate all exported vehicle GLBs, manifests, hardpoint anchors, joints, bounds, and gear GLBs.""" +from __future__ import annotations + +import json +import math +import struct +import sys +from pathlib import Path +from typing import Any + +import numpy as np + +REPO_ROOT = Path(__file__).resolve().parents[2] +VEHICLES_DIR = REPO_ROOT / "assets" / "vehicles" +GEAR_DIR = REPO_ROOT / "assets" / "gear" + +EXPECTED_VEHICLES = ( + "jackal", "mule", "ferret", "hornet", "mammoth", "ironclad", "anvil", "condor", + "breaker", "paladin", "raptor", "manticore", "bastion", "spectre", "kestrel", +) +RETROFIT_MECHS = frozenset({"breaker", "paladin", "raptor", "manticore", "bastion", "spectre", "kestrel"}) +EXPECTED_GEAR = ("mg_762", "autocannon", "recoilless", "copper_rad", "gilded_lance", "gold_radiator") + + +def parse_glb(glb_path: Path) -> tuple[dict[str, Any], bytes]: + data = glb_path.read_bytes() + if len(data) < 20: + raise AssertionError(f"{glb_path}: file too small ({len(data)} bytes)") + magic, version, total_len = struct.unpack_from(" dict[str, Any]: + return parse_glb(glb_path)[0] + + +def _node_local_matrix(node: dict[str, Any]) -> np.ndarray: + if "matrix" in node: + return np.array(node["matrix"], dtype=np.float64).reshape(4, 4).T + m = np.eye(4, dtype=np.float64) + if "scale" in node: + sx, sy, sz = node["scale"] + m = m @ np.diag([sx, sy, sz, 1.0]) + if "rotation" in node: + qx, qy, qz, qw = node["rotation"] + xx, yy, zz = qx * qx, qy * qy, qz * qz + xy, xz, yz = qx * qy, qx * qz, qy * qz + wx, wy, wz = qw * qx, qw * qy, qw * qz + r = np.array([ + [1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy), 0.0], + [2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx), 0.0], + [2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy), 0.0], + [0.0, 0.0, 0.0, 1.0], + ], dtype=np.float64) + m = r @ m + if "translation" in node: + tx, ty, tz = node["translation"] + m[:3, 3] = [tx, ty, tz] + return m + + +def compute_glb_stats(gltf: dict[str, Any], bin_blob: bytes = b"") -> tuple[int, np.ndarray, np.ndarray]: + nodes = gltf.get("nodes", []) + meshes = gltf.get("meshes", []) + accessors = gltf.get("accessors", []) + buffer_views = gltf.get("bufferViews", []) + scenes = gltf.get("scenes", []) + root_indices = scenes[gltf.get("scene", 0)]["nodes"] if scenes else list(range(len(nodes))) + + tri_total = 0 + g_min = np.array([math.inf, math.inf, math.inf], dtype=np.float64) + g_max = np.array([-math.inf, -math.inf, -math.inf], dtype=np.float64) + + def walk(node_idx: int, parent_mat: np.ndarray) -> None: + nonlocal tri_total, g_min, g_max + node = nodes[node_idx] + world = parent_mat @ _node_local_matrix(node) + if "mesh" in node: + mesh = meshes[node["mesh"]] + for prim in mesh.get("primitives", []): + mode = prim.get("mode", 4) + if mode == 4: + if "indices" in prim: + tri_total += accessors[prim["indices"]]["count"] // 3 + elif "POSITION" in prim.get("attributes", {}): + tri_total += accessors[prim["attributes"]["POSITION"]]["count"] // 3 + pos_acc_idx = prim.get("attributes", {}).get("POSITION") + if pos_acc_idx is not None: + acc = accessors[pos_acc_idx] + if bin_blob and "bufferView" in acc and acc.get("componentType") == 5126 and acc.get("type") == "VEC3": + bv = buffer_views[acc["bufferView"]] + off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0) + stride = bv.get("byteStride", 12) + count = acc["count"] + if stride == 12: + pts = np.frombuffer(bin_blob, dtype=" np.ndarray: + acc = accessors[acc_idx] + bv = buffer_views[acc["bufferView"]] + off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0) + count = acc["count"] + ct = acc["componentType"] + typ = acc["type"] + if typ == "VEC3" and ct == 5126: + stride = bv.get("byteStride", 12) + if stride == 12: + return np.frombuffer(bin_blob, dtype=" float: + ab = b - a + ac = c - a + ap = p - a + d1 = float(np.dot(ab, ap)) + d2 = float(np.dot(ac, ap)) + if d1 <= 0.0 and d2 <= 0.0: + return float(np.dot(ap, ap)) + bp = p - b + d3 = float(np.dot(ab, bp)) + d4 = float(np.dot(ac, bp)) + if d3 >= 0.0 and d4 <= d3: + return float(np.dot(bp, bp)) + vc = d1 * d4 - d3 * d2 + if vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0: + denom = d1 - d3 + v = d1 / denom if denom > 1e-18 else 0.0 + q = a + v * ab + return float(np.dot(p - q, p - q)) + cp = p - c + d5 = float(np.dot(ab, cp)) + d6 = float(np.dot(ac, cp)) + if d6 >= 0.0 and d5 <= d6: + return float(np.dot(cp, cp)) + vb = d5 * d2 - d1 * d6 + if vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0: + denom = d2 - d6 + w = d2 / denom if denom > 1e-18 else 0.0 + q = a + w * ac + return float(np.dot(p - q, p - q)) + va = d3 * d6 - d5 * d4 + if va <= 0.0 and (d4 - d3) >= 0.0 and (d5 - d6) >= 0.0: + denom = (d4 - d3) + (d5 - d6) + w = (d4 - d3) / denom if denom > 1e-18 else 0.0 + q = b + w * (c - b) + return float(np.dot(p - q, p - q)) + s = va + vb + vc + if s <= 1e-18: + return min(float(np.dot(ap, ap)), float(np.dot(bp, bp)), float(np.dot(cp, cp))) + denom = 1.0 / s + q = a + ab * (vb * denom) + ac * (vc * denom) + return float(np.dot(p - q, p - q)) + + +def _min_dist_to_tris( + pt: np.ndarray, + tris: np.ndarray, + tri_mins: np.ndarray, + tri_maxs: np.ndarray, +) -> float: + d_box = np.maximum(0.0, np.maximum(tri_mins - pt, pt - tri_maxs)) + d2_box = np.sum(d_box * d_box, axis=1) + order = np.argsort(d2_box) + min_d2 = math.inf + for idx in order: + if d2_box[idx] > min_d2: + break + t = tris[idx] + d2 = _pt_tri_dist2(pt, t[0], t[1], t[2]) + if d2 < min_d2: + min_d2 = d2 + return math.sqrt(min_d2) + + +def measure_hardpoint_gaps(gltf: dict[str, Any], bin_blob: bytes) -> dict[str, tuple[float, float]]: + """Return {hp_id: (center_to_hull_m, min_slot_vert_to_hull_m)} for all hardpoints in GLB.""" + nodes = gltf.get("nodes", []) + meshes = gltf.get("meshes", []) + accessors = gltf.get("accessors", []) + buffer_views = gltf.get("bufferViews", []) + scenes = gltf.get("scenes", []) + root_indices = scenes[gltf.get("scene", 0)]["nodes"] if scenes else list(range(len(nodes))) + + parent_of: dict[int, int] = {} + for idx, n in enumerate(nodes): + for c in n.get("children", []): + parent_of[c] = idx + + hp_roots: dict[int, str] = {} + hp_anchors: dict[str, int] = {} + for idx, n in enumerate(nodes): + extras = n.get("extras") or {} + if "rtd.id" in extras: + hp_id = str(extras["rtd.id"]) + hp_anchors[hp_id] = idx + p = parent_of.get(idx) + if p is not None and str(nodes[p].get("name", "")).startswith("slot_frame."): + hp_roots[p] = hp_id + + hp_node_set: dict[int, str] = {} + def mark_hp(idx: int, hp_id: str) -> None: + hp_node_set[idx] = hp_id + for c in nodes[idx].get("children", []): + mark_hp(c, hp_id) + for r_idx, hp_id in hp_roots.items(): + mark_hp(r_idx, hp_id) + + hull_tris: list[np.ndarray] = [] + hp_pts: dict[str, list[np.ndarray]] = {} + node_world: dict[int, np.ndarray] = {} + + def walk(idx: int, pmat: np.ndarray) -> None: + n = nodes[idx] + w = pmat @ _node_local_matrix(n) + node_world[idx] = w + if "mesh" in n: + for prim in meshes[n["mesh"]].get("primitives", []): + if prim.get("mode", 4) != 4: + continue + pos = _read_accessor(accessors, buffer_views, bin_blob, prim["attributes"]["POSITION"]) + wpos = pos @ w[:3, :3].T + w[:3, 3] + if idx in hp_node_set: + hp_pts.setdefault(hp_node_set[idx], []).append(wpos) + else: + if "indices" in prim: + ind = _read_accessor(accessors, buffer_views, bin_blob, prim["indices"]).reshape(-1, 3) + else: + ind = np.arange(len(pos), dtype=np.int64).reshape(-1, 3) + hull_tris.append(wpos[ind]) + for c in n.get("children", []): + walk(c, w) + + ident = np.eye(4, dtype=np.float64) + for r_idx in root_indices: + walk(r_idx, ident) + + if not hull_tris: + return {} + tris = np.concatenate(hull_tris, axis=0) + tri_mins = tris.min(axis=1) + tri_maxs = tris.max(axis=1) + + gaps: dict[str, tuple[float, float]] = {} + for r_idx, hp_id in hp_roots.items(): + p_slot = node_world[r_idx][:3, 3] + p_anchor = node_world[hp_anchors[hp_id]][:3, 3] + out_vec = p_anchor - p_slot + out_len = float(np.linalg.norm(out_vec)) + n_out = out_vec / out_len if out_len > 1e-6 else np.array([0.0, 1.0, 0.0]) + + d_center = _min_dist_to_tris(p_slot, tris, tri_mins, tri_maxs) + pts = np.concatenate(hp_pts.get(hp_id, []), axis=0) if hp_id in hp_pts else np.empty((0, 3)) + if len(pts) > 0: + proj = (pts - p_slot) @ n_out + base_pts = pts[proj <= 0.03] + if len(base_pts) == 0: + base_pts = pts + if len(base_pts) > 256: + base_pts = base_pts[np.linspace(0, len(base_pts) - 1, 256, dtype=int)] + d_vert = min(_min_dist_to_tris(p, tris, tri_mins, tri_maxs) for p in base_pts) + else: + d_vert = d_center + gaps[hp_id] = (d_center, d_vert) + return gaps + + +def validate_vehicle(vid: str) -> dict[str, Any]: + vdir = VEHICLES_DIR / vid + glb_path = vdir / f"{vid}.glb" + manifest_path = vdir / "manifest.json" + if not glb_path.is_file(): + raise AssertionError(f"Missing GLB: {glb_path}") + if not manifest_path.is_file(): + raise AssertionError(f"Missing manifest: {manifest_path}") + + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + gltf, bin_blob = parse_glb(glb_path) + nodes = gltf.get("nodes", []) + + # 1. Check hardpoint grid bounds, mask activity, and zero overlaps + gw, gh = int(manifest["gridWidth"]), int(manifest["gridHeight"]) + mask = manifest["mask"] + if len(mask) != gw * gh: + raise AssertionError(f"{vid}: mask length {len(mask)} != {gw * gh}") + + occupied: dict[tuple[int, int], str] = {} + for hp in manifest["hardpoints"]: + hx, hy, hw, hh = hp["x"], hp["y"], hp["w"], hp["h"] + if not (0 <= hx and hx + hw <= gw and 0 <= hy and hy + hh <= gh): + raise AssertionError(f"{vid}: hardpoint {hp['id']} out of grid bounds ({hx},{hy} {hw}x{hh} on {gw}x{gh})") + for cy in range(hy, hy + hh): + for cx in range(hx, hx + hw): + if not mask[cy * gw + cx]: + raise AssertionError(f"{vid}: hardpoint {hp['id']} covers inactive cell ({cx},{cy})") + if (cx, cy) in occupied: + raise AssertionError(f"{vid}: cell ({cx},{cy}) overlaps between {occupied[(cx, cy)]} and {hp['id']}") + occupied[(cx, cy)] = hp["id"] + + # 2. Check every manifest hardpoint modelNodeId exists as a unique node with extras["rtd.id"] and extras["rtd.kind"] + by_rtd_id: dict[str, list[dict]] = {} + by_rtd_joint: dict[str, list[dict]] = {} + for node in nodes: + extras = node.get("extras") or {} + if "rtd.id" in extras: + by_rtd_id.setdefault(str(extras["rtd.id"]), []).append(node) + if "rtd.joint" in extras: + by_rtd_joint.setdefault(str(extras["rtd.joint"]), []).append(node) + + for hp in manifest["hardpoints"]: + target_id = hp["modelNodeId"] + matches = by_rtd_id.get(target_id, []) + if len(matches) != 1: + raise AssertionError(f"{vid}: hardpoint {target_id!r} matched {len(matches)} GLB nodes (expected 1)") + node = matches[0] + extras = node.get("extras", {}) + if extras.get("rtd.kind") != hp["kind"]: + raise AssertionError(f"{vid}: node {target_id} rtd.kind={extras.get('rtd.kind')!r} != manifest {hp['kind']!r}") + if node.get("name") != target_id: + raise AssertionError(f"{vid}: node name {node.get('name')!r} != {target_id!r}") + + # 3. Check every manifest joint exists with rtd.joint, rtd.axis, rtd.min, rtd.max + for j in manifest["joints"]: + jid = j["id"] + matches = by_rtd_joint.get(jid, []) + if len(matches) != 1: + raise AssertionError(f"{vid}: joint {jid!r} matched {len(matches)} GLB nodes (expected 1)") + extras = matches[0].get("extras", {}) + for key in ("rtd.axis", "rtd.min", "rtd.max"): + if key not in extras: + raise AssertionError(f"{vid}: joint {jid!r} missing {key} in GLB extras") + + plane = manifest.get("plane") + if plane not in ("Dorsal", "Coronal"): + raise AssertionError(f"{vid}: invalid plane {plane!r}") + + # 4. Check GLB triangle count & grounded +Y-up / +Z-forward bounds + tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob) + max_tris = 50000 if vid in RETROFIT_MECHS else 35000 + min_tris = 15000 if vid in RETROFIT_MECHS else 1500 + if not (min_tris <= tri_total <= max_tris): + raise AssertionError(f"{vid}: tri count {tri_total} outside [{min_tris}, {max_tris}]") + if abs(tri_total - manifest["triCount"]) > 0: + raise AssertionError(f"{vid}: GLB tri count {tri_total} != manifest triCount {manifest['triCount']}") + if abs(float(g_min[1])) > 0.02: + raise AssertionError(f"{vid}: GLB not grounded at minY=0 (got minY={g_min[1]:.4f})") + size = g_max - g_min + if vid in RETROFIT_MECHS: + if not (2.5 <= size[0] <= 14.0 and 5.0 <= size[1] <= 12.5 and 2.5 <= size[2] <= 16.0): + raise AssertionError(f"{vid}: implausible mech bounds size {size.tolist()}") + elif not (1.2 <= size[0] <= 5.0 and 1.0 <= size[1] <= 3.5 and 2.5 <= size[2] <= 6.5): + raise AssertionError(f"{vid}: implausible bounds size {size.tolist()}") + + # 5. Flush-seating check: every hardpoint slot center and base vertices must sit <= 0.025m from hull geometry + hp_gaps = measure_hardpoint_gaps(gltf, bin_blob) + if len(hp_gaps) != len(manifest["hardpoints"]): + raise AssertionError(f"{vid}: measured {len(hp_gaps)} hardpoint slots != manifest {len(manifest['hardpoints'])}") + max_gap = 0.0 + for hp in manifest["hardpoints"]: + hid = hp["modelNodeId"] + d_center, d_vert = hp_gaps[hid] + if d_center > 0.025 or d_vert > 0.025: + raise AssertionError( + f"{vid}: floating/buried hardpoint {hid!r} (center_to_hull={d_center:.4f}m, base_to_hull={d_vert:.4f}m > 0.025m)" + ) + max_gap = max(max_gap, d_center, d_vert) + + return { + "id": vid, + "plane": plane, + "tris": tri_total, + "bytes": glb_path.stat().st_size, + "hardpoints": len(manifest["hardpoints"]), + "joints": len(manifest["joints"]), + "mechanisms": len((manifest.get("mechanisms") or {}).get("dofs", [])), + "minY": round(float(g_min[1]), 4), + "maxHpGap": round(max_gap, 4), + "size": [round(float(v), 3) for v in size], + } + + +def validate_gear(gid: str) -> dict[str, Any]: + glb_path = GEAR_DIR / f"{gid}.glb" + if not glb_path.is_file(): + raise AssertionError(f"Missing gear GLB: {glb_path}") + gltf, bin_blob = parse_glb(glb_path) + tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob) + if tri_total <= 0 or tri_total > 10000: + raise AssertionError(f"gear/{gid}: unexpected tri count {tri_total}") + if abs(float(g_min[1])) > 0.02: + raise AssertionError(f"gear/{gid}: not grounded at minY=0 (got {g_min[1]:.4f})") + return { + "id": gid, + "tris": tri_total, + "bytes": glb_path.stat().st_size, + "size": [round(float(v), 3) for v in (g_max - g_min)], + } + + +def main() -> int: + v_reports = [validate_vehicle(v) for v in EXPECTED_VEHICLES] + g_reports = [validate_gear(g) for g in EXPECTED_GEAR] + print("=== VEHICLE GLB VALIDATION PASSED ===") + for r in v_reports: + mech_tag = f" | dofs={r['mechanisms']}" if r["mechanisms"] else "" + print(f" {r['id']:10s} | {r['plane']:7s} | tris={r['tris']:5d} | size={r['size']} | minY={r['minY']} | hpGap={r['maxHpGap']:.4f}m | hps={r['hardpoints']} | joints={r['joints']}{mech_tag} | {r['bytes']/1024:.1f} KiB") + print("=== GEAR GLB VALIDATION PASSED ===") + for r in g_reports: + print(f" {r['id']:14s} | tris={r['tris']:4d} | size={r['size']} | {r['bytes']/1024:.1f} KiB") + return 0 + + +if __name__ == "__main__": + sys.exit(main())