ARCHITECTURE.md 41 KB

Sculpt Engine — Architecture (Project Cold Water)

Sculpt Engine is the custom pure-Rust, zero-external-assets 3D tactical engine powering Project Cold Water—unifying procedural GPU rendering, two-level SAH/BVH raytraced acoustics, real-time convex CSG subtraction destruction, swept ballistics, enterable CSG architecture, hierarchical AI navigation, combined-arms wheeled/tracked/helicopter/multi-barrel vehicles, a sandboxed pure-Rust Luau VM + ColdFlux visual scripting runtime, and authoritative UDP multiplayer with in-memory mod streaming.

1. Technology Stack & Cargo Features

Defined in Cargo.toml:

  • Cargo Features (default = ["client", "cold_water_assets"]):
    • client: Separates GUI, GPU, and audio dependencies behind client, allowing cold_water_server and core simulation/modding/scripting/netcode/replay logic to compile cleanly with --no-default-features for headless Windows and static Linux (x86_64-unknown-linux-musl) servers with zero OS graphics, audio, or C/C++ dependencies (the Luau VM in src/scripting/vm.rs and ColdFlux compiler in src/scripting/flux.rs are 100% pure Rust).
    • cold_water_assets: Gates Project Cold Water's procedural weapons, Soviet vehicles, Chechen urban structures, valley map, and starter blueprints. Building sculpt with --no-default-features --features client strips all Cold Water game assets in favor of lightweight neutral geometric fallbacks and boots into the Sculpt Engine Hub over a selectable project workspace.
Crate Feature Purpose
wgpu (24) client Cross-platform GPU compute & HDR forward rendering pipelines, depth/shadow/paraboloid passes, headless offscreen verification & cinematic PNG replay export
winit (0.30) client Window lifecycle, raw mouse input, keyboard/mouse events, event-loop frame pacing
egui / egui-wgpu / egui-winit (0.31) client Immediate-mode HUD, Main Menu, Sculpt Engine Hub, Direct Connect, Game Director, Deployment (+ Kit Selector), Squad Manager (U), VHF Radio Tuner (N), Inventory/Kit (I), AI Helpers Bar (Z), Audio Studio, Map Generator, Interactive 2D Grid Map Painter & MapGen Asset Palette Editor (mapgen_ui.rs), Asset Pack Builder (pack_builder.rs), Replay Library & Cinematic Studio (replay_ui.rs), ColdFlux Visual Scripting Studio, Server Admin & Permissions panel, Script-Extensible UI panels/windows (script_ui.rs), and Asset Studio inspector + 2D/3D entity gizmo overlay
cpal (0.15) client Low-latency audio output callback stream and microphone VoIP input capture (MicCaptureHandle)
rtrb (0.3) client Wait-free single-producer/single-consumer ring buffer for lock-free audio DSP events
crossbeam-channel (0.5) client Non-blocking command channel from simulation to background acoustic propagation worker
pollster (0.4) client Synchronous wgpu device initialization
glam (0.29) + bytemuck (1) always SIMD-friendly vectors/matrices (with serde feature) and zero-copy GPU vertex/instance buffer uploads
serde / serde_json (1) always Blueprint serialization (./mods/*.json), audio patch banks, server_config.json, ColdFlux/script configs, UDP snapshots/handshakes
png (0.17) always 8-bit/16-bit heightmap PNG import/export (file & in-memory bytes) and --verify-render screenshot output
rand (0.8), log, env_logger always RNG and structured logging

2. High-Level System & Threading Model

Main / Event Thread (src/app.rs: ColdWaterApp + AppRuntime; LaunchMode::{ColdWater, Sculpt})
 ├── Screen State Machine: AppScreen::{MainMenu, InGame, AssetStudio, ReplayViewer}
 ├── Project Workspace & ModRegistry (./mods or ./sculpt_projects/<name>/): weapons, vehicles, maps, stamps, mapgen_palettes, grids, scripts, packs (.cwassetopack.json)
 ├── Frame Pacing (about_to_wait): WaitUntil <=60 FPS stream-safe, sub-16ms yield/Poll for 90-500 FPS / Max
 ├── Replay Recorder & Cinematic Playback (src/replay/: .cwrep.json capture, timeline scrub, CSG destruction/vehicle replay, Catmull-Rom PNG/FFmpeg export)
 ├── Fixed-Step Simulation (src/sim/)
 │    ├── FpsPlayerState (src/sim/player.rs) & Multi-Crew Vehicles (src/sim/vehicles.rs: wheeled, tracked + 3D track shoes, helicopters, emplaced turrets, multi-barrel weapons, HeliBehavior/GroundVehicleTactic AI, gravity wreck crashes)
 │    ├── Magazine-Based Ammo (src/sim/ammo.rs: discrete magazines, +1 chamber, partial mag retention, tactical/dry reload speed, mag repack, bullet mass)
 │    ├── Non-Visual Inventory & 7 Tactical Kits (src/sim/inventory.rs: bleeding/bandages/morphine, bouncing frag/smoke grenades, Ammo Bag/Medkit/Rally Kit, weight-scaled speed)
 │    ├── Tactical VHF Radio & Proximity Comms (src/sim/radio.rs: 30.000–87.975 MHz, dual-watch manpack, terrain ridge diffraction, Conflict relay boost, encryption toggle)
 │    ├── Sensory Squad AI, Formations, ROE & AI Helpers (src/sim/ai.rs, src/sim/orders.rs: FollowLeader, MountVehicle, PopSmoke, Medic heal, Ammo Bearer resupply, radio contact callouts)
 │    ├── Swept Ballistics, SACLOS ATGMs, Barrel-to-Target Tracers & Hit FX (src/sim/ballistics.rs, src/sim/effects.rs)
 │    ├── Batched Real-Time CSG Subtraction Destruction & Structural Collapse (destruction.rs: apply_destruction_crater_batched -> immediate substep BVH swap + NavGrid breach carving + load-bearing Pancake/Cantilever-V/A-Frame collapse)
 │    ├── Sandboxed Luau / ColdFlux ScriptingRuntime (src/scripting/: instruction/memory budgets, PermissionsConfig roles, extensible UI registry ui_ext.rs, disk persistence storage.rs)
 │    └── Conflict Radio-Link Capture, Game Director, Spawns (incl. Squad Rally Points) & Objectives (conflict.rs, director.rs, spawn.rs)
 │
 ├── Multiplayer Client & In-Memory Mod Overlay (src/net/client.rs, src/main.rs)
 │    ├── Non-blocking UdpTransport (PCHP UDP hole punch + PCW1 fragmented/reliable UDP)
 │    ├── Automatic diff & transfer of missing server mods (.json + heightmap .png) -> temporary overlay
 │    ├── 60 Hz client-side FPS prediction + cosmetic local ballistics (step_client_cosmetic_fx)
 │    ├── Frequency-matched & proximity UDP VoIP TX/RX (ClientMessage::{Voice, RadioTune}, ServerMessage::Voice)
 │    ├── Replicated NetDestructionEvent history (including late-joiner replay) + NetScriptSync / Admin RPCs
 │    └── Per-frame WorldSnapshot vehicle (track offsets & helicopter rotor telemetry) / soldier interpolation + clean ./mods/ restore on disconnect
 │
 ├── Authoritative Server / Rendezvous Process (src/net/server.rs, src/net/punch.rs)
 │    ├── Listen Server (HostedServerHandle background thread) OR Dedicated Binary (cold_water_server)
 │    ├── 60 Hz authoritative sim + 20 Hz interest-filtered WorldSnapshot + 250ms lag-comp rewind + CSG destruction, script sync & VoIP frequency/proximity relay
 │    └── Optional --rendezvous UDP Hole-Punch Broker pairing NAT peers via Room Code
 │
 ├── Async Acoustics Worker Thread (src/audio/propagation.rs, client-only)
 │    ├── Receives SoundEvent & ListenerPose via crossbeam-channel
 │    ├── Hot-swaps two-level Arc<AcousticBvh> (immutable base FlatBvh + < 0.1 ms dynamic DynamicBvh rebuilt on CSG craters) without blocking audio
 │    └── Traces multi-bounce rays, air absorption, and edge diffraction -> pushes ResolvedTaps via rtrb
 │
 ├── Real-Time Audio Callback Thread (src/audio/engine.rs, client-only)
 │    ├── Never allocates or locks mutexes on the callback path
 │    ├── Captures PTT VoIP via MicCaptureHandle -> 8 kHz IMA ADPCM frames (src/audio/voip.rs)
 │    ├── Mixes 8 lock-free VoiceStreamSlots (300–3000 Hz radio bandpass/static/squelch + proximity binaural occlusion)
 │    ├── Synthesizes weapon/ballistic/impact/vehicle/UI/ambience audio (src/audio/synth/ + patch.rs)
 │    └── Spatializes ITD/ILD binaural taps + Hadamard FDN late reverb (src/audio/dsp.rs)
 │
 └── GPU Render Graph (src/render/mod.rs, client-only)
      ├── 0. Zero-Alloc COPY_DST Static Tail Upload (update_static_tail for real-time CSG destruction)
      ├── 1. Cloud Shadow Compute Pass
      ├── 2. Sun Shadow Depth Pass (snapped 2048x2048 ortho)
      ├── 3. Dual Paraboloid Reflection Pass (front/back hemispheres + mipmaps)
      ├── 4. Main Forward HDR Pass (Terrain LODs, Static, Skinned 11-Bone, MAX_ACTOR_INSTANCES = 6144 across 46 packed buckets, Water, Lines, Viewmodel)
      ├── 5. Volumetric Cloud Raymarching Pass
      ├── 6. Post-Process Pass (ACES Filmic, Suppression Pixelation/Chromatic/Vignette, Damage Flash, F4 PIP)
      └── 7. egui Composite Pass

3. GPU Render Graph & Shaders (shaders/)

The renderer (src/render/mod.rs) executes a multi-pass HDR pipeline backed by 13 WGSL shaders:

  1. Startup Procedural Synthesis:
  2. Per-Frame Secondary Passes:
  3. Main Forward HDR Pass (src/render/main_pass.rs):
    • shaders/pbr_main.wgsl + shaders/common.wgsl: Renders frustum-culled adaptive chunked terrain LODs (8×8 or 16×16 chunks, 3 tiers + drop skirts sized proportionally to chunk scale, dynamic LOD distances & dynamic 2800m–10000m far clip / fog end), static buildings/props, 11-bone GPU-skinned infantry (SkinnedSoldierInstance), up to MAX_ACTOR_INSTANCES = 6144 instanced meshes across 46 packed buckets (ActorInstanceRaw: weapons, wheeled/tracked/helicopter hulls & turrets, animated 3D track shoes & roadwheels, rotors, custom CSG parts, and bullet-hit FX), and the zero-clip foreground FPS viewmodel depth range ([0.0..0.05]). Static building buffers use COPY_DST with 1.5× headroom (src/render/resources.rs, src/render/mod.rs) so CSG crater updates stream via zero-allocation tail uploads without reallocating world buffers. Supports Catmull-Rom bicubic material sampling and Vogel Disk PCF (8/16/32 samples). Also drives offscreen PNG sequence export for Replay Studio cinematics (normalize_readback_to_rgba converting Bgra8Unorm swapchains to RGBA8).
    • shaders/water.wgsl: Renders animated, fresnel-reflective river surfaces sampling the Dual Paraboloid reflection map (safely skipped when a dry map has water_indices.is_empty()).
    • shaders/debug_lines.wgsl: Renders F3 acoustic bounce rays, squad tactical lines, Game Director ghosts/badges, CSG Asset Studio + Map Editor 3D wireframes (spawn diamonds, objective capture radius rings, oriented vehicle boxes + heading arrows), TTL-aged multi-line bullet tracer ribbons converging from muzzle_world to the eye-ray trajectory, and HDR spark streaks.
  4. Volumetrics, Post-Process & UI:
    • shaders/volumetric_clouds.wgsl: Depth-aware raymarched sky & cloud layer using shared cloud_weather_uvs (seeded offset/rotation cloud_seed_offset / cloud_seed_angle + organic cloud-top height variation, matched 1:1 with cloud_shadow.wgsl) composited over HDR scene color.
    • shaders/post.wgsl (src/render/post.rs): ACES Filmic tonemapping, suppression radial block pixelation / peripheral chromatic split / adrenaline desaturation / pulsed tunnel vignette (u.flags.z), crimson damage flash (u.flags.w), and F4 debug PIP overlays.

4. Module Directory Breakdown

src/core/ — Configuration, Materials & Events

  • config.rs: EngineConfig (RenderConfig including cloud_seed_offset, cloud_seed_angle, and randomize_clouds, plus AudioConfig, SimConfig, AiSkillLevel), default Stream-Safe / VSync / fps_cap settings.
  • materials.rs: MaterialId (GPU_LAYER_COUNT = 21, TireRubber = 20, acoustic-only ColdWater = 21) storing PBR roughness/metallic/tiling alongside acoustic reflectivity and high-frequency damping.
  • events.rs: SoundEvent, SoundKind (26 procedural sounds, including Autocannon23mm, Autocannon30mm, TankCannon125mm, TowLaunch, HelicopterRotor, WallCollapse, TrackClatter), DynamicLight, TracerSegment (ttl, max_ttl, owner_player), and DebugAcousticRay.
  • math.rs: Geometry, interpolation, and ray intersection helpers.

src/world/ — Maps, Chunked Terrain, Meshes & Navigation

  • terrain.rs: TerrainGrid, 9-biome ZoneType (SovietCityCore/CityCore, SuburbanTown, IndustrialOutskirts, MilitaryOutpost, RiverCrossing, Forest, OpenField, FoothillRidge, WaterLake), TerrainGridZoneMap O(1) 2×2 bilinear sampling, playable_half_extents() separation with biome-aware +25% scenic out-of-bounds skirt (open water for WaterLake edges, rolling ridges for land), adaptive 8×8/16×16 3-LOD chunked terrain (256×256 / 512×512 spanning exact [-half_extent, +half_extent]), coarse grid water mesh synthesis, and 8-bit/16-bit PNG heightmap loader (build_from_heightmap_png & in-memory build_from_heightmap_png_bytes).
  • palette.rs: MapGenPalette, MapGenSlot, MapGenAssetRef (MapStamp or BuiltIn), WeightedAssetEntry, mapgen_palettes/*.json persistence, place_palette_asset, place_builtin_key, and 1-click export_builtin_preset_to_map_stamp conversion into editable CSG blueprints.
  • generator.rs: Parametric & grid map generation (RiverValleyTown, SmallSovietCity, TwinBridgeCrossing, DryCityOutskirts, stitched 3-zone corridors, 2×2 stitched quads, 3 km theater, and CustomGridSpec from 3×3 to 128×128 across Block32m/District64m/Sector128m scopes up to 16.4 km × 16.4 km + +25% skirt), GridTemplateKind presets, .cwgrid.json persistence, PlacementGuard (strict painted bounds, < water_level + 0.4 m underwater rejection, normal.y < 0.82 steep-cliff rejection), auto-roads/bridges, auto_register_tall_structures, and 12_000-panel CSG destructible cap (cap_destructibles_converting_overflow_to_static).
  • assets.rs & structures.rs: Engine-neutral blockout/bridge/cover/tower/stamp builders (place_map_stamp, cap_destructibles_converting_overflow_to_static), plus #[cfg(feature = "cold_water_assets")] Second Chechen War geometry with per-panel watertight subdivision (<= 4.8m sub-boxes) across Khrushchyovkas, Panelka towers, AdminPalace, brick compounds, industrial warehouses, Caucasus houses, sandbags, concrete fences, and checkpoint barricades for localized CSG destruction.
  • points.rs & nav.rs: Connected TacticalPointGraph (SpawnPoint ↔ ObjectivePoint + CenterOfOperations), water-safe & playable-bounds-clamped NavGrid A* (2m precision / <= 256×256 hierarchical regional mode on > 800 m maps), find_vehicle_path, CSG doorway-preserving wall/floor integration (apply_csg_geometry, wall_blocked_move, doorway_nudge, surface_height_csg, point_inside_solid), and incremental wall breach carving (update_csg_region).
  • actors_mesh.rs, weapons_mesh.rs, vehicles_mesh.rs: Shared procedural mesh library (ActorMeshLibrary) providing neutral geometric placeholder fallbacks when cold_water_assets is disabled, and full Second Chechen War procedural meshes when enabled: 11-bone soldiers, 6 detailed weapons + PG-7V, 16-sided outward-wound chevron TireRubber wheels, 12 stock vehicles (UAZ-469, Ural-4320, BTR-80, BTR-80A, TOW Tripod, Mi-8MTV-2, Mi-24V Hind, T-72B, BMP-2, MT-LB, ZU-23-2, BMPT Terminator), 56-shoe procedural 3D track assemblies (sample_track_perimeter), helicopter rotors, multi-barrel pods, and bullet hit FX meshes.
  • world/mod.rs: Top-level WorldData container (up to MAX_SKINNED_SOLDIERS = 192).

src/sim/ — Simulation & Gameplay Logic

  • sim/mod.rs: Simulation orchestrating fixed-step ticks, multi-player sessions (PlayerSession), SimCombatFx replication capture, step_client_cosmetic_fx for MP predicted ballistics/FX, batched real-time CSG destruction flush (apply_destruction_crater_batched, flush_destruction_updates), step_thrown_grenades, step_ai_helpers, squad creation/join/leave/recruit/rally APIs (create_player_squad, join_squad, deploy_squad_rally_point, issue_ai_assist_request), DestructibleWorld ownership, ScriptingRuntime dispatch, custom vehicle spawning, and map hot-reloading.
  • ammo.rs: Arma/Squad-style discrete magazine simulation (Magazine, MagazineWeaponState, closed-bolt +1 chamber, partial mag retention on tactical reloads with 0.85x vs 1.15x duration scaling, round-conserving repack_one_step, and per-round mass calculation total_mass_kg).
  • inventory.rs: Non-visual inventory and 7 tactical KitRoles (Rifleman, Medic, MachineGunner, Marksman, AntiTank, SquadLeader, AmmoBearer), ItemKind (FieldBandage, Morphine, FragGrenade, SmokeGrenade, AmmoBag, Medkit, RallyKit, RadioUnit), ThrownGrenade, and weight-based encumbrance speed scaling (total_weight_kg, speed_multiplier).
  • radio.rs: Frequency-based VHF radio (30.000–87.975 MHz, 25 kHz grid), RadioType (None, Handheld, BackpackLongRange dual-watch), RadioEar panning (Both/Left/Right), evaluate_radio_reception (terrain ridge diffraction, relay boost, unencrypted eavesdropping vs encryption gating), evaluate_proximity_reception (35 m/60 m with BVH occlusion), and RadioLogEntry.
  • session.rs: PlayerId, PlayerRole (Guest..Owner with GM/script permissions), ClientInputCmd, and PlayerSession (storing FpsPlayerState, RadioState, and last_vehicle_input).
  • conflict.rs: Dynamic Conflict mode (ConflictState) with BFS radio-signal connectivity from Main HQ bases, relay_range_boost for tactical voice radio extension, sector capture progress, forward spawn activation, and compact ConflictSnapshot sync.
  • player.rs: FpsPlayerState, navigation-clamped + carry-weight-scaled FPS movement, zero-parallax eye-ray bullet spawning with visual_offset convergence, MagazineWeaponState banks (mag_banks), kit-restricted try_select_weapon_kit, mag check/repack timers, bleeding + medical item timers, grenade throwing, first-person viewmodel matrix building (stock & custom CSG weapons), PSO-1 / 1PZ-2 optics, and select_weapon cooldown preservation.
  • ai.rs & orders.rs: Squad state machine (SquadFormation::{Wedge, Line, Column, Spread}, RulesOfEngagement, TacticalOrder::{FollowLeader, MountVehicle, PopSmoke}, AiAssistRequest), vision cone + smoke-puff LOS obstruction + spotting timer, hearing alerts, aim settling, suppression pinning, cover node claiming, AI Medic & Ammo Bearer field helpers, radio contact callouts, and dead-slot recycling.
  • ballistics.rs: Swept projectile stepping against terrain/structures (two-level BVH), vehicles (including directional armor 0.50x front glacis / 1.50x rear engine deck on MBTs/IFVs), and multi-zone SoldierHitbox capsules (Head/Torso/Legs, helmet vs body detection), SACLOS wire-guided ATGM steering (ProjectileGuidance::SaclosWireGuided), autocannon/HE/rocket CSG crater triggers, unified push_projectile_tracer, supersonic crack triggers, and HE blasts.
  • effects.rs: ImpactEffectsState managing pooled particles (360), HDR spark streaks (280), and persistent surface decals (160) across all MaterialId surfaces, vehicles, soldiers, and explosions.
  • vehicles.rs: Unified Vehicle physics (OwnedVehicleSpec), simultaneous multi-crew step_vehicles_multi + VehicleControlOverride (independent Driver + Gunner ownership across MP players & AI), VehicleLocomotion (Wheeled 4-wheel suspension/steering, Tracked dual-track differential kinematics + neutral pivot turns in place + 3D track shoe animation, Helicopter collective/cyclic/tail-rotor aerodynamics + Auto-Hover, and EmplacedTurret), role-aware tactical AI (HeliBehavior::{Cas, Transport, Move} with terrain lookahead, S-8 rocket runs, controlled -2.6 m/s LZ landings & ground-only troop dismount; GroundVehicleTactic::{Move, AssistInfantry, ArmoredPush, SuppressPosition} with frontal armor neutral-pivoting, sudden-damage tactical reverse, and convoy spacing; multi-domain AI gunnery step_ai_turret_gunner for AA vs helicopters, ATGM/coax priority, velocity lead, and area suppression), gravity/spin-out physics on destroyed helicopters and falling wrecks, multi-barrel TurretWeaponSpec firing (Alternating / Salvo, 1..=6 barrels, horizontal/quad/rotary layouts), secondary weapons (TOW / Ataka-T / S-8 rockets), 125 mm cannon hull recoil, amphibious water checks, and push_custom_vehicle_instances.
  • director.rs, objectives.rs, spawn.rs: Game Director entity browser (spawn_vehicles_crewed toggle, gm_set_vehicle_tactic, commands, fire support), 6-stage MissionState state machine, and faction deployment spawn points (PlayerSpawnPoint.is_rally, RespawnState.selected_kit, and sandbox_all_weapons).
  • weapons.rs: Ballistic & mechanical specs for all 6 base weapon archetypes.

src/modding/ — Sculpt Engine CSG Modding, Destruction, Modifiers & Asset Studio

  • csg.rs: Pure-Rust BSP boolean tree evaluator (evaluate_csg_tree, MAX_BSP_DEPTH = 96, balanced splitter, vertex deduplication), convex half-space polygon clipping (clip_polygon_by_plane_back, clip_polygon_inside_convex, clip_polygon_outside_convex, build_convex_polyhedron_from_planes), clip_polygons_inside_bsp, non-self-splitting csg_subtract, primitives (Box, Cylinder, Sphere, Cone, Wedge, Torus), AssetStampKind stamps, CsgShape::Group material overrides & recursive count_csg_nodes, ray_pick_node, and nav-obstacle extraction.
  • modifiers.rs: Non-destructive procedural ModifierStack (Array Linear/Radial/Grid, RandomizeTransforms, Curve Catmull-Rom spline placement, plus programmable Luau & ColdFlux modifiers with typed custom parameters).
  • destruction.rs: Real-time CSG subtraction destruction & dynamic structural collapse system: DestructibleStructure (exact 6-plane box fast path from_box_polygons + untouched base_polys fallback for custom stamps, applied_cutters, per-panel cached vertex/index/acoustic buffers, max_craters = 256, 12000 polygon guard, load-bearing collapse modes Pancake, CantileverV, and AFrame) and DestructibleWorld (12-plane strictly convex dodecahedral generate_convex_crater, leak-proof clipping strictly inside the untouched base and outside prior craters, splinter cleanup < 0.12 m²).
  • blueprint.rs: Serde JSON schemas (AssetBlueprint, WeaponBlueprint, VehicleBlueprint, VehicleLocomotion, TurretWeaponSpec across 8 presets with barrel_count, BarrelFireMode, BarrelLayout, barrel_spacing, ProjectileGuidance, MapBlueprint, MapStampBlueprint, MapTerrainBase) and #[cfg(feature = "cold_water_assets")]-gated starter blueprints (as_val_custom, gun_truck_zsu, bunker_outpost, guard_watchtower) with clean neutral engine starters when disabled.
  • pack.rs: .cwassetopack.json multi-mod bundles (AssetPack, AssetPackGrid) combining CSG blueprints (weapons, vehicles, maps, stamps), MapGenPalettes, custom grids (.cwgrid.json), and ColdFlux/Luau scripts (excluding heightmaps), with packs/ discovery, save_asset_pack, unpack_asset_pack_to_dir, and delete_asset_pack.
  • registry.rs: ModRegistry managing {project_root}/{weapons,vehicles,maps,stamps,mapgen_palettes,grids,scripts,packs,heightmaps} via load_project_dir / reload_project_dir (merging .cwassetopack.json bundles first with loose-file override precedence, plus list_all_grid_names / find_grid), compile_blueprints, with_temporary_overlay + temp_heightmaps for non-destructive MP mod syncing, lookup_blueprint_transfer, and rebuilding WorldData (with enterable CSG NavGrid::apply_csg_geometry, MapGenPalette-aware dynamic generation, and evaluated map modifiers) from MapBlueprint.
  • studio.rs: AssetStudioState managing StudioMode::{Weapon, Vehicle, Map, MapStamp}, undo/redo history, CSG & modifier stack editing, add_custom_map_stamp, align_stamp_to_ground_and_center, unpack_selected_group, camera orbit/pan/zoom, live preview compilation, and 3D transform + anchor (StudioAnchor: WeaponMuzzle, VehicleTurretMount, VehicleTurretMuzzle, VehicleWheelAxle, MapSpawn, MapObjective, MapVehicle) gizmos for moving spawns, moving/radius-scaling objectives (R), and moving/yaw-rotating stock & custom vehicles (E).

src/scripting/ — Sandboxed Luau VM, ColdFlux Visual Scripting, UI Extensions & Persistence

  • vm.rs: Pure-Rust sandboxed Luau interpreter (ScriptVm, LuaValue, ScriptBudget) enforcing deterministic instruction & memory quotas with zero C/C++ build dependencies.
  • flux.rs: ColdFlux visual node-graph representation (ColdFluxGraph, FluxNode, FluxNodeKind, FluxPortDesc, FluxPortType, FluxWire) and compiler generating sandboxed Luau source across runtime, procedural modifier, and UI extension graphs.
  • api.rs: Host API (cw.*) exposing read-only simulation queries (ScriptReadView) and deferred side-effect requests (ScriptAction, ScriptVar) for raycasts, scenario variables, explosions, vehicle spawning, sounds, and dynamic lights.
  • ui_ext.rs: UiExtensionRegistry, UiSurface, UiScreenKind, and UiEvent enabling ColdFlux graphs and Luau scripts to extend Live Game, Game Master, and Asset Studio panels or spawn custom floating windows.
  • storage.rs: Persistent disk save, load, export, and autoload manager for .coldflux.json and .luau scripts under ./mods/scripts/ (with packed .cwassetopack.json script fallback and starter scripts including the vertical spinning staircase modifier).
  • perms.rs: Role-based PermissionsConfig, RoleCapabilities (Guest..Owner), ScriptScope, and ScriptAuditEntry execution audit log.
  • runtime.rs & mod.rs: ScriptingRuntime & ActiveScript execution manager dispatching lifecycle/combat/UI hooks and draining validated ScriptActions into Simulation.

src/net/ & src/bin/cold_water_server.rs — Multiplayer Netcode, NAT Traversal, VoIP Relay & Server Packaging

  • transport.rs: Non-blocking UdpTransport (b"PCW1" header) with 1100-byte MTU fragmentation/reassembly, reliable ACK/retransmit, and LAN broadcast support.
  • protocol.rs: ClientMessage / ServerMessage enums, WorldSnapshot (replicated soldiers including ActorPosture::Dead corpses, vehicles + speed, left_track_offset, right_track_offset, rotor_rpm, rotor_spin, NetTracer, NetCombatFx, NetSoundFx, your_hit_marker, ConflictSnapshot, roster), VoiceMode / VoicePacket (RadioTune, Voice), NetDestructionEvent history + late-joiner sync, NetScriptSync / AdminScriptAction RPCs, and RequestMods / ModPayload mod transfer packets.
  • handshake.rs: ServerHandshake, HandshakeMapSource, FNV-1a ModManifestEntry diffing, and safety caps (MAX_TEMP_MOD_COUNT = 64, MAX_TEMP_MOD_JSON_BYTES = 512 KB, MAX_TEMP_HEIGHTMAP_BYTES = 2 MB, MAX_TEMP_CSG_NODES = 512).
  • punch.rs: PunchMessage (b"PCHP" multiplex on the same UdpTransport socket) and RendezvousServer (cold_water_server --rendezvous) for NAT reflection and simultaneous UDP hole punching via Room Code.
  • config.rs: ServerConfigFile (server_config.json auto-creation/loading, map selection, admin_callsigns, hole-punch settings) and hostname/port resolution (resolve_socket_addr).
  • lag_comp.rs: LagCompBuffer keeping 250 ms of historical SoldierHitbox frames for RTT-rewound BVH-clamped hit validation.
  • server.rs: Authoritative 60 Hz NetServer + listen-server HostedServerHandle, AI-crewed vehicle boarding/seat swapping (toggle_session_vehicle, switch_session_seat), admin_callsigns Owner assignment, permission-checked script/admin RPCs, VoIP frequency/encryption/Conflict-relay/proximity filtering, CSG destruction event history/broadcast, rendezvous keepalives, and reliable mod serving.
  • client.rs: NetClient (direct IP, connect_via_punch, SyncingMods hash/size verification, send_voice / send_radio_tune / drain_incoming_voice, soldier table expansion, per-frame smooth interpolation, destruction & script replication, LanDiscoveryScanner).
  • src/bin/cold_water_server.rs: Standalone headless dedicated server + --rendezvous relay executable built natively for Windows and cross-compiled statically to Linux ELF64 via .cargo/config.toml, scripts/build_linux_server.ps1, scripts/build_linux_server.sh, and Dockerfile.server (dist/linux/).

src/audio/ — Two-Level BVH Acoustics, Procedural Synth & VoIP DSP (client)

  • bvh.rs: Always-compiled two-level composite AcousticBvh combining an immutable terrain/static base: Arc<FlatBvh> with a fast < 0.1 ms dynamic: Option<Arc<DynamicBvh>> rebuilt incrementally (build_split, with_updated_destructibles) for zero-stutter CSG destruction collision, ballistic sweeps, and acoustic raycasts.
  • voip.rs: Pure-Rust 8 kHz IMA ADPCM encoder/decoder (ImaAdpcmEncoder, ImaAdpcmDecoder, VOIP_SAMPLE_RATE = 8000, VOIP_FRAME_SAMPLES = 160) + cpal PTT microphone capture (MicCaptureHandle).
  • propagation.rs, patch.rs, dsp.rs, engine.rs, src/audio/synth/*: Async BVH propagation worker + ITD/ILD binaural + Hadamard FDN late reverb + 8-slot lock-free VoiceStreamSlot radio/proximity VoIP DSP mixer (VoicePlaybackChunk, radio bandpass/static/squelch, binaural/occluded proximity).

src/replay/ — Admin & Cinematic Replay System

  • format.rs: ReplayFile (.cwrep.json), ReplayHeader (including HandshakeMapSource reconstruction, legacy custom-map recovery, vehicle_catalog of VehicleKind / custom mod IDs, and weather snapshots), ReplayTickFrame, soldier/vehicle delta states, tracer/FX/destruction events, admin bookmarks/pins, and ReplayCatalogEntry.
  • recorder.rs: ReplayRecorder capturing simulation frames, combat events, destruction history, and dynamically spawned GM/CSG custom vehicles in both client matches (F11 / Shift+F11) and cold_water_server.
  • player.rs: ReplayPlaybackState interpolating soldier/vehicle transforms & animations (speed, track offsets, helicopter rotor RPM/spin), syncing dynamic GM/CSG vehicle creation & despawning via vehicle_catalog, rebuilding & flushing batched CSG destruction craters cleanly on seek, and running playback POVs (FreeCam, FollowSoldier, FirstPerson).
  • cinematic.rs & mod.rs: CameraKeyframe Catmull-Rom spline evaluation with shortest-angle yaw unwrap, TimeKeyframe variable-speed time remapping, ReplayExportJob state, and PNG sequence / FFmpeg output orchestration.

src/ui/ & Shell (src/app.rs, src/main.rs, src/bin/sculpt.rs, src/camera.rs, client)

  • src/app.rs, src/main.rs, src/bin/sculpt.rs: Unified LaunchMode::{ColdWater, Sculpt} runtime (ColdWaterApp + AppRuntime), --project <dir> workspace switching (switch_project_root), open_mods_folder, --verify-render, temporary MP mod backup/restore lifecycle, step_client_cosmetic_fx, live Replay Studio & offline PNG/FFmpeg export loop, VoIP mic polling / loopback / UDP TX+RX, helicopter controls, GridDesignerState + MapGenStudioActions dispatch, and FPS pacing.
  • src/camera.rs: CameraController (Tactical Free-Cam clamped to playable_half_extents(), First-Person camera, zero-clip viewmodel projection, dynamic far_plane scaling up to 10 km, Gribb-Hartmann frustum extraction).
  • src/ui/sculpt_hub.rs, mapgen_ui.rs, pack_builder.rs, replay_ui.rs, main_menu.rs, hud.rs, director_ui.rs, squad_ui.rs, script_ui.rs, asset_studio.rs, audio_editor.rs, flux_editor.rs, server_admin.rs: Complete UI layer including Main Menu & Sculpt Engine Hub (sculpt_hub.rs), Interactive 2D Grid Map Painter (3×3..128×128) & MapGen Asset Palette Editor (mapgen_ui.rs), Asset Pack Builder (.cwassetopack.json) (pack_builder.rs), Replay Library & Cinematic Studio (replay_ui.rs), Multiplayer (Host/LAN + Hole Punch toggle), Direct Connect, Arma/Squad magazine HUD + quick-use strip + Radio/VoIP status pill, Weather/GM Randomize Clouds, Respawn kit-scoped Weapon & 7-role Kit/Sandbox selector, Game Director "Spawn with AI Crew" toggle & per-vehicle AI Tactic controls (director_ui.rs), Squad Manager (U), VHF Radio Tuner (N), Inventory & Magazines (I), AI Helpers Bar (Z), Asset Studio & Map Editor gizmo/modifier panels, ColdFlux Visual Scripting & Luau Studio (F9), extensible script UI overlays/windows, and Server Admin & Permissions (F10).

5. Testing & Verification Suites (tests/)

All subsystems are covered by 101 integration, networking, modding, replay, scripting, mapgen, tactical, and GPU tests:

  • tests/acoustics_and_sim.rs (25 tests): Two-level BVH occlusion/diffraction, multi-bounce canyon echoes, Hadamard FDN + ITD/ILD, procedural sound/patch DSP, unified soldier variety, swept capsule ballistics, suppression spike/recovery, AI sensory/accuracy curves, 3 km chunked terrain + hierarchical nav, wheeled suspension/BTR armor, helicopters (collective/cyclic/auto-hover), autocannons, SACLOS TOW/ATGMs, tracked differential drive + neutral pivot turns + directional heavy armor, multi-barrel alternating/salvo firing, bullet hit effects, dynamic & stitched maps, Game Director recycling, and all 6 mission objective types.
  • tests/gpu_shaders.rs (7 tests): Headless wgpu verification of all 13 WGSL shaders, cloud/shadow non-empty pass outputs, 3 km chunked theater rendering, dry/small city hot-reloads, stitched theater hot-reloads, custom CSG weapon/vehicle/map rendering, and Bgra8Unorm -> RGBA8 PNG readback channel normalization.
  • tests/modding_csg.rs (22 tests): CSG BSP boolean ops & stamps, convex CSG crater subtraction + repeated/overlapping crater limits & post-breach collision clearance, 3-mode building structural collapse (Pancake, CantileverV, AFrame), non-destructive Array/RandomizeTransforms/Curve modifiers + map modifier baking, blueprint JSON/heightmap/BVH roundtrips, .cwassetopack.json multi-mod pack roundtrip/loose-override/unpacking (scripts + grids + blueprints + palettes), custom turreted gunner seat/optic behavior, multi-barrel/tracked blueprint serialization, WIP empty-hull loading, 3D node transform gizmo drag/rollback, interactive turret/muzzle/wheel-axle & Map Editor spawn/objective/vehicle 3D gizmos, Map Stamp Creator (align_stamp_to_ground_and_center, add_custom_map_stamp, unpack_selected_group), and enterable CSG building doorway/wall navigation & FPS collision.
  • tests/multiplayer_server.rs (14 tests): TireRubber 16-sided outward-wound chevron wheels, multiplayer sessions/deploy/input/disconnect, deterministic handshake & mod manifest diff, live UDP server-client loop, lag compensation RTT rewind, Conflict radio capture & forward spawns, server_config.json auto-creation/roundtrip, live UDP hole-punch rendezvous pairing & unknown-room rejection, world-hit tracer/FX emission, WorldSnapshot soldier expansion + replicated combat FX, multi-crew MP vehicle boarding/driving/gunnery/exit + tracked/helicopter sync, on-foot MP weapon firing + dead corpse posture sync, NetDestructionEvent replication/late-join sync, and automatic temporary mod transfer & cleanup.
  • tests/replay_system.rs (7 tests): Live & server-side .cwrep.json recording and catalog listing, interpolation & POV sync, Catmull-Rom cinematic camera & shortest-angle yaw/FOV/roll + time-ramp spline evaluation, CSG destruction crater rebuild + animation + deduplication, custom map & legacy label reconstruction, and dynamic GM/CSG custom vehicle spawning/animation/despawning via vehicle_catalog.
  • tests/scripting_and_coldflux.rs (10 tests): Sandboxed pure-Rust Luau VM quotas & cw.* API, ColdFlux visual node-graph & modifier compilation, Luau modifier scripts & custom params, extensible UI surfaces & ColdFlux/Luau UI click/change events, persistent .coldflux.json/.luau disk save/load/export/autoload, role-based PermissionsConfig enforcement + audit logs, and authoritative MP script sync/RPC checks.
  • tests/sculpt_and_grid_mapgen.rs (6 tests): MapGenPalette custom CSG stamp binding + export_builtin_preset_to_map_stamp conversion, 3×3 small and 128×128 (Sector128m) chunked scaling + bounded NavGrid, terrain bounds & biome-aware +25% skirt across square/rectangular/island grids with zero out-of-bounds object placement, full CSG destruction across placed grid buildings, empty Sculpt workspace starter isolation (load_project_dir(..., false)), and 2D grid painting tools + .cwgrid.json roundtrip.
  • tests/tactical_systems.rs (10 tests): Discrete magazine partial-retention/+1 chamber/repack/mass, 7-kit inventory + kit-locked scroll cycling + bleeding/bandage/frag/smoke + weight encumbrance, VHF frequency snapping/terrain static/encryption/dual-watch + 8 kHz IMA ADPCM roundtrip, UDP VoIP frequency/encryption/proximity relay, squad management/formations/ROE/rally + AI Medic/Ammo Bearer helpers, helicopter CAS/Transport/Move auto-behaviors & safe LZ dismount, tracked Move/AssistInfantry/ArmoredPush/SuppressPosition tactics & tactical reverse, multi-domain ZU-23 AA & ATGM prioritization, Game Director "Spawn with AI Crew" toggle, and shot-down helicopter gravity fall & crash impact.

Engine-only headless verification (no Cold Water assets, GPU, or window required, 26 tests):

cargo test --no-default-features --test sculpt_and_grid_mapgen --test scripting_and_coldflux --test tactical_systems