diff --git a/content/Architecture/hbgpu-vulkan-hud.md b/content/Architecture/hbgpu-vulkan-hud.md new file mode 100644 index 0000000..68c2d4b --- /dev/null +++ b/content/Architecture/hbgpu-vulkan-hud.md @@ -0,0 +1,77 @@ +--- +title: Single-Draw-Call HarfBuzz hb-gpu Vulkan HUD +description: How Rust to Dust renders all combat HUD typography, radar vectors, and target overlays in one Vulkan draw call at 0.229 ms on a GTX 1070 with zero steady-state GC allocations. +--- + +Combat HUDs with shifting numeric readouts, world-projected lock boxes, radar blips, and multi-cell thermal schematics stress retained UI trees. Updating dozens of Godot `Control` labels and `_Draw()` widgets every frame rebuilds canvas items, fragments dynamic font atlases, allocates managed strings, and multiplies draw calls across the frame loop. + +To remove widget-tree overhead from the combat frame, `RustToDust.HbGpu` and `HbGpuCanvas` batch every combat HUD glyph, bar, bracket, and radar ring into one `RenderingDevice` draw call backed by HarfBuzz 15.2.0 `hb-gpu`. + +![Combat HUD over Sion rendered in one Vulkan draw call using HarfBuzz hb-gpu and Monaspace Krypton](../media/hud-hbgpu-sion.webp) + +## 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`. + +- **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`. + +## Atlas Partitioning & Upload Flow + +```mermaid +flowchart LR + H["Hud.Sync (C#)"] --> W["HbGpuCommandWriter (80 B/quad, <= 4096 quads)"] + H --> S["HbGpuBlobCache (glyphs + vector shapes)"] + S --> A["HbGpuAtlasAllocator (262,144 texels RGBA16I)"] + A --> U["RenderingDevice.TextureUpdate (1024x256 R16G16B16A16Sint)"] + W --> B["SSBO Upload (<= 320 KiB)"] + U --> D["1x DrawListDraw (6 procedural verts x quadCount)"] + B --> D + 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)`. + +## 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. + +`HbGpuQuadInstance` adds `FlagSolidRect` (`v_flags & 2u`), mapping every solid rectangle into em-space `[-500, 500]^2` and branching in the fragment shader: + +```glsl +if ((v_flags & 2u) != 0u) { + vec2 edgeDist = (500.0 - abs(v_em)) * pixelsPerEm; + cov = clamp(min(edgeDist.x, edgeDist.y) + 0.5, 0.0, 1.0); +} else { + cov = _hb_gpu_slug(v_em, pixelsPerEm, v_blob_loc); + if ((v_flags & 1u) != 0u) { + float ppem = hb_gpu_ppem(v_em, v_blob_loc); + if (cov > 0.0 && cov < 1.0) { + float brightness = dot(v_color.rgb, vec3(1.0 / 3.0)); + cov = hb_gpu_stem_darken(cov, brightness, ppem); + } + } +} +``` + +Expressed mathematically, Euclidean box coverage for `FlagSolidRect` evaluates in 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**. + +## 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. + +## 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. diff --git a/content/Architecture/index.md b/content/Architecture/index.md index 2b1c9ee..6e4de36 100644 --- a/content/Architecture/index.md +++ b/content/Architecture/index.md @@ -3,11 +3,16 @@ title: Architecture description: Engineering teardowns and captures for Rust to Dust subsystems. --- -Subsystem teardowns authored by Nibu. Each slot below tracks an upcoming technical document and capture set: +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. -1. **`hb-gpu` Vulkan HUD** — GPU-driven cockpit/HUD rendering pipeline and frame telemetry. -2. **`0.5 m` swisstopo DEM + Box3D + `CultCache` scar ledger** — Alpine terrain ingestion, building footprints, and cached bake provenance. -3. **Watertight CGA Sion city** — Procedural architectural grammar and manifold mesh generation. -4. **Zero-ambient SDFGI + flow-field volumetrics** — Signed-distance global illumination and volumetric flow fields. -5. **Upright mech walkers** — Articulated locomotion, stance balance, and chassis kinematics. -6. **Win64 release** — Packaging, shipping layout, and server/client distribution. +## 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. + +## 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. diff --git a/content/Architecture/sdfgi-lighting-and-volumetrics.md b/content/Architecture/sdfgi-lighting-and-volumetrics.md new file mode 100644 index 0000000..f9cd0ff --- /dev/null +++ b/content/Architecture/sdfgi-lighting-and-volumetrics.md @@ -0,0 +1,53 @@ +--- +title: Zero-Ambient SDFGI Lighting & Gradient-Offset Volumetric Plumes +description: Removing flat black-floor lifters in favor of zero-ambient 3-cascade SDFGI + AgX, plus a 4-pass PostSky compute pipeline for gradient-offset volumetric plumes and 3D blast flow. +--- + +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. + +![Zero-ambient 3-cascade SDFGI lighting across Sion with AgX tonemapping and post_gamma=1.32](../media/lighting-sdfgi-sion.webp) + +![Zero-ambient SDFGI 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: + +- **`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. + +## Gradient-Offset Volumetric Plumes (`PostSky`) + +```mermaid +flowchart LR + P0["Pass 0: flow_field_step.glsl (64x24x64 RGBA16F ping-pong)"] --> GF["Global rtd_flow_field (Texture3Drd)"] + GF --> P2["Pass 2: volumetric_raymarch.glsl (sweep-line + gradient-offset SDF)"] + P1["Pass 1: volumetric_tile_cull.glsl (16x16 tiles, 128-slot Bitonic sort)"] --> P2 + 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}}$: + +$$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. + +![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. + +![Settings -> Graphics modal overlay with live-applied VFX resolution, sample count, SDFGI, and display 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. diff --git a/content/Architecture/sion-dem-and-tiled-physics.md b/content/Architecture/sion-dem-and-tiled-physics.md new file mode 100644 index 0000000..36b716b --- /dev/null +++ b/content/Architecture/sion-dem-and-tiled-physics.md @@ -0,0 +1,45 @@ +--- +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. + +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. + +![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`): + +$$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. + +## Unified Compute Terrain (`terrain_tile_bake.glsl`) + +```mermaid +flowchart LR + DEM["Sion 6145x6145 Rh 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 + FB["1x1 Neutral Fallback (Unscarred Tiles)"] --> SH + 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: + +- **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`. + +## 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: + +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`. +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. diff --git a/content/Architecture/thermal-grid-ballistics-netcode.md b/content/Architecture/thermal-grid-ballistics-netcode.md new file mode 100644 index 0000000..b5afc8c --- /dev/null +++ b/content/Architecture/thermal-grid-ballistics-netcode.md @@ -0,0 +1,55 @@ +--- +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. +--- + +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. + +## 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. + +```mermaid +flowchart TD + F["Weapon Fire / Engine Thrust / Beam Hit"] --> INJ["InjectHeat(x, y) / _cellThermalMass"] + 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"] + RAD --> PERF["Trapezoidal Performance(T) Curve per Mounted Module"] + PERF --> EFF["Weapon Cooldown / Drive Thrust / Cooling Power"] +``` + +Inside `ChassisGrid.StepHeat`, thermal simulation advances in substeps clamped to `subDt <= 0.02 s`: + +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`. + +## Localized Armor Stripping & Mid-Match Salvage + +When a round lands, `ChassisGrid.ApplyHit` maps world-space hit offsets `(localRight, localForward, localHeightNorm)` to cell `(cx, cy)`: + +- **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. + +## Recursive Ordnance & `60 Hz` `Ymir.Box3D` Simulation + +`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. + +## `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 +``` + +`SnapshotCodec` splits replication across two `CultNet` / `CultMesh` channels: + +- **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. diff --git a/content/Architecture/upright-mech-walkers.md b/content/Architecture/upright-mech-walkers.md new file mode 100644 index 0000000..5604765 --- /dev/null +++ b/content/Architecture/upright-mech-walkers.md @@ -0,0 +1,41 @@ +--- +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. +--- + +> [!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. + +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`. + +## 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`: + +$$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. + +## 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: + +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. + +## In-Progress Target: ABI 22 Angular-Locked Capsules + +```mermaid +flowchart LR + SP["WalkerSurfaceProbe (TerrainField + Box3D)"] --> PRE["PreStepWalker (TryStep 0.65m + Slope Guard + Yaw)"] + PRE --> STEP["Box3DSoaWorld.Step (AddCapsule + LockAngularX/Z + DisableContactRecycling)"] + STEP --> POST["PostStepWalker (Reground 0.75m + 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`. diff --git a/content/Architecture/watertight-cga-sion-and-foliage.md b/content/Architecture/watertight-cga-sion-and-foliage.md new file mode 100644 index 0000000..af699db --- /dev/null +++ b/content/Architecture/watertight-cga-sion-and-foliage.md @@ -0,0 +1,37 @@ +--- +title: Watertight CGA Destructible Sion City & Real Species Foliage (Planned / In Build) +description: Upcoming pipeline turning swissBUILDINGS3D 3.0 footprints into <= 64-zone closed 2-manifold RCGA v1 destructible buildings and swisstopo Valais tree species driven by rtd_flow_field wind. +--- + +> [!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. + +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. + +## 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: + +```mermaid +flowchart LR + SB["swissBUILDINGS3D 3.0 Footprints"] --> CGA["cga_builder.py (Watertight RCGA v1, <= 64 zones/building)"] + CGA --> CAT["SionCityCatalog (16x16 192 m Lattice)"] + CAT --> REND["WorldCityRenderer + sion_building.gdshader"] + CAT --> DEST["SionCityDestructionState (uint64 CollapsedMask + SupportMask DAG)"] + DEST -->|"BuildingFractureEvent"| SCAR["ArenaScarLedger + TerrainBrushKind.Rubble"] + 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. + +## 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: + +- **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`. diff --git a/content/index.md b/content/index.md index 34671b2..99ebb2e 100644 --- a/content/index.md +++ b/content/index.md @@ -1,17 +1,34 @@ --- title: Rust to Dust -description: Engineering architecture, live Sion lobby telemetry, and setting notes for Rust to Dust. +description: Salvage-grid vehicular and mech combat in a 3 km Swiss Alpine valley, with engineering teardowns and live Sion lobby telemetry. ---
-

GameCult // Subsite Scaffold

+

GameCult // Vehicle & Mech Arena

RUST TO DUST

-

Technical documentation, subsystem teardowns, and setting notes for Rust to Dust. Built on GameCult-Quartz with self-hosted Monaspace Krypton and zero external font requests.

+

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.

Sion Lobby · rtd.gamecult.org:3076
+![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) + +## 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. + +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. + +![Low-gamma SDFGI lighting across the Sion Old Town and Valère skyline during active combat](media/lighting-sdfgi-sion.webp) + +![Volumetric blast plumes advected by the camera-snapped 3D flow field in Sion](media/plume-sion.webp) + ## Sections -- [Architecture](/Architecture/) — Engineering teardowns and captures (Nibu). +- [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). diff --git a/content/media/hud-hbgpu-sion.webp b/content/media/hud-hbgpu-sion.webp new file mode 100644 index 0000000..389d2df Binary files /dev/null and b/content/media/hud-hbgpu-sion.webp differ diff --git a/content/media/lighting-sdfgi-desert.webp b/content/media/lighting-sdfgi-desert.webp new file mode 100644 index 0000000..e1f1d9f Binary files /dev/null and b/content/media/lighting-sdfgi-desert.webp differ diff --git a/content/media/lighting-sdfgi-sion.webp b/content/media/lighting-sdfgi-sion.webp new file mode 100644 index 0000000..d852140 Binary files /dev/null and b/content/media/lighting-sdfgi-sion.webp differ diff --git a/content/media/plume-closeup.webp b/content/media/plume-closeup.webp new file mode 100644 index 0000000..d9a42e7 Binary files /dev/null and b/content/media/plume-closeup.webp differ diff --git a/content/media/plume-sion.webp b/content/media/plume-sion.webp new file mode 100644 index 0000000..fdd9202 Binary files /dev/null and b/content/media/plume-sion.webp differ diff --git a/content/media/settings-graphics.webp b/content/media/settings-graphics.webp new file mode 100644 index 0000000..77339fe Binary files /dev/null and b/content/media/settings-graphics.webp differ diff --git a/content/media/sion-05m-dem.webp b/content/media/sion-05m-dem.webp new file mode 100644 index 0000000..210c47c Binary files /dev/null and b/content/media/sion-05m-dem.webp differ