Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
Meta Vens
1039304e5a Add Brokkr-style actuator armor shrouds across retrofitted mechs 2026-12-04 17:39:13 +01:00
Meta Vens
8578bfb8d9 Retrofit Bastion, Spectre, and Kestrel mechs with BVH-snapped hardpoints 2026-12-04 17:12:19 +01:00
Meta Vens
af11d2a2c5 Upgrade Breaker to fable-breaker-3 and snap all hardpoints flush to hull 2026-12-04 16:49:47 +01:00
Meta Vens
916bac2904 Retrofit 4 Brokkr mechs with hardpoints, LOD GLBs, and mechanisms 2026-12-04 16:15:48 +01:00
Meta Vens
19b7e69ff0 Export Wave 2 vehicle GLBs, manifests, and 4-panel previews 2026-12-04 15:47:40 +01:00
Meta Vens
7a46132eba Add Wave 2 vehicle builders (mammoth, ironclad, anvil, condor) and update GLB validator 2026-12-04 15:47:39 +01:00
Meta Vens
5d9aad99e5 Export Wave 1 vehicle GLBs, manifests, previews, and starter gear modules 2026-12-04 15:34:38 +01:00
Meta Vens
bf733f1e71 Add Brokkr vehicle pipeline, Wave 1 builders, gear builder, and GLB validator 2026-12-04 15:34:13 +01:00
Meta Vens
3bd66c3b64 Fix BroadcastFeed chyron freeze past 32 lines and isolate Smoke.cs crater rebake 2026-12-04 14:28:09 +01:00
Meta Vens
3cb60447ff Client HUD/Renderer: fix dead laser visibility, radar orientation, Garage grow direction, chyron churn, and NativeLibraries 2026-12-04 14:16:05 +01:00
Meta Vens
bb68620d1c Client Terrain: fix HeightViewport alpha blending, 1-texel border gutters, road rut axis, and GPU readback smoke 2026-12-04 14:16:05 +01:00
Meta Vens
6507a71c23 Core/Ymir: fix Raptor engine mount, Cleared provocation, cover clearance, road loop, and broadside muzzle 2026-12-04 14:16:05 +01:00
Meta Vens
9c4c68d431 TerrainField: exact footprint check keeps cover pads flat while allowing mid-arena dunes 2026-12-04 14:00:13 +01:00
Meta Vens
de3786feb6 TerrainField: prevent dune/mesa over-stacking and widen traversal test 2026-12-04 13:59:25 +01:00
Meta Vens
215b5ea834 RustToDust Phase 2: Procedural brush terrain, 4-corner Ymir support, and Godot 4.7.2 Mono client 2026-12-04 13:57:44 +01:00
Meta Vens
32b040a59b RustToDust Tests: observe tracer emission across 120 ticks before 90ms decay 2026-12-04 13:48:59 +01:00
Meta Vens
1e6efd7b55 RustToDust Phase 1: Core simulation, Ymir Box3D arena, and behavioral tests 2026-12-04 13:47:43 +01:00
96 changed files with 18321 additions and 18 deletions

4
.gitignore vendored
View file

@ -2,3 +2,7 @@
__pycache__/ __pycache__/
/out/ /out/
/scratch/ /scratch/
bin/
obj/
.godot/
.vs/

6
Directory.Build.props Normal file
View file

@ -0,0 +1,6 @@
<Project>
<PropertyGroup>
<YmirRoot Condition="'$(YmirRoot)' == '' and '$(YMIR_ROOT)' != ''">$(YMIR_ROOT)</YmirRoot>
<YmirRoot Condition="'$(YmirRoot)' == ''">$(MSBuildThisFileDirectory)..\Ymir</YmirRoot>
</PropertyGroup>
</Project>

View file

@ -8,21 +8,54 @@ The lore lives in Weksa: `settings/rust-to-dust/` in
[GameCult/Weksa](https://github.com/GameCult/Weksa) (setting, story, battle [GameCult/Weksa](https://github.com/GameCult/Weksa) (setting, story, battle
royale, aliens, language design). This repo holds no lore. 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 - **`RustToDust.Core`**:
prototyped: - 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 `384m x 384m` desert terrain divided into a
`4x4` (`96m x 96m`) 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) ## Build, test, and run
(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.
That work currently lives on `nibu/fable-*` experiment branches in Requires a sibling `Ymir` checkout beside `RustToDust` (or `YMIR_ROOT` set),
GameCult/Brokkr and moves here as it settles. 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. # Build the Godot 4.7.2 Mono client assembly (also builds Ymir native Box3D)
- Rig generator and goal-space retargeting solver. dotnet build client/RustToDust.Client.csproj -c Debug
- A playable walk-and-fight prototype.
# 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.

9
RustToDust.slnx Normal file
View file

@ -0,0 +1,9 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/RustToDust.Core/RustToDust.Core.csproj" />
<Project Path="src/RustToDust.Ymir/RustToDust.Ymir.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/RustToDust.Tests/RustToDust.Tests.csproj" />
</Folder>
</Solution>

BIN
assets/gear/autocannon.glb Normal file

Binary file not shown.

BIN
assets/gear/copper_rad.glb Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
assets/gear/mg_762.glb Normal file

Binary file not shown.

BIN
assets/gear/recoilless.glb Normal file

Binary file not shown.

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -0,0 +1,943 @@
{
"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.2567,
1.8859
],
"size": [
4.7164,
6.2567,
3.1599
]
},
"triCount": 39196,
"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": [],
"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
}
]
}
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

View file

@ -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
}

Binary file not shown.

772
client/ArenaRenderer.cs Normal file
View file

@ -0,0 +1,772 @@
using System;
using System.Collections.Generic;
using Godot;
using RustToDust.Core;
using RustToDust.Ymir;
namespace RustToDust.Client;
/// <summary>
/// Renders the 3D arena entities from <see cref="ArenaSession"/>:
/// cover ruins, shrinking Safe Circle ring, 6 distinct chassis silhouettes,
/// 3 alien spectator tiers + status halos/lock lasers, salvage drops, and weapon tracers.
/// </summary>
public partial class ArenaRenderer : Node3D
{
private static readonly Color OlivePaint = Color.FromHtml("#9bb06a");
private static readonly Color SignalOrange = Color.FromHtml("#e08a4a");
private static readonly Color RivalSteel = Color.FromHtml("#6a584b");
private static readonly Color RivalAccent = 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("#18181d");
private static readonly Color ExemplarCrimson = Color.FromHtml("#c92a2a");
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 Node3D Root = null!;
public Node3D? AimPivot;
public StandardMaterial3D HeatMat = null!;
public MeshInstance3D? HaloMesh;
public StandardMaterial3D? HaloMat;
public MeshInstance3D? LaserMesh;
public StandardMaterial3D? LaserMat;
public string ChassisId = "";
}
private Node3D _staticGroup = null!;
private Node3D _actorsGroup = null!;
private Node3D _dropsGroup = null!;
private Node3D _tracersGroup = null!;
private MeshInstance3D _safeRingMesh = null!;
private ImmediateMesh _safeRingImm = null!;
private readonly Dictionary<int, ActorVisual> _contenderVisuals = new();
private readonly Dictionary<int, ActorVisual> _spectatorVisuals = new();
private readonly Dictionary<int, Node3D> _dropVisuals = new();
private readonly List<MeshInstance3D> _tracerPool = new();
private StandardMaterial3D _safeRingMat = null!;
private StandardMaterial3D _coverMat = null!;
private StandardMaterial3D _bermMat = null!;
private StandardMaterial3D _humanCrateMat = null!;
private StandardMaterial3D _imperialCrateMat = null!;
private StandardMaterial3D _cyanBeaconMat = null!;
private MatchState? _builtForState;
public override void _Ready()
{
_staticGroup = new Node3D { Name = "StaticArena" };
_actorsGroup = new Node3D { Name = "Actors" };
_dropsGroup = new Node3D { Name = "GroundDrops" };
_tracersGroup = new Node3D { Name = "Tracers" };
AddChild(_staticGroup);
AddChild(_actorsGroup);
AddChild(_dropsGroup);
AddChild(_tracersGroup);
_coverMat = new StandardMaterial3D { AlbedoColor = CoverRust, Roughness = 0.88f, Metallic = 0.25f };
_bermMat = new StandardMaterial3D { AlbedoColor = BermDark, Roughness = 0.94f, Metallic = 0.1f };
_humanCrateMat = new StandardMaterial3D { AlbedoColor = OlivePaint, Roughness = 0.65f, Metallic = 0.3f };
_imperialCrateMat = new StandardMaterial3D
{
AlbedoColor = TouristGold,
Roughness = 0.35f,
Metallic = 0.8f,
EmissionEnabled = true,
Emission = TouristGold,
EmissionEnergyMultiplier = 1.4f
};
_cyanBeaconMat = new StandardMaterial3D
{
AlbedoColor = CyanSalvage,
EmissionEnabled = true,
Emission = CyanSalvage,
EmissionEnergyMultiplier = 1.5f,
Transparency = BaseMaterial3D.TransparencyEnum.Alpha
};
_cyanBeaconMat.AlbedoColor = new Color(CyanSalvage.R, CyanSalvage.G, CyanSalvage.B, 0.72f);
_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 void Sync(ArenaSession session, float elapsedSeconds)
{
var state = session.State;
if (!ReferenceEquals(_builtForState, state))
{
RebuildStaticArena(state);
ClearDynamicVisuals();
_builtForState = state;
}
UpdateSafeCircleRing(state.Terrain, state.Spectators.SafeRadius);
SyncContenders(session);
SyncSpectators(session, elapsedSeconds);
SyncGroundDrops(state, elapsedSeconds);
SyncTracers(state.Tracers);
}
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)
};
_staticGroup.AddChild(mesh);
}
}
private void ClearDynamicVisuals()
{
ClearChildren(_actorsGroup);
ClearChildren(_dropsGroup);
_contenderVisuals.Clear();
_spectatorVisuals.Clear();
_dropVisuals.Clear();
}
private void UpdateSafeCircleRing(TerrainField terrain, float safeRadius)
{
_safeRingImm.ClearSurfaces();
_safeRingImm.SurfaceBegin(Mesh.PrimitiveType.Triangles);
const int segments = 96;
const float halfThick = 0.65f;
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)
{
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))
{
deadVis.Root.Visible = false;
}
continue;
}
if (!_contenderVisuals.TryGetValue(c.Id, out var vis) || vis.ChassisId != c.Grid.Spec.Id)
{
if (vis is not null)
{
vis.Root.QueueFree();
}
vis = BuildChassisVisual(
c.Grid.Spec.Id,
primary: c.IsPlayer ? OlivePaint : RivalSteel,
accent: c.IsPlayer ? SignalOrange : RivalAccent,
isSpectator: false,
tier: SpectatorTier.Patron);
_actorsGroup.AddChild(vis.Root);
_contenderVisuals[c.Id] = vis;
}
vis.Root.Visible = true;
var body = session.GetContenderBody(c.Id);
if (body is { } h)
{
int lane = h.Lane;
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]);
vis.Root.Transform = new Transform3D(new Basis(q), pos);
}
else
{
vis.Root.Position = new Vector3(c.X, c.Y, c.Z);
vis.Root.Rotation = new Vector3(0f, c.Yaw, 0f);
}
if (vis.AimPivot is not null)
{
float aimYawWorld = MathF.Atan2(c.AimX - c.X, c.AimZ - c.Z);
float relYaw = MatchRules.NormalizeAngle(aimYawWorld - c.Yaw);
vis.AimPivot.Rotation = new Vector3(0f, relYaw, 0f);
}
UpdateHeatGlow(vis.HeatMat, c.Grid);
}
}
private void SyncSpectators(ArenaSession session, float elapsedSeconds)
{
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.Root.Visible = false;
if (deadVis.LaserMesh is not null)
{
deadVis.LaserMesh.Visible = false;
}
}
continue;
}
if (!_spectatorVisuals.TryGetValue(s.Id, out var vis))
{
var (primary, accent) = s.Tier switch
{
SpectatorTier.Tourist => (TouristGold, TouristIvory),
SpectatorTier.Patron => (PatronTeal, PatronBronze),
_ => (ExemplarObsidian, ExemplarCrimson)
};
vis = BuildChassisVisual(s.Grid.Spec.Id, primary, accent, isSpectator: true, tier: s.Tier);
_actorsGroup.AddChild(vis.Root);
_spectatorVisuals[s.Id] = vis;
}
vis.Root.Visible = true;
var body = session.GetSpectatorBody(s.Id);
Vector3 specPos;
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]);
vis.Root.Transform = new Transform3D(new Basis(q), specPos);
}
else
{
specPos = new Vector3(s.X, s.Y, s.Z);
vis.Root.Position = specPos;
vis.Root.Rotation = new Vector3(0f, s.Yaw, 0f);
}
// Status halo
if (vis.HaloMat is not null && vis.HaloMesh is not null)
{
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)
{
ContenderState? target = s.TargetContenderId.HasValue &&
s.TargetContenderId.Value >= 0 &&
s.TargetContenderId.Value < session.State.Contenders.Count
? session.State.Contenders[s.TargetContenderId.Value]
: null;
if (s.Stance != SpectatorStance.Neutral && 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)
{
vis.LaserMesh.Visible = true;
vis.LaserMesh.GlobalPosition = (start + end) * 0.5f;
Vector3 dir = (end - start) / dist;
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
{
vis.LaserMesh.Visible = false;
}
}
else
{
vis.LaserMesh.Visible = false;
}
}
UpdateHeatGlow(vis.HeatMat, s.Grid);
}
}
private void SyncGroundDrops(MatchState state, float elapsedSeconds)
{
for (int i = 0; i < state.GroundDrops.Count; i++)
{
var d = state.GroundDrops[i];
if (d.PickedUp)
{
if (_dropVisuals.TryGetValue(d.Id, out var pickedNode))
{
pickedNode.Visible = false;
}
continue;
}
if (!_dropVisuals.TryGetValue(d.Id, out var node))
{
node = BuildGroundDropVisual(d, state.Terrain);
_dropsGroup.AddChild(node);
_dropVisuals[d.Id] = node;
}
node.Visible = true;
float bob = d.Module is not null ? MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f : 0f;
float baseY = state.Terrain.SampleHeight(d.X, d.Z);
node.Position = new Vector3(d.X, baseY + bob, d.Z);
if (d.Module is not null)
{
node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f);
}
}
}
private void SyncTracers(IReadOnlyList<TracerEvent> 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, TerrainField terrain)
{
var root = new Node3D { Name = $"Drop_{drop.Id}" };
if (drop.Module is { } mod)
{
var mat = mod.IsImperial ? _imperialCrateMat : _humanCrateMat;
root.AddChild(new MeshInstance3D
{
Mesh = new BoxMesh { Size = new Vector3(1.1f, 0.8f, 1.1f) },
MaterialOverride = mat,
Position = new Vector3(0f, 0.5f, 0f)
});
if (mod.IsImperial)
{
root.AddChild(new MeshInstance3D
{
Mesh = new CylinderMesh { TopRadius = 0.08f, BottomRadius = 0.25f, Height = 5.5f, RadialSegments = 8 },
MaterialOverride = _imperialCrateMat,
Position = new Vector3(0f, 3.0f, 0f)
});
}
}
else if (drop.Chassis is { } ch)
{
var hull = BuildChassisVisual(ch.Id, new Color(0.32f, 0.35f, 0.36f), CyanSalvage, isSpectator: false, tier: SpectatorTier.Patron);
hull.Root.Position = new Vector3(0f, ch.HalfHeight * 0.85f, 0f);
hull.Root.Scale = new Vector3(0.85f, 0.85f, 0.85f);
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.15f, 0f)
};
root.AddChild(ring);
}
return root;
}
private ActorVisual BuildChassisVisual(
string chassisId,
Color primary,
Color accent,
bool isSpectator,
SpectatorTier tier)
{
var root = new Node3D { Name = $"Chassis_{chassisId}" };
var bodyMat = new StandardMaterial3D { AlbedoColor = primary, Roughness = 0.55f, Metallic = 0.45f };
var accentMat = new StandardMaterial3D { AlbedoColor = accent, Roughness = 0.45f, Metallic = 0.55f };
var darkMat = new StandardMaterial3D { AlbedoColor = new Color(0.14f, 0.15f, 0.14f), Roughness = 0.8f, Metallic = 0.35f };
var heatMat = new StandardMaterial3D
{
AlbedoColor = accent,
Roughness = 0.4f,
Metallic = 0.6f,
EmissionEnabled = true,
Emission = new Color(1.0f, 0.35f, 0.1f),
EmissionEnergyMultiplier = 0.0f
};
var aimPivot = new Node3D { Name = "AimPivot" };
root.AddChild(aimPivot);
switch (chassisId)
{
case "buggy":
BuildBuggyParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat);
break;
case "technical":
BuildTechnicalParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat);
break;
case "tank":
BuildTankParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat);
break;
case "manticore":
BuildManticoreParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat);
break;
case "raptor":
case "exemplar_frame":
BuildRaptorParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat, isExemplar: chassisId == "exemplar_frame");
break;
case "paladin":
BuildPaladinParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat, isTourist: isSpectator && tier == SpectatorTier.Tourist);
break;
default:
BuildBuggyParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat);
break;
}
var vis = new ActorVisual
{
Root = root,
AimPivot = aimPivot,
HeatMat = heatMat,
ChassisId = chassisId
};
if (isSpectator)
{
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, 3.3f, 0f),
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
};
root.AddChild(halo);
vis.HaloMesh = halo;
vis.HaloMat = haloMat;
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);
vis.LaserMesh = laser;
vis.LaserMat = laserMat;
}
return vis;
}
private static void BuildBuggyParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat)
{
AddBox(root, new Vector3(1.5f, 0.45f, 2.9f), new Vector3(0f, -0.25f, 0f), bodyMat);
AddBox(root, new Vector3(1.1f, 0.45f, 1.3f), new Vector3(0f, 0.25f, -0.2f), accentMat); // rollcage canopy
AddBox(root, new Vector3(0.8f, 0.32f, 0.5f), new Vector3(0f, 0.15f, -1.35f), heatMat); // rear radiator
// 4 wheels
AddWheel(root, new Vector3(-0.98f, -0.45f, 1.05f), 0.36f, 0.32f, darkMat);
AddWheel(root, new Vector3( 0.98f, -0.45f, 1.05f), 0.36f, 0.32f, darkMat);
AddWheel(root, new Vector3(-0.98f, -0.45f, -1.05f), 0.36f, 0.32f, darkMat);
AddWheel(root, new Vector3( 0.98f, -0.45f, -1.05f), 0.36f, 0.32f, darkMat);
// Roof MG turret
aimPivot.Position = new Vector3(0f, 0.6f, 0f);
AddBox(aimPivot, new Vector3(0.45f, 0.26f, 0.55f), Vector3.Zero, darkMat);
AddBox(aimPivot, new Vector3(0.12f, 0.12f, 1.25f), new Vector3(0f, 0.04f, 0.65f), accentMat);
}
private static void BuildTechnicalParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat)
{
AddBox(root, new Vector3(2.0f, 0.55f, 4.2f), new Vector3(0f, -0.25f, 0f), bodyMat);
AddBox(root, new Vector3(1.85f, 0.72f, 1.5f), new Vector3(0f, 0.35f, 0.85f), accentMat); // armored cab
AddBox(root, new Vector3(1.9f, 0.38f, 2.0f), new Vector3(0f, 0.20f, -0.95f), bodyMat); // bed walls
AddBox(root, new Vector3(1.2f, 0.30f, 0.4f), new Vector3(0f, 0.20f, -2.0f), heatMat); // tail radiator
AddWheel(root, new Vector3(-1.12f, -0.55f, 1.45f), 0.44f, 0.36f, darkMat);
AddWheel(root, new Vector3( 1.12f, -0.55f, 1.45f), 0.44f, 0.36f, darkMat);
AddWheel(root, new Vector3(-1.12f, -0.55f, -1.45f), 0.44f, 0.36f, darkMat);
AddWheel(root, new Vector3( 1.12f, -0.55f, -1.45f), 0.44f, 0.36f, darkMat);
aimPivot.Position = new Vector3(0f, 0.72f, -0.8f);
AddBox(aimPivot, new Vector3(0.65f, 0.4f, 0.7f), Vector3.Zero, darkMat);
AddBox(aimPivot, new Vector3(0.14f, 0.14f, 1.7f), new Vector3(-0.18f, 0.08f, 0.8f), accentMat);
AddBox(aimPivot, new Vector3(0.14f, 0.14f, 1.7f), new Vector3( 0.18f, 0.08f, 0.8f), accentMat);
}
private static void BuildTankParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat)
{
AddBox(root, new Vector3(2.4f, 0.85f, 4.6f), new Vector3(0f, -0.2f, 0f), bodyMat);
AddBox(root, new Vector3(0.55f, 0.72f, 4.9f), new Vector3(-1.32f, -0.45f, 0f), darkMat); // left track pod
AddBox(root, new Vector3(0.55f, 0.72f, 4.9f), new Vector3( 1.32f, -0.45f, 0f), darkMat); // right track pod
AddBox(root, new Vector3(1.6f, 0.35f, 0.7f), new Vector3(0f, 0.25f, -1.7f), heatMat); // rear engine deck
aimPivot.Position = new Vector3(0f, 0.65f, 0.2f);
AddBox(aimPivot, new Vector3(1.75f, 0.68f, 2.2f), Vector3.Zero, accentMat);
AddBox(aimPivot, new Vector3(0.24f, 0.24f, 3.0f), new Vector3(0f, 0.05f, 2.0f), darkMat); // main cannon
}
private static void BuildManticoreParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat)
{
// Wide dorsal carapace + 4 splayed articulated legs + radiator flanks
AddBox(root, new Vector3(2.2f, 0.75f, 2.8f), new Vector3(0f, 0.25f, 0f), bodyMat);
AddBox(root, new Vector3(1.3f, 0.55f, 1.2f), new Vector3(0f, 0.45f, 1.2f), accentMat); // chin armor
AddBox(root, new Vector3(0.45f, 0.45f, 1.4f), new Vector3(-1.25f, 0.45f, -0.4f), heatMat);
AddBox(root, new Vector3(0.45f, 0.45f, 1.4f), new Vector3( 1.25f, 0.45f, -0.4f), heatMat);
Vector3[] legAnchors =
{
new(-1.35f, -0.35f, 1.25f),
new( 1.35f, -0.35f, 1.25f),
new(-1.35f, -0.35f, -1.25f),
new( 1.35f, -0.35f, -1.25f)
};
for (int i = 0; i < legAnchors.Length; i++)
{
AddBox(root, new Vector3(0.42f, 1.35f, 0.42f), legAnchors[i], darkMat);
AddBox(root, new Vector3(0.68f, 0.26f, 0.68f), legAnchors[i] + new Vector3(0f, -0.7f, 0f), accentMat);
}
aimPivot.Position = new Vector3(0f, 0.8f, 0.2f);
AddBox(aimPivot, new Vector3(0.9f, 0.38f, 1.0f), Vector3.Zero, darkMat);
AddBox(aimPivot, new Vector3(0.18f, 0.18f, 1.7f), new Vector3(-0.6f, 0f, 0.75f), accentMat);
AddBox(aimPivot, new Vector3(0.18f, 0.18f, 1.7f), new Vector3( 0.6f, 0f, 0.75f), accentMat);
}
private static void BuildRaptorParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat, bool isExemplar)
{
float scale = isExemplar ? 0.78f : 1.0f;
// Tall bipedal legs
AddBox(root, new Vector3(0.42f * scale, 1.85f * scale, 0.52f * scale), new Vector3(-0.62f * scale, -0.8f * scale, 0f), darkMat);
AddBox(root, new Vector3(0.42f * scale, 1.85f * scale, 0.52f * scale), new Vector3( 0.62f * scale, -0.8f * scale, 0f), darkMat);
// Angled torso + head sensor
AddBox(root, new Vector3(1.55f * scale, 1.15f * scale, 1.25f * scale), new Vector3(0f, 0.45f * scale, 0f), bodyMat);
AddBox(root, new Vector3(0.65f * scale, 0.45f * scale, 0.85f * scale), new Vector3(0f, 1.25f * scale, 0.25f * scale), accentMat);
AddBox(root, new Vector3(0.95f * scale, 0.55f * scale, 0.35f * scale), new Vector3(0f, 0.6f * scale, -0.75f * scale), heatMat);
aimPivot.Position = new Vector3(0f, 0.5f * scale, 0f);
AddBox(aimPivot, new Vector3(0.32f * scale, 0.35f * scale, 1.55f * scale), new Vector3(-1.05f * scale, 0f, 0.55f * scale), accentMat);
AddBox(aimPivot, new Vector3(0.32f * scale, 0.35f * scale, 1.55f * scale), new Vector3( 1.05f * scale, 0f, 0.55f * scale), accentMat);
}
private static void BuildPaladinParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat, bool isTourist)
{
// Broad heavy bipedal silhouette + shoulder pods + chest reactor
AddBox(root, new Vector3(0.68f, 2.0f, 0.82f), new Vector3(-0.85f, -1.1f, 0f), darkMat);
AddBox(root, new Vector3(0.68f, 2.0f, 0.82f), new Vector3( 0.85f, -1.1f, 0f), darkMat);
AddBox(root, new Vector3(2.25f, 1.65f, 1.65f), new Vector3(0f, 0.45f, 0f), bodyMat);
AddBox(root, new Vector3(0.85f, 0.75f, 0.35f), new Vector3(0f, 0.55f, 0.85f), heatMat); // chest reactor
// Twin shoulder pods
AddBox(root, new Vector3(0.75f, 0.72f, 1.15f), new Vector3(-1.35f, 1.45f, 0f), accentMat);
AddBox(root, new Vector3(0.75f, 0.72f, 1.15f), new Vector3( 1.35f, 1.45f, 0f), accentMat);
if (isTourist)
{
// Gaudy gilded luxury dome on top so Tourists are unmistakable loot pinatas
var dome = new MeshInstance3D
{
Mesh = new CylinderMesh { TopRadius = 0.5f, BottomRadius = 0.95f, Height = 0.75f, RadialSegments = 12 },
MaterialOverride = bodyMat,
Position = new Vector3(0f, 1.65f, 0f)
};
root.AddChild(dome);
}
aimPivot.Position = new Vector3(0f, 0.45f, 0f);
AddBox(aimPivot, new Vector3(0.45f, 0.48f, 2.0f), new Vector3(-1.45f, 0f, 0.65f), accentMat);
AddBox(aimPivot, new Vector3(0.45f, 0.48f, 2.0f), new Vector3( 1.45f, 0f, 0.65f), accentMat);
}
private static void AddBox(Node3D parent, Vector3 size, Vector3 pos, Material mat)
{
parent.AddChild(new MeshInstance3D
{
Mesh = new BoxMesh { Size = size },
MaterialOverride = mat,
Position = pos
});
}
private static void AddWheel(Node3D parent, Vector3 pos, float radius, float width, Material mat)
{
parent.AddChild(new MeshInstance3D
{
Mesh = new CylinderMesh { TopRadius = radius, BottomRadius = radius, Height = width, RadialSegments = 12 },
MaterialOverride = mat,
Position = pos,
Rotation = new Vector3(0f, 0f, MathF.PI * 0.5f)
});
}
private static void UpdateHeatGlow(StandardMaterial3D heatMat, ChassisGrid grid)
{
float maxTemp = ChassisGrid.AmbientTemp;
for (int i = 0; i < grid.Mounted.Count; i++)
{
maxTemp = MathF.Max(maxTemp, grid.Mounted[i].CurrentTemp);
}
float glow = Math.Clamp((maxTemp - 65f) / 110f, 0f, 1f);
heatMat.EmissionEnergyMultiplier = glow * 2.6f;
}
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();
}
}
}

791
client/Hud.cs Normal file
View file

@ -0,0 +1,791 @@
using System;
using System.Collections.Generic;
using Godot;
using RustToDust.Core;
using RustToDust.Ymir;
namespace RustToDust.Client;
/// <summary>
/// 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).
/// </summary>
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<ArenaSession?> _getSession;
private readonly Action<int, string> _onEquipCargo;
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 _promptLabel = null!;
private Label _controlsHint = null!;
private RadarWidget _radar = null!;
private SchematicPanel _schematic = null!;
private VBoxContainer _cargoList = null!;
private Label _cargoHeader = null!;
private Label _garageDetails = null!;
private PanelContainer _bottomLeftPanel = null!;
private VBoxContainer _chyronBox = null!;
private readonly Label[] _chyronLabels = new Label[3];
private BroadcastFeed? _lastBroadcastFeed;
private long _lastChyronVersion = -1;
private PanelContainer _outcomeBanner = null!;
private Label _outcomeLabel = null!;
private int _selectedCargoIndex = -1;
private int _lastCargoHash = -1;
private bool _garageExpanded;
public Hud(Func<ArenaSession?> getSession, Action<int, string> onEquipCargo)
{
_getSession = getSession;
_onEquipCargo = onEquipCargo;
Layer = 10;
}
public bool GarageExpanded => _garageExpanded;
public void ToggleGarage()
{
_garageExpanded = !_garageExpanded;
_garageDetails.Visible = _garageExpanded;
_schematic.CustomMinimumSize = _garageExpanded ? new Vector2(236f, 250f) : new Vector2(180f, 190f);
_schematic.QueueRedraw();
}
public override void _Ready()
{
BuildTopLeft();
BuildTopRightRadar();
BuildBottomLeftSchematic();
BuildBottomCenterChyron();
BuildOutcomeBanner();
}
public bool IsPointerOverInteractiveHud(Vector2 screenPos)
{
return _bottomLeftPanel.GetGlobalRect().HasPoint(screenPos);
}
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++;
}
_statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}";
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;
}
_promptLabel.Text = BuildInteractionPrompt(state, player);
_promptLabel.Visible = !string.IsNullOrEmpty(_promptLabel.Text);
// Radar
_radar.SetState(state);
_radar.QueueRedraw();
// Schematic + Cargo
_schematic.SetGrid(player.Grid, _selectedCargoIndex);
_schematic.QueueRedraw();
SyncCargoButtons(player.Grid);
if (_garageExpanded)
{
_garageDetails.Text = BuildGarageDetails(player.Grid);
}
// Broadcast Chyron
SyncBroadcastChyron(state.Broadcast);
// Outcome
if (state.Phase == MatchPhase.Victory)
{
_outcomeBanner.Visible = true;
_outcomeLabel.Text = "VICTORY — LAST RIG STANDING\n[R] New Drop";
_outcomeLabel.Modulate = OliveCol;
}
else if (state.Phase == MatchPhase.Defeat)
{
_outcomeBanner.Visible = true;
_outcomeLabel.Text = "CHASSIS DESTROYED\n[R] Redeploy";
_outcomeLabel.Modulate = RedCol;
}
else
{
_outcomeBanner.Visible = false;
}
}
private void BuildTopLeft()
{
var panel = CreateStyledPanel();
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);
_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 | LMB Fire | E Loot/Swap | Tab Garage | R Reset" };
_controlsHint.AddThemeColorOverride("font_color", TextMuted);
_controlsHint.AddThemeFontSizeOverride("font_size", 11);
vbox.AddChild(_controlsHint);
}
private void BuildTopRightRadar()
{
var panel = CreateStyledPanel();
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();
_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", 10);
_bottomLeftPanel.AddChild(hbox);
var leftCol = new VBoxContainer();
leftCol.AddThemeConstantOverride("separation", 4);
hbox.AddChild(leftCol);
var title = new Label { Text = "AETHERIA HEAT & HARDPOINTS" };
title.AddThemeColorOverride("font_color", OrangeCol);
title.AddThemeFontSizeOverride("font_size", 12);
leftCol.AddChild(title);
_schematic = new SchematicPanel(OnHardpointClicked)
{
CustomMinimumSize = new Vector2(180f, 190f)
};
leftCol.AddChild(_schematic);
var rightCol = new VBoxContainer { CustomMinimumSize = new Vector2(178f, 0f) };
rightCol.AddThemeConstantOverride("separation", 4);
hbox.AddChild(rightCol);
_cargoHeader = new Label { Text = "SALVAGE CARGO (0/4)" };
_cargoHeader.AddThemeColorOverride("font_color", OliveCol);
_cargoHeader.AddThemeFontSizeOverride("font_size", 12);
rightCol.AddChild(_cargoHeader);
_cargoList = new VBoxContainer();
_cargoList.AddThemeConstantOverride("separation", 3);
rightCol.AddChild(_cargoList);
_garageDetails = new Label { Visible = false, AutowrapMode = TextServer.AutowrapMode.Word };
_garageDetails.AddThemeColorOverride("font_color", TextMuted);
_garageDetails.AddThemeFontSizeOverride("font_size", 11);
_garageDetails.CustomMinimumSize = new Vector2(200f, 0f);
hbox.AddChild(_garageDetails);
}
private void BuildBottomCenterChyron()
{
var panel = CreateStyledPanel();
panel.AnchorLeft = 0.5f;
panel.AnchorRight = 0.5f;
panel.AnchorTop = 1f;
panel.AnchorBottom = 1f;
panel.OffsetLeft = -150f;
panel.OffsetRight = 460f;
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();
_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 SyncCargoButtons(ChassisGrid grid)
{
int hash = grid.Cargo.Count * 97 + (_selectedCargoIndex + 10);
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
};
selectBtn.AddThemeFontSizeOverride("font_size", 11);
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" };
fitBtn.AddThemeFontSizeOverride("font_size", 11);
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 = null;
float bestD2 = MatchState.PickupRadius * MatchState.PickupRadius;
for (int i = 0; i < state.GroundDrops.Count; i++)
{
var d = state.GroundDrops[i];
if (d.PickedUp) continue;
float dx = d.X - player.X;
float dz = d.Z - player.Z;
float d2 = dx * dx + dz * dz;
if (d2 <= bestD2)
{
bestD2 = d2;
nearest = d;
}
}
if (nearest is null) return "";
if (nearest.Module is { } mod)
{
return $"[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<string>
{
$"CONDUCTIVITY {grid.Spec.HullConductivity:F1} | THRUST {grid.ComputeDriveThrust():F0} N",
"MOUNTED:"
};
for (int i = 0; i < grid.Mounted.Count; i++)
{
var m = grid.Mounted[i];
lines.Add($"• {m.HardpointId}: {m.Spec.Name} ({m.CurrentTemp:F0}°C, {(m.CurrentPerformance * 100f):F0}%)");
}
return string.Join("\n", lines);
}
private static PanelContainer CreateStyledPanel()
{
var panel = new PanelContainer();
var style = new StyleBoxFlat
{
BgColor = new Color(BgDark.R, BgDark.G, BgDark.B, 0.88f),
BorderColor = BorderCol,
ContentMarginLeft = 10,
ContentMarginRight = 10,
ContentMarginTop = 8,
ContentMarginBottom = 8
};
style.SetBorderWidthAll(2);
style.SetCornerRadiusAll(3);
panel.AddThemeStyleboxOverride("panel", style);
return panel;
}
private sealed partial class RadarWidget : Control
{
private MatchState? _state;
public void SetState(MatchState state) => _state = state;
private static Vector2 WorldToRadar(Vector2 center, float scale, float wx, float wz) =>
// Match chase camera orientation: screen-up = +Z, screen-right = -X.
center + new Vector2(-wx, -wz) * scale;
public override void _Draw()
{
Vector2 center = Size * 0.5f;
float radius = MathF.Min(Size.X, Size.Y) * 0.47f;
float scale = radius / MatchState.ArenaHalfExtent;
DrawCircle(center, radius, BgInner);
DrawArc(center, radius, 0f, MathF.Tau, 48, BorderCol, 1.5f);
if (_state is null) return;
// Safe Circle
float safePx = _state.Spectators.SafeRadius * scale;
DrawArc(center, safePx, 0f, MathF.Tau, 56, 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 = WorldToRadar(center, scale, d.X, d.Z);
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 (scaled by RadarSignature) + red target lock lines
var specs = _state.Spectators.Spectators;
for (int i = 0; i < specs.Count; i++)
{
var s = specs[i];
if (!s.Alive) continue;
var p = WorldToRadar(center, scale, s.X, s.Z);
float blipR = 1.6f + s.RadarSignature * 3.1f;
Color col = s.Tier switch
{
SpectatorTier.Tourist => GoldCol,
SpectatorTier.Patron => PatronColor,
_ => RedCol
};
if (s.Stance != SpectatorStance.Neutral && s.TargetContenderId.HasValue)
{
int tid = s.TargetContenderId.Value;
if (tid >= 0 && tid < _state.Contenders.Count && _state.Contenders[tid].Alive)
{
var tgt = _state.Contenders[tid];
var tp = WorldToRadar(center, scale, tgt.X, tgt.Z);
DrawLine(p, tp, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f), 1.3f);
}
col = RedCol;
}
DrawCircle(p, blipR, col);
}
// Contenders
for (int i = 0; i < _state.Contenders.Count; i++)
{
var c = _state.Contenders[i];
if (!c.Alive) continue;
var p = WorldToRadar(center, scale, c.X, c.Z);
if (c.IsPlayer)
{
var dir = new Vector2(-MathF.Sin(c.Yaw), -MathF.Cos(c.Yaw));
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);
}
else
{
DrawCircle(p, 3.3f, OrangeCol);
}
}
}
private static readonly Color PatronColor = Color.FromHtml("#4ba8a5");
}
private sealed partial class SchematicPanel : Control
{
private readonly Action<string> _onHardpointClick;
private readonly List<(Rect2 Rect, string HardpointId)> _hitBoxes = new();
private ChassisGrid? _grid;
private int _selectedCargoIndex = -1;
public SchematicPanel(Action<string> onHardpointClick)
{
_onHardpointClick = onHardpointClick;
}
public void SetGrid(ChassisGrid grid, int selectedCargoIndex)
{
_grid = grid;
_selectedCargoIndex = selectedCargoIndex;
}
public override void _GuiInput(InputEvent @event)
{
if (@event is InputEventMouseButton mb && mb.Pressed && mb.ButtonIndex == MouseButton.Left)
{
for (int i = 0; i < _hitBoxes.Count; i++)
{
if (_hitBoxes[i].Rect.HasPoint(mb.Position))
{
_onHardpointClick(_hitBoxes[i].HardpointId);
AcceptEvent();
return;
}
}
}
}
public override void _Draw()
{
_hitBoxes.Clear();
if (_grid is null) return;
var spec = _grid.Spec;
float cellSize = MathF.Min((Size.X - 8f) / spec.Width, (Size.Y - 8f) / spec.Height);
float originX = (Size.X - spec.Width * cellSize) * 0.5f;
float originY = (Size.Y - spec.Height * cellSize) * 0.5f;
for (int y = 0; y < spec.Height; y++)
{
for (int x = 0; x < spec.Width; x++)
{
if (!spec.IsActive(x, y)) continue;
var rect = new Rect2(originX + x * cellSize + 1.5f, originY + y * cellSize + 1.5f, cellSize - 3f, cellSize - 3f);
float temp = _grid.Temperature[x, y];
Color fill = TempToColor(temp);
DrawRect(rect, fill);
// Armor bar at bottom of cell
float maxArm = MathF.Max(1f, _grid.MaxArmor[x, y]);
float armRatio = Math.Clamp(_grid.Armor[x, y] / maxArm, 0f, 1f);
var armRect = new Rect2(rect.Position.X + 2f, rect.End.Y - 5f, (rect.Size.X - 4f) * armRatio, 3f);
DrawRect(armRect, OliveCol);
// Border radiator highlight
Color border = _grid.BorderCells[x, y] ? CyanCol : BorderCol;
DrawRect(rect, border, filled: false, width: _grid.BorderCells[x, y] ? 1.5f : 1.0f);
}
}
// Hardpoints & mounted module temperature badges
ModuleSpec? selectedCargo = _selectedCargoIndex >= 0 && _selectedCargoIndex < _grid.Cargo.Count
? _grid.Cargo[_selectedCargoIndex]
: null;
for (int i = 0; i < spec.Hardpoints.Length; i++)
{
var hp = spec.Hardpoints[i];
var rect = new Rect2(
originX + hp.X * cellSize + 2f,
originY + hp.Y * cellSize + 2f,
hp.Width * cellSize - 4f,
hp.Height * cellSize - 4f);
_hitBoxes.Add((rect, hp.Id));
bool compatible = selectedCargo is not null && ChassisGrid.CanFit(hp, selectedCargo);
Color hpBorder = compatible ? GoldCol : TextLight;
DrawRect(rect, hpBorder, filled: false, width: compatible ? 2.4f : 1.4f);
var mounted = _grid.GetMountedOn(hp.Id);
string tag = mounted is not null
? $"{mounted.Spec.Kind.ToString()[..1]}:{mounted.CurrentTemp:F0}°"
: hp.Kind.ToString()[..3].ToUpperInvariant();
DrawString(
ThemeDB.FallbackFont,
rect.Position + new Vector2(3f, 13f),
tag,
HorizontalAlignment.Left,
rect.Size.X - 4f,
10,
mounted is { Spec.IsImperial: true } ? GoldCol : TextLight);
}
}
private static Color TempToColor(float temp)
{
if (temp < 45f)
{
float t = Math.Clamp((temp - 20f) / 25f, 0f, 1f);
return new Color(0.18f, 0.23f, 0.26f).Lerp(new Color(0.32f, 0.45f, 0.28f), t);
}
if (temp < 95f)
{
float t = Math.Clamp((temp - 45f) / 50f, 0f, 1f);
return new Color(0.32f, 0.45f, 0.28f).Lerp(new Color(0.62f, 0.69f, 0.36f), t);
}
if (temp < 140f)
{
float t = Math.Clamp((temp - 95f) / 45f, 0f, 1f);
return new Color(0.62f, 0.69f, 0.36f).Lerp(OrangeCol, t);
}
float hotT = Math.Clamp((temp - 140f) / 60f, 0f, 1f);
return OrangeCol.Lerp(RedCol, hotT);
}
}
}

256
client/Main.cs Normal file
View file

@ -0,0 +1,256 @@
using System;
using Godot;
using RustToDust.Core;
using RustToDust.Ymir;
namespace RustToDust.Client;
/// <summary>
/// Root Godot node for Rust to Dust.
/// Godot physics is Dummy; <see cref="ArenaSession"/> owns 100% of vehicle, thermal, spectator, and terrain physics at 60 Hz.
/// </summary>
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 _cameraDistance = 30f;
private Vector3 _cameraSmoothedTarget = Vector3.Zero;
private float _elapsedSeconds;
private bool _interactQueued;
private int _seed = 42;
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 override void _Ready()
{
SetupLightingAndSky();
_terrain = new TerrainRenderer { Name = "Terrain" };
AddChild(_terrain);
_arena = new ArenaRenderer { Name = "Arena" };
AddChild(_arena);
_camera = new Camera3D
{
Name = "TacticalCamera",
Current = true,
Fov = 48f,
Far = 520f
};
AddChild(_camera);
_hud = new Hud(() => _session, OnEquipCargo) { Name = "Hud" };
AddChild(_hud);
Reset(_seed);
}
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;
_cameraSmoothedTarget = new Vector3(p.X, p.Y, p.Z);
_terrain.InvalidateAll();
_terrain.Sync(_session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds);
_hud.Sync(_session);
}
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 InputEventKey key && key.Pressed && !key.Echo)
{
switch (key.Keycode)
{
case Key.E:
_interactQueued = true;
break;
case Key.Tab:
_hud.ToggleGarage();
break;
case Key.R:
Reset(_seed + 1);
break;
case Key.Escape:
Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Confined
? Input.MouseModeEnum.Visible
: Input.MouseModeEnum.Confined;
break;
}
}
else if (@event is InputEventMouseButton mb && mb.Pressed)
{
if (mb.ButtonIndex == MouseButton.WheelUp)
{
_cameraDistance = Math.Clamp(_cameraDistance - 2.5f, 16f, 58f);
}
else if (mb.ButtonIndex == MouseButton.WheelDown)
{
_cameraDistance = Math.Clamp(_cameraDistance + 2.5f, 16f, 58f);
}
}
}
public override void _PhysicsProcess(double delta)
{
if (_session is null)
{
return;
}
_elapsedSeconds += (float)delta;
var input = _scriptedInput ?? GatherPlayerInput();
_interactQueued = false;
_session.Step(input);
_terrain.Sync(_session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds);
}
public override void _Process(double delta)
{
if (_session is null)
{
return;
}
UpdateCamera((float)delta);
_hud.Sync(_session);
}
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 brake = Input.IsKeyPressed(Key.Space);
Vector2 mousePos = GetViewport().GetMousePosition();
bool pointerOnHud = _hud.IsPointerOverInteractiveHud(mousePos);
bool fire = !pointerOnHud && Input.IsMouseButtonPressed(MouseButton.Left);
var (aimX, aimZ) = ComputeMouseTerrainAim(mousePos);
return new PlayerInput(
Throttle: throttle,
Steer: steer,
AimWorldX: aimX,
AimWorldZ: aimZ,
Fire: fire,
InteractPickup: _interactQueued,
Brake: brake);
}
private (float AimX, float AimZ) ComputeMouseTerrainAim(Vector2 mousePos)
{
var player = Session.State.Player;
Vector3 rayOrigin = _camera.ProjectRayOrigin(mousePos);
Vector3 rayDir = _camera.ProjectRayNormal(mousePos);
if (Session.State.Terrain.Raycast(
rayOrigin.X, rayOrigin.Y, rayOrigin.Z,
rayDir.X, rayDir.Y, rayDir.Z,
maxDistance: 320f,
out float hx, out _, out float hz, out _))
{
return (hx, hz);
}
if (MathF.Abs(rayDir.Y) > 1e-4f)
{
float t = (player.Y - rayOrigin.Y) / rayDir.Y;
if (t > 0f)
{
Vector3 p = rayOrigin + rayDir * t;
return (p.X, p.Z);
}
}
return (player.X + MathF.Sin(player.Yaw) * 25f, player.Z + MathF.Cos(player.Yaw) * 25f);
}
private void UpdateCamera(float dt)
{
var p = Session.State.Player;
var target = new Vector3(p.X, p.Y + 1.0f, p.Z);
float blend = 1f - MathF.Exp(-dt * 9f);
_cameraSmoothedTarget = _cameraSmoothedTarget.Lerp(target, blend);
// Angled tactical 3rd-person desert chase view
Vector3 offset = new Vector3(0f, _cameraDistance * 0.78f, -_cameraDistance * 0.72f);
_camera.GlobalPosition = _cameraSmoothedTarget + offset;
_camera.LookAt(_cameraSmoothedTarget, 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,
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,
FogLightColor = new Color(0.74f, 0.55f, 0.38f),
FogDensity = 0.0022f
};
AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env });
}
}

6
client/Main.tscn Normal file
View file

@ -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")

61
client/NativeLibraries.cs Normal file
View file

@ -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;
/// <summary>
/// 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 <c>--path</c> loads the library from the
/// project's build directory; an exported run from the data folder Godot puts beside the executable.
/// </summary>
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";
}

View file

@ -0,0 +1,13 @@
<Project Sdk="Godot.NET.Sdk/4.7.2">
<!-- The Godot client: presentation and input over ArenaSession. Building it builds Ymir (cmake and a C compiler) and RustToDust into .godot/mono/temp/bin/Debug. -->
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<EnableDynamicLoading>true</EnableDynamicLoading>
<Nullable>enable</Nullable>
<AssemblyName>RustToDust.Client</AssemblyName>
<RootNamespace>RustToDust.Client</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" />
</ItemGroup>
</Project>

333
client/TerrainRenderer.cs Normal file
View file

@ -0,0 +1,333 @@
using System;
using System.Collections.Generic;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Top-down orthographic SubViewport brush-to-tile PBR + displacement terrain baker.
/// Maintains a 4x4 grid of 96m x 96m terrain tiles covering [-192, +192] in X and Z.
/// Only tiles whose <see cref="TerrainField.TileVersions"/> changed are re-baked.
/// </summary>
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 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 Shader _brushAddShader = null!;
private Shader _brushSubShader = null!;
private Shader _brushAlbedoShader = null!;
private Shader _surfaceShader = null!;
private TerrainField? _lastTerrain;
public int BakedTileCount { get; private set; }
public int DirtyRebakes { get; private set; }
public override void _Ready()
{
_brushAddShader = GD.Load<Shader>("res://terrain_brush.gdshader");
_brushSubShader = GD.Load<Shader>("res://terrain_brush_sub.gdshader");
_brushAlbedoShader = GD.Load<Shader>("res://terrain_brush_albedo.gdshader");
_surfaceShader = GD.Load<Shader>("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;
}
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 != version)
{
BakeTile(tx, tz, tile, terrain);
if (tile.BakedVersion < 0)
{
BakedTileCount++;
}
else
{
DirtyRebakes++;
}
tile.BakedVersion = version;
}
}
}
terrain.ClearDirtyMask();
}
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 plane = new PlaneMesh
{
Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize),
SubdivideWidth = 48,
SubdivideDepth = 48
};
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);
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 = plane,
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,
RenderTargetClearMode = SubViewport.ClearMode.Always,
RenderTargetUpdateMode = SubViewport.UpdateMode.Disabled
};
var cam = new Camera2D
{
AnchorMode = Camera2D.AnchorModeEnum.FixedTopLeft,
Position = Vector2.Zero,
Enabled = true
};
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
tile.HeightCanvas.AddChild(new ColorRect
{
Position = Vector2.Zero,
Size = new Vector2(ViewportSize, ViewportSize),
Color = HeightClearColor
});
tile.AlbedoCanvas.AddChild(new ColorRect
{
Position = Vector2.Zero,
Size = new Vector2(ViewportSize, ViewportSize),
Color = AlbedoClearColor
});
float tileMinX = -TerrainField.HalfExtent + tx * TerrainField.TileSize;
float tileMinZ = -TerrainField.HalfExtent + tz * TerrainField.TileSize;
IReadOnlyList<int> 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));
tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta));
}
else if (b.Kind == TerrainBrushKind.Track)
{
tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta));
tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta));
}
else if (b.Kind == TerrainBrushKind.Road || b.HeightDelta < 0f)
{
tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta));
}
else
{
tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta));
}
// 2. Albedo brush pass
var albedoQuad = new ColorRect
{
Position = new Vector2(px - rxPx, py - rzPx),
Size = new Vector2(rxPx * 2f, rzPx * 2f),
PivotOffset = new Vector2(rxPx, rzPx),
Rotation = b.RotationRad
};
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 ColorRect CreateBrushQuad(
float px, float py,
float rxPx, float rzPx,
float rotationRad,
Shader shader,
int kindInt,
float heightDelta)
{
var quad = new ColorRect
{
Position = new Vector2(px - rxPx, py - rzPx),
Size = new Vector2(rxPx * 2f, rzPx * 2f),
PivotOffset = new Vector2(rxPx, rzPx),
Rotation = rotationRad
};
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();
}
}
}

33
client/project.godot Normal file
View file

@ -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"

View file

@ -0,0 +1,67 @@
shader_type canvas_item;
render_mode blend_add;
// Encodes positive height deltas into R ([-12m, +16m] => span 28m),
// 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 = 28.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);
}

View file

@ -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);
}

View file

@ -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 = 28.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);
}

View file

@ -0,0 +1,53 @@
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 = -12.0;
uniform float height_max = 16.0;
uniform float tile_size = 96.0;
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 * 253.0 + 1.5) / 256.0;
}
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);
const float texel_step = 1.0 / 256.0;
float world_step = tile_size / 253.0;
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;
}

159
client/tests/Smoke.cs Normal file
View file

@ -0,0 +1,159 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client.Tests;
/// <summary>
/// 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.
/// <c>godot --headless --path client res://tests/Smoke.tscn</c>
/// </summary>
public partial class Smoke : Node
{
private const double WatchdogSeconds = 60.0;
private readonly List<string> _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<PackedScene>("res://Main.tscn").Instantiate<Main>();
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 == 16, $"Expected 16 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(-48f, -48f);
float gpuBefore = 0f;
if (!isHeadless)
{
bool hasGpuBefore = _main.Terrain.TrySampleBakedHeight(-48f, -48f, out gpuBefore);
Check(hasGpuBefore, "Expected GPU HeightViewport readback to succeed before crater");
if (hasGpuBefore)
{
Check(MathF.Abs(gpuBefore - cpuBefore) <= 0.25f,
$"Expected baked GPU height ({gpuBefore:F2}m) to match CPU height ({cpuBefore:F2}m) before crater");
}
}
_main.Session.State.Terrain.StampCrater(-48f, -48f, 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(-48f, -48f);
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(-48f, -48f, out float gpuAfter);
Check(hasGpuAfter, "Expected GPU HeightViewport readback to succeed after crater");
if (hasGpuAfter)
{
Check(MathF.Abs(gpuAfter - cpuAfter) <= 0.25f,
$"Expected baked GPU height ({gpuAfter:F2}m) to match CPU height ({cpuAfter:F2}m) after crater");
Check(gpuAfter < gpuBefore - 0.8f,
$"Expected baked GPU height to drop after crater (before {gpuBefore:F2}m, after {gpuAfter:F2}m)");
}
}
_main.SetPhysicsProcess(true);
}
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);
}
}

6
client/tests/Smoke.tscn Normal file
View file

@ -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")

View file

@ -0,0 +1,74 @@
using System.Collections.Generic;
namespace RustToDust.Core
{
public enum BroadcastKind
{
MatchStart,
TouristPull,
ExemplarWakeup,
PatronClearance,
ChassisSwap,
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<BroadcastLine> _lines = new();
public IReadOnlyList<BroadcastLine> 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. Eight 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 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.");
}
}

View file

@ -0,0 +1,583 @@
using System;
using System.Collections.Generic;
namespace RustToDust.Core
{
public static class Catalog
{
private static bool[] ParseMask(params string[] rows)
{
int h = rows.Length;
int w = rows[0].Length;
var mask = new bool[w * h];
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
mask[y * w + x] = rows[y][x] == '#';
}
}
return mask;
}
// ---------------- CHASSIS (6 PLAYABLE) ----------------
public static readonly ChassisSpec Buggy = new(
Id: "buggy",
Name: "Dune Buggy",
Plane: GridPlane.Dorsal,
Width: 3,
Height: 4,
Mask: ParseMask(
"###",
"###",
"###",
"###"),
Hardpoints: new[]
{
new HardpointSpec("wpn_roof", HardpointKind.Weapon, 1, 0, 1, 1, 5f),
new HardpointSpec("eng_mid", HardpointKind.Engine, 1, 2, 1, 1, 5f),
new HardpointSpec("rad_rear", HardpointKind.Radiator, 1, 3, 1, 1, 0f)
},
HullConductivity: 8f,
BaseCellThermalMass: 10f,
BaseCellArmor: 24f,
MassKg: 950f,
BaseThrust: 13500f,
BaseTurnRate: 4.2f,
MaxSpeed: 32f,
HalfWidth: 1.05f,
HalfHeight: 0.75f,
HalfLength: 1.65f,
CargoCapacity: 4);
public static readonly ChassisSpec Technical = new(
Id: "technical",
Name: "Gun Truck",
Plane: GridPlane.Dorsal,
Width: 3,
Height: 5,
Mask: ParseMask(
"###",
"###",
"###",
"###",
"###"),
Hardpoints: new[]
{
new HardpointSpec("wpn_cab", HardpointKind.Weapon, 1, 0, 1, 1, 6f),
new HardpointSpec("eng_hood", HardpointKind.Engine, 1, 1, 1, 1, 6f),
new HardpointSpec("wpn_bed", HardpointKind.Weapon, 1, 2, 1, 2, 8f),
new HardpointSpec("rad_tail", HardpointKind.Radiator, 2, 4, 1, 1, 0f),
new HardpointSpec("arm_bumper", HardpointKind.Armor, 0, 0, 1, 1, 10f)
},
HullConductivity: 8.5f,
BaseCellThermalMass: 13f,
BaseCellArmor: 34f,
MassKg: 1850f,
BaseThrust: 22000f,
BaseTurnRate: 3.3f,
MaxSpeed: 27f,
HalfWidth: 1.25f,
HalfHeight: 0.95f,
HalfLength: 2.3f,
CargoCapacity: 6);
public static readonly ChassisSpec Tank = new(
Id: "tank",
Name: "Ironclad Tank",
Plane: GridPlane.Dorsal,
Width: 4,
Height: 5,
Mask: ParseMask(
"####",
"####",
"####",
"####",
"####"),
Hardpoints: new[]
{
new HardpointSpec("arm_glacis", HardpointKind.Armor, 1, 0, 2, 1, 24f),
new HardpointSpec("wpn_coax", HardpointKind.Weapon, 0, 1, 1, 1, 10f),
new HardpointSpec("wpn_turret", HardpointKind.Weapon, 1, 1, 2, 2, 18f),
new HardpointSpec("arm_skirt", HardpointKind.Armor, 0, 2, 1, 1, 16f),
new HardpointSpec("eng_rear", HardpointKind.Engine, 1, 3, 2, 2, 10f),
new HardpointSpec("rad_deck", HardpointKind.Radiator, 3, 3, 1, 1, 0f)
},
HullConductivity: 9.5f,
BaseCellThermalMass: 18f,
BaseCellArmor: 62f,
MassKg: 4200f,
BaseThrust: 38000f,
BaseTurnRate: 2.1f,
MaxSpeed: 20f,
HalfWidth: 1.65f,
HalfHeight: 1.1f,
HalfLength: 2.65f,
CargoCapacity: 8);
public static readonly ChassisSpec Manticore = new(
Id: "manticore",
Name: "Manticore Quadruped",
Plane: GridPlane.Dorsal,
Width: 5,
Height: 5,
Mask: ParseMask(
"#####",
".###.",
"#####",
".###.",
"#.#.#"),
Hardpoints: new[]
{
new HardpointSpec("wpn_chin", HardpointKind.Weapon, 2, 0, 1, 1, 10f),
new HardpointSpec("wpn_left", HardpointKind.Weapon, 0, 2, 1, 1, 8f),
new HardpointSpec("wpn_right", HardpointKind.Weapon, 4, 2, 1, 1, 8f),
new HardpointSpec("eng_core", HardpointKind.Engine, 2, 1, 1, 2, 12f),
new HardpointSpec("rad_left", HardpointKind.Radiator, 1, 1, 1, 1, 4f),
new HardpointSpec("rad_right", HardpointKind.Radiator, 3, 1, 1, 1, 4f),
new HardpointSpec("arm_back", HardpointKind.Armor, 2, 3, 1, 1, 18f)
},
HullConductivity: 11f,
BaseCellThermalMass: 15f,
BaseCellArmor: 46f,
MassKg: 2800f,
BaseThrust: 33000f,
BaseTurnRate: 3.6f,
MaxSpeed: 25f,
HalfWidth: 1.6f,
HalfHeight: 1.35f,
HalfLength: 2.1f,
CargoCapacity: 7);
public static readonly ChassisSpec Raptor = new(
Id: "raptor",
Name: "Raptor Biped",
Plane: GridPlane.Coronal,
Width: 5,
Height: 6,
Mask: ParseMask(
"..#..",
".###.",
"#####",
"#.#.#",
".#.#.",
".#.#."),
Hardpoints: new[]
{
new HardpointSpec("rad_lsh", HardpointKind.Radiator, 1, 1, 1, 1, 4f),
new HardpointSpec("rad_rsh", HardpointKind.Radiator, 3, 1, 1, 1, 4f),
new HardpointSpec("wpn_larm", HardpointKind.Weapon, 0, 2, 1, 2, 8f),
new HardpointSpec("eng_chest", HardpointKind.Engine, 2, 2, 1, 2, 12f),
new HardpointSpec("wpn_rarm", HardpointKind.Weapon, 4, 2, 1, 2, 8f)
},
HullConductivity: 10.5f,
BaseCellThermalMass: 14f,
BaseCellArmor: 42f,
MassKg: 2300f,
BaseThrust: 30000f,
BaseTurnRate: 4.1f,
MaxSpeed: 26f,
HalfWidth: 1.35f,
HalfHeight: 1.95f,
HalfLength: 1.15f,
CargoCapacity: 6);
public static readonly ChassisSpec Paladin = new(
Id: "paladin",
Name: "Paladin Heavy Biped",
Plane: GridPlane.Coronal,
Width: 6,
Height: 7,
Mask: ParseMask(
"..##..",
".####.",
"######",
"######",
".####.",
".#..#.",
".#..#."),
Hardpoints: new[]
{
new HardpointSpec("wpn_lsh", HardpointKind.Weapon, 1, 1, 1, 1, 12f),
new HardpointSpec("arm_collar", HardpointKind.Armor, 2, 1, 2, 1, 22f),
new HardpointSpec("wpn_rsh", HardpointKind.Weapon, 4, 1, 1, 1, 12f),
new HardpointSpec("wpn_larm", HardpointKind.Weapon, 0, 2, 1, 2, 12f),
new HardpointSpec("eng_core", HardpointKind.Engine, 2, 2, 2, 2, 16f),
new HardpointSpec("wpn_rarm", HardpointKind.Weapon, 5, 2, 1, 2, 12f),
new HardpointSpec("rad_l", HardpointKind.Radiator, 1, 4, 1, 1, 6f),
new HardpointSpec("arm_waist", HardpointKind.Armor, 2, 4, 2, 1, 20f),
new HardpointSpec("rad_r", HardpointKind.Radiator, 4, 4, 1, 1, 6f)
},
HullConductivity: 11.5f,
BaseCellThermalMass: 18f,
BaseCellArmor: 58f,
MassKg: 4100f,
BaseThrust: 41000f,
BaseTurnRate: 2.7f,
MaxSpeed: 21f,
HalfWidth: 1.75f,
HalfHeight: 2.35f,
HalfLength: 1.4f,
CargoCapacity: 9);
public static readonly IReadOnlyList<ChassisSpec> AllChassis = new[]
{
Buggy, Technical, Tank, Manticore, Raptor, Paladin
};
// ---------------- HUMAN SALVAGE MODULES (8) ----------------
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: 75f,
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: 95f,
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: 48f,
FireCooldown: 0.65f,
ProjectileSpeed: 185f,
SpreadRad: 0.14f,
BurstCount: 5);
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: 120f,
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 (5) ----------------
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: 130f,
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: 95f,
FireCooldown: 0.18f,
ProjectileSpeed: 310f,
SpreadRad: 0.02f,
BurstCount: 1);
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<ModuleSpec> HumanModules = new[]
{
Mg762, Autocannon, Flak, Recoilless, DieselCore, TurboCore, CopperRad, WeldedPlate
};
public static readonly IReadOnlyList<ModuleSpec> ImperialModules = new[]
{
GildedLance, TouringPlasma, GoldRadiator, NobleCore, GildedPlate
};
public static readonly IReadOnlyList<ModuleSpec> AllModules = new[]
{
Mg762, Autocannon, Flak, Recoilless, DieselCore, TurboCore, CopperRad, WeldedPlate,
GildedLance, TouringPlasma, GoldRadiator, NobleCore, GildedPlate
};
public static ChassisGrid CreateStarterBuggy()
{
var grid = new ChassisGrid(Buggy);
grid.TryMount(Mg762, "wpn_roof");
grid.TryMount(DieselCore, "eng_mid");
grid.TryMount(CopperRad, "rad_rear");
return grid;
}
}
}

View file

@ -0,0 +1,913 @@
using System;
using System.Collections.Generic;
namespace RustToDust.Core
{
public enum GridPlane
{
Dorsal,
Coronal
}
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);
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)
{
/// <summary>
/// Exact Aetheria trapezoidal plateau curve:
/// 0 outside [MinTemp, MaxTemp], 1 on [OptimalTemp - PlateauWidth/2, OptimalTemp + PlateauWidth/2],
/// linear ramp between bounds and plateau.
/// </summary>
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)
{
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<MountedModule> Mounted { get; } = new();
public List<ModuleSpec> Cargo { get; } = new();
public float CoreHp { get; private set; }
public float MaxCoreHp { get; private set; }
public bool IsDestroyed => CoreHp <= 0f;
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 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<ModuleSpec>? 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<ModuleSpec>? 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 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);
}
return new HitResult(cx, cy, absorbed, spill, IsDestroyed);
}
public List<ModuleSpec> SwapChassis(ChassisSpec next)
{
if (next is null)
{
throw new ArgumentNullException(nameof(next));
}
var previousMounted = new List<ModuleSpec>(Mounted.Count);
for (int i = 0; i < Mounted.Count; i++)
{
previousMounted.Add(Mounted[i].Spec);
}
var previousCargo = new List<ModuleSpec>(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<ModuleSpec>();
// 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 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);
}
}
}
}

View file

@ -0,0 +1,360 @@
using System;
namespace RustToDust.Core
{
public static class MatchRules
{
public static float NormalizeAngle(float rad)
{
while (rad > MathF.PI) rad -= MathF.Tau;
while (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.FireCmd = false;
player.BrakeCmd = true;
return;
}
player.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f);
player.SteerCmd = Math.Clamp(input.Steer, -1f, 1f);
player.AimX = input.AimWorldX;
player.AimZ = input.AimWorldZ;
player.FireCmd = input.Fire;
player.BrakeCmd = input.Brake;
if (input.InteractPickup)
{
if (!state.TryPickupNearbyModule(0))
{
state.TrySwapNearbyChassis(0);
}
}
}
public static void UpdateAiContenders(MatchState state, float dt)
{
float safeLimit = MathF.Max(15f, state.Spectators.SafeRadius - 10f);
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) * 20f;
float aimZ = ai.Z + MathF.Cos(ai.Yaw) * 20f;
// 1. Stay inside the shrinking Safe Circle
if (distFromCenter > safeLimit)
{
goalX = 0f;
goalZ = 0f;
hasGoal = true;
}
// 2. Find nearest hostile contender
ContenderState? target = null;
float bestEnemyDistSq = 90f * 90f;
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)
{
bestEnemyDistSq = d2;
target = other;
}
}
// 3. Scavenge nearby upgrades when safe
if (!hasGoal && ai.AiScavengeCooldown <= 0f)
{
GroundDrop? bestDrop = null;
float bestDropDistSq = 34f * 34f;
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 <= 72f;
if (!hasGoal)
{
if (dist > 34f)
{
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) * 26f;
goalZ = target.Z + MathF.Sin(tangentAngle) * 26f;
}
hasGoal = true;
}
}
else if (!hasGoal && state.LastGunfireX.HasValue && state.LastGunfireZ.HasValue &&
state.Time - state.LastGunfireTime < 8f)
{
goalX = state.LastGunfireX.Value;
goalZ = state.LastGunfireZ.Value;
hasGoal = true;
}
else if (!hasGoal)
{
float patrolAngle = ai.Id * 0.9f + state.Time * 0.15f;
float r = MathF.Min(safeLimit * 0.65f, 45f);
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;
ai.AimX = aimX;
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.GetPerimeterSlot(spec);
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.GetPerimeterSlot(spec);
aimX = 0f;
aimZ = 0f;
shouldFire = false;
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 <= 115f;
// 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
};
}
}
}

View file

@ -0,0 +1,400 @@
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);
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 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;
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 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 bool FireCmd { get; set; }
public bool BrakeCmd { get; set; }
public float AiScavengeCooldown { get; set; }
public bool Alive => !Grid.IsDestroyed;
}
public sealed class MatchState
{
public const int ContenderCount = 8;
public const float ArenaHalfExtent = 195f;
public const float PickupRadius = 6.5f;
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<ContenderState> Contenders { get; } = new();
public SpectatorRing Spectators { get; }
public List<GroundDrop> GroundDrops { get; } = new();
public List<TracerEvent> Tracers { get; } = new();
public BroadcastFeed Broadcast { get; }
public IReadOnlyList<ArenaBoxSpec> ArenaCoverBoxes { get; }
public IReadOnlyList<ArenaBoxSpec> ArenaBoundaryBoxes { get; }
public float? LastGunfireX { get; set; }
public float? LastGunfireZ { get; set; }
public float LastGunfireTime { get; set; } = -100f;
public ContenderState Player => Contenders[0];
public event Action<ContenderState>? ChassisSwapped;
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<ModuleSpec>();
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 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;
}
}
if (nearest is null || nearest.Module is null)
{
return false;
}
if (!contender.Grid.TryAddCargo(nearest.Module))
{
return false;
}
nearest.PickedUp = true;
return true;
}
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;
}
}
if (nearest is null || nearest.Chassis is null)
{
return false;
}
var oldChassis = contender.Grid.Spec;
var overflow = contender.Grid.SwapChassis(nearest.Chassis);
nearest.PickedUp = true;
// Leave old hull behind and drop overflow modules around the swap site
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.Y = Terrain.SampleHeight(contender.X, contender.Z) + contender.Grid.Spec.HalfHeight + 0.15f;
Broadcast.EmitChassisSwap(Time, contender.Id, contender.Grid.Spec.Name);
ChassisSwapped?.Invoke(contender);
return true;
}
private void SpawnContenders()
{
// Spawn 8 contenders evenly around an inner ring (radius 95m, well inside SafeRadius = 150m)
const float spawnRadius = 95f;
for (int i = 0; i < ContenderCount; i++)
{
float angle = (i / (float)ContenderCount) * MathF.Tau;
float x = MathF.Cos(angle) * spawnRadius;
float z = MathF.Sin(angle) * spawnRadius;
float yaw = MathF.Atan2(-x, -z);
string name = i == 0 ? "Contender 01 (You)" : $"Contender {i + 1:00}";
var contender = new ContenderState(i, name, i == 0, Catalog.CreateStarterBuggy(), x, z, yaw);
contender.Y = Terrain.SampleHeight(x, z) + contender.Grid.Spec.HalfHeight + 0.15f;
Contenders.Add(contender);
}
}
private void ScatterInitialLoot()
{
// Deterministic chassis wrecks across arena ruins
(ChassisSpec Spec, float X, float Z)[] chassisPlacements =
{
(Catalog.Technical, 45f, 35f),
(Catalog.Technical, -52f, -28f),
(Catalog.Tank, 12f, -68f),
(Catalog.Manticore, -42f, 54f),
(Catalog.Raptor, 64f, -40f),
(Catalog.Paladin, 0f, 18f)
};
foreach (var (spec, x, z) in chassisPlacements)
{
SpawnChassisDrop(x, z, spec);
}
// Deterministic salvage module crates
ModuleSpec[] salvagePool =
{
Catalog.Autocannon, Catalog.Flak, Catalog.Recoilless,
Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate,
Catalog.Autocannon, Catalog.Flak, Catalog.TurboCore,
Catalog.WeldedPlate, Catalog.CopperRad, Catalog.Mg762
};
for (int i = 0; i < salvagePool.Length; i++)
{
float angle = (i / (float)salvagePool.Length) * MathF.Tau + 0.25f;
float r = 24f + (i % 3) * 26f;
SpawnModuleDrop(MathF.Cos(angle) * r, MathF.Sin(angle) * r, salvagePool[i]);
}
}
private static IReadOnlyList<ArenaBoxSpec> BuildCoverBoxes()
{
// 16 deterministic ruin walls / cover blocks placed clear of the 95m spawn ring and (0,0) center wreck
return new ArenaBoxSpec[]
{
new(28f, 1.8f, 16f, 4.5f, 1.8f, 1.4f, false),
new(-28f, 1.8f, -16f, 4.5f, 1.8f, 1.4f, false),
new(16f, 1.8f, -32f, 1.4f, 1.8f, 4.5f, false),
new(-16f, 1.8f, 32f, 1.4f, 1.8f, 4.5f, false),
new(58f, 2.2f, 18f, 3.2f, 2.2f, 3.2f, false),
new(-58f, 2.2f, -18f, 3.2f, 2.2f, 3.2f, false),
new(22f, 2.2f, 62f, 5.0f, 2.2f, 1.6f, false),
new(-22f, 2.2f, -62f, 5.0f, 2.2f, 1.6f, false),
new(72f, 1.6f, -52f, 2.8f, 1.6f, 2.8f, false),
new(-72f, 1.6f, 52f, 2.8f, 1.6f, 2.8f, false),
new(46f, 2.0f, -72f, 4.0f, 2.0f, 1.5f, false),
new(-46f, 2.0f, 72f, 4.0f, 2.0f, 1.5f, false),
new(118f, 2.4f, 24f, 3.5f, 2.4f, 3.5f, false),
new(-118f, 2.4f, -24f, 3.5f, 2.4f, 3.5f, false),
new(24f, 2.4f, -118f, 3.5f, 2.4f, 3.5f, false),
new(-24f, 2.4f, 118f, 3.5f, 2.4f, 3.5f, false)
};
}
private static IReadOnlyList<ArenaBoxSpec> SeatBoxesOnTerrain(IReadOnlyList<ArenaBoxSpec> 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<ArenaBoxSpec> BuildBoundaryBoxes()
{
const float wallY = 2f;
const float wallHalfH = 10f;
const float wallHalfThick = 2f;
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)
};
}
}
}

View file

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,405 @@
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);
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 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 = 150f;
public const float MinRadius = 35f;
public const float GraceDuration = 20f;
public const float ShrinkDuration = 240f;
public const int DefaultSpectatorCount = 40;
private readonly List<SpectatorState> _spectators = new();
private readonly Dictionary<int, bool> _aliveById = 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<SpectatorState> 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<RingContact> contenders)
{
_aliveById.Clear();
for (int i = 0; i < contenders.Length; i++)
{
_aliveById[contenders[i].Id] = contenders[i].Alive;
}
// Keep Provoked lock while target is alive; reset Cleared to Neutral for clean re-evaluation.
for (int i = 0; i < _spectators.Count; i++)
{
var spec = _spectators[i];
if (!spec.Alive)
{
spec.TargetContenderId = null;
continue;
}
if (spec.Stance == SpectatorStance.Provoked)
{
if (!spec.TargetContenderId.HasValue ||
!_aliveById.TryGetValue(spec.TargetContenderId.Value, out bool alive) ||
!alive)
{
spec.Stance = SpectatorStance.Neutral;
spec.TargetContenderId = null;
}
}
else
{
spec.Stance = SpectatorStance.Neutral;
spec.TargetContenderId = null;
}
}
// Assign Cleared spectators to contenders outside the Safe Circle.
for (int c = 0; c < contenders.Length; c++)
{
var contender = contenders[c];
if (!contender.Alive)
{
continue;
}
float distFromCenter = MathF.Sqrt(contender.X * contender.X + contender.Z * contender.Z);
float outsideDist = MathF.Max(0f, distFromCenter - SafeRadius);
if (outsideDist <= 0f)
{
continue;
}
int allowedCleared = Math.Min(8, 1 + (int)(outsideDist / 12f));
for (int k = 0; k < allowedCleared; k++)
{
SpectatorState? nearest = null;
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 - contender.X;
float dz = spec.Z - contender.Z;
float d2 = dx * dx + dz * dz;
if (d2 < bestDistSq)
{
bestDistSq = d2;
nearest = spec;
}
}
if (nearest is null)
{
break;
}
nearest.Stance = SpectatorStance.Cleared;
nearest.TargetContenderId = contender.Id;
}
}
}
public bool OnSpectatorDamaged(SpectatorState spectator, int attackerContenderId)
{
if (!spectator.Alive)
{
return false;
}
if (spectator.Stance == SpectatorStance.Neutral || spectator.Stance == SpectatorStance.Cleared)
{
spectator.Stance = SpectatorStance.Provoked;
spectator.TargetContenderId = attackerContenderId;
return true;
}
return false;
}
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;
}
float angularSpeed = spec.Tier == SpectatorTier.Exemplar ? 0.045f : 0.02f;
spec.RingAngle += angularSpeed * 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 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<ModuleSpec> RollSalvageDrops(SpectatorState spec, Random rng)
{
var drops = new List<ModuleSpec>();
switch (spec.Tier)
{
case SpectatorTier.Tourist:
{
// Guaranteed 1-2 Imperial high-end modules
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:
{
// Mixed salvage: 1 module (50% imperial, 50% human upgraded)
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:
{
// Minimal/no high-end loot: only an occasional modest scrap trophy (never IsImperial)
if (rng.NextDouble() < 0.4)
{
drops.Add(Catalog.WeldedPlate);
}
break;
}
}
return drops;
}
private void SpawnRing(Random rng, int count)
{
// ~45% Tourists, ~35% Patrons, ~20% Exemplars
int touristCount = (int)MathF.Round(count * 0.45f);
int patronCount = (int)MathF.Round(count * 0.35f);
var tiers = new List<SpectatorTier>(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);
}
// Deterministic shuffle so tiers are evenly distributed around the perimeter
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 = 10f + (float)rng.NextDouble() * 16f;
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, "wpn_larm");
MountRequired(grid, Catalog.TouringPlasma, "wpn_lsh");
MountRequired(grid, Catalog.NobleCore, "eng_core");
MountRequired(grid, Catalog.GoldRadiator, "rad_l");
MountRequired(grid, Catalog.GildedPlate, "arm_collar");
return new SpectatorState(
id, tier, grid, angle, ringOffset,
radarSignature: 1.0f,
aimSpreadRad: 0.14f,
maxSpeed: 16f,
preferredRange: 42f);
}
case SpectatorTier.Patron:
{
var grid = new ChassisGrid(Catalog.Raptor);
MountRequired(grid, Catalog.Autocannon, "wpn_larm");
MountRequired(grid, Catalog.Flak, "wpn_rarm");
MountRequired(grid, Catalog.TurboCore, "eng_chest");
MountRequired(grid, Catalog.CopperRad, "rad_lsh");
return new SpectatorState(
id, tier, grid, angle, ringOffset,
radarSignature: 0.6f,
aimSpreadRad: 0.055f,
maxSpeed: 24f,
preferredRange: 36f);
}
default: // Exemplar
{
// Lightly armored, lethal precision, blazing speed
var exemplarSpec = Catalog.Raptor with
{
Id = "exemplar_frame",
Name = "Exemplar Frame",
BaseCellArmor = 22f,
MassKg = 1150f,
BaseThrust = 26000f,
BaseTurnRate = 6.2f,
MaxSpeed = 38f,
HalfWidth = 0.8f,
HalfHeight = 1.55f,
HalfLength = 0.8f
};
var grid = new ChassisGrid(exemplarSpec);
MountRequired(grid, Catalog.GildedLance, "wpn_rarm");
MountRequired(grid, Catalog.TouringPlasma, "wpn_larm");
MountRequired(grid, Catalog.NobleCore, "eng_chest");
MountRequired(grid, Catalog.GoldRadiator, "rad_lsh");
MountRequired(grid, Catalog.GoldRadiator, "rad_rsh");
return new SpectatorState(
id, tier, grid, angle, ringOffset,
radarSignature: 0.22f,
aimSpreadRad: 0.006f,
maxSpeed: 38f,
preferredRange: 24f);
}
}
}
}
}

View file

@ -0,0 +1,583 @@
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 = 384f;
public const float HalfExtent = 192f;
public const int TileGridCount = 4;
public const float TileSize = ArenaSize / TileGridCount; // 96m
public const float MinWorldHeight = -12f;
public const float MaxWorldHeight = 16f;
public const int MaxDynamicDecals = 256;
private readonly List<TerrainBrush> _brushes = new();
private readonly List<int>[,] _tileBrushIndices = new List<int>[TileGridCount, TileGridCount];
private readonly Queue<int> _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<int>(24);
}
}
}
public ulong Seed { get; }
public IReadOnlyList<TerrainBrush> Brushes => _brushes;
public int[,] TileVersions { get; }
public uint DirtyTileMask { get; private set; }
public void ClearDirtyMask() => DirtyTileMask = 0u;
public IReadOnlyList<int> GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz];
public static TerrainField Generate(ulong seed, IReadOnlyList<ArenaBoxSpec> 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: 16f,
RadiusZ: 16f,
HeightDelta: 0.15f,
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) + 7.5f;
field.AddBrush(new TerrainBrush(
Id: 0,
Kind: TerrainBrushKind.SalvagePad,
X: box.X,
Z: box.Z,
RotationRad: 0f,
RadiusX: padR,
RadiusZ: padR,
HeightDelta: 0.1f + (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-arena loop (r ~ 76..92m)
const int roadCount = 8;
for (int i = 0; i < roadCount; i++)
{
float angle = (i / (float)roadCount) * MathF.Tau + 0.18f;
float r = 82f + (float)(rng.NextDouble() * 8.0 - 4.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: 34f,
RadiusZ: 9f,
HeightDelta: -0.18f,
Roughness: 0.94f,
Metallic: 0.02f,
AlbedoR: 0.56f,
AlbedoG: 0.40f,
AlbedoB: 0.25f,
Dynamic: false));
}
// 3. Sweeping desert dune ridges (~20 ridges + 2 dry-wash troughs), kept clear of cover box pads
int duneCount = 0;
int attempts = 0;
while (duneCount < 20 && attempts < 360)
{
attempts++;
float x = (float)(rng.NextDouble() * 300.0 - 150.0);
float z = (float)(rng.NextDouble() * 300.0 - 150.0);
float radiusX = 12f + (float)rng.NextDouble() * 11f;
float radiusZ = 24f + (float)rng.NextDouble() * 22f;
if (MathF.Abs(field.SampleHeight(x, z)) > 1.8f)
{
continue;
}
bool dryWash = duneCount is 5 or 13;
float heightDelta = dryWash
? -(1.2f + (float)rng.NextDouble() * 0.9f)
: 1.6f + (float)rng.NextDouble() * 2.0f;
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: dryWash ? 0.96f : 0.89f,
Metallic: 0.02f,
AlbedoR: dryWash ? 0.58f : 0.78f,
AlbedoG: dryWash ? 0.41f : 0.56f,
AlbedoB: dryWash ? 0.27f : 0.34f,
Dynamic: false);
if (!IsBrushClearOfCover(in candidate, coverBoxes))
{
continue;
}
field.AddBrush(candidate);
duneCount++;
}
// 4. Terraced rust-mesa hills (~7 mesas), mainly mid/outer desert away from spawns & cover
int mesaCount = 0;
attempts = 0;
while (mesaCount < 7 && attempts < 200)
{
attempts++;
float angle = (float)(rng.NextDouble() * MathF.Tau);
float dist = 54f + (float)rng.NextDouble() * 116f;
float x = MathF.Cos(angle) * dist;
float z = MathF.Sin(angle) * dist;
float rx = 14f + (float)rng.NextDouble() * 10f;
float rz = 13f + (float)rng.NextDouble() * 10f;
if (OverlapsSpawnRing(x, z, MathF.Max(rx, rz) + 5f) ||
MathF.Abs(field.SampleHeight(x, z)) > 1.6f)
{
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: 3.1f + (float)rng.NextDouble() * 2.4f,
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++;
}
// 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 |= 1u << (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)
{
var brush = 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));
_ = brush;
}
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++)
{
var b = _brushes[indices[i]];
if (b.Kind == TerrainBrushKind.Scorch)
{
continue;
}
h += EvaluateBrushHeight(in b, 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)
{
const float stepSize = 1.5f;
float prevT = 0f;
float prevDiff = oy - SampleHeight(ox, oz);
if (prevDiff <= 0f)
{
hitX = ox;
hitY = oy;
hitZ = oz;
hitDist = 0f;
return true;
}
for (float t = stepSize; t <= maxDistance + stepSize; t += stepSize)
{
float ct = MathF.Min(t, maxDistance);
float px = ox + dx * ct;
float py = oy + dy * ct;
float pz = oz + dz * ct;
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;
prevDiff = diff;
if (ct >= maxDistance)
{
break;
}
}
hitX = 0f;
hitY = 0f;
hitZ = 0f;
hitDist = maxDistance;
return false;
}
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;
}
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);
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;
RegisterBrushInTiles(slot, in brush, incrementTileVersion: true);
_dynamicDecalSlots.Enqueue(slot);
return brush;
}
int index = _brushes.Count;
_brushes.Add(brush);
RegisterBrushInTiles(index, in brush, incrementTileVersion: true);
_dynamicDecalSlots.Enqueue(index);
return brush;
}
private void RegisterBrushInTiles(int index, in TerrainBrush brush, bool incrementTileVersion)
{
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);
if (incrementTileVersion)
{
TileVersions[tx, tz]++;
DirtyTileMask |= 1u << (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);
TileVersions[tx, tz]++;
DirtyTileMask |= 1u << (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 = 1.0f;
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<ArenaBoxSpec> coverBoxes)
{
if (MathF.Abs(EvaluateBrushHeight(in candidate, 0f, 0f)) > 0.35f)
{
return false;
}
const float margin = 1.5f;
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.35f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X - hx, c.Z - hz)) > 0.35f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X + hx, c.Z - hz)) > 0.35f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X - hx, c.Z + hz)) > 0.35f ||
MathF.Abs(EvaluateBrushHeight(in candidate, c.X + hx, c.Z + hz)) > 0.35f)
{
return false;
}
}
return true;
}
private static bool OverlapsSpawnRing(float x, float z, float radius)
{
float dist = MathF.Sqrt(x * x + z * z);
return MathF.Abs(dist - 95f) < radius + 6f;
}
}
}

View file

@ -0,0 +1,951 @@
using System;
using System.Collections.Generic;
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 = 256;
private const ulong GroundStableId = 1;
private const ulong StaticBoxStableIdBase = 10;
private const ulong ContenderStableIdBase = 1000;
private const ulong SpectatorStableIdBase = 3000;
private readonly Box3DSoaWorld _world;
private readonly Dictionary<int, Box3DSoaBodyHandle> _contenderBodies = new();
private readonly Dictionary<int, Box3DSoaBodyHandle> _spectatorBodies = new();
private readonly Dictionary<ulong, (bool IsContender, int Index)> _entityByStableId = new();
private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount];
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();
}
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 Step(PlayerInput input)
{
ObjectDisposedException.ThrowIf(_disposed, this);
State.Time += FixedDt;
MatchRules.AdvanceTracers(State, FixedDt);
State.Spectators.UpdateSafeRadius(State.Time);
State.Spectators.AdvancePerimeterOrbits(FixedDt);
UpdateRingClearance();
MatchRules.ApplyPlayerInput(State, input);
MatchRules.UpdateAiContenders(State, FixedDt);
ApplyPhysicsDrives();
_world.Step(FixedDt, SubStepCount);
SyncBodiesFromWorld();
StepThermalAndCooldowns();
ProcessWeapons();
MatchRules.UpdateMatchOutcome(State);
}
private void BuildStaticArena()
{
// Safety floor slab at y = -12m below the lowest possible terrain valley;
// primary terrain support comes from 4-corner spring-damper sampling of State.Terrain.
_world.AddStaticBox(
GroundStableId,
(0f, -13f, 0f),
(210f, 1f, 210f),
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 spawnY = State.Terrain.SampleHeight(c.X, c.Z) + spec.HalfHeight + 0.15f;
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);
}
}
private void SpawnSpectatorBodies()
{
for (int i = 0; i < State.Spectators.Spectators.Count; i++)
{
var s = State.Spectators.Spectators[i];
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, i);
}
}
private void UpdateRingClearance()
{
Span<RingContact> 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);
}
State.Spectators.UpdateClearance(contacts);
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 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]);
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;
// Drive thrust along slope-aligned forward with smooth terminal velocity drag at MaxSpeed
force += driveForward * (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 targetUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, 0.85f));
Vector3 tiltAxis = Vector3.Cross(up, targetUp);
Vector3 torque = supportTorque + tiltAxis * (mass * 16f) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6f);
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 targetUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, 0.7f));
Vector3 tiltAxis = Vector3.Cross(up, targetUp);
Vector3 torque = supportTorque + tiltAxis * (mass * 16f) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6f);
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 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;
float hx = spec.HalfWidth * 0.9f;
float hz = spec.HalfLength * 0.9f;
float bottomY = -spec.HalfHeight;
const float restTravel = 0.12f;
float kSpring = mass * 50f;
float cDamp = mass * 7.0f;
Span<Vector3> 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++;
float vCornerY = vel.Y + Vector3.Cross(angVel, r).Y;
float fY = Math.Clamp(kSpring * pen - cDamp * vCornerY, 0f, mass * 120f);
supportForce.Y += fY;
supportTorque += Vector3.Cross(r, new Vector3(0f, fY, 0f));
}
}
var (nx, ny, nz) = State.Terrain.SampleNormal(pos.X, pos.Z);
terrainNormal = new Vector3(nx, ny, nz);
}
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 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 || !c.FireCmd || !_contenderBodies.TryGetValue(c.Id, out var handle))
{
continue;
}
ulong shooterStableId = ContenderStableIdBase + (ulong)c.Id;
FireMountedWeapons(
shooterStableId,
shooterContender: c,
shooterLabel: c.Name,
isSpectatorShooter: false,
shooterGrid: c.Grid,
shooterPos: new Vector3(c.X, c.Y, c.Z),
shooterYaw: c.Yaw,
aimX: c.AimX,
aimZ: c.AimZ,
extraSpread: 0f,
view: 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 _))
{
continue;
}
MatchRules.ComputeSpectatorBehavior(s, State, out _, out _, out float aimX, out float aimZ, out bool shouldFire);
if (!shouldFire)
{
continue;
}
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,
aimX: aimX,
aimZ: aimZ,
extraSpread: s.AimSpreadRad,
view: view);
}
}
private void FireMountedWeapons(
ulong shooterStableId,
ContenderState? shooterContender,
string shooterLabel,
bool isSpectatorShooter,
ChassisGrid shooterGrid,
Vector3 shooterPos,
float shooterYaw,
float aimX,
float aimZ,
float extraSpread,
Box3DSoaView view)
{
float targetY = ResolveAimTargetY(aimX, aimZ, shooterStableId);
for (int m = 0; m < shooterGrid.Mounted.Count; m++)
{
var mod = shooterGrid.Mounted[m];
if (mod.Spec.Kind != HardpointKind.Weapon || mod.Cooldown > 0f || mod.CurrentPerformance <= 0.05f)
{
continue;
}
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) * shooterGrid.Spec.HalfWidth +
MathF.Abs(localDirZ) * shooterGrid.Spec.HalfLength +
0.35f;
Vector3 muzzle = new Vector3(
shooterPos.X + horizDir.X * clearance,
shooterPos.Y + shooterGrid.Spec.HalfHeight * 0.25f,
shooterPos.Z + horizDir.Z * clearance);
Vector3 baseAim = new Vector3(aimX - muzzle.X, targetY - muzzle.Y, aimZ - muzzle.Z);
if (baseAim.LengthSquared() < 1e-4f)
{
baseAim = horizDir;
}
else
{
baseAim = Vector3.Normalize(baseAim);
}
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 : 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)
{
bool newlyProvoked = State.Spectators.OnSpectatorDamaged(spec, shooterContender.Id);
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();
}
}
}

View file

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RustToDust.Core\RustToDust.Core.csproj" />
<ProjectReference Include="$(YmirRoot)/src/Ymir.Box3D/Ymir.Box3D.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,132 @@
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("wpn_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);
// Cover block #0 sits at (28, 1.8, 16) with half-extents (4.5, 1.8, 1.4).
// A ray from one side (28, 1.0, 10) to the other side (28, 1.0, 22) must hit the static cover wall!
var blockedHit = session.World.CastRayClosest((28f, 1.0f, 10f), (0f, 0f, 15f));
Assert.True(blockedHit.Hit);
Assert.True(blockedHit.Point.Z < 16f, $"Expected cover hit before z=16, got z={blockedHit.Point.Z:F2}");
Assert.InRange(blockedHit.StableId, 10UL, 99UL); // Static cover StableId range
// Ray high above the cover block (y = 5.0 > 3.6 top) passes unobstructed
var clearHit = session.World.CastRayClosest((28f, 5.0f, 10f), (0f, 0f, 15f));
Assert.False(clearHit.Hit);
}
[Fact]
public void BroadsideFire_UsesDirectionalSupportRadiusNotMaxExtent()
{
using var session = new ArenaSession(seed: 19);
var player = session.State.Player;
// Swap to Tank (HalfWidth = 1.65m, HalfLength = 2.65m) where broadside vs forward differs by 1.0m.
session.State.SpawnChassisDrop(player.X + 0.5f, player.Z + 0.5f, Catalog.Tank);
Assert.True(session.TrySwapNearbyChassis());
Assert.Equal("tank", 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);
}
}
}

View file

@ -0,0 +1,128 @@
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();
// wpn_roof is at (1, 0). Neighbor (0, 0) and (1, 1) start at ambient 20f.
grid.InjectHardpointHeat("wpn_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, 1]);
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, 1] > 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()
{
// Tank has 2x2 turret hardpoint: smaller 1x1 weapon fits loosely; 2x2 weapon must NOT fit 1x1 buggy roof.
var tankGrid = new ChassisGrid(Catalog.Tank);
Assert.True(tankGrid.TryMount(Catalog.Recoilless, "wpn_turret")); // 2x2 into 2x2
Assert.True(tankGrid.TryMount(Catalog.Mg762, "wpn_coax")); // 1x1 into 1x1
Assert.True(tankGrid.TryMount(Catalog.TurboCore, "eng_rear")); // 1x2 into 2x2
Assert.True(tankGrid.TryMount(Catalog.GoldRadiator, "rad_deck")); // 1x1 into 1x1
Assert.True(tankGrid.TryMount(Catalog.WeldedPlate, "arm_glacis")); // 1x1 into 2x1
Assert.True(tankGrid.TryMount(Catalog.GildedPlate, "arm_skirt")); // 1x1 into 1x1
// Fill cargo near buggy capacity (4) so swapping down to Buggy overflows to ground!
Assert.True(tankGrid.TryAddCargo(Catalog.Flak));
Assert.True(tankGrid.TryAddCargo(Catalog.CopperRad));
List<ModuleSpec> dropped = tankGrid.SwapChassis(Catalog.Buggy);
// Buggy has 1x1 Weapon (mg_762 fits, recoilless 2x2 does not!), 1x1 Engine (turbo_core 1x2 does not fit!), 1x1 Radiator (gold_radiator fits!), 0 Armor hardpoints.
Assert.Equal("buggy", tankGrid.Spec.Id);
Assert.Contains(tankGrid.Mounted, m => m.Spec.Id == "mg_762");
Assert.Contains(tankGrid.Mounted, m => m.Spec.Id == "gold_radiator");
Assert.DoesNotContain(tankGrid.Mounted, m => m.Spec.Id == "recoilless");
// 6 mounted on Tank: 2 transferred (mg_762, gold_radiator), 4 leftover + 2 cargo = 6 items -> 4 in Buggy Cargo, 2 dropped!
Assert.Equal(Catalog.Buggy.CargoCapacity, tankGrid.Cargo.Count);
Assert.Equal(2, dropped.Count);
}
}
}

View file

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RustToDust.Core\RustToDust.Core.csproj" />
<ProjectReference Include="..\..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,149 @@
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; // 150f
// 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);
}
}
}

View file

@ -0,0 +1,211 @@
using System;
using System.Collections.Generic;
using RustToDust.Core;
using RustToDust.Ymir;
using Xunit;
namespace RustToDust.Tests
{
public sealed class TerrainTests
{
[Fact]
public void Generate_ProducesDeterministicNonFlatReliefWithinBounds()
{
var emptyCover = Array.Empty<ArenaBoxSpec>();
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 = -160; gx <= 160; gx += 16)
{
for (int gz = -160; gz <= 160; gz += 16)
{
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 > 2.5f, $"Expected non-flat dune/mesa relief > 2.5m span, got [{minH:F2}, {maxH:F2}]");
Assert.InRange(minH, -4.5f, 1.0f);
Assert.InRange(maxH, 2.0f, 9.5f);
Assert.True(anyDifferentSeed, "Different seeds should generate distinct desert relief");
}
[Fact]
public void StampCrater_LowersCenterRaisesRimAndDirtyOnlyOverlappingTiles()
{
var terrain = TerrainField.Generate(42UL, Array.Empty<ArenaBoxSpec>());
terrain.ClearDirtyMask();
// Tile (1, 1) spans X in [-96, 0), Z in [-96, 0).
// Point (-48, -48) with radius 6m is strictly inside tile (1, 1) and nowhere else.
const float cx = -48f;
const float cz = -48f;
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 (1, 1) 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 == 1 && tz == 1) ? 2 : 1;
Assert.Equal(expected, terrain.TileVersions[tx, tz]);
}
}
Assert.Equal(1u << (1 * TerrainField.TileGridCount + 1), terrain.DirtyTileMask);
}
[Fact]
public void StampTrack_BoundsDynamicDecalCount()
{
var terrain = TerrainField.Generate(7UL, Array.Empty<ArenaBoxSpec>());
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.True(maxCoverCornerDelta <= 0.5f,
$"Expected MaxCoverCornerDelta <= 0.5m for seed {seed}, got {maxCoverCornerDelta:F3}m");
}
[Fact]
public void RoadBrushes_MajorAxisRunsTangentiallyToFormRingLoop()
{
var terrain = TerrainField.Generate(42UL, Array.Empty<ArenaBoxSpec>());
var roads = new List<TerrainBrush>();
for (int i = 0; i < terrain.Brushes.Count; i++)
{
if (terrain.Brushes[i].Kind == TerrainBrushKind.Road)
{
roads.Add(terrain.Brushes[i]);
}
}
Assert.Equal(8, 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}");
}
}
}
}

View file

@ -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()

View file

@ -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()

View file

@ -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()

View file

@ -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()

View file

@ -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()

View file

@ -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()

View file

@ -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()

View file

@ -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()

View file

@ -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()

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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("<III", data, 0)
if magic != 0x46546C67 or version != 2:
raise AssertionError(f"{glb_path}: invalid GLB header magic={hex(magic)} version={version}")
if total_len != len(data):
raise AssertionError(f"{glb_path}: header length {total_len} != file size {len(data)}")
chunk_len, chunk_type = struct.unpack_from("<II", data, 12)
if chunk_type != 0x4E4F534A:
raise AssertionError(f"{glb_path}: first chunk is not JSON ({hex(chunk_type)})")
gltf = json.loads(data[20 : 20 + chunk_len].decode("utf-8"))
bin_off = 20 + chunk_len
bin_blob = b""
if bin_off + 8 <= len(data):
b_len, b_type = struct.unpack_from("<II", data, bin_off)
if b_type == 0x004E4942:
bin_blob = data[bin_off + 8 : bin_off + 8 + b_len]
return gltf, bin_blob
def parse_glb_json(glb_path: Path) -> 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="<f4", count=count * 3, offset=off).reshape(count, 3)
else:
raw = np.frombuffer(bin_blob, dtype=np.uint8, count=count * stride, offset=off).reshape(count, stride)
pts = raw[:, :12].view("<f4").reshape(count, 3)
wc = pts @ world[:3, :3].T + world[:3, 3]
else:
pmin = np.array(acc["min"], dtype=np.float64)
pmax = np.array(acc["max"], dtype=np.float64)
corners = np.array([
[x, y, z, 1.0]
for x in (pmin[0], pmax[0])
for y in (pmin[1], pmax[1])
for z in (pmin[2], pmax[2])
], dtype=np.float64)
wc = (world @ corners.T).T[:, :3]
g_min = np.minimum(g_min, wc.min(axis=0))
g_max = np.maximum(g_max, wc.max(axis=0))
for child_idx in node.get("children", []):
walk(child_idx, world)
ident = np.eye(4, dtype=np.float64)
for r_idx in root_indices:
walk(r_idx, ident)
return tri_total, g_min, g_max
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="<f4", count=count * 3, offset=off).reshape(count, 3).astype(np.float64)
raw = np.frombuffer(bin_blob, dtype=np.uint8, count=count * stride, offset=off).reshape(count, stride)
return raw[:, :12].view("<f4").reshape(count, 3).astype(np.float64)
if typ == "SCALAR":
dtype = {5121: np.uint8, 5123: "<u2", 5125: "<u4"}[ct]
return np.frombuffer(bin_blob, dtype=dtype, count=count, offset=off).astype(np.int64)
raise ValueError(f"Unsupported accessor type={typ} componentType={ct}")
def _pt_tri_dist2(p: np.ndarray, a: np.ndarray, b: np.ndarray, c: np.ndarray) -> 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())