Kaynağa Gözat

Upload files to ''

Vasily 18 saat önce
ebeveyn
işleme
4e7c302778
3 değiştirilmiş dosya ile 848 ekleme ve 2 silme
  1. 201 0
      ARCHITECTURE.md
  2. 467 0
      MODDING_GUIDE.md
  3. 180 2
      README.md

+ 201 - 0
ARCHITECTURE.md

@@ -0,0 +1,201 @@
+# 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.toml):
+
+- **Cargo Features (`default = ["client", "cold_water_assets"]`)**:
+  - `client`: Separates GUI, GPU, and audio dependencies behind `client`, allowing [`cold_water_server`](src/bin/cold_water_server.rs) 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`](src/scripting/vm.rs) and ColdFlux compiler in [`src/scripting/flux.rs`](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`](src/bin/sculpt.rs) 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
+
+```text
+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`](src/render/mod.rs)) executes a multi-pass HDR pipeline backed by 13 WGSL shaders:
+
+1. **Startup Procedural Synthesis**:
+   - [`shaders/gen_materials.wgsl`](shaders/gen_materials.wgsl) + [`shaders/gen_mat_mip.wgsl`](shaders/gen_mat_mip.wgsl): Synthesizes 21 `MaterialId` texture layers (`GPU_LAYER_COUNT = 21`, including `TireRubber` off-road chevron tread albedo, bump normals, and vulcanized ORM) and their mip chains in GPU storage/sampled textures ([`src/render/textures.rs`](src/render/textures.rs)).
+   - [`shaders/gen_cloud_noise.wgsl`](shaders/gen_cloud_noise.wgsl): Generates 3D Perlin-Worley curl/cloud noise textures ([`src/render/clouds.rs`](src/render/clouds.rs)).
+2. **Per-Frame Secondary Passes**:
+   - **Cloud Shadows**: [`shaders/cloud_shadow.wgsl`](shaders/cloud_shadow.wgsl) + [`shaders/common.wgsl`](shaders/common.wgsl) (`cloud_weather_uvs`, `GlobalUniforms.cloud_params`) project drifting volumetric cloud transmittance onto terrain/objects using dual rotated, domain-warped weather octaves (throttled in `stream_safe_mode`).
+   - **Sun Shadows**: [`shaders/shadow_depth.wgsl`](shaders/shadow_depth.wgsl) renders static structures, terrain, skinned soldiers, vehicles, and `fx_chunks` (skipping `fx_puff` and `fx_decal`) into a texel-snapped cascade ([`src/render/shadows.rs`](src/render/shadows.rs)).
+   - **Dual Paraboloid Reflections**: [`shaders/paraboloid.wgsl`](shaders/paraboloid.wgsl) + [`shaders/paraboloid_mip.wgsl`](shaders/paraboloid_mip.wgsl) render front/back hemisphere cubemap-free reflections at lower cadence ([`src/render/paraboloid.rs`](src/render/paraboloid.rs)).
+3. **Main Forward HDR Pass ([`src/render/main_pass.rs`](src/render/main_pass.rs))**:
+   - [`shaders/pbr_main.wgsl`](shaders/pbr_main.wgsl) + [`shaders/common.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/resources.rs), [`src/render/mod.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`](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`](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`](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`](shaders/post.wgsl) ([`src/render/post.rs`](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`](src/core/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`](src/core/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`](src/core/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`](src/core/math.rs): Geometry, interpolation, and ray intersection helpers.
+
+### `src/world/` — Maps, Chunked Terrain, Meshes & Navigation
+- [`terrain.rs`](src/world/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`](src/world/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`](src/world/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`](src/world/assets.rs) & [`structures.rs`](src/world/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`](src/world/points.rs) & [`nav.rs`](src/world/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`](src/world/actors_mesh.rs), [`weapons_mesh.rs`](src/world/weapons_mesh.rs), [`vehicles_mesh.rs`](src/world/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`](src/world/mod.rs): Top-level `WorldData` container (up to `MAX_SKINNED_SOLDIERS = 192`).
+
+### `src/sim/` — Simulation & Gameplay Logic
+- [`sim/mod.rs`](src/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`](src/sim/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`](src/sim/inventory.rs): Non-visual inventory and 7 tactical `KitRole`s (`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`](src/sim/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`](src/sim/session.rs): `PlayerId`, `PlayerRole` (`Guest`..`Owner` with GM/script permissions), `ClientInputCmd`, and `PlayerSession` (storing `FpsPlayerState`, `RadioState`, and `last_vehicle_input`).
+- [`conflict.rs`](src/sim/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`](src/sim/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`](src/sim/ai.rs) & [`orders.rs`](src/sim/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`](src/sim/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`](src/sim/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`](src/sim/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`](src/sim/director.rs), [`objectives.rs`](src/sim/objectives.rs), [`spawn.rs`](src/sim/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`](src/sim/weapons.rs): Ballistic & mechanical specs for all 6 base weapon archetypes.
+
+### `src/modding/` — Sculpt Engine CSG Modding, Destruction, Modifiers & Asset Studio
+- [`csg.rs`](src/modding/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`](src/modding/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`](src/modding/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`](src/modding/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`](src/modding/pack.rs): `.cwassetopack.json` multi-mod bundles (`AssetPack`, `AssetPackGrid`) combining CSG blueprints (weapons, vehicles, maps, stamps), `MapGenPalette`s, 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`](src/modding/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`](src/modding/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`](src/scripting/vm.rs): Pure-Rust sandboxed Luau interpreter (`ScriptVm`, `LuaValue`, `ScriptBudget`) enforcing deterministic instruction & memory quotas with zero C/C++ build dependencies.
+- [`flux.rs`](src/scripting/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`](src/scripting/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`](src/scripting/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`](src/scripting/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`](src/scripting/perms.rs): Role-based `PermissionsConfig`, `RoleCapabilities` (`Guest`..`Owner`), `ScriptScope`, and `ScriptAuditEntry` execution audit log.
+- [`runtime.rs`](src/scripting/runtime.rs) & [`mod.rs`](src/scripting/mod.rs): `ScriptingRuntime` & `ActiveScript` execution manager dispatching lifecycle/combat/UI hooks and draining validated `ScriptAction`s into `Simulation`.
+
+### `src/net/` & `src/bin/cold_water_server.rs` — Multiplayer Netcode, NAT Traversal, VoIP Relay & Server Packaging
+- [`transport.rs`](src/net/transport.rs): Non-blocking `UdpTransport` (`b"PCW1"` header) with 1100-byte MTU fragmentation/reassembly, reliable ACK/retransmit, and LAN broadcast support.
+- [`protocol.rs`](src/net/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`](src/net/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`](src/net/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`](src/net/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`](src/net/lag_comp.rs): `LagCompBuffer` keeping 250 ms of historical `SoldierHitbox` frames for RTT-rewound BVH-clamped hit validation.
+- [`server.rs`](src/net/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`](src/net/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`](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`](.cargo/config.toml), [`scripts/build_linux_server.ps1`](scripts/build_linux_server.ps1), [`scripts/build_linux_server.sh`](scripts/build_linux_server.sh), and [`Dockerfile.server`](Dockerfile.server) (`dist/linux/`).
+
+### `src/audio/` — Two-Level BVH Acoustics, Procedural Synth & VoIP DSP (`client`)
+- [`bvh.rs`](src/audio/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`](src/audio/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`](src/audio/propagation.rs), [`patch.rs`](src/audio/patch.rs), [`dsp.rs`](src/audio/dsp.rs), [`engine.rs`](src/audio/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`](src/replay/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`](src/replay/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`](src/replay/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`](src/replay/cinematic.rs) & [`mod.rs`](src/replay/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/app.rs), [`src/main.rs`](src/main.rs), [`src/bin/sculpt.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`](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`](src/ui/sculpt_hub.rs), [`mapgen_ui.rs`](src/ui/mapgen_ui.rs), [`pack_builder.rs`](src/ui/pack_builder.rs), [`replay_ui.rs`](src/ui/replay_ui.rs), [`main_menu.rs`](src/ui/main_menu.rs), [`hud.rs`](src/ui/hud.rs), [`director_ui.rs`](src/ui/director_ui.rs), [`squad_ui.rs`](src/ui/squad_ui.rs), [`script_ui.rs`](src/ui/script_ui.rs), [`asset_studio.rs`](src/ui/asset_studio.rs), [`audio_editor.rs`](src/ui/audio_editor.rs), [`flux_editor.rs`](src/ui/flux_editor.rs), [`server_admin.rs`](src/ui/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`](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`](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`](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`](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`](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`](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`](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`](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**):
+```powershell
+cargo test --no-default-features --test sculpt_and_grid_mapgen --test scripting_and_coldflux --test tactical_systems
+```

+ 467 - 0
MODDING_GUIDE.md

@@ -0,0 +1,467 @@
+# Project Cold Water & Sculpt Engine — Modding Guide
+
+This guide covers creating, editing, scripting, packaging, and hosting custom **Weapons**, **Vehicles**, **Reusable Map Stamps**, **Maps & Missions**, **Custom Grid Maps (`.cwgrid.json`)**, **MapGen Asset Palettes**, **ColdFlux / Luau Scripts**, and **Asset Packs (`.cwassetopack.json`)** in **Project Cold Water** and **Sculpt Engine**.
+
+You can author almost everything visually inside the in-engine **Asset Studio** and **Grid & Palette Studio**, or write/tweak the JSON and Luau files directly.
+
+See [`README.md`](README.md) for general controls and CLI flags, and [`ARCHITECTURE.md`](ARCHITECTURE.md) for internal engine details.
+
+---
+
+## Table of Contents
+
+1. [Modding Folder Layout & Reloading](#1-modding-folder-layout--reloading)
+2. [CSG Sculpting, Materials & Procedural Modifiers](#2-csg-sculpting-materials--procedural-modifiers)
+3. [Custom Weapons (`mods/weapons/`)](#3-custom-weapons-modsweapons)
+4. [Custom Vehicles & Turrets (`mods/vehicles/`)](#4-custom-vehicles--turrets-modsvehicles)
+5. [Reusable Map Stamps (`mods/stamps/`)](#5-reusable-map-stamps-modsstamps)
+6. [Maps, Missions & Default AI Behavior (`mods/maps/`)](#6-maps-missions--default-ai-behavior-modsmaps)
+7. [Custom Grids (`.cwgrid.json`) & Asset Palettes (`mods/mapgen_palettes/`)](#7-custom-grids-cwgridjson--asset-palettes-modsmapgen_palettes)
+8. [ColdFlux & Luau Scripting (`mods/scripts/`, `F9`)](#8-coldflux--luau-scripting-modsscripts-f9)
+9. [Packaging Mods with `.cwassetopack.json` (`📦 Pack Builder`)](#9-packaging-mods-with-cwassetopackjson--pack-builder)
+10. [Multiplayer Hosting, Live Map Switching & Temp Mod Sync](#10-multiplayer-hosting-live-map-switching--temp-mod-sync)
+
+---
+
+## 1. Modding Folder Layout & Reloading
+
+### Cold Water vs Isolated Sculpt Projects
+- **`project_cold_water`** reads mods from **`./mods/`** by default (or the path passed to `--project <dir>`).
+- **`sculpt`** (the engine-only binary built with `--no-default-features --features client`) uses isolated workspaces under **`./sculpt_projects/<name>/`** (`--project sculpt_projects/default` by default) with zero Cold Water starter assets preloaded.
+
+Both project roots share the exact same subfolder structure:
+
+```text
+mods/  (or sculpt_projects/<name>/)
+├── weapons/*.json              # Custom CSG weapons + ballistics/audio stats
+├── vehicles/*.json             # Custom CSG vehicles + locomotion/turret/armor specs
+├── maps/*.json                 # Custom CSG maps, missions & terrain/generator configs
+├── stamps/*.json               # Reusable CSG building/cover stamps
+├── mapgen_palettes/*.json      # Weighted asset tables per biome & slot for MapGen
+├── grids/*.cwgrid.json         # Painted 3x3..128x128 custom grid maps
+├── scripts/
+│   ├── *.luau                  # Persistent Luau gameplay / UI / modifier scripts
+│   └── *.coldflux.json         # Saved ColdFlux visual node-graph scripts
+├── packs/*.cwassetopack.json   # Multi-mod bundles (excludes heightmaps)
+└── heightmaps/*.png            # 8-bit / 16-bit grayscale terrain heightmaps
+```
+
+### Envelope Format (`AssetBlueprint`)
+Weapons, vehicles, maps, and map stamps share the top-level JSON wrapper `AssetBlueprint` (`schema_version: 1`):
+
+```json
+{
+  "schema_version": 1,
+  "id": "my_custom_id",
+  "name": "Display Name",
+  "author": "Your Name",
+  "payload": {
+    "Weapon": { }
+  }
+}
+```
+
+Valid `payload` tags are `"Weapon"`, `"Vehicle"`, `"Map"`, and `"MapStamp"`. IDs are normalized with lowercase alphanumeric + underscores (`a-z`, `0-9`, `_`).
+
+### Hot Reloading & Precedence
+- Click **`📁 Open Mod Folder`** in the Main Menu or Asset Studio toolbar to open your active mods root in Explorer.
+- Click **`↻ Reload`** (Main Menu / Asset Studio) after hand-editing JSON or dropping packs/scripts on disk.
+- **Override Precedence:** Loose files in `weapons/`, `vehicles/`, `maps/`, `stamps/`, `mapgen_palettes/`, `grids/`, and `scripts/` take priority over assets of the same ID inside `.cwassetopack.json` packs.
+
+---
+
+## 2. CSG Sculpting, Materials & Procedural Modifiers
+
+### CSG Tree (`CsgNode`)
+Every weapon, vehicle hull, vehicle turret, map stamp, and map structure is a sequence of CSG nodes:
+- **Operations (`op`)**: `"Union"` (`+`), `"Subtract"` (`-`), `"Intersect"` (`∩`). Keep at least one solid `"Union"` base before `"Subtract"` cutters so negative space carves cleanly.
+- **Shapes (`shape`)**:
+  - `{"Primitive": "Box"}`
+  - `{"Primitive": {"Cylinder": {"segments": 12}}}`
+  - `{"Primitive": {"Sphere": {"rings": 8, "sectors": 12}}}`
+  - `{"Primitive": {"Cone": {"segments": 12}}}`
+  - `{"Primitive": "Wedge"}`
+  - `{"Primitive": {"Torus": {"major_segs": 12, "minor_segs": 8}}}`
+  - `{"Primitive": {"AssetStamp": "Ak74m"}}` — clones built-in geometry (`Ak74m`, `Akm`, `Aks74u`, `Pkm`, `Svd`, `Rpg7v`, `Uaz469Body`, `Ural4320Body`, `Btr80Hull`, `Btr80Turret`, `VehicleWheel`, `SandbagWall`, `ConcreteBarrier`, `BunkerShell`, `PineTree`)
+  - `{"Group": [ ...CsgNode... ]}` — reusable nested group (used by **Map Stamps**).
+- **Transforms**: `pos: [x, y, z]`, `rot_deg: [rx, ry, rz]`, `scale: [sx, sy, sz]`.
+
+### Asset Studio Viewport Controls
+| Input | Action |
+| :--- | :--- |
+| `LMB` | Pick CSG node, `TURRET` / `MUZZLE` / `AXLE` anchor, or `SPAWN` / `OBJ` / `VEH` marker and drag gizmo |
+| `W` / `R` / `E` | Switch Gizmo: Move / Scale (or Objective Radius) / Rotate (or Vehicle Yaw) |
+| Hold `Ctrl` | Grid / angle snapping during drag |
+| `F` | Focus camera on selected part/marker |
+| `RMB` drag | Orbit camera |
+| `MMB` drag or `Shift + RMB` | Pan camera target |
+| `Scroll` | Zoom (scales dynamically to map extent up to 2.6 km in Map mode) |
+| `Ctrl+Z` / `Ctrl+Y` | Undo / Redo CSG & property edits |
+
+### Materials (`MaterialId`)
+Textures, PBR roughness/wetness, 3-band acoustic absorption/scattering, and ballistic resistance/ricochet are all driven by `MaterialId`:
+
+| `MaterialId` | Surface Description | Typical Use |
+| :--- | :--- | :--- |
+| `"Concrete"` | Poured Soviet concrete | Bunkers, panelkas, barriers |
+| `"BrickRubble"` | Cracked masonry brick | Old compounds, warehouses |
+| `"WinterMud"` | Wet frozen dirt | Ground, berms, earthworks |
+| `"WetAsphalt"` | Slick dark road tarmac | Highways, airstrips, intersections |
+| `"MountainRock"` | Sharp Caucasus cliff granite | Cliffs, outcrops, boulders |
+| `"WinterSnow"` | Packed snowdrift | Alpine peaks, drifts |
+| `"SteelHulk"` | Painted heavy armor steel | Tanks, APC hulls, turrets, girders |
+| `"Sandbag"` | Heavy woven canvas | Sandbag walls, revetments |
+| `"WinterPine"` | Dark evergreen bark & needles | Conifers, timber logs |
+| `"FloraCamo"` | VSR-98 green camouflage fabric | Gear, tarps |
+| `"MilitiaCloth"` | Muted wool/cotton uniform cloth | Fabric wraps |
+| `"Gunmetal"` | Blued machined receiver steel | Rifle receivers, barrels, rails |
+| `"Vsr93Barvikha"` | Vertical-stripe camo fabric | Tarps, webbing |
+| `"GorkaKhaki"` | Mountain suit khaki canvas | Canvas covers, pouches |
+| `"M81Woodland"` | Four-color woodland camo | Pouches, gear |
+| `"AfghankaOlive"` | Olive drab field canvas | Field packs, seat fabric |
+| `"WinterOverwhite"` | Winter camo white cloth | Arctic wraps |
+| `"WoolFleece"` | Dark knit fleece | Trim, grips |
+| `"WoodFurniture"` | Laminated birch stock wood | AK stocks, crates, doors |
+| `"BakelitePlum"` | Dark plum/orange phenolic polymer | Magazines, pistol grips |
+| `"TireRubber"` | Molded off-road lugged rubber | Vehicle tires, mudflaps |
+| `"ColdWater"` | Acoustic water surface *(non-GPU solid)* | River water reference only |
+
+### Procedural Modifier Stack
+Each `CsgNode` can hold non-destructive `modifiers: [...]`:
+- **`Array`**:
+  - `mode`: `"Linear"`, `"Radial"`, or `"Grid"`.
+  - Linear/Grid repeat by `offset` (world meters) and/or `relative_offset`, plus per-step `step_rot_deg` and `step_scale`.
+  - Radial sweeps around `radial_radius` across `radial_arc_deg` with optional `radial_align`.
+  - Set `snap_to_terrain: true` in Map mode to drape fence posts, dragon's teeth, or streetlights onto terrain height.
+- **`RandomizeTransform`**:
+  - Deterministic seeded variation (`seed`) within `pos_min..pos_max`, `rot_min_deg..rot_max_deg`, `scale_min..scale_max`, optional `uniform_scale`, random `skip_chance`, and `snap_to_terrain`.
+- **`Curve`**:
+  - Distributes clones along local control `points` OR references a shared `MapNamedCurve` via `shared_curve_id`.
+  - Supports `"CatmullRom"` or `"Polyline"`, `"FitCount"` or `"FixedSpacing"`, `spacing_m`, `follow_tangent`, `forward_axis` (`"PosZ"`, `"PosX"`, `"NegZ"`, `"NegX"`), `bank_pitch`, `lateral_offset`, `vertical_offset`, `snap_to_terrain`, and `align_to_slope`.
+- **`LuauScript` / `ColdFlux`**:
+  - Scripted transform/modifier evaluation with live numeric sliders (`params`).
+
+> **Engine Caps:** `MAX_MODIFIER_INSTANCES = 128` instances per node, `MAX_BLUEPRINT_MODIFIER_INSTANCES = 512` destructible expanded structures per map, `MAX_CURVE_CONTROL_POINTS = 64`.
+
+---
+
+## 3. Custom Weapons (`mods/weapons/`)
+
+### Authoring Workflow in Asset Studio
+1. Open **Asset Studio** -> select **`🔫 Weapon`**.
+2. Pick a `base_archetype` (`"Ak74m"`, `"Akm"`, `"Aks74u"`, `"Pkm"`, `"Svd"`, `"Rpg7v"`) or click **Starter** for the suppressed carbine template.
+3. Add or subtract CSG parts around the origin (`+Z` points forward toward the muzzle; `+Y` is up).
+4. Toggle **`MUZZLE`** anchor selection (or click the 3D `MUZZLE` gizmo) to align tracer/flash spawn (`muzzle_local`).
+5. Adjust `sight_height_y` (ADS iron-sight alignment height in meters) and `ads_fov_deg` (zoomed FOV; enable `has_pso1_scope: true` for the 4× PSO-1 optic overlay).
+6. Click **`💾 Save JSON`** (writes `mods/weapons/<id>.json`) or **`🚀 Save & Test in Valley`** to spawn immediately holding your weapon.
+
+### `WeaponBlueprint` Field Reference
+- `base_archetype`: `"Ak74m" | "Akm" | "Aks74u" | "Pkm" | "Svd" | "Rpg7v"`
+- `damage`: base torso damage (`f32`; Headshots deal `2.2×`, Legs deal `0.75×`)
+- `rpm`: cyclic fire rate (`60.0 / fire_interval`)
+- `muzzle_velocity`: projectile speed (`m/s`)
+- `drag_coeff`: air resistance decay (`~0.0008`–`0.0020`)
+- `suppression_power`: suppression spike inflicted on nearby targets per bullet
+- `mag_capacity` / `reserve_default` / `reload_secs`: magazine size, starting spare rounds, and base reload time
+- `spread_rad`: base angular dispersion in radians
+- `recoil_pitch` / `recoil_yaw` / `recoil_kick_z`: per-shot climb, horizontal kick, and camera/viewmodel pushback
+- `auto_capable`: `true` enables `[B]` Full-Auto / Semi toggle
+- `is_rocket` / `blast_radius`: enable explosive warheads + CSG cratering on impact
+- `tracer_every`: `1` = every round has a visible tracer; `4` = every 4th round
+- `sound`: `"Ak74mShot" | "AkmShot" | "SvdShot" | "PkmShot" | "RpgLaunch" | ...`
+
+<details>
+<summary>Minimal Example: <code>mods/weapons/vintorez_9x39.json</code></summary>
+
+```json
+{
+  "schema_version": 1,
+  "id": "vintorez_9x39",
+  "name": "VSS Vintorez 9x39",
+  "author": "Modder",
+  "payload": {
+    "Weapon": {
+      "nodes": [
+        {
+          "id": 1,
+          "name": "Receiver Stamp",
+          "op": "Union",
+          "shape": { "Primitive": { "AssetStamp": "Aks74u" } },
+          "pos": [0.0, 0.0, 0.0],
+          "rot_deg": [0.0, 0.0, 0.0],
+          "scale": [1.0, 1.0, 1.0],
+          "material": "Gunmetal"
+        },
+        {
+          "id": 2,
+          "name": "Integral Suppressor",
+          "op": "Union",
+          "shape": { "Primitive": { "Cylinder": { "segments": 12 } } },
+          "pos": [0.0, 0.016, 0.48],
+          "rot_deg": [90.0, 0.0, 0.0],
+          "scale": [0.022, 0.28, 0.022],
+          "material": "Gunmetal"
+        }
+      ],
+      "base_archetype": "Svd",
+      "damage": 58.0,
+      "rpm": 700.0,
+      "muzzle_velocity": 295.0,
+      "drag_coeff": 0.0014,
+      "suppression_power": 0.16,
+      "mag_capacity": 20,
+      "reserve_default": 120,
+      "reload_secs": 2.1,
+      "spread_rad": 0.012,
+      "recoil_pitch": 0.014,
+      "recoil_yaw": 0.005,
+      "recoil_kick_z": 0.032,
+      "auto_capable": true,
+      "is_rocket": false,
+      "blast_radius": 0.0,
+      "tracer_every": 5,
+      "sound": "Aks74uShot",
+      "sight_height_y": 0.095,
+      "muzzle_local": [0.0, 0.016, 0.64],
+      "ads_fov_deg": 24.0,
+      "has_pso1_scope": true,
+      "script_hooks": []
+    }
+  }
+}
+```
+
+</details>
+
+---
+
+## 4. Custom Vehicles & Turrets (`mods/vehicles/`)
+
+### Authoring Workflow in Asset Studio
+1. Open **Asset Studio** -> select **`🚚 Vehicle`**.
+2. Switch **Edit Layer** between **`Hull`** (`hull_nodes`) and **`Turret`** (`turret_nodes`, rotated at `turret_mount_local`).
+3. Choose **Locomotion** (`locomotion`):
+   - `"Wheeled"`: configure `wheel_offsets` (`[x, z, can_steer]` with `AXLE 1..N` 3D markers), `wheel_radius`, `wheel_width`, `is_amphibious`. Engine auto-generates 16-sided off-road `TireRubber` lugged wheels at runtime.
+   - `"Tracked"`: configure `track_half_width`, `track_length`, `track_height`, `roadwheel_count`, `pivot_turn_rate` (differential steering & neutral pivot turns).
+   - `"Helicopter"`: configure `rotor_mount_local`, `tail_rotor_mount_local`, `rotor_radius`, `lift_power`, `max_climb_rate`.
+   - `"EmplacedTurret"`: stationary AA/AT tripod or gun emplacement (`has_turret` enabled).
+4. Set **3D Anchors**: drag `TURRET` (`turret_mount_local`) and `MUZZLE` (`turret_muzzle_local`) visually in the viewport.
+5. Configure **Turret Weapons** (`turret_primary` and optional `turret_secondary`):
+   - **Presets (`kind`)**: `"HeavyMg14_5mm"`, `"Autocannon30mm"`, `"TwinAutocannon23mm"`, `"TwinAutocannon30mm"`, `"TankCannon125mm"`, `"TowAtgmLauncher"`, `"AtakaQuadAtgm"`, `"RocketPodS8"`.
+   - **Multi-Barrel & Guidance**: `barrel_count` (`1..6`), `barrel_fire_mode` (`"Alternating"` | `"Salvo"`), `barrel_layout` (`"Horizontal"` | `"QuadGrid"` | `"Rotary"`), `barrel_spacing`, and `guidance` (`"Unguided"` | `"SaclosWireGuided"`).
+6. Set **Crew Seats** (`seat_roles`): mix of `"Driver"`, `"Gunner"`, and `"Passenger"` entries.
+7. Click **`💾 Save JSON`** to save to `mods/vehicles/<id>.json`. Your custom vehicle immediately appears in:
+   - **Game Director (`F7`)** -> *Vehicles* palette (with the **`Spawn with AI Crew`** toggle).
+   - **Map Editor (`🏔 Map / Heightmap`)** -> *Vehicles* panel dropdown (`Mod`).
+
+---
+
+## 5. Reusable Map Stamps (`mods/stamps/`)
+
+Use **Map Stamps** to build a building, guard tower, checkpoint, or barricade once and stamp it cleanly across any Map or MapGen Asset Palette.
+
+1. Switch Asset Studio to **`🧱 Map Stamp`**.
+2. Sculpt solid walls/pillars with **`+ Union`** and carve enterable doorways & firing windows with **`- Subtract`**.
+   - **Important for AI & Player entry:** Carve doors all the way down to `Y = 0` (at least `1.2 m` wide and `2.1 m` tall) so `NavGrid` carves walkable transitions cleanly through openings while solid walls block movement.
+3. Use **`Sit Base on Ground`** and **`Center XZ Pivot`** so the building rests cleanly at `Y = 0`.
+4. Click **`💾 Save JSON`** (or **`Save & Open in Map Editor`**) to save to `mods/stamps/<id>.json`.
+5. When placed in a `MapBlueprint` (or spawned by a `MapGenPalette`), each `MapStamp` compiles automatically as an independent **destructible structure** supporting **CSG craters** and **structural collapse** (`Pancaking`, `Cantilever V-Frame`, `A-Frame`).
+
+---
+
+## 6. Maps, Missions & Default AI Behavior (`mods/maps/`)
+
+Switch Asset Studio to **`🏔 Map / Heightmap`** to author playable maps and mission templates saved to `mods/maps/<id>.json`.
+
+### Choosing Base Terrain (`base_terrain`)
+Four terrain modes are available directly inside the **Terrain** selector:
+
+1. **`FlatSandbox`**: customizable `half_extent` (`120..450 m`) and GPU ground `material`.
+2. **`ClassicFoothills`**: builds on the built-in Foothill River Town valley terrain.
+3. **`HeightmapPng`**: loads 8-bit or 16-bit grayscale PNGs from `mods/heightmaps/` (or `<project>/heightmaps/`), with `half_extent`, `min_height`, `max_height`, `enable_water`, and `water_level`. Click **`🏔 Generate Demo Heightmap PNG`** to create a sample valley PNG immediately.
+4. **`Dynamic(MapGenConfig)`**: exposes **every procedural world generator** directly in the Map Editor:
+   - **Single Zone**: `"RiverValleyTown"`, `"SmallCity"`, `"TwinBridgeCrossing"`, `"DryCityOutskirts"`.
+   - **3-Zone Corridor**: customizable W / C / E biome strip (`Transition Blend`).
+   - **2×2 Quad**: 4-corner NW / NE / SW / SE stitched biomes.
+   - **3 km Theater**: `3072 m × 3072 m` chunked combined-arms map.
+   - **Custom Grid**: embeds any `CustomGridSpec` directly in the map! Pick any saved `.cwgrid.json`, adjust `Cell Scale` (`32m` / `64m` / `128m`), `Auto Roads`, `Auto Bridges`, `Seed`, `Asset Palette`, `Urban Density`, and `Rubble Density`, or click **`🎨 Open Grid & Palette Designer`** to paint cells live and click **`🗺 Apply Grid to Map Editor`** to push the painted grid right back into your map.
+
+### Placing Spawns, Objectives, Vehicles & Shared Curves
+- Click **`+ Fed Spawn` / `+ Mil Spawn`**, **`+ Add Objective`**, or **`+ Fed Vehicle` / `+ Mil Vehicle`**.
+- Drag any 3D marker directly with `LMB` (`W` Move, `R` scales Objective radius, `E` rotates Vehicle yaw), or use **`🔍`** to focus the camera.
+- Use **Shared Curves** (`named_curves`) to draw Catmull-Rom/Polyline roads or ridgelines and bind multiple `Curve` modifiers to follow the same path.
+
+### Configuring Mission Default Behavior (`mission_defaults`) & Per-Unit Overrides
+Inside the **`⚙ Mission Default Behavior`** panel in the Map Editor, you can define how missions and AI behave by default whenever the map loads, switches in multiplayer, or resets (`Reset`):
+
+- **Player / Mission Side (`friendly_faction`)**: `"Federal"` or `"Militia"`.
+- **Federal AI Defaults** & **Militia AI Defaults**:
+  - **Starting Order (`federal_behavior` / `militia_behavior`)**:
+    - `"MoveToObjective"` — march/advance tactically to objective
+    - `"AssaultObjective"` — aggressive assault on objective
+    - `"HoldCover"` — hold fortified cover at spawn point
+    - `"SuppressObjective"` — deliver suppressive fire onto objective sector
+  - **Formation (`federal_formation` / `militia_formation`)**: `"Wedge"`, `"Line"`, `"Column"`, `"Spread"`
+  - **ROE (`federal_roe` / `militia_roe`)**: `"WeaponsFree"`, `"ReturnFireOnly"`, `"HoldFire"`
+- **Vehicle AI Defaults**:
+  - `default_vehicle_tactic`: `"Auto"`, `{"Ground": "Move" | "AssistInfantry" | "ArmoredPush" | "SuppressPosition"}`, or `{"Heli": "Cas" | "Transport" | "Move"}`
+  - `vehicles_engage_objective`: when `true`, crewed vehicles automatically receive an `ai_target` on the primary (or selected) objective at match start
+- **Match Rules**:
+  - `default_ai_skill`: `null` (use user/server setting) or `"Conscript" | "Regular" | "Spetsnaz"`
+  - `respawn_delay_secs`: player respawn timer (`0..30 s`)
+  - `auto_director_waves`: automatically spawn reinforcement waves
+  - `sandbox_all_weapons`: allow all 6 weapons regardless of kit role
+
+Every individual **Squad Spawn** (`mb.spawns[i]`) and **Vehicle** (`mb.vehicles[i]`) can leave its behavior on **`Mission Default`** (inheriting faction/map defaults) or override its starting behavior, formation, ROE, objective engagement, and target objective index (`target_objective_idx`, `0`-based).
+
+<details>
+<summary>Example JSON snippet: <code>mission_defaults</code> + per-spawn / per-vehicle overrides inside <code>MapBlueprint</code></summary>
+
+```json
+"mission_defaults": {
+  "friendly_faction": "Federal",
+  "federal_behavior": "AssaultObjective",
+  "federal_formation": "Line",
+  "federal_roe": "WeaponsFree",
+  "militia_behavior": "HoldCover",
+  "militia_formation": "Wedge",
+  "militia_roe": "ReturnFireOnly",
+  "default_vehicle_tactic": { "Ground": "AssistInfantry" },
+  "vehicles_engage_objective": true,
+  "auto_director_waves": false,
+  "default_ai_skill": "Regular",
+  "respawn_delay_secs": 8.0,
+  "sandbox_all_weapons": false
+},
+"spawns": [
+  {
+    "name": "Federal Assault",
+    "faction": "Federal",
+    "pos": [-60.0, 0.0, -25.0],
+    "behavior": "MissionDefault",
+    "formation": null,
+    "roe": null,
+    "target_objective_idx": null
+  },
+  {
+    "name": "Overwatch PKM",
+    "faction": "Federal",
+    "pos": [-75.0, 0.0, 40.0],
+    "behavior": "SuppressObjective",
+    "formation": "Spread",
+    "roe": "WeaponsFree",
+    "target_objective_idx": 1
+  }
+],
+"vehicles": [
+  {
+    "name": "Mi-24V Gunship",
+    "stock_kind": "Mi24Gunship",
+    "custom_vehicle_id": null,
+    "faction": "Federal",
+    "pos": [-110.0, 0.0, 0.0],
+    "yaw_deg": 90.0,
+    "crewed": true,
+    "tactic_mode": { "Heli": "Cas" },
+    "engage_objective": true,
+    "target_objective_idx": 0
+  }
+]
+```
+
+</details>
+
+---
+
+## 7. Custom Grids (`.cwgrid.json`) & Asset Palettes (`mods/mapgen_palettes/`)
+
+Open **Grid & Palette Studio** via **`F6` -> `🗺 Grid & Palette Studio`**, **`F8`** in tactical view, **Sculpt Engine Hub**, or **`🗺 Grid & Palette Designer`** inside the Map Editor.
+
+### Painting `.cwgrid.json` Maps
+- **Dimensions**: `3×3` up to `128×128` tiles.
+- **Cell Scopes (`GridCellScope`)**:
+  - `"Block32m"` (`32 m` per cell — tight CQB towns)
+  - `"District64m"` (`64 m` per cell — standard districts & valleys)
+  - `"Sector128m"` (`128 m` per cell — up to `16.4 km × 16.4 km` theater scale)
+- **9 Biomes (`ZoneType`)**: `"SovietCityCore"`, `"SuburbanTown"`, `"IndustrialOutskirts"`, `"MilitaryOutpost"`, `"RiverCrossing"`, `"Forest"`, `"OpenField"`, `"FoothillRidge"`, `"WaterLake"`.
+- **Tools**: `Brush` (radius `1/2/4/8/16`), `Line / River` (clean continuous river channels with auto bank-to-bank bridges), `Flood Fill`, and `Eyedropper`, plus 6 quick templates (`Valley River`, `Twin Cities`, `Archipelago`, `Military Corridor`, `Random Biomes`, `Clear Field`).
+- Saved files live in `<mods_or_project_root>/grids/<name>.cwgrid.json` and can be launched from **Grid Studio**, **Multiplayer Host**, `server_config.json` (`"grid:<name>"`), or embedded inside a **Map Editor** map.
+
+### Customizing `MapGenPalette` (`mapgen_palettes/*.json`)
+Each `MapGenPalette` maps `(ZoneType, MapGenSlot)` -> weighted asset entries:
+- **Slots (`MapGenSlot`)**: `"LargeBuilding"`, `"MediumBuilding"`, `"SmallBuilding"`, `"Landmark"`, `"CoverProp"`, `"Bridge"`, `"Vegetation"`.
+- **Entry Types (`MapGenAssetRef`)**:
+  - `{"MapStamp": "your_stamp_id"}` — spawns one of your custom CSG stamps (`mods/stamps/*.json`)
+  - `{"BuiltIn": "<key>"}` — procedural built-in preset (`khrushchyovka`, `panelka`, `warehouse`, `brick_house`, `bunker`, `guard_tower`, `pine`, `sandbag`, etc.)
+- Each entry controls `weight`, `footprint_radius`, `min_scale`, `max_scale`, `random_yaw`, and `destructible`.
+- Inside the **MapGen Asset Palette Editor** tab, click **`Edit in Studio`** on any stamp or **`Convert -> CSG Stamp`** on any built-in preset to inspect/re-sculpt it in CSG Asset Studio.
+
+---
+
+## 8. ColdFlux & Luau Scripting (`mods/scripts/`, `F9`)
+
+Open the **ColdFlux / Luau Scripting Studio** with **`F9`** (or **`⚡ ColdFlux (F9)`** in Asset Studio).
+- **ColdFlux (`.coldflux.json`)**: Visual node graph compiled straight into sandboxed Luau source. Great for timers, triggers, variable checks, HUD buttons, explosions, lighting, and scenario scripting.
+- **Luau (`.luau`)**: Write sandboxed Luau scripts directly. Set `auto_load: true` in saved `.coldflux.json`/`.luau` headers to load scripts automatically with the world, or attach scripts directly onto a blueprint's `script_hooks` array.
+- Scripts run with `on_tick(dt)` every simulation tick inside strict VM caps (by role via `ScriptBudget`: e.g. `max_instructions`, `max_memory_bytes`, default `512 KB`).
+
+### Core `cw.*` API Quick Reference
+| Category | Functions |
+| :--- | :--- |
+| **World & Queries** | `cw.time()`, `cw.ground_height(x, z)` / `cw.ground_height(vec3)`, `cw.is_walkable(x, z)`, `cw.raycast(origin, dir, max_dist)`, `cw.find_entities_in_radius(center, radius)`, `cw.get_soldier(id)`, `cw.get_vehicle(id)` |
+| **Variables** | `cw.get_var(key)`, `cw.set_var(key, val)` |
+| **Combat & FX** | `cw.play_sound(kind, pos, gain)`, `cw.spawn_light(pos, r, g, b, intensity, radius)`, `cw.spawn_explosion(pos, radius, damage, crater_radius)`, `cw.spawn_vehicle(kind, faction, pos)`, `cw.damage_entity(kind, id, amount)`, `cw.call_artillery(pos)`, `cw.broadcast_banner(text)` |
+| **UI Extensions (`cw.ui.*`)** | `cw.ui.panel(id, title, surface, opts)`, `cw.ui.window(id, title, w, h, screens)`, `cw.ui.heading(panel, id, text)`, `cw.ui.label(...)`, `cw.ui.button(panel, id, label)` *(returns `true` on click)*, `cw.ui.checkbox(...)`, `cw.ui.slider(...)`, `cw.ui.set_open(panel, bool)`, `cw.ui.is_open(panel)`, `cw.ui.clear(panel)`, `cw.ui.remove(panel)`, `cw.ui.toast(text, secs)`, `cw.ui.context()` |
+| **Game Director (`cw.gm.*`)** | `cw.gm.set_time_scale(scale)`, `cw.gm.set_paused(bool)`, `cw.gm.set_weather(sun_elev, clouds, wetness)`, `cw.gm.heal_all(faction_or_nil)` |
+| **Asset Studio (`cw.editor.*`)** | `cw.editor.add_primitive(kind, name, pos, size)`, `cw.editor.set_selected_pos/rot/scale(vec3)`, `cw.editor.duplicate_selected()`, `cw.editor.focus_selection()`, `cw.editor.set_status(text)`, `cw.editor.add_map_spawn(name, faction, pos)`, `cw.editor.add_map_objective(name, pos)` |
+
+<details>
+<summary>Example: Simple Luau Script Adding a Live Artillery Call HUD Window (<code>mods/scripts/arty_button.luau</code>)</summary>
+
+```lua
+function on_tick(dt)
+    cw.ui.window("mod_support_win", "Custom Support", 240, 120, "LiveGame")
+    cw.ui.label("mod_support_win", "info", "Click to call danger-close smoke/HE:")
+    if cw.ui.button("mod_support_win", "fire_btn", "Fire Mission (0, 0, 0)") then
+        cw.call_artillery({ x = 0, y = 0, z = 0 })
+        cw.broadcast_banner("Custom Luau Fire Mission Inbound!")
+    end
+end
+```
+
+</details>
+
+---
+
+## 9. Packaging Mods with `.cwassetopack.json` (`📦 Pack Builder`)
+
+Instead of sharing dozens of separate JSON files, open **`📦 Pack Builder`** inside Asset Studio to bundle a full mod collection into a single `./mods/packs/<id>.cwassetopack.json`:
+- Select any combination of **Weapons**, **Vehicles**, **Maps**, **Map Stamps**, **MapGen Palettes**, **Custom Grids**, and **ColdFlux/Luau Scripts**.
+- **Important:** Heightmap `.png` files are intentionally excluded from packs (`heightmaps/*.png` must still be distributed separately if a map uses `HeightmapPng`).
+- **Pack Builder Actions**:
+  - **`Export Pack`**: saves `./mods/packs/<id>.cwassetopack.json`.
+  - **`Edit in Builder`**: opens an existing pack to add/remove items or change version/author metadata.
+  - **`Unpack to Loose`**: extracts every bundled asset, palette, `.cwgrid.json`, and script back into loose folders so they can be edited individually or override the pack.
+
+---
+
+## 10. Multiplayer Hosting, Live Map Switching & Temp Mod Sync
+
+### Hosting Custom Maps & Grids
+1. **In-App Host UI (`🌐 Multiplayer -> Host`)**:
+   - Select any built-in map, any saved **Custom Grid (`.cwgrid.json`)**, or any **Custom CSG Map (`mods/maps/*.json`)**.
+   - Configure `GM Password (PIN)` (lets trusted players claim `GameMaster` live in `F10`) and `Allow All GM` (open sandbox, off by default).
+   - While in-game, `Owner` / `Admin` players can switch maps live via **`F6` Map Gen** or **Grid & Palette Studio** (`ChangeMap` reloads the world across all connected clients without dropping their session).
+2. **Dedicated Server (`server_config.json`)**:
+   - Set `"map"` to `"foothills"`, `"small_city"`, `"twin_bridges"`, `"dry_city"`, `"theater_3km"`, `"custom:<map_id>"`, or `"grid:<grid_name>"`.
+   - Set `"mods_dir"`, `"admin_callsigns"`, `"gm_password"`, and `"allow_all_gm"`.
+
+### Automatic Temporary Mod Sync Limits
+When clients join a modded server (or when the host switches to a custom map live), the server compares FNV-1a manifests and transfers missing blueprints, palettes/grids embedded in `MapBlueprint`, and heightmap PNGs automatically into an **in-memory session overlay** (never overwriting the client's local `./mods/` folder):
+- `MAX_TEMP_MOD_COUNT`: `64` entries
+- `MAX_TEMP_MOD_JSON_BYTES`: `512 KB` per blueprint
+- `MAX_TEMP_CSG_NODES`: `512` CSG nodes per blueprint
+- `MAX_TEMP_HEIGHTMAP_BYTES`: `2 MB` per heightmap PNG
+- `NET_PROTOCOL_VERSION`: `2`
+
+If a blueprint fails validation or exceeds these limits during multiplayer sync, trim complex CSG node counts using **Instanced Modifiers** (`Array` / `Curve` instead of hundreds of raw manual `CsgNode`s) so the blueprint JSON stays compact and fast to transfer.

+ 180 - 2
README.md

@@ -1,3 +1,181 @@
-# Sculpt-Engine
+# Project Cold Water *(powered by Sculpt Engine)*
 
-engine and game code for Sculpt and Project Cold Water
+**Project Cold Water** is a tactical skirmishing simulator, first-person shooter (FPS), combined-arms sandbox, and authoritative UDP multiplayer game set in the Second Chechen War (winter 1999–2000), built on **Sculpt Engine** — a custom, pure-Rust (`wgpu 24` + `winit 0.30` + `egui 0.31` + `cpal 0.15`) procedural and CSG-first 3D engine.
+
+Rather than relying on external model packs, texture packs, or audio libraries, **Sculpt Engine** generates or sculpts **every texture, mesh, sound effect, acoustic reflection, world theater, and JSON mod in-engine**.
+
+See [`ARCHITECTURE.md`](ARCHITECTURE.md) for the full **Sculpt Engine** architecture, threading model, GPU render graph, networking stack, and module breakdown, and [`MODDING_GUIDE.md`](MODDING_GUIDE.md) for creating custom weapons, vehicles, CSG stamps, maps, missions, grids, asset packs, and ColdFlux/Luau scripts.
+
+---
+
+## Key Features
+
+### 1. First-Person Combat, Ballistics, Inventory & Ammo
+- **Tactical FPS Mode (`V`) & Kit-Based Deployment Menu (`M`)**: Entering any skirmish, map, or multiplayer match opens the interactive **Deployment & Spawn Select (`M`)** screen with clickable 3D map spawn pins (including deployed **Squad Rally Points**), faction choice, **7 Tactical Kit Roles** (`Rifleman`, `Combat Medic`, `Machine Gunner`, `Marksman`, `Anti-Tank`, `Squad Leader`, `Ammo Bearer`), kit-scoped weapon selection, and a **Sandbox All-Weapons** override toggle. Possess any living soldier with raw mouse aiming, carry-weight encumbrance speed scaling, sprint, crouch, jump, BVH-clamped leaning (`Q` / `E`), Full-Auto/Semi switching (`B`), aligned 3D iron sights (`RMB`), and a 4× **PSO-1** chevron optic overlay on the `SVD Dragunov`.
+- **Arma / Squad Magazine-Based Ammo System (`R`, `Ctrl+R`, `Shift+R`)**: Replaces pooled ammo with discrete tracked magazines (`MagazineWeaponState`), `+1` chambered round mechanics on closed-bolt rifles, partial magazine retention on tactical reloads (`0.85×` reload duration when chambered vs `1.15×` dry), per-round cartridge weight reduction, round-conserving spare magazine repacking (`Shift+R`), and a tactical HUD magazine fullness bar + `+1` chamber pip + spare mag pips (approximate descriptors `FULL`/`~3/4`/`~HALF`/`LOW`/`EMPTY` by default, exact round counts revealed on **Mag Check (`Ctrl+R`)** or optional HUD toggle).
+- **Non-Visual Inventory, Trauma & Throwables (`I`, `7`–`0`)**: Open the **Inventory, Kit & Magazines (`I`)** drawer or use quick keys for `Field Bandage` (`7`, stops bleeding & heals), `RGD-5 Frag Grenade` (`8`, bouncing ballistics & HE/fragmentation/destruction), `RDG-2 Smoke Grenade` (`9`, spawns `SmokePuff` screens that conceal soldiers from AI line-of-sight), and kit utility gear (`0`: `Medkit`, `Ammo Bag`, `Squad Rally Beacon`, or `Morphine`).
+- **6 Iconic Weapons**: `AK-74M` (5.45×39), `AKM` (7.62×39), `AKS-74U`, `PKM` (7.62×54mmR), `SVD Dragunov`, and `RPG-7V` (with visible `PG-7V` warhead) — plus custom CSG weapons loaded from `./mods/weapons/` or synced temporarily in multiplayer.
+- **Continuous Swept Capsule Ballistics & Visible Barrel-to-Target Tracers**: Posture-matched `Head` (2.2×), `Torso` (1.0×), and `Legs` (0.75×) hitboxes clamped behind world BVH walls, supersonic bullet cracks (closest point of approach), HE rocket/mortar blast radii, visible tracer/ballistic ribbons converging smoothly from weapon muzzle to crosshair impact across all trajectories (including terrain/wall hits), and distinct Body / Headshot / Kill hit markers.
+- **Snappy Suppression & Trauma Post-Processing**: Near-miss gunfire, close impacts, and explosions drive GPU radial block pixelation, peripheral chromatic aberration, adrenaline desaturation, and pulsed tunnel-vision vignette (`shaders/post.wgsl`), with fast recovery once you leave gunfire.
+- **Material-Aware 3D Bullet Hit Effects**: Flying debris chunks, dust/snow/water/smoke puffs, HDR ricochet spark streaks, brief dynamic impact lights, and persistent bullet-hole/scorch decals tailored per material (`Concrete`, `BrickRubble`, `SteelHulk`/`Gunmetal`, `WinterSnow`, `WinterMud`/`Sandbag`, `WoodFurniture`/`WinterPine`, `ColdWater`), plus armored vs unarmored vehicle hits, helmet vs torso soldier hits, and HE explosion bursts.
+
+### 2. Squad AI, Squad Management, Combined-Arms Vehicles & Game Director
+- **Sensory Tactical AI (up to 192 Soldiers)**: Forward vision cones (blocked dynamically by `SmokePuff` screens), range/stance-scaled spotting delays, gunfire hearing, opening-burst spread + aim settling, suppression pinning, bleeding & self-bandaging, cover peek/crouch states, flanking fireteams, and live `Conscript` / `Regular` / `Spetsnaz` AI skill presets.
+- **Squad Management (`U`) & AI Bot Helpers (`Z`)**: Create, join, leave, or lock squads, set `SquadFormation` (`Wedge`, `Line`, `Column`, `Spread`) and `RulesOfEngagement` (`Weapons Free`, `Return Fire`, `Hold Fire`), sync squad net frequencies, recruit up to 4 nearby AI riflemen, and deploy active **Squad Rally Points** (`RallyKit`). Use the **AI Squad Helpers (`Z`)** quick bar or autonomous AI routines for **Combat Medic** auto-approach & bleeding patch/heal (including the player), **Ammo Bearer** spare magazine resupply, `Follow Me`, `Pop Smoke`, `Mount Vehicle`, `Dismount All`, and live AI radio contact callouts.
+- **12 Driveable & Multi-Crew Combined-Arms Vehicles**:
+  - **Wheeled**: `UAZ-469` (4×4 scout jeep), `Ural-4320` (6×6 cargo/troop truck), `BTR-80` (8×8 amphibious APC with rotating **14.5 mm KPVT** turret and `1PZ-2` gunner optic), and `BTR-80A` (30 mm autocannon + TOW ATGM).
+  - **Tracked Armor**: `T-72B` (125 mm 2A46 cannon with hull recoil & directional heavy armor `0.50×` front glacis / `1.50×` rear engine deck), `BMP-2` (amphibious IFV, 30 mm + ATGM), `MT-LB` (amphibious tracked APC), and `BMPT Terminator` (T-72B hull + twin 30 mm 2A42 alternating autocannons + quad 9M120 Ataka-T SACLOS ATGMs). Tracked vehicles feature dual-track differential kinematics, neutral pivot turns in place, and 56 animated 3D track shoes + 16 roadwheels/idlers/sprockets.
+  - **Helicopters**: `Mi-8MTV-2` (transport) and `Mi-24V Hind` (gunship with chin 30 mm, SACLOS TOW, and S-8 rocket pods) with collective/cyclic/tail-rotor aerodynamics and Auto-Hover (`Space`).
+  - **Emplaced Weapons**: `TOW Tripod` (SACLOS wire-guided anti-tank launcher) and `ZU-23-2` (twin 23 mm AA autocannon with `-10°..+85°` elevation and linked salvo fire).
+  - **Multi-Barrel & Guided Systems**: Supports configurable 1–6 barrel turrets (`Alternating` / `Salvo` fire modes; horizontal, quad-grid, and rotary layouts), SACLOS wire-guided ATGMs (`MMB` / secondary fire), custom JSON/CSG vehicles with procedural 16-sided `TireRubber` off-road chevron wheels, terrain suspension tilt (`pitch` / `roll`), `[F]` enter/exit (evicting AI crew safely in both SP and MP), `[1..3]` Driver/Gunner/Passenger seat switching (including independent multi-player Driver + Gunner seats in MP), and `[V]` chase/cockpit camera toggling.
+  - **Tactical Vehicle AI Behaviors & Wreck Physics**:
+    - **Helicopters (`Auto` + GM override)**: Automatically selects between **`CAS`** (`Ingress` → nose-tracked `AttackRun` with chin gun + S-8 wing rocket salvos → `BreakawayOrbit`), **`Transport`** (`CruiseToLz` → controlled `-2.6 m/s` `DescendingToLz` → ground-only troop dismount (`agl <= 3.0 m`) → `LiftoffClear`), and **`Move`** transit with terrain-clearance lookahead. Shot-down helicopters obey gravity, spin out with trailing dark smoke, crash onto the terrain with an explosion fireball/crater burst, and settle as ground wrecks.
+    - **Tracked & Ground Vehicles (`Auto` + GM override)**: Automatically chooses between **`Move`**, **`AssistInfantry`** (escorts nearby friendly dismounted squads at infantry speed), **`ArmoredPush`** (front-glacis-first breakthrough), and **`SuppressPosition`** (standoff fire support with sustained suppression bursts even into occupied zones without direct LOS). Includes neutral-pivot frontal armor angling (`0.50×` glacis), tactical reverse under heavy damage, friendly convoy spacing, and multi-domain AI gunnery (`ZU-23-2` / AA turrets prioritize helicopters with velocity lead; tanks & IFVs prioritize enemy armor with ATGMs/coax).
+- **Game Director Mode (`F7`) & Deployment (`M`)**: Arma-style live scenario sandbox with a 3D placement ghost for spawning/deleting/teleporting/ordering squads, vehicles (with a **`Spawn with AI Crew`** toggle across both stock and custom vehicles), live AI vehicle tactic badges/inspector overrides (plus safe airborne helicopter land-and-dismount), player spawns, mission objectives, and fire support (`120mm` mortar salvo, precision HE, tactical smoke).
+- **6-Stage Tactical Mission Loop**: Supports `MoveToPosition`, `SuppressPosition`, `CallArtillery`, `AssaultPosition`, `ClearBuilding`, and `DefendPosition` with 3D perimeter beacons, HUD waypoints, and counterattack waves.
+
+### 3. Worlds, Real-Time CSG Destruction, Structural Collapse & Enterable Navigation
+- **Real-Time CSG Subtraction Destruction & Dynamic Building Collapse**: 23 mm/30 mm autocannons, 125 mm tank shells, RPG-7V rockets, ATGMs, frags, and mortars dynamically carve strictly convex craters through per-panel subdivided buildings (`Khrushchyovka`, `Panelka`, `AdminPalace`, brick compounds, industrial warehouses, Caucasus houses, sandbags, concrete fences, and checkpoint barricades) with leak-proof hole clipping so follow-up shots and soldiers pass cleanly through mid-air breaches, incremental `NavGrid` breach carving, sub-millisecond two-level `AcousticBvh` updates, zero-allocation GPU tail streaming, and multiplayer late-joiner sync. Reaching a structure's load-bearing damage threshold triggers full **Structural Collapse** (`Pancaking`, `Cantilever V-Frame`, or `A-Frame`), rebuilding collapsed rubble geometry and playing debris/collapse effects.
+- **Dynamic, Stitched & Custom Grid Maps (`F6`)**: Single-zone presets (`RiverValleyTown`, `SmallSovietCity`, `TwinBridgeCrossing`, `DryCityOutskirts`), 3-zone stitched corridors, 2×2 stitched quadrant theaters with organic domain-warped transitions, a **3 km × 3 km Combined-Arms Theater**, and **Custom-Size Grid Map Generation (`3×3` to `128×128`)** via an interactive viewport-culled **2D Grid Map Painter** (`Brush`, `Line / River`, `Flood Fill`, `Eyedropper`, radius `1/2/4/8/16`, zoom/pan, 6 layout templates, `.cwgrid.json` save/load). Choose from 9 biomes (`City Core`, `Town / Suburbs`, `Industrial`, `Military Outpost`, `River Crossing`, `Forest / Woods`, `Open Field`, `Foothill / Mountain`, `Water / Lake`) and 3 cell scopes (`32m Block`, `64m District`, `128m Sector`, up to `16.4 km × 16.4 km` playable) with adaptive `8×8` / `16×16` 3-LOD chunked terrain (`256×256` / `512×512` vertices), a biome-aware `+25%` (`>= 48 m`) scenic out-of-bounds terrain skirt (open water past `WaterLake` edges, rolling ridges past land edges), dynamic camera far-plane/fog/LOD scaling (up to `10 km`), and strict placement safety (rejecting out-of-bounds, underwater `< water_level + 0.4 m`, and `> ~35°` cliff placements).
+- **Editable MapGen Asset Palettes**: Customize `MapGenPalette` JSON files (`mapgen_palettes/*.json`) per biome and slot (`LargeBuilding`, `MediumBuilding`, `SmallBuilding`, `Landmark`, `CoverProp`, `Bridge`, `Vegetation`) with weighted CSG `MapStamp`s or built-in presets, plus 1-click **"Edit in Asset Studio"** and **"Convert -> CSG Stamp"** directly from the **MapGen Asset Palette Editor**.
+- **Hierarchical Navigation, Doorway Carving & BVH Collision**: `2m` fine A* grid on standard maps and bounded (`<= 256×256`) coarse regional grid paired with exact obstacle/bridge checks and playable-bounds clamping on large theaters, plus **CSG wall/doorway carving** and exact `AcousticBvh` swept wall & floor collision (`STEP_UP_HEIGHT = 0.55m`) so both FPS players and AI squads can walk cleanly through doorways and wall breaches while staying blocked by solid walls and rivers.
+- **Live Map Hot-Reload**: Rebuilds GPU terrain/water buffers, acoustic BVH, `NavGrid`, and simulation state without restarting.
+
+### 4. Sculpt Engine Asset Studio, Procedural Modifiers & `./mods/`
+- **Live-3D Main Menu & `Open Mod Folder`**: Launch into a real-time orbiting valley backdrop with Quick Skirmish, 3 km Theater, Custom & Dynamic Maps, Game Director, Multiplayer, Direct Connect, Asset Studio, Audio Synthesizer Studio, Settings, mod counts (`Weapons • Vehicles • Maps • Stamps`), `↻ Reload`, and `📁 Open Mod Folder`.
+- **CSG Boolean Sculptor**: `+ Union`, `- Subtract`, and `∩ Intersect` over primitives (`Box`, `Cylinder`, `Sphere`, `Cone`, `Wedge`, `Torus`) and existing asset stamps (`weapons`, `vehicle parts`, `bunkers`, `cover`, `pines`) with undo/redo, Mirror X, Duplicate, and layer editing (`Hull` + rotating `Turret`), plus Vehicle Editor controls for `Wheeled`/`Tracked`/`Helicopter`/`EmplacedTurret` locomotion and configurable multi-barrel `TurretWeaponSpec` presets (`HeavyMg14_5mm`..`RocketPodS8`, barrel count/layout/fire mode).
+- **Procedural Modifier Stack (Array, Randomize Transforms, Curve & Scripted Modifiers)**: Attach non-destructive `Array` (Linear, Radial, Grid), `Randomize Transforms` (deterministic seeded position/rotation/scale randomization), `Curve` (Catmull-Rom spline placement integrated with arrays), and programmable **Luau & ColdFlux** modifiers with live parameter controls (including the starter **Vertical Spinning Staircase** Luau script).
+- **Map Stamp Asset Creator (`🧱 Map Stamp`)**: Sculpt reusable static buildings, watchtowers, checkpoints, and cover out of CSG primitives, align them flush to `Y=0` (**Sit Base on Ground** / **Center XZ Pivot**), save them to `./mods/stamps/*.json` (with the built-in `guard_watchtower` starter stamp), and stamp them into the Map Editor as self-contained, movable/rotatable/scalable `CsgShape::Group` objects (with **Override Group Material** and **Unpack Group**).
+- **Grabbable 3D Transform, Anchor & Map Entity Gizmos**: Interactive `Move [W]`, `Scale [R]`, and `Rotate [E]` handles with `Ctrl` snap, clickable 3D viewport markers (`TURRET`, `MUZZLE`, `AXLE 1..N`) to drag turret pivots, weapon/turret muzzles, and symmetrical wheel axles live, plus **Map Editor Entity Placement & Gizmos** (`SPAWN:`, `OBJ:`, `VEH:`) featuring ground diamonds, objective capture radius rings, oriented vehicle wireframes, `R` Objective Radius Scale, `E` Vehicle Yaw Rotate, `Undo`/`Redo`, camera focus, and collapsible Spawns / Objectives / Vehicles (stock & custom mod) inspector panels.
+- **PNG Heightmap Importer, JSON Pipeline & `.cwassetopack.json` Packs (`📦 Pack Builder`)**: Load 8-bit/16-bit PNG heightmaps alongside CSG outpost geometry (`./mods/heightmaps/`), export lightweight JSON blueprints (`./mods/{weapons,vehicles,maps,stamps}/`), bundle combinations of weapons, vehicles, maps, stamps, `MapGenPalette` presets, `.cwgrid.json` custom grids, and `.coldflux.json`/`.luau` scripts (excluding heightmaps) into portable **`./mods/packs/*.cwassetopack.json`** files via Asset Studio's **Pack Builder** window (`Edit in Builder`, `Unpack to Loose`, loose-override precedence), copy JSON to clipboard, or click **Save & Test in Valley**.
+
+### 5. GPU Rendering, Randomized Clouds, Raytraced Acoustics & VoIP/Radio
+- **Custom `wgpu 24` Render Pipeline**: 21 procedural PBR material layers (including `TireRubber` off-road lugs) with Catmull-Rom bicubic filtering (`A/B` toggleable), snapped sun shadow maps + Vogel Disk PCF (`8`/`16`/`32` taps), Dual Paraboloid reflections (`DPR`), raymarched 3D volumetric clouds with domain-warped dual rotated weather octaves & synced 2D cloud shadows (plus **Randomize Clouds** in Weather and GM Environment panels), reflective cold river water, zero-clip foreground FPS viewmodel pass, `F4` debug render PIP, and `F3` 3D acoustic bounce ray overlay.
+- **Frequency-Based VoIP & Tactical VHF Radio (`CapsLock`, `X`, `N`)**: Real-time `cpal` microphone capture compressed with pure-Rust 8 kHz IMA ADPCM and streamed over UDP. Supports 3D proximity voice (`CapsLock`, `35–60 m` with BVH wall occlusion) and tunable `30.000–87.975 MHz` VHF tactical radio (`X` PTT, `N` Tuner), Squad Leader dual-watch (`Left`/`Both`/`Right` ear routing), terrain ridge static + Conflict relay range boost, unencrypted cross-faction eavesdropping vs per-channel encryption, radio bandpass/static/squelch DSP mixing, offline **Loopback Mic Test (DSP)**, and a live comms log.
+- **Raytraced Procedural Audio (`F5`)**: Asynchronous two-level BVH multi-bounce acoustic propagation + diffraction feeding a real-time `cpal` procedural synth & DSP engine (ITD/ILD binaural panning + Hadamard FDN late reverb), with live `Audio Synthesizer Studio` (`F5`) patch editing.
+- **Flexible Frame Pacing & Capture Modes**: Stream-Safe capture mode (`F8`), VSync toggle (`Fifo` vs `Mailbox`/`Immediate`), full FPS cap controls (`30`, `60`, `90`, `120`, `144`, `165`, `240`, `360`, custom up to `500`, `Max`), and CLI launch flags.
+
+### 6. Multiplayer, Conflict Mode, UDP Hole Punching & Temp Mod Sync
+- **Authoritative 60 Hz UDP Server (Windows & Static Linux)**: Run listen servers from **`🌐 Multiplayer (Host / LAN)`** or deploy headless [`cold_water_server`](src/bin/cold_water_server.rs) on Windows or Linux (`x86_64-unknown-linux-musl` static ELF / Docker) configured via [`server_config.json`](server_config.json).
+- **Direct Connect & Built-In NAT Hole Punching (`🔗 Direct Connect`)**: Join directly by `IP:Port` (with recent server history), discover LAN hosts, or punch through home NAT routers with zero port forwarding via Room Code + Rendezvous Relay (`cold_water_server --rendezvous --port 27016`).
+- **Dynamic Conflict Mode**: Radio-signal BFS chain propagation from Main HQ bases to capture sectors, extend tactical VoIP relay coverage, push frontlines, and unlock forward respawn bases.
+- **Lag-Compensated Combat & Client Prediction**: 250 ms server hitbox history rewind, instant client cosmetic bullet/impact prediction merged with replicated remote tracers, combat FX, sounds, CSG destruction events (`NetDestructionEvent`), frequency/proximity VoIP packets, and `ActorPosture::Dead` corpse drops, plus full multi-crew vehicle driving, tracked offsets, helicopter rotor sync, and turret combat.
+- **Automatic Temporary Mod Sync (Zero `./mods/` Pollution)**: Joining a modded server automatically compares FNV-1a manifests, downloads only missing/mismatched `.json` blueprints and custom-map heightmap `.png`s reliably over UDP with hash/size validation, compiles them into a temporary in-memory session overlay so you can see and use every server weapon/vehicle/map, and restores your clean local `./mods/` on disconnect.
+
+### 7. ColdFlux Visual Scripting, Extensible UI, Luau VM & Server Admin
+- **ColdFlux Visual Scripting, UI Extensions & Disk Persistence (`F9`)**: Build scenario triggers, custom procedural modifiers, and extended UI overlays/windows visually with node graphs (**ColdFlux** compiled straight to Luau) or write Luau scripts directly on an embedded pure-Rust sandboxed Luau VM with deterministic instruction/memory budgets and the `cw.*` simulation API (raycasts, scenario variables, explosions, vehicle spawning, sounds, dynamic lights, Live Game/GM/Asset Studio UI widgets & click/change callbacks). Save, load, export, and autoload scripts on disk under `./mods/scripts/`.
+- **Server Admin & Role Permissions (`F10`)**: Manage player roles (`Guest`..`Owner`), role-gated script capabilities and scopes, live script execution, and security audit logs across singleplayer and authoritative multiplayer (`NetScriptSync` & admin RPCs).
+
+### 8. Engine-Only `sculpt` Binary & Sculpt Engine Hub
+- **Asset-Free Engine Binary (`sculpt`)**: Build with `--no-default-features --features client` (disabling `cold_water_assets`) to compile **only Sculpt Engine**—zero Cold Water maps, weapons, Soviet vehicles, urban buildings, or starter blueprints compiled in (replaced with clean neutral geometric fallbacks).
+- **Sculpt Engine Hub & Project Switcher**: Boots over a clean neutral sandbox viewport with selectable project workspaces defaulting to `./sculpt_projects/default/` (`--project <dir>` CLI flag or in-app switcher/`+ New Project`), giving direct access to **CSG Asset & Map Studio**, **Grid Map Painter (`3×3..128×128`)**, **MapGen Asset Palette Editor**, **Playtest & GM Sandbox**, **Luau & ColdFlux Editor**, **Procedural Audio Synth**, **Multiplayer**, and **Replay Studio**.
+
+### 9. Admin & Cinematic Replay System (`F11` / `Shift+F11`)
+- **Live & Dedicated Server Recording**: Toggle recording in-match with `F11` to capture timeline keyframes, gunfire, tracers, destruction events, custom vehicles, and `Shift+F11` admin bookmarks into `./replays/*.cwrep.json` (plus automatic/configurable recording on `cold_water_server`).
+- **Replay Library & Viewer**: Scrub playback (`0.25×`–`4×`, Free-Cam / Follow Soldier / First-Person POV) with faithful custom map reconstruction, dynamic GM & CSG vehicle spawning/animation/despawning, batched CSG crater rebuilds, soldier/FX animations, and capped Admin inspection pins (kills, hits, bookmarks, CSG craters).
+- **Minecraft Replay Mod-Style Cinematic Studio**: Keyframe **Catmull-Rom** spline camera paths (`Pos`, shortest-angle `Yaw`, `Pitch`, `Roll`, `FOV`) and replay time-ramp keyframes, preview live paths in-viewport, and export color-accurate offline **PNG sequences** (auto-normalizing `BGRA` windowed readback to `RGBA`) + optional **FFmpeg MP4** renders (`replays/renders/`).
+
+---
+
+## Quick Start & CLI Flags
+
+### Build & Run Project Cold Water (Client)
+```powershell
+cargo run --release
+```
+
+### Build & Run Engine-Only Sculpt Binary (Zero Cold Water Assets)
+```powershell
+cargo build --release --bin sculpt --no-default-features --features client
+cargo run --release --bin sculpt --no-default-features --features client -- --project sculpt_projects/default
+```
+
+### Optional Client CLI Arguments
+- `--quick-play`: Skip the Main Menu and load straight into the foothill valley skirmish (with Deployment menu open).
+- `--fps-cap <N>`: Override initial FPS cap (`0` = Uncapped, e.g. `--fps-cap 144 --no-vsync`).
+- `--no-vsync`: Start with VSync disabled so frame rates can exceed monitor refresh rate.
+- `--project <dir>`: Select the project workspace root directory (defaults to `sculpt_projects/default` in `sculpt`, or `mods` in `project_cold_water`).
+- `--verify-render [dir]`: Run headless DX12/GPU verification (`cold_water_assets` feature) and write the `verify_*.png` capture suite.
+
+### Dedicated Server, `server_config.json` & UDP Hole Punching (Windows & Linux)
+- **`server_config.json`**: Auto-created on first launch of `cold_water_server` with server name, bind IP/port, map (`theater_3km`, `foothills`, `small_city`, `twin_bridges`, `dry_city`, `custom:<id>`), seed, tick rate, max players, `mods_dir`, `admin_callsigns`, and hole-punch settings (`enable_hole_punch`, `rendezvous_addr`, `room_code`).
+- **Windows Dedicated Server**:
+  ```powershell
+  cargo run --release --no-default-features --bin cold_water_server -- --config server_config.json
+  # Optional public UDP hole-punching rendezvous broker:
+  cargo run --release --no-default-features --bin cold_water_server -- --rendezvous --port 27016
+  ```
+- **Linux Dedicated Server (`x86_64-unknown-linux-musl` static ELF / Docker)**:
+  ```powershell
+  powershell -ExecutionPolicy Bypass -File .\scripts\build_linux_server.ps1
+  ```
+  Outputs a standalone static Linux ELF binary and config bundle in `dist/linux/` (`cold_water_server`, `server_config.json`, `start_server.sh`, `start_rendezvous.sh`, `mods/`), or build via [`Dockerfile.server`](Dockerfile.server) (`docker build -f Dockerfile.server -t cold-water-server .`) or natively on Linux with [`scripts/build_linux_server.sh`](scripts/build_linux_server.sh).
+
+### Automated Tests
+```powershell
+# Full suite (101 tests: acoustics/sim, GPU shaders, CSG modding/destruction/modifiers/packs, multiplayer/networking, replay system, Luau/ColdFlux scripting, Sculpt & custom grid mapgen, vehicle tactics & tactical VoIP/ammo/kits/squads):
+cargo test
+# Engine-only headless suite without Cold Water assets or GPU (26 tests):
+cargo test --no-default-features --test sculpt_and_grid_mapgen --test scripting_and_coldflux --test tactical_systems
+```
+
+---
+
+## Controls Reference
+
+### First-Person & Vehicle Mode
+| Action | Key / Input |
+| :--- | :--- |
+| Enter / Exit FPS Mode (`Play FPS`) | `V` |
+| Move / Sprint / Jump | `WASD` / `Shift` / `Space` |
+| Crouch (toggle / hold) / Lean Left & Right | `C` / `Ctrl` / `Q` & `E` |
+| Fire / Aim Down Sights (`PSO-1` / `1PZ-2` Optic) | `LMB` / Hold `RMB` |
+| Secondary Vehicle Weapon (`TOW` / `Ataka-T` / `S-8 Rockets`) | `MMB` (or `Space` in ground vehicles) |
+| Helicopter Flight (Pilot Seat) | `W`/`S` Collective, `A`/`D` Tail-Rotor Pedals, Mouse Cyclic Pitch/Roll (hold `Ctrl` for free-look), `Space` Auto-Hover Toggle |
+| Select Weapon (`1`–`6`, kit-scoped) or Vehicle Seat (`Driver`/`Gunner`/`Passenger`) | `1`–`6` (or `Mouse Wheel` on foot) |
+| Reload / Mag Check / Mag Repack / Auto-Semi Fire Mode | `R` / `Ctrl+R` / `Shift+R` / `B` |
+| Field Bandage / Frag Grenade / Smoke Grenade / Kit Gear | `7` / `8` / `9` / `0` |
+| Squad Manager / VHF Radio Tuner / Inventory & Kit / AI Helpers Bar | `U` / `N` / `I` / `Z` |
+| Proximity VoIP PTT (35 m) / Tactical Radio PTT | Hold `CapsLock` / Hold `X` |
+| Enter / Exit Nearest Vehicle | `F` |
+| Toggle Chase / Cockpit Camera (in vehicle) | `V` |
+| Squad Orders (`Assault` / `Hold Cover` / `Suppress`) | `G` / `H` / `Y` |
+| Call `120mm` Mortar Barrage | `T` |
+| Switch Alive Squadmate / Deployment & Kit Screen | `Tab` / `M` |
+| Unlock Cursor Top Bar / Close Open Panel | `Esc` |
+
+### Tactical Free-Cam & Hotkeys
+- `WASD` + `Q`/`E` fly, `Shift` boost, **Right-Drag** look, **Right-Click** order selected squad (`1`–`6`)
+- `F3`: 3D acoustic rays | `F4`: Render pass PIP | `F5`: Audio Synth Studio | `F6`: Dynamic Map Gen (or Grid & Palette Studio in Sculpt) | `F7`: Game Director (GM) | `F8`: Stream-Safe Capture (`in-game` when HUD focus isn't captured; `Grid & Palette Studio` shortcut when non-FPS) | `F9`: ColdFlux / Luau Scripting Studio | `F10`: Server Admin & Permissions | `F11`: Start/Save Replay (`Shift+F11`: Admin Bookmark) | `Space`: Pause
+
+### Asset Studio & Map Editor
+- `LMB`: Pick CSG part, `TURRET` / `MUZZLE` / `AXLE` vehicle anchor, or `SPAWN` / `OBJ` / `VEH` Map Editor marker and drag gizmo handles
+- `W` Move | `R` Scale (Objective Radius in Map Editor) | `E` Rotate (Vehicle Yaw in Map Editor) | `F` Focus Selection | Hold `Ctrl` Snap
+- `RMB` Orbit | `MMB` or `Shift+RMB` Pan | `Scroll` Zoom | `Ctrl+Z` / `Ctrl+Y` Undo/Redo
+
+---
+
+## Modding Directory (`./mods/`)
+See [`MODDING_GUIDE.md`](MODDING_GUIDE.md) for schemas, Asset Studio workflows, Map Mission Defaults, ColdFlux/Luau APIs, and `.cwassetopack.json` bundling.
+
+Click **`📁 Open Mod Folder`** in the Main Menu or Asset Studio toolbar to open:
+- `mods/weapons/*.json` — Custom CSG weapon blueprints & ballistics/audio specs
+- `mods/vehicles/*.json` — Custom CSG vehicle hulls, turrets, wheels/tracks/rotors, multi-barrel weapons, seats & physics specs
+- `mods/maps/*.json` — Custom CSG outpost/terrain blueprints (including procedural modifier stacks and PNG heightmap references)
+- `mods/stamps/*.json` — Reusable CSG **Map Stamp** buildings/props (`guard_watchtower.json`, etc.)
+- `mods/mapgen_palettes/*.json` — Editable weighted zone/slot asset palettes for the Dynamic & Grid Map Generator (`MapStamp`s & built-in presets)
+- `mods/grids/*.cwgrid.json` — Saved painted custom-size (`3×3..128×128`) grid map layouts (`CustomGridSpec`)
+- `mods/scripts/` — Persistent ColdFlux (`.coldflux.json`) and Luau (`.luau`) gameplay, modifier, and UI extension scripts
+- `mods/packs/*.cwassetopack.json` — Self-contained multi-mod asset bundles (weapons, vehicles, maps, stamps, palettes, grids, scripts; excludes heightmaps), auto-loaded alongside loose files (loose files override packed duplicates)
+- `mods/heightmaps/*.png` — 8-bit or 16-bit grayscale heightmaps
+- `replays/*.cwrep.json` — Recorded admin/cinematic replays (plus PNG sequence / FFmpeg renders under `replays/renders/`)
+- `sculpt_projects/<name>/` — Isolated project folders created and opened by the `sculpt` binary (each containing its own `weapons/`, `vehicles/`, `maps/`, `stamps/`, `mapgen_palettes/`, `grids/`, `scripts/`, `packs/`, `replays/`, and `audio_patches.json`)
+
+
+The Source Code is protected under the GNU Public Liscence V3.
+
+
+this means you can, build, modify, redistribute, sell the built binaries.
+BUT... your source code will have to be that same GPLv3 Liscence.
+
+However. Mods and other .json files arent