Prose Council Stage 4 repair: public glosses, core mechanism clarity, and spatial precision

This commit is contained in:
Meta Vens 2026-12-06 03:31:58 +01:00
commit 802af74b47
8 changed files with 107 additions and 116 deletions

View file

@ -11,11 +11,9 @@ To remove widget-tree overhead from the combat frame, `RustToDust.HbGpu` and `Hb
## Native `rtd_hbgpu.dll` Footprint
The C17 shim under `native/rtd_hbgpu/` links HarfBuzz 15.2.0 (`harfbuzz` + `harfbuzz-gpu`) statically and exports six functions for shader source retrieval, variable-font creation, UTF-16 shaping, glyph curve encoding, and 2D vector path encoding. `CMakeLists.txt` disables ICU, FreeType, Cairo, Glib, font subsetting, rasterization, and CPU vector backends, compiling with `/O2 /GL /Gy` and `/OPT:REF /OPT:ICF /LTCG`.
The C17 shim under `native/rtd_hbgpu/` links HarfBuzz 15.2.0 (`harfbuzz` and `harfbuzz-gpu`) statically and exports eight C functions covering version reporting, embedded shader retrieval, variable-font lifecycle, UTF-16 text shaping, glyph curve encoding, and 2D vector path encoding. `CMakeLists.txt` disables ICU, FreeType, Cairo, Glib, font subsetting, rasterization, and CPU vector backends, compiling with whole-program optimization (`/O2 /GL /Gy` and `/OPT:REF /OPT:ICF /LTCG`).
- **Binary footprint:** `1.37 MiB` on Win64.
- **OS imports:** Links only `KERNEL32.dll`.
- **Variable typeface:** Ships unmodified `Monaspace Krypton v1.400` (`Krypton.ttf`, `1,363,340` bytes, `2000` UPEM) for SIL OFL 1.1 compliance, queried across `(FontId, qWght, qWdth, qSlnt)` keys in `HbGpuFontCache`.
The resulting Win64 `rtd_hbgpu.dll` weighs **`1.37 MiB`** and imports only `KERNEL32.dll`. It loads unmodified `Monaspace Krypton v1.400` (`Krypton.ttf`, `1,363,340` bytes at `2000` units per em) in compliance with SIL Open Font License 1.1 redistribution terms, caching font instances in `HbGpuFontCache` by `(FontId, weight, width, slant)`.
## Atlas Partitioning & Upload Flow
@ -31,15 +29,15 @@ flowchart LR
D --> T["R8G8B8A8Unorm Texture2Drd (PremultAlpha)"]
```
- **2D integer atlas (`HB_GPU_ATLAS_2D`):** `HbGpuAtlasAllocator` manages `262,144` texels (`1024 × 256` `R16G16B16A16Sint`, `2.0 MiB` total). Texels `[0..229,376)` form a persistent region for cached glyphs and static vector icons, resetting at a `75%` occupancy watermark between frames. Texels `[229,376..262,144)` act as a per-frame ring for dynamic paths such as curved heat arcs.
- **Zero-allocation frame submission:** `Hud` maintains pre-allocated `_scratch` character arrays, pre-wrapped `_chyronDisplayLines`, and fixed quad/atlas staging buffers (`HbGpuQuadInstance[4096]`, `80` bytes per instance). `HbGpuNativeTests` and the headless `Smoke` suite assert `0 B` of managed heap allocations across steady-state `Hud.Sync` loops.
- **In-place GPU sync:** On the render thread, `HbGpuVulkanBackend` uploads only newly encoded atlas chunks via `TextureUpdate` and writes the active slice of `HbGpuQuadInstance` records into the storage buffer before issuing `DrawListDraw(instances: quadCount, proceduralVertexCount: 6)`.
`HbGpuAtlasAllocator` partitions a `1024 × 256` signed-integer texture (`HB_GPU_ATLAS_2D`, `R16G16B16A16Sint`, `262,144` texels or `2.0 MiB`) into two regions: texels `[0..229,376)` form a persistent cache for shaped glyphs and static icons that resets between frames once occupancy passes `75%`, while texels `[229,376..262,144)` act as a per-frame ring for transient geometry such as curved heat arcs.
On the CPU side, `Hud` maintains pre-allocated character scratch buffers, pre-wrapped broadcast chyron line caches, and fixed staging arrays (`4096` `HbGpuQuadInstance` records at `80` bytes each). Both `HbGpuNativeTests` and the headless `Smoke` suite assert `0 B` of managed heap allocations across steady-state `Hud.Sync` loops. On the render thread, `HbGpuVulkanBackend` pushes newly encoded atlas spans in place via `RenderingDevice.TextureUpdate`, uploads the active slice of the quad storage buffer, and issues one `DrawListDraw` call generating six procedural vertices per quad instance into a premultiplied `R8G8B8A8Unorm` `Texture2Drd`.
## Analytic `FlagSolidRect` Fast Path vs Slug Bezier Bands
HarfBuzz's `_hb_gpu_slug` fragment evaluator decodes quadratic Bezier bands from the integer atlas to compute exact analytical coverage for arbitrary curves. Running that band loop on every axis-aligned health bar, panel fill, and crosshair tick wastes ALU cycles on straight edges.
HarfBuzz's `_hb_gpu_slug` fragment evaluator decodes quadratic Bezier bands stored in the integer atlas at `v_blob_loc` to compute exact coverage for arbitrary curves. Running that band loop on every axis-aligned health bar, panel background, and crosshair tick spends unnecessary ALU cycles on straight edges.
`HbGpuQuadInstance` adds `FlagSolidRect` (`v_flags & 2u`), mapping every solid rectangle into em-space `[-500, 500]^2` and branching in the fragment shader:
`HbGpuQuadInstance` introduces `FlagSolidRect` (`v_flags & 2u`), mapping solid rectangles into em-space `[-500, 500]^2` and taking a direct analytic branch in the fragment shader, while glyphs and curved shapes enter `_hb_gpu_slug` with optional `hb_gpu_stem_darken` (`v_flags & 1u`):
```glsl
if ((v_flags & 2u) != 0u) {
@ -57,21 +55,16 @@ if ((v_flags & 2u) != 0u) {
}
```
Expressed mathematically, Euclidean box coverage for `FlagSolidRect` evaluates in four scalar ALU operations per fragment:
Euclidean box coverage for `FlagSolidRect` reduces to four scalar ALU operations per fragment:
$$\text{cov} = \text{clamp}\!\left(\min\!\left((500 - |v_{\text{em}}.x|)\,p_x,\ (500 - |v_{\text{em}}.y|)\,p_y\right) + 0.5,\ 0,\ 1\right)$$
where $p = (1 / \|\nabla v_{\text{em}}.x\|,\ 1 / \|\nabla v_{\text{em}}.y\|)$ is the screen-space derivative scale computed once from `dFdx`/`dFdy`. All remaining shapes—radar rings, target brackets, squad chevrons, and `Krypton.ttf` glyphs—route through `_hb_gpu_slug` with optional stem darkening.
On a GTX 1070 at `1080p`, the complete combat HUD pass executes in **`0.229 ms` GPU time** in **`1` draw call**.
where $p = (1 / \|\nabla v_{\text{em}}.x\|,\ 1 / \|\nabla v_{\text{em}}.y\|)$ is the inverse em-per-pixel Jacobian derived once from `dFdx` and `dFdy`. On a GTX 1070 at `1080p`, the entire combat HUD pass completes in **`0.229 ms` GPU time** in **`1` draw call**.
## Thermal Raster Under Vector Brackets
In the lower-left corner of the HUD, `InventoryGridControl` separates interior cell shading from vector overlays:
1. **`inventory_grid.gdshader` (interior raster):** Reads a nearest-filtered `3W × H` `data_tex` (armor/module tints, 8-bit neighbor mismatch mask for corner folding, cell flags, and hit-pulse flash) alongside a bilinear `W × H` `temp_tex` mapping `[20°C..200°C]` to a continuous thermal glow and 45° fracture hatching on stripped cells.
2. **`HbGpuCanvas` (vector overlay):** Draws hardpoint L-brackets, hull perimeters, stripped X-marks, compatibility highlights, and `W:25°` / `E:21°` / `R:20°` Krypton cell tags straight into the parent `Hud` draw call.
In the lower-left schematic panel, `InventoryGridControl` pairs a stateless interior cell shader (`inventory_grid.gdshader`) with `HbGpuCanvas` vector overlays. The interior shader samples a nearest-filtered `3W × H` metadata texture (encoding armor/module tints, an 8-bit neighbor mismatch mask for corner folding, cell flags, and hit flashes) together with a bilinear `W × H` thermal texture mapping `[20°C..200°C]` to continuous heat glow and `45°` fracture hatching across stripped cells. `HbGpuCanvas` then draws hardpoint L-brackets, hull outlines, stripped X-marks, compatibility highlights, and Krypton cell tags (`W` for Weapon, `E` for Engine, `R` for Radiator) into the parent HUD draw call.
## Planned Migration Off Godot Modal Controls
Pre-match menu screens (`MainMenu`, `LobbyScreen`, `ServerBrowser`, `SettingsOverlay`, and the `[F9]` network panel) still run on Godot `Control` nodes styled with `ImperialChrome` and `panel_chrome.gdshader`. Planned UI work lowers those modal screens and text inputs across the upcoming Thing 2 `thing_ffi` boundary onto `HbGpuCanvas` so the entire front end shares one rendering path.
Pre-match menu screens (`MainMenu`, `LobbyScreen`, `ServerBrowser`, `SettingsOverlay`, and the `[F9]` network debug panel) still rely on Godot `Control` nodes styled through `ImperialChrome` and `panel_chrome.gdshader`. Upcoming UI work migrates those modal panels and text inputs across the `thing_ffi` boundary into GameCult's `Thing 2` layout engine onto `HbGpuCanvas`, unifying the entire front end onto one renderer.

View file

@ -3,16 +3,16 @@ title: Architecture
description: Engineering teardowns and captures for Rust to Dust subsystems.
---
Six subsystem teardowns covering the live `RustToDust` engine stack (`Godot 4.7.2` Forward+ Vulkan, `Ymir.Box3D` ABI 22, `CultNet`, and `HarfBuzz 15.2.0` `hb-gpu`) along with active work in progress.
Six subsystem teardowns covering the live `RustToDust` engine stack (`Godot 4.7.2` Forward+ Vulkan, `Ymir.Box3D` rigid-body physics, `CultNet` multiplayer, and `HarfBuzz 15.2.0` `hb-gpu`), alongside two active systems still in build.
## Shipped Subsystems
1. **[Single-Draw-Call HarfBuzz `hb-gpu` Vulkan HUD](hbgpu-vulkan-hud.md)** — `rtd_hbgpu.dll` (`1.37 MiB`), the `1024×256` `R16G16B16A16Sint` atlas, analytic Euclidean-AA `FlagSolidRect` vs Slug Bezier bands, `0.229 ms` GPU / `1` draw call at `1080p` on GTX 1070, `inventory_grid.gdshader` thermal raster, and the upcoming Thing 2 `thing_ffi` UI seam.
2. **[0.5 m swisstopo DEM, Unified Compute Terrain & Tiled Box3D Physics](sion-dem-and-tiled-physics.md)** — `swissALTI3D` `6145×6145` `heightmap_05m.u16z`, shared `192 m` `16×16` lattice across `TerrainField`, `terrain_tile_bake.glsl` (`96`-slot LRU `Texture2Drd`, `0.37 ms/frame`), lazy `Box3DPhysicsTileSync`, and persistent `CultCache` `ArenaScarLedger` + `576 m` local geometry bubble.
3. **[Zero-Ambient SDFGI Lighting & Gradient-Offset Volumetric Plumes](sdfgi-lighting-and-volumetrics.md)** — Removing flat ambient lifters, tuning 3-cascade half-res SDFGI + AgX + `post_gamma=1.32` to `62 FPS` (`p95 = 13.28 ms`) on GTX 1070, gradient-offset `triNoise3d` volumetric plumes in `PostSky` compute, live `Settings → Graphics`, and `rtd_flow_field` advection.
4. **[Thermal Grid Chassis, Ballistics & Netcode (`CultNet` + `Ymir`)](thermal-grid-ballistics-netcode.md)** — Conductive 2D chassis grids, localized stripping and mid-match salvage, recursive `OrdnanceGraph` weapons, server-authoritative `60 Hz` `Box3D` simulation, `<= 1,152 B` unreliable UDP `CorePvs`, reliable `Schema` syncing, and the `3×3` client prediction window.
1. **[Single-Draw-Call HarfBuzz `hb-gpu` Vulkan HUD](hbgpu-vulkan-hud.md)** — Batches all combat HUD typography, radar rings, and target lock boxes into one Vulkan draw call at `0.229 ms` (`1080p`, GTX 1070) with `0 B/frame` steady-state managed allocations.
2. **[0.5 m swisstopo DEM, Unified Compute Terrain & Tiled Box3D Physics](sion-dem-and-tiled-physics.md)** — Streams a `6145×6145` Swiss Alpine heightmap across shared `192 m` tiles for GPU compute crater baking (`0.37 ms/frame` on GTX 1070), demand-paged physics, and persistent match-to-match scars.
3. **[Zero-Ambient SDFGI Lighting & Gradient-Offset Volumetric Plumes](sdfgi-lighting-and-volumetrics.md)** — Removes flat ambient offsets in favor of half-resolution indirect lighting and AgX tonemapping (`62 FPS`, `p95 = 13.28 ms` at `1080p` on GTX 1070) paired with four-pass compute plumes and live graphics controls.
4. **[Thermal Grid Chassis, Ballistics & Netcode (`CultNet` + `Ymir`)](thermal-grid-ballistics-netcode.md)** — Ties conductive 2D chassis grids, mid-match module salvage, and multi-stage ordnance graphs to a `60 Hz` authoritative server under a `1,152 B` UDP snapshot cap and a `3×3` client prediction window.
## Active Work in Progress & Planned Pipeline
5. **[Upright Mech Walkers (`Ymir` Box3D ABI 22 — Work in Progress)](upright-mech-walkers.md)** — Moving from Hybrid B virtual-GRF box balancing to angular-locked `AddCapsule` bodies, ZMP/inverted-pendulum pelvis offsets, stride kinematics, and terrain slope failure modes currently being resolved.
6. **[Watertight CGA Destructible Sion City & Real Species Foliage (Planned / In Build)](watertight-cga-sion-and-foliage.md)** — Turning `swissBUILDINGS3D 3.0` footprints into `<= 64`-zone closed 2-manifold `RCGA v1` buildings with `SupportMask` collapse DAGs and swisstopo Valais tree species driven by `rtd_flow_field` wind.
5. **[Upright Mech Walkers (`Ymir` Box3D ABI 22 — Work in Progress)](upright-mech-walkers.md)** — Documents the active migration from virtual ground-reaction-force box balancing to upright angular-locked capsules and Zero-Moment Point pelvis kinematics.
6. **[Watertight CGA Destructible Sion City & Real Species Foliage (Planned / In Build)](watertight-cga-sion-and-foliage.md)** — Covers the upcoming offline shape-grammar pipeline converting `2,319` Sion buildings into closed destructible zones alongside Valais-accurate tree stands bent by blast wind.

View file

@ -5,19 +5,19 @@ description: Removing flat black-floor lifters in favor of zero-ambient 3-cascad
Early outdoor captures looked flat under harsh alpine sun because three separate lighting compensators were lifting shadow floors simultaneously: non-zero `AmbientLightEnergy`, shadowless fill lights, and self-emitting fog and smoke floors. While those offsets kept dark steel readable, they washed out sunlit walls and turned dense smoke cores milky gray.
Removing all ambient lifters and tuning Godot 4.7 Forward+ SDFGI, AgX tonemapping, and a 4-pass `PostSky` compute volumetric pipeline brought frame time on a GTX 1070 at `1080p` to **`62 FPS` (`p95 = 13.28 ms`)** while restoring deep charcoal smoke contours and hard valley shadow contrast.
Removing all ambient lifters and tuning Godot 4.7 Forward+ SDFGI, AgX tonemapping, and a four-pass `PostSky` compute volumetric pipeline brought frame time on a GTX 1070 at `1080p` to **`62 FPS` (`p95 = 13.28 ms`)** while restoring deep charcoal smoke contours and hard valley shadow contrast.
![Zero-ambient 3-cascade SDFGI lighting across Sion with AgX tonemapping and post_gamma=1.32](../media/lighting-sdfgi-sion.webp)
![Zero-ambient indirect lighting across Sion with AgX tonemapping and post-tonemap contrast grading](../media/lighting-sdfgi-sion.webp)
![Zero-ambient SDFGI lighting across the procedural desert mesas and dunes](../media/lighting-sdfgi-desert.webp)
![Zero-ambient indirect lighting across the procedural desert mesas and dunes](../media/lighting-sdfgi-desert.webp)
## Killing Black-Floor Lifters & Calibrating SDFGI
`AtmosphereSystem` enforces zero flat ambient injection across every layer:
`AtmosphereSystem` enforces zero flat ambient injection across every lighting layer. `WorldEnvironment` runs with `AmbientLightEnergy = 0.0` (`AmbientSource.Disabled`), pulling indirect sky and terrain bounce strictly from 3-cascade half-resolution SDFGI (`SdfgiMinCellSize = 0.8 m`, `SdfgiYScale = 75%`, `SdfgiBounceFeedback = 0.60`, `SdfgiEnergy = 0.85`, 4 rays per probe, 10-frame convergence) paired with SSAO (`Radius = 1.15 m`, `Intensity = 1.85`) for foot and tire grounding.
- **`AmbientLightEnergy = 0.0` (`AmbientSource.Disabled`):** Indirect fill comes strictly from `WorldEnvironment` sky-coupled SDFGI (`SdfgiCascades = 3`, `SdfgiMinCellSize = 0.8 m`, `SdfgiYScale = 75%`, `SdfgiBounceFeedback = 0.60`, `SdfgiEnergy = 0.85`, half-resolution GI with 4 rays/probe and 10-frame convergence) plus SSAO (`Radius = 1.15 m`, `Intensity = 1.85`) for foot and tire grounding.
- **Zero fog self-emission:** Tier-1 froxel volumetric fog (`0..460 m` on Sion, `0..380 m` on Desert) runs with `VolumetricFogAmbientInject = 0.0` and `VolumetricFogEmissionEnergy = 0.0`, while Tier-2 depth aerial perspective (`FogSkyAffect = 0.0`) leaves the analytical sky LUT untouched.
- **AgX + post-tonemap gamma:** `TonemapMode = Agx` (`TonemapAgxWhite = 6.0`, `TonemapAgxContrast = 1.50`, `TonemapExposure = 0.84`) rolls off bright muzzle flashes and blackbody fireballs without hue-shifting amber plumes to yellow, followed by `film_grain.gdshader` applying `post_gamma = 1.32` before the `Layer = 10` HUD.
Atmospheric haze avoids shadow-floor lifting as well: near froxel volumetric fog (`0..460 m` on Sion, `0..380 m` on Desert) runs with `VolumetricFogAmbientInject = 0.0` and `VolumetricFogEmissionEnergy = 0.0`, while far depth-based aerial perspective (`FogSkyAffect = 0.0`) leaves the analytical sky lookup tables untouched.
`TonemapMode = Agx` (`TonemapAgxWhite = 6.0`, `TonemapAgxContrast = 1.50`, `TonemapExposure = 0.84`) rolls off bright muzzle flashes and blackbody fireballs without hue-shifting amber plumes to yellow. Immediately afterward—at `CanvasLayer 5`, strictly after AgX and normalized additive HDR bloom (`GlowHdrThreshold = 1.0`) and before the `Layer 10` HUD—`film_grain.gdshader` applies `pow(src.rgb, vec3(1.32))` (`post_gamma = 1.32`) plus midtone-weighted interleaved gradient noise to deepen compressed shadow rolloff without touching HUD crispness.
## Gradient-Offset Volumetric Plumes (`PostSky`)
@ -29,25 +29,20 @@ flowchart LR
P2 --> P3["Pass 3: volumetric_composite.glsl (2x2 depth bilateral upsample pre-tonemap)"]
```
Multiplying a radial plume density by 3D noise breaks silhouette continuity and creates floating disconnected blobs. `volumetric_raymarch.glsl` follows a gradient-offset SDF rule where two octaves of `triNoise3d` only displace the normalized radial coordinate $d_{\text{norm}}$:
Pass 1 (`volumetric_tile_cull.glsl`) subdivides the march target into `16 × 16` tiles, tests up to `128` active emitter capsules against each tile's frustum and maximum linearized depth, and runs an adaptive shared-memory Bitonic sort over packed `(entryDistance, emitterIndex)` keys so only the `24` closest emitters reach the raymarcher sorted front-to-back. Pass 2 (`volumetric_raymarch.glsl`) intersects each pixel against its tile's `<= 24` capsules, sorts hit intervals by entry distance `t0`, and advances a monotonic sweep-line cursor—admitting and retiring capsules across each step interval and leaping straight to the next `t0` whenever no emitter is active.
Multiplying a radial plume density by 3D noise breaks silhouette continuity and creates floating disconnected blobs. Instead, `volumetric_raymarch.glsl` applies a gradient-offset SDF law where two octaves of `triNoise3d` ($n_1, n_2$) only displace the normalized radial coordinate $d_{\text{norm}}$:
$$d_{\text{warped}} = \text{clamp}\!\left(d_{\text{norm}} - \left((n_1 - 0.45 n_2 - 0.11)\cdot 0.88\cdot(0.35 + 0.65\min(d_{\text{norm}}, 1))\right),\ 0,\ 1.2\right)$$
Because the unwarped gradient increases monotonically outward, displacing $d_{\text{norm}}$ curls outer smoke billows while keeping interiors solid. Extinction and scattering then split into two regimes:
1. **Charcoal soot contour:** An inverse-density weight $\text{soot} = \frac{1}{1 + 4.6 \rho}$ suppresses scattering inside thick cores (keeping dense interiors dark soot) and focuses Henyey-Greenstein sun scattering onto thin outer vapor edges.
2. **Core-gated blackbody combustion:** A steep radial temperature falloff (`pow(1 - warpedDist, 2.35)`) gated by `smoothstep(0.72, 1.05, coreSignal)` exposes `blackbodyRamp` emission strictly through turbulent crevices.
Because $d_{\text{norm}}$ increases monotonically outward, displacing $d_{\text{norm}}$ curls outer smoke billows while keeping interiors solid. Accumulated smoke density $\rho$ and core combustion temperature `coreSignal` (radial falloff $(1 - d_{\text{warped}})^{2.35}$ modulated by $n_1, n_2$) then separate scattering from emission: an inverse-density soot factor $\frac{1}{1 + 4.6 \rho}$ keeps thick interiors dark charcoal while focusing Henyey-Greenstein sun scattering onto thin outer vapor edges, and `smoothstep(0.72, 1.05, coreSignal)` gates `blackbodyRamp` emission strictly through turbulent crevices. Pass 3 (`volumetric_composite.glsl`) performs a `2 × 2` depth-aware bilateral upsample back onto the HDR scene buffer before tonemapping.
![Close-up of a gradient-offset volumetric smoke and combustion plume rendered before tonemapping](../media/plume-closeup.webp)
## Blast Advection (`rtd_flow_field`) & Live Graphics Settings
`flow_field_step.glsl` updates a camera-snapped `64 × 24 × 64` `RGBA16F` grid (`3.0 m` voxels covering `192 × 72 × 192 m`) every frame, advecting planetary wind alongside radial `ShockShell` blast impulses stored in `flowSample.rgb` and shock pressure `flowSample.a`. `AtmosphereSystem` publishes that `Texture3Drd` globally as `rtd_flow_field`, driving plume shear, shock cavity carving, `GpuSparksSystem`, `ParticlePool`, and upcoming foliage wind shaders from one vector field.
`flow_field_step.glsl` updates a camera-snapped `64 × 24 × 64` `RGBA16F` volume (`3.0 m` voxels covering `192 × 72 × 192 m`) every frame, advecting planetary wind alongside radial `ShockShell` blast impulses (`rgb` velocity and `a` shock pressure). `AtmosphereSystem` publishes that `Texture3Drd` globally as `rtd_flow_field`, driving plume shear, shock cavity carving, `GpuSparksSystem`, `ParticlePool`, and upcoming tree wind shaders from one vector field.
![Settings -> Graphics modal overlay with live-applied VFX resolution, sample count, SDFGI, and display controls](../media/settings-graphics.webp)
![Settings -> Graphics modal overlay with live-applied VFX resolution, sample count, and SDFGI controls](../media/settings-graphics.webp)
`GraphicsSettings` (`user://graphics_settings.json`) and `SettingsOverlay` expose four live-applied parameters via the `272 B` `VolumetricFrame` UBO and `WorldEnvironment`:
- **VFX / Fog Resolution:** `Half (0.5x)`, `High (0.75x)`, or `Full (1.0x)` dynamically reallocates the march target and bypasses the `2 × 2` bilateral upsample at `1.0x`.
- **Volumetric Sample Count:** `Low (8)`, `Medium (10)`, `High (16)`, or `Ultra (24)` scales raymarch step budget (`stepScale = 10.0 / maxSteps`) in place with zero shader recompilation.
- **SDFGI Quality & Display Mode:** Toggles `Off / Balanced / High` GI cascades and `Borderless Fullscreen / Windowed` immediately on change.
`GraphicsSettings` (`user://graphics_settings.json`) and `SettingsOverlay` expose live rendering controls through the `272 B` `VolumetricFrame` uniform buffer and `WorldEnvironment`. Switching `VFX / Fog Resolution` (`Half 0.5x`, `High 0.75x`, `Full 1.0x`) reallocates the march target and bypasses the `2 × 2` upsample at native `1.0x`, `Volumetric Sample Count` (`Low 8`, `Medium 10`, `High 16`, `Ultra 24`) scales raymarch step density in place without shader recompilation, and `SDFGI Quality` (`Off`, `Balanced`, `High`) reconfigures GI cascades immediately.

View file

@ -3,27 +3,25 @@ title: 0.5 m swisstopo DEM, Unified Compute Terrain & Tiled Box3D Physics
description: Streaming a 6145x6145 Swiss Alpine elevation grid across shared 192 m tiles for compute height baking, lazy Box3D physics, and persistent match-to-match scars.
---
The initial Sion prototype sampled `swissALTI3D` at `3 m` (`1025 × 1025`) and rebuilt the terrain heightfield monolithically in `Ymir.Box3D`. Three-meter spacing rounded off road embankments, terraced vineyard walls, and canal banks, while scaling up to `0.5 m` (`6145 × 6145` samples) meant a single full-map float heightfield consumed `~144 MiB` (`~288 MiB` across rebuild buffers). Rebuilding that whole mesh whenever an artillery shell dug a crater stalled the `60 Hz` physics loop.
The initial Sion prototype sampled `swissALTI3D` at `3 m` (`1025 × 1025`) and rebuilt the terrain heightfield monolithically inside `Ymir.Box3D`, GameCult's custom native rigid-body physics library. Three-meter spacing blurred road embankments, terraced vineyard walls, and canal banks, while stepping up to `0.5 m` (`6145 × 6145` samples) meant a full-map float heightfield consumed `~144 MiB` per copy (`~288 MiB` across rebuild buffers). Rebuilding that whole mesh whenever an artillery shell dug a crater stalled the `60 Hz` physics loop.
Both the `3,072 m × 3,072 m` Sion valley and the `1,536 m × 1,536 m` Desert arena now share a unified `192 m` tile lattice (`16 × 16` on Sion, `8 × 8` on Desert) across simulation, GPU compute baking, physics collision, and network replication.
Both the `3,072 m × 3,072 m` Sion valley and the `1,536 m × 1,536 m` Desert arena now share one `192 m` tile lattice (`16 × 16` tiles on Sion, `8 × 8` on Desert) across simulation, GPU compute baking, physics collision, and network replication.
![Sion 0.5 m swisstopo terrain with crater deformation and legacy building tiles](../media/sion-05m-dem.webp)
## `0.5 m` swisstopo DEM Ingestion
Offline tool `tools/maps/sion/bake_sion.py` mosaics 16 `swissALTI3D` `0.5 m` tiles (`EPSG:2056`) centered on Valère and Tourbillon (`E 2594150, N 1120050`, base elevation `483.41 m` ASL), covering `310.841 m` of relief (`-5.885 m` to `+304.957 m`):
Offline tool `tools/maps/sion/bake_sion.py` mosaics 16 `swissALTI3D` `0.5 m` tiles (`EPSG:2056`) centered on Valère and Tourbillon (`E 2594150, N 1120050`, base elevation `483.41 m` ASL), covering `310.841 m` of local vertical relief (`-5.885 m` to `+304.957 m` relative to the `483.41 m` datum):
$$y_{\text{world}} = y_{\min} + s \cdot h_{\text{u16}}, \qquad s = 0.00474314\text{ m/step}$$
- **Compressed storage:** `heightmap_05m.u16z` encodes the `6145 × 6145` grid using zig-zag delta encoding + zlib (`rdhm_v2_u16_zigzag_zlib`), packing `37.76M` elevation samples into `31.9 MB` (`31,924,416` bytes) with **`4.74 mm`** vertical step resolution.
- **Process-cached base array:** `SionMapLoader` decodes one immutable `ushort[]` (`_sharedU16Heights`) shared across matches. `TerrainField` never allocates a per-match full-map `float[]` copy; only tiles touched by runtime brushes allocate sparse `385 × 385` float patches (`_scarredTileHeights`).
- **Decoupled dirty versioning:** `TerrainField` maintains two independent version counters per tile—`StructuralTileVersions[tx, tz]` (height changes) and `VisualTileVersions[tx, tz]` (albedo/scorch/track changes). Each downstream consumer (`TerrainRenderer`, `Box3DPhysicsTileSync`, and `ServerMatchHost`) tracks its own last-synced version per tile without clearing shared dirty flags.
`heightmap_05m.u16z` encodes the `6145 × 6145` grid using zig-zag delta encoding and zlib (`rdhm_v2_u16_zigzag_zlib`), packing `37.76M` elevation samples into `31.9 MB` (`31,924,416` bytes) with **`4.74 mm`** vertical quantization precision. At load time, `SionMapLoader` decodes one immutable `ushort[]` base array shared across matches so `TerrainField` allocates zero full-map float copies; only tiles modified by runtime brushes allocate sparse `385 × 385` float height patches. `TerrainField` tracks two independent version counters per tile—`StructuralTileVersions[tx, tz]` for elevation edits and `VisualTileVersions[tx, tz]` for albedo, scorch, and tire-track updates—allowing physics, GPU baking, and network sync to track their own last-synced tile versions without clearing shared dirty state.
## Unified Compute Terrain (`terrain_tile_bake.glsl`)
```mermaid
flowchart LR
DEM["Sion 6145x6145 Rh DEM + Albedo/Mask PNGs (Read-Only)"] --> SH["terrain_surface.gdshader"]
DEM["Sion 6145x6145 Half-Float DEM + Albedo/Mask PNGs (Read-Only)"] --> SH["terrain_surface.gdshader"]
BR["TerrainField Dynamic Brushes (Crater / Scorch / Track / Rubble)"] --> CS["terrain_tile_bake.glsl (8x8 Compute)"]
CS --> LRU["96-Slot LRU Pool (388x388 RGBA16F + RGBA8, 2-texel gutter)"]
LRU --> SH
@ -31,15 +29,15 @@ flowchart LR
LOD["3 Shared PlaneMesh LODs (192 / 48 / 12 subdivs)"] --> SH
```
`TerrainRenderer` keeps the Layer-0 `Rh` DEM texture, `terrain_surface.png` (`4096 × 4096`), and `terrain_surface_mask.png` (`2048 × 2048`) immutable on the GPU. Any tile with craters, tracks, scorches, or rubble receives a slot from a `96`-entry LRU `Texture2Drd` pool:
`TerrainRenderer` uploads the base elevation map once into a read-only single-channel half-float (`Rh`) `Texture2Drd` alongside `terrain_surface.png` (`4096 × 4096`) and `terrain_surface_mask.png` (`2048 × 2048`). Any tile scarred by craters, tracks, scorches, or rubble claims a slot from a `96`-entry LRU `Texture2Drd` pool baked by `terrain_tile_bake.glsl`:
- **Seam-free gutters:** Each tile delta texture spans `388 × 388` texels (`384 × 384` inner span at `0.5 m/texel` plus a 2-texel border overlapping neighboring tiles) in `RGBA16F` (height delta, roughness, scorch) and `RGBA8` (albedo delta).
- **Fixed per-frame budget:** At most `4` dirty tiles bake per sync (`0.37 ms/frame` on GTX 1070). Unscarred tiles bind shared `1 × 1` neutral textures at zero VRAM cost, and visible tiles draw from three shared `PlaneMesh` LODs (`192`, `48`, and `12` subdivisions) with continuous edge morphing in `terrain_surface.gdshader`.
- **Seam-free gutters:** Each `192 m` tile spans `384` intervals at `0.5 m` spacing (`385 × 385` shared-edge physics vertices). On the GPU, `terrain_tile_bake.glsl` writes a `388 × 388` texture (`RGBA16F` height, roughness, and scorch deltas plus `RGBA8` albedo deltas) whose inner `384 × 384` texel-center span aligns to those `0.5 m` grid intervals while adding a 2-texel overlap border (`gutter`) on every side so bilinear filtering in `terrain_surface.gdshader` stays seamless across tile edges.
- **Fixed per-frame budget:** At most `4` dirty tiles bake per sync (`0.37 ms/frame` on GTX 1070). Unscarred tiles bind shared `1 × 1` neutral textures at zero extra VRAM cost, and visible tiles draw from three shared `PlaneMesh` LODs (`192`, `48`, and `12` subdivisions) with vertex edge morphing in `terrain_surface.gdshader`.
## Lazy `Box3DPhysicsTileSync` & Persistent `CultCache` Scars
In `RustToDust.Ymir`, `Box3DPhysicsTileSync` maps each `192 m` lattice cell to an independent `Box3D` `StaticHeightField` body (`stableId 10_000..10_255`) using `385 × 385` float samples (`0.5 m` spacing) extracted on demand:
In `RustToDust.Ymir`, `Box3DPhysicsTileSync` maps each `192 m` lattice cell to an independent `Ymir.Box3D` `StaticHeightField` body (`stableId 10_000..10_255` for terrain tiles; `11_000+` and `12_000+` reserved for upcoming destructible building and tree-trunk tiles) extracted from `385 × 385` float heights on demand:
1. **Demand paging:** Server `ArenaSession` mounts a `3 × 3` neighborhood (`halfTileRadius: 1`) around active contenders, single tiles (`0`) around stationary actors and descending orbital pods, and DDA-traversed tiles along weapon rays via `EnsureTilesAlongRay` before `CastRayClosest`.
1. **Demand paging:** Server `ArenaSession` mounts a `3 × 3` tile neighborhood (`halfTileRadius: 1`) around active contenders, single tiles (`0`) around stationary actors and descending orbital pods, and DDA-traversed tiles along weapon rays via `EnsureTilesAlongRay` before `CastRayClosest`.
2. **Throttled crater rebuilds:** Dirty heightfields queue into `FlushDirtyHeightfields(maxTilesPerTick: 4)` so simultaneous barrage impacts rebuild at most four `192 m` patches per `60 Hz` step.
3. **Match-to-match scar persistence:** `ArenaScarLedger` records up to `4,096` terrain scars (`0.75 m` spatial coalescing for overlapping craters and scorches) into `CultCache` (`GameCult.Caching.MessagePack`, keyed by `AssetFingerprint`). On multiplayer join or match reset, `ServerMatchHost` transmits the full ledger compressed with ZLib inside `InitialMatchStateDto.PersistentScars`, then streams live `TerrainStampEvent` updates only when a peer enters a `576 m` local geometry bubble around the stamp.
3. **Match-to-match scar persistence:** `ArenaScarLedger` records up to `4,096` terrain scars (`0.75 m` spatial coalescing for overlapping craters and scorches) into `CultCache`, GameCult's persistent MessagePack cache, keyed by `AssetFingerprint`. On multiplayer join or match reset, `ServerMatchHost` transmits the full ledger compressed with ZLib inside `InitialMatchStateDto.PersistentScars`, then streams live `TerrainStampEvent` updates whenever a peer moves within a `576 m` circular radius around a stamp.

View file

@ -1,17 +1,17 @@
---
title: Thermal Grid Chassis, Ballistics & Netcode (CultNet + Ymir)
description: Conductive 2D chassis thermal grids, cell-level armor stripping, recursive ordnance, 60 Hz Ymir.Box3D physics, <= 1152 B UDP snapshots, and 3x3 client prediction.
description: Conductive 2D chassis thermal grids, cell-level armor stripping, multi-stage ordnance graphs, 60 Hz Ymir.Box3D physics, <= 1152 B UDP snapshots, and 3x3 client prediction.
---
Hitpoint pools treat a vehicle as one number until it explodes. *Rust to Dust* simulates every hull as a conductive 2D grid of armor cells and hardpoint rectangles, ties weapon fire and impacts directly to local cell temperature, and replicates both combat state and terrain deformation across `CultNet` under a `1,152 B` unreliable UDP cap.
Hitpoint pools treat a vehicle as one number until it explodes. *Rust to Dust* simulates every hull as a conductive 2D grid of armor cells and hardpoint rectangles, ties weapon fire and impacts directly to local cell temperature, and replicates combat state and terrain deformation across `CultNet`—GameCult's UDP networking stack—under a `1,152 B` unreliable datagram cap.
## Conductive 2D Chassis Grids
`Catalog` loads `15` vehicle and mech chassis (`Jackal`, `Mule`, `Ferret`, `Hornet`, `Mammoth`, `Ironclad`, `Anvil`, `Condor`, `Breaker`, `Paladin`, `Raptor`, `Manticore`, `Bastion`, `Spectre`, `Kestrel`, plus `exemplar_frame`), `9` human salvage modules, and `6` Imperial Tourist modules. Wheeled, tracked, VTOL, and quadruped hulls use a top-down `Dorsal` grid; bipedal walkers use an upright `Coronal` silhouette grid.
`Catalog` loads `15` distinct chassis spanning wheeled buggies, tracked tanks, VTOL craft, quadruped walkers, and bipedal mechs, alongside `9` human salvage modules and `6` Imperial Tourist modules. Wheeled, tracked, VTOL, and quadruped hulls map onto a top-down `Dorsal` grid; bipedal walkers map onto an upright front-facing `Coronal` silhouette grid.
```mermaid
flowchart TD
F["Weapon Fire / Engine Thrust / Beam Hit"] --> INJ["InjectHeat(x, y) / _cellThermalMass"]
F["Weapon Fire / Engine Thrust / Beam Hit"] --> INJ["InjectHeat(x, y) / Cell Thermal Mass"]
INJ --> SUB["50 Hz+ Substeps (subDt <= 0.02 s)"]
SUB --> COND["4-Neighbor Conduction: pairCond * (T_nb - T) * subDt"]
SUB --> RAD["Border-Only T^4 Radiative Cooling + Active Radiators"]
@ -19,37 +19,35 @@ flowchart TD
PERF --> EFF["Weapon Cooldown / Drive Thrust / Cooling Power"]
```
Inside `ChassisGrid.StepHeat`, thermal simulation advances in substeps clamped to `subDt <= 0.02 s`:
Inside `ChassisGrid.StepHeat`, thermal simulation advances in substeps clamped to `subDt <= 0.02 s`. Each active cell exchanges heat with its active east and south neighbors using the mean conductivity of the pair, conserving energy across hardpoint boundaries. Only perimeter cells (`BorderCells[x, y]`) radiate heat according to $T^4$, while active radiators subtract `CoolingPower * Performance(T)` across their footprint cells.
1. **Conservative pairwise conduction:** Each active cell exchanges heat with its active east and south neighbors using the mean cell conductivity `0.5 * (c_a + c_b)`, conserving energy across hardpoint boundaries.
2. **Border and radiator dissipation:** Only perimeter cells (`BorderCells[x, y]`) radiate heat according to $T^4$. Active radiators subtract `CoolingPower * Performance(T)` evenly across their footprint cells, so an overheating or damaged radiator loses cooling throughput.
3. **Trapezoidal operating plateau:** Every module evaluates `ModuleSpec.Performance(T)`: `1.0` across `[OptimalTemp - PlateauWidth/2, OptimalTemp + PlateauWidth/2]`, ramping linearly down to `0` at `MinTemp` and `MaxTemp`.
Every mounted module evaluates `ModuleSpec.Performance(T)`, returning `1.0` across `[OptimalTemp - PlateauWidth/2, OptimalTemp + PlateauWidth/2]` and ramping linearly down to `0` at `MinTemp` and `MaxTemp`. Because cells initialize at `20°C` (`AmbientTemp`) while high-output weapons and supercharged engines enter full plateau efficiency around `30°C–40°C`, cold gear warms up slightly during initial fire before excess sustained heat pushes past the upper shoulder into thermal stall.
## Localized Armor Stripping & Mid-Match Salvage
When a round lands, `ChassisGrid.ApplyHit` maps world-space hit offsets `(localRight, localForward, localHeightNorm)` to cell `(cx, cy)`:
When a round hits, `ChassisGrid.ApplyHit` projects the local impact point differently by grid plane: `Dorsal` hulls project `(right, forward)` outward toward the nearest perimeter cell facing the impact vector, whereas `Coronal` bipedal walkers map `(right, height)` directly onto the nearest active silhouette cell. Damage subtracts from that cell's armor first, spilling any overflow into `CoreHp`.
- **Cell armor & core spill:** Damage subtracts from `Armor[cx, cy]` first; any remainder spills straight into `CoreHp`.
- **Hardpoint disablement:** A mounted weapon, engine, or radiator stays active only while at least one cell under its rectangle holds armor above zero (`IsHardpointOperational`). On walkers, leg-zone armor ratios feed `GetLegIntegrities`, cutting `ComputeDriveThrust` and `ComputeTurnRate` as legs take fire.
- **Field salvage (`[E]` / `[Tab]`):** Crates and destroyed hulls drop physical modules and chassis husks. `TryQuickBoltOrCargo` mounts picked-up gear straight into the first empty matching hardpoint rectangle or stashes it in cargo; `SwapChassis` moves a pilot into a field wreck while carrying over any mounted gear that fits the new grid.
A mounted weapon, engine, or radiator remains functional while at least one cell under its hardpoint holds armor above zero (`IsHardpointOperational`). On walkers, left and right leg-cell armor ratios feed `GetLegIntegrities`, reducing drive thrust and turn rate as legs lose plating. Crates and destroyed hulls drop physical modules and wrecks: `TryQuickBoltOrCargo` mounts picked-up gear straight into the first matching empty hardpoint rectangle or stashes it in cargo, and `SwapChassis` transfers compatible mounted gear into a field wreck while preserving core health ratio.
## Recursive Ordnance & `60 Hz` `Ymir.Box3D` Simulation
## Multi-Stage `OrdnanceGraph` & `60 Hz` `Ymir.Box3D` Physics
`OrdnanceGraph` models ballistic shells, lasers, plasma bolts, airburst flak, and MIRV sub-munitions as validated finite graphs (`OrdnanceGraphValidator.ValidateAndFlatten`). `ArenaSession` runs the single authoritative `60 Hz` simulation loop over `Ymir.Box3D` (`Box3DSoaWorld`, `WorldBodyCapacity = 1024`), issuing `EnsureTilesAlongRay` DDA prewarms against `Box3DPhysicsTileSync` before every `CastRayClosest` hitscan or projectile step.
`OrdnanceGraph` models hitscan beams, ballistic shells, rocket-boosted salvos, homing missiles, loitering laser drones, and stationary mines as directed trees (`OrdnanceNodeDef`). Nodes attach `WhileAlive` periodic pulse emitters and up to six trigger conditions (`Impact`, `Timeout`, `Altitude`, `Proximity`, `StageElapsed`, `Apex`) driving `Detonate`, `Split`, `Transition`, or `Fizzle` transitions—for example, a sabot carrier splitting into homing sub-munitions at apex or an airburst flak shell detonating on proximity.
At load or weapon-generation time, `OrdnanceGraphValidator.ValidateAndFlatten` rejects cyclic graphs and non-finite fields, enforces a maximum tree depth of `4` and `<= 16` peak sub-spawns per shot, and flattens the tree into `<= 32` indexed nodes so `OrdnanceRuntime` steps projectiles in flat arrays with zero runtime recursion or heap allocation. Server `ArenaSession` owns the authoritative `60 Hz` `Ymir.Box3D` simulation (`Box3DSoaWorld`, capacity `1024`), calling `Box3DPhysicsTileSync.EnsureTilesAlongRay` to page in `192 m` terrain tiles along raycasts before `CastRayClosest`.
## `CultNet` Replication & `3×3` Prediction Window
```mermaid
flowchart LR
IN["ClientInputPacket (36 B UDP)"] --> SRV["ServerMatchHost + ArenaSession (60 Hz Box3D)"]
SRV -->|"latest (<= 1152 B UDP)"| CLI["RemoteArenaSession._viewState"]
SRV -->|"schema (ZLib scars + SimEvents + 576m bubble)"| CLI
CLI --> PRED["RemoteArenaSession._predWorld (60 Hz, cap 256)"]
SYNC["Box3DPhysicsTileSync 3x3 Window (halfTileRadius=1)"] --> PRED
IN["ClientInputPacket (36 B UDP)"] --> SRV["ServerMatchHost + ArenaSession (60 Hz Ymir.Box3D)"]
SRV -->|"latest (unreliable <= 1152 B UDP)"| CLI["RemoteArenaSession Client View"]
SRV -->|"schema (reliable ZLib scars + SimEvents + 576 m radius bubble)"| CLI
CLI --> PRED["Client Prediction World (60 Hz, cap 256)"]
SYNC["Box3DPhysicsTileSync 3x3 Window (576 m x 576 m)"] --> PRED
```
`SnapshotCodec` splits replication across two `CultNet` / `CultMesh` channels:
`SnapshotCodec` splits replication across two `CultMesh` channels inside `CultNet`:
- **Unreliable `"latest"` (`CorePvs`):** Strictly capped at **`1,152 B`** on the wire (`42 B` `CultNetRudp` header + `52 B` `CultMesh` header leaves **`1,058 B`** maximum payload per datagram). `EncodeCorePvs` packs quantized poses, velocities, health, heat, and PVS-filtered contender/walker/spectator states within that ceiling even at worst-case 12-contender density.
- **Reliable `"schema"`:** Delivers `InitialMatchStateDto` (including ZLib-compressed `PersistentScars` from `ArenaScarLedger`), reliable loadout/drop/broadcast `SimEvent`s, and `TerrainStampEvent`s as peers enter the `576 m` local geometry bubble.
- **`3×3` local physics prediction:** `RemoteArenaSession` maintains a `256`-body client `Box3DSoaWorld` (`_predWorld`), replaying buffered `36 B` `ClientInputPacket`s on rollback while sliding `_predTileSync.SyncWindow(..., halfTileRadius: 1)` (`3 × 3` tiles = `576 m × 576 m` at `0.5 m` resolution) around the local player.
- **`"latest"` (unreliable, latest-state-wins UDP):** Strictly capped at **`1,152 B`** on the wire (`42 B` `CultNetRudp` packet header plus `52 B` `CultMesh` frame header leaves **`1,058 B`** maximum payload per datagram). `EncodeCorePvs` packs quantized poses, velocities, health, heat, and visibility-filtered contender, walker, and spectator states inside that ceiling even at worst-case 12-contender density.
- **`"schema"` (reliable ordered UDP):** Delivers `InitialMatchStateDto` (including ZLib-compressed `PersistentScars` from `ArenaScarLedger`), reliable loadout, drop, and broadcast `SimEvent`s, and `TerrainStampEvent`s streamed as peers enter a **`576 m` circular radius** around each terrain scar.
- **`3 × 3` client prediction window:** `RemoteArenaSession` runs a `256`-body local `Ymir.Box3D` prediction world replaying buffered `36 B` `ClientInputPacket`s on rollback, while `Box3DPhysicsTileSync.SyncWindow` slides a `3 × 3` grid (`halfTileRadius: 1`, spanning `576 m × 576 m` around the player) of `0.5 m` heightfield tiles so predicted movement stays deterministic without holding the entire `3,072 m` valley in prediction memory.

View file

@ -1,41 +1,46 @@
---
title: Upright Mech Walkers (Ymir Box3D ABI 22 — Work in Progress)
description: Active work in progress migrating bipedal and quadruped walkers from Hybrid B virtual-GRF box balancing to upright angular-locked Box3D capsules and ZMP pelvis kinematics.
description: Active work in progress migrating bipedal and quadruped walkers from Hybrid B virtual-GRF box balancing to upright angular-locked Box3D capsules and Zero-Moment Point pelvis kinematics.
---
> [!WARNING] Work in Progress
> The shipped branch (`154ac25`) runs **Hybrid B** virtual-GRF box balancing in `WalkerLocomotion.cs`. `Ymir.Box3D` ABI 22 already exports `LockAngularX/Y/Z`, `DisableContactRecycling`, `CastCapsuleClosest`, and `SetBodyMotion`, while the `RustToDust` integration (`AddCapsule` bodies, `WalkerSurfaceProbe`, `PreStepWalker`/`PostStepWalker`, and `+5 B` pelvis/lean network sync) is currently in build and not yet merged.
> In the current build, walkers run **Hybrid B** virtual ground-reaction-force (GRF) box balancing in `WalkerLocomotion.cs`. `Ymir.Box3D` ABI 22 already exports `LockAngularX/Y/Z`, `DisableContactRecycling` (preventing the solver from reusing stale contact manifolds across vertical steps), `CastCapsuleClosest`, and `SetBodyMotion`, while the `RustToDust` integration (`AddCapsule` bodies, `WalkerSurfaceProbe`, `PreStepWalker`/`PostStepWalker`, and `+5 B` pelvis/lean network sync) is currently in build and not yet merged.
Seven of the 15 chassis (`Breaker`, `Paladin`, `Raptor`, `Spectre`, `Kestrel`, and quadrupeds `Manticore` and `Bastion`) walk on articulated legs evaluated via 2-bone and 3-bone IK (`WalkerLocomotion`) and synchronized to `VehicleRigAnimator` and `WalkerFootstepTracker`.
Seven of the 15 chassis (five bipeds and two quadrupeds) walk on articulated legs solved with 2-bone and 3-bone inverse kinematics (`WalkerLocomotion`) and synchronized to `VehicleRigAnimator` and `WalkerFootstepTracker`.
## Current Shipped Model: Hybrid B Virtual GRF
In the live build, `ArenaSession` spawns walkers as `AddBox` rigid bodies in `Box3DSoaWorld`. Each `60 Hz` tick, `WalkerLocomotion.StepWalker` computes a centroidal vertical spring-damper force toward `effectiveGroundY + rideHeight`:
In the live build, `ArenaSession` spawns walkers as `AddBox` rigid bodies in `Box3DSoaWorld`. Each `60 Hz` tick, `WalkerLocomotion.StepWalker` computes a centroidal vertical spring-damper force toward the target ride height above sampled ground:
$$F_{y,\text{des}} = \max\!\left(0,\ m g + m k_p (y_{\text{target}} - y) + m k_d (\dot{y}_{\text{terrain}} - v_y)\right)$$
along with virtual pitch/roll restoring torques derived from `ComputeHullSlopeNormal` and `AlignUpToSlope`. Swing feet plan capture-point step targets (`stepOffset = v_H * (0.56 T) + v_err * k_capture`), clamp against `MaxLegReach`, and trace smooth `sin(pi * u)` clearance arcs.
along with virtual pitch and roll restoring torques computed from `ComputeHullSlopeNormal` and `AlignUpToSlope`. Swing feet compute capture-point landing offsets:
$$\Delta \mathbf{p}_{\text{step}} = \mathbf{v}_H \,(0.56\,T) + \mathbf{v}_{\text{err}}\,k_{\text{capture}}$$
where $\mathbf{v}_H$ is current horizontal hip velocity, $T$ is effective stride duration, $\mathbf{v}_{\text{err}} = \mathbf{v}_H - \mathbf{v}_{H,\text{des}}$ is velocity tracking error, and $k_{\text{capture}} = 0.22 / \omega_0$ is the inverted-pendulum capture gain. Targets clamp inside `MaxLegReach` and advance along a normalized swing phase $u \in [0, 1]$ with a $\sin(\pi u)$ vertical clearance arc.
## Failure Modes on `0.5 m` Sion Terrain & Curbs
Testing Hybrid B against Sion's `0.5 m` elevation steps and building perimeters exposed three structural issues:
Testing Hybrid B against Sion's `0.5 m` elevation steps and building perimeters exposed two rigid-body solver failures alongside a separate footstep probing mismatch:
1. **Box corners snagging on micro-relief:** Sharp bottom edges on an `AddBox` collision proxy catch on `0.5 m` terrain terraces and vertical curb risers, forcing `StepWalker` to stack forward height probes (`aheadNorm`, `uphillFootGroundY`) that inject extra upward lift during movement.
2. **Torque fighting solver contacts:** When a box corner touches a crater rim or building ledge, `Box3D` generates contact impulses that fight Hybrid B's virtual righting torque, producing oscillation on steep slopes.
3. **Terrain-only foot probing:** `WalkerFootstepTracker` currently clamps footstep contact audio and dust to `terrain.SampleHeight`, dropping elevated building-curb footsteps down to base ground height.
1. **Box hull snagging on `0.5 m` relief:** Sharp bottom corners on an `AddBox` collision proxy catch on `0.5 m` terrain terraces and vertical curb risers, forcing `StepWalker` to run extra forward height probes that inject upward lift during movement.
2. **Virtual torque fighting contact manifolds:** When one box corner clips a crater rim or building ledge, `Box3D` emits contact impulses that fight Hybrid B's virtual righting torque, causing pitch oscillation on steep slopes.
Separately from rigid-body balance, `WalkerFootstepTracker` currently clamps footstep dust and audio height down to `terrain.SampleHeight`, which pulls elevated curb footsteps below building plinths.
## In-Progress Target: ABI 22 Angular-Locked Capsules
```mermaid
flowchart LR
SP["WalkerSurfaceProbe (TerrainField + Box3D)"] --> PRE["PreStepWalker (TryStep 0.65m + Slope Guard + Yaw)"]
SP["WalkerSurfaceProbe (TerrainField + Box3D)"] --> PRE["PreStepWalker (TryStep 0.65 m + Slope Guard + Yaw)"]
PRE --> STEP["Box3DSoaWorld.Step (AddCapsule + LockAngularX/Z + DisableContactRecycling)"]
STEP --> POST["PostStepWalker (Reground 0.75m + ZMP PelvisOffset + SecondaryLean)"]
STEP --> POST["PostStepWalker (Reground 0.75 m + ZMP PelvisOffset + SecondaryLean)"]
POST --> NET["SnapshotCodec (+5 B/walker) & VehicleRigAnimator"]
```
The migration replaces virtual-GRF box balancing with kinematic-assisted rigid capsules built on `Ymir.Box3D` ABI 22:
- **Solver-enforced upright capsule:** Walkers spawn via `AddCapsule` with `LockAngularX | LockAngularZ | DisableContactRecycling`, letting the physics solver handle horizontal wall sliding and vertical support directly without pitch/roll tipping fights.
- **Unified `WalkerSurfaceProbe`:** Queries both `TerrainField` and `Box3D` static geometry so `TryStep(0.65 m)` clears curbs and rubble piles cleanly before `_world.Step`, and `Reground(0.75 m)` prevents airborne popping over crest transitions in `PostStepWalker`.
- **ZMP / inverted-pendulum visual kinematics:** `PostStepWalker` drives a damped `PelvisOffset` and dynamic `SecondaryLean` (`±8°` per axis, `<= 14.5°` combined tilt) in `WalkerVisualSnapshot`, replicated in `SnapshotCodec` (`+5 B` per walker) and conjugated onto `ModelRoot.Transform` and `FootNormal` in `VehicleRigAnimator`.
- **Solver-enforced upright capsule:** Walkers spawn via `AddCapsule` with `LockAngularX | LockAngularZ | DisableContactRecycling`, letting the physics solver handle wall deflection and vertical support cleanly without pitch or roll tipping fights.
- **Unified `WalkerSurfaceProbe`:** Queries both `TerrainField` and `Box3D` static geometry so `TryStep(0.65 m)` clears curbs and rubble piles before `Box3DSoaWorld.Step`, and `Reground(0.75 m)` keeps walkers grounded over crest transitions in `PostStepWalker`.
- **Zero-Moment Point (ZMP) pelvis & lean kinematics:** `PostStepWalker` computes a damped `PelvisOffset` and dynamic acceleration-driven `SecondaryLean` (`±8°` per axis, `<= 14.5°` combined tilt) in `WalkerVisualSnapshot`, replicated in `SnapshotCodec` (`+5 B` per walker). `VehicleRigAnimator` applies `PelvisOffset` and `(LeanPitch, LeanRoll)` onto `ModelRoot.Transform` while transforming world-space `FootNormal` into the leaned body's local coordinate frame via the inverse body rotation so foot plates stay parallel to terrain slopes.

View file

@ -4,13 +4,13 @@ description: Upcoming pipeline turning swissBUILDINGS3D 3.0 footprints into <= 6
---
> [!NOTE] Planned / In Build
> In the live build (`154ac25`), Sion buildings render via `SionMapRenderer` from `36` static `512 m` tiles (`6 × 6` grid, `2,319` buildings) using `lod1/lod2_*.glb` meshes and `RCOL v1` triangle collision, and no runtime tree field is active yet. The `RCGA v1` destructible city and `cosmo_tree_gen` foliage systems described below are the active next pipeline stages.
> In the current build, Sion buildings render via `SionMapRenderer` from `36` static `512 m` tiles (`6 × 6` grid, `2,319` buildings) using `lod1/lod2_*.glb` meshes and legacy static triangle collision chunks (`RCOL v1`), and no runtime tree field is active yet. The `RCGA v1` destructible city and `cosmo_tree_gen` foliage pipelines described below are the active next stages.
Two visual and structural gaps remain in the Sion arena: its `2,319` `swissBUILDINGS3D 3.0` structures are indestructible open shells on a legacy `6 × 6` tile grid, and the alpine hillsides are bare of the orchards, pines, and vineyards that cover the real Rhône valley floor.
Two visual and structural gaps remain in the Sion arena: its `2,319` `swissBUILDINGS3D 3.0` structures are indestructible open shells on a legacy `6 × 6` tile grid, and the alpine hillsides lack the orchards, pines, and vineyards that cover the real Rhône valley floor.
## Watertight `RCGA v1` Destructible Sion Buildings
Raw `swissBUILDINGS3D 3.0` exports carry open bottom faces, intersecting gable caps, and coplanar party walls that fail closed-volume fracture and produce thin collision slivers. The offline `cga_builder.py` baker turns those footprints into closed 2-manifold buildings aligned to the same `16 × 16` (`192 m`) lattice used by terrain and physics:
Raw `swissBUILDINGS3D 3.0` exports carry open bottom faces, intersecting gable caps, and coplanar party walls that fail closed-volume fracture and produce thin collision slivers. The offline `cga_builder.py` baker uses a Computer Generated Architecture (CGA) shape grammar to extrude and partition those footprints into closed 2-manifold building packs (`RCGA v1`) aligned to the same `16 × 16` (`192 m`) lattice used by terrain and physics:
```mermaid
flowchart LR
@ -22,16 +22,17 @@ flowchart LR
DEST --> PHYS["Box3DPhysicsTileSync (Building Tiles 11_000+)"]
```
- **`<= 64` structural zones per building:** Each building subdivides into floors, bays, and roof sections packed into one `uint64` `CollapsedMask` and `DamagedMask` (`BuildingScarEntry` already exists in `ArenaScarLedger.cs`).
- **`SupportMask` collapse DAG:** Every zone $z$ stores a static 64-bit `SupportMask[z]` listing its load-bearing neighbors below. When incoming fire collapses a support zone, any dependent zone satisfying $(\text{SupportMask}[z]\ \&\ \sim\text{CollapsedMask}) = 0$ cascades into collapse, emitting `BuildingFractureEvent`, spawning `DebrisSystem` masonry, and stamping `TerrainBrushKind.Rubble` onto `TerrainField`.
- **Unified `192 m` replication:** Removing `SionMapRenderer` and `RCOL v1` aligns building collision tiles (`stableId 11_000+`) and `BuildingFractureEvent` streaming inside the existing `576 m` local geometry bubble.
Each building subdivides into `<= 64` structural zones—floors, bays, and roof sections—tracked via a 64-bit `CollapsedMask` and `DamagedMask`. Every zone $z$ stores a static 64-bit `SupportMask[z]` listing its load-bearing neighbors below; when incoming fire collapses a support zone, any dependent zone satisfying $(\text{SupportMask}[z]\ \&\ \sim\text{CollapsedMask}) = 0$ cascades into collapse, emitting `BuildingFractureEvent`, spawning `DebrisSystem` masonry, and stamping `TerrainBrushKind.Rubble` onto `TerrainField`. Retiring `SionMapRenderer` and `RCOL v1` aligns building physics tiles (`stableId 11_000+`) and fracture event replication inside the `576 m` radius geometry bubble.
## Real-Species Valais Foliage (`cosmo_tree_gen` + `rtd_flow_field`)
The central Valais valley around Sion sits in a dry inner-alpine rain shadow. Placing generic temperate broadleaf mixes puts wild beech (*Fagus sylvatica*) onto slopes where it does not grow naturally.
The planned `bake_sion_trees.py` / `cosmo_tree_gen` pipeline generates `trees_sion.bin` from swisstopo vegetation masks using species present in the Sion basin:
The central Valais valley around Sion sits in a dry inner-alpine rain shadow. Placing generic temperate broadleaf mixes puts wild beech (*Fagus sylvatica*) onto slopes where it does not grow naturally, so the planned `bake_sion_trees.py` pipeline invokes `cosmo_tree_gen` (an MIT-licensed procedural tree generator) against swisstopo vegetation masks to populate `trees_sion.bin` with species native to the Sion basin:
- **Valley floor & warm south slopes:** Pubescent oak, Scots pine, silver birch, sweet chestnut, and cultivated orchard rows along vineyard terraces.
- **Higher alpine flanks:** European larch and Norway spruce climbing the upper valley walls, with zero wild beech on the valley floor.
- **Flow-field wind & destructible trunks:** `FoliageRenderer` binds `tree_leaves.gdshader` and `tree_bark.gdshader` to the global `rtd_flow_field` `Texture3Drd` already updated by `flow_field_step.glsl`, so nearby shell detonations and expanding `ShockShell` blast waves whip canopies outward in real time. Felled trunks update `SionTreeDestructionState` (`TreeStateEvent` and `Box3DPhysicsTileSync` `12_000+` trunk bodies) and persist across matches in `ArenaScarLedger`.
- **Higher alpine flanks:** European larch and Norway spruce climbing the upper valley walls.
On the valley floor and lower slopes, wild beech is excluded altogether.
## Flow-Field Wind & Destructible Trunks
At runtime, `FoliageRenderer` binds `tree_leaves.gdshader` and `tree_bark.gdshader` to the global `rtd_flow_field` `Texture3Drd` already stepped every frame by `flow_field_step.glsl`. Nearby shell detonations and expanding `ShockShell` blast waves push canopies outward in real time using the same 3D velocity volume that advects smoke plumes and sparks. Felled trunks update `SionTreeDestructionState`, emit `TreeStateEvent`, add or remove trunk physics tiles (`Box3DPhysicsTileSync` `stableId 12_000+`), and persist across matches inside `ArenaScarLedger`.

View file

@ -6,29 +6,30 @@ description: Salvage-grid vehicular and mech combat in a 3 km Swiss Alpine valle
<section class="rtd-hero">
<p class="rtd-kicker">GameCult // Vehicle &amp; Mech Arena</p>
<h1>RUST TO DUST</h1>
<p>Salvage-grid vehicular and mech combat across a 3 km Swiss Alpine valley around Sion. Twelve contenders drop in by orbital pod inside a shrinking ring, fighting rival pilots and gilded Imperial Patrons while bolting salvaged weapons onto live thermal chassis mid-match.</p>
<p>Salvage-grid vehicular and mech combat across a 3 km Swiss Alpine valley around Sion. Twelve contenders drop in by orbital pod inside a shrinking ring, fighting rival pilots and gilded Imperial spectators while bolting salvaged weapons onto live thermal chassis mid-match.</p>
</section>
<div class="rtd-telemetry" data-rtd-lobby-status>Sion Lobby &middot; <code>rtd.gamecult.org:3076</code></div>
![Jackal buggy engaging gilded Imperial Patron walkers in the Sion Alpine valley under a single-draw-call HarfBuzz Vulkan HUD](media/hud-hbgpu-sion.webp)
![Jackal buggy engaging gilded Imperial walkers on the Sion valley floor under a single-draw-call Vulkan HUD](media/hud-hbgpu-sion.webp)
## What the Game Is
*Rust to Dust* drops 12 human contenders into an arena surrounded by Imperial spectators. On the ground, you pilot one of 15 chassis—light buggies, tracked tanks, VTOL craft, four-legged walkers, and tall bipedal mechs—while gilded Patron and Tourist hulls patrol the perimeter ring. Firing near spectators provokes them into hunting the aggressor, turning a duel between contenders into a three-way firefight under live Imperial Broadcast commentary.
*Rust to Dust* drops 12 contenders—solo or in squads—into a live arena ring. The last contender or squad left standing after final-ring orbital redeployments close wins the match. On the ground, you pilot one of 15 chassis spanning wheeled buggies, tracked tanks, VTOL craft, four-legged walkers, and tall bipedal mechs. Around the perimeter orbit three tiers of Imperial spectators—heavy gilded Tourist walkers, agile Patron hunters, and stealthy Exemplar escorts—who stay neutral until provoked. Opening fire near them triggers a lethal hunt under live Imperial Broadcast commentary, while bringing one down drops high-tier Imperial weapons and multi-stage ordnance onto the field.
Every vehicle and mech is simulated as a physical 2D thermal grid:
- **Conductive heat and performance plateaus:** Firing a weapon or running a turbo core heats the cells under that hardpoint. Heat conducts across four neighbors at 50 Hz+ substeps, cools through border cells and active radiators, and pushes every mounted module along a trapezoidal efficiency curve. Overheated guns stall and damaged radiators lose cooling capacity.
- **Localized armor and module stripping:** Incoming hits strike specific hull coordinates mapped to grid cells. Once a cell's armor reaches zero, overflow damage spills to the core hull and any hardpoint whose supporting cells are all stripped goes offline.
- **Field salvage and chassis swaps:** Wrecked vehicles and orbital supply drops scatter 9 human salvage modules, 6 Imperial Tourist parts, and procedural recursive ordnance across the valley. Pull alongside a crate or wreck to bolt a salvaged weapon straight onto an open hardpoint or swap into a heavier mech mid-match.
- **Persistent battlefields:** Artillery craters, scorched earth, and vehicle ruts stamp into the shared `192 m` terrain lattice and survive between matches in a `CultCache` scar ledger.
- **Conductive heat and operating bands:** Firing weapons or pushing a supercharged engine heats the cells under that hardpoint, and heat conducts across neighboring cells while cooling through exposed hull edges and active radiators. Each weapon, engine, and radiator peaks across a warm operating plateau: cold idle engines and heavy guns run slightly below peak output until combat warms them up, while overheating drops efficiency to zero and stalls weapons or cuts thrust.
- **Localized armor and module stripping:** Incoming shots hit specific grid cells mapped from the impact point on the hull. Once a cell's armor strips to zero, overflow damage hits the core hull and any hardpoint whose supporting cells are all destroyed goes offline; on bipedal and quadruped walkers, leg armor loss slows movement and turning.
- **Field salvage and multi-stage weapons:** Destroyed hulls and orbital supply drops scatter 9 human salvage modules, 6 Imperial Tourist parts, and procedurally rolled multi-stage weapons—from airburst flak and prism lances to MIRV sub-munition carriers and loitering laser drones. Pull alongside a crate or wreck to bolt salvaged gear straight into an open hardpoint or swap into an intact chassis mid-match.
![Low-gamma SDFGI lighting across the Sion Old Town and Valère skyline during active combat](media/lighting-sdfgi-sion.webp)
That combat plays out over a `3,072 m × 3,072 m` Swiss Alpine valley centered on Sion alongside a `1,536 m × 1,536 m` desert testbed. Artillery craters, blast scorches, and tire tracks stamp straight into the shared `192 m` terrain grid, altering physics collision and surviving from match to match in a persistent scar cache.
![Volumetric blast plumes advected by the camera-snapped 3D flow field in Sion](media/plume-sion.webp)
![Sunlight and deep valley shadows across Sion Old Town and the Valère citadel during a skirmish](media/lighting-sdfgi-sion.webp)
![Artillery smoke plumes drifting across the Sion arena behind a Jackal buggy and hostile walkers](media/plume-sion.webp)
## Sections
- [Architecture](/Architecture/) — Six engineering teardowns covering the Vulkan `hb-gpu` HUD, `0.5 m` swisstopo DEM and tiled Box3D physics, zero-ambient SDFGI and gradient-offset volumetrics, thermal grid netcode, upright mech walkers (work in progress), and planned watertight CGA destructible Sion buildings and real-species foliage.
- [Lore](/Lore/) — Setting notes and world documentation (Weksa).
- [Architecture](/Architecture/) — Six engineering teardowns covering the single-draw-call Vulkan HUD, `0.5 m` swisstopo terrain and tiled physics, lighting and volumetric plumes, thermal-grid netcode, upright mech walkers (work in progress), and planned destructible Sion buildings and valley foliage.
- [Lore](/Lore/) — Setting notes and world documentation authored by Weksa.