diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d0d6371 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto eol=lf +*.png binary diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 668a2a7..f5a31ea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -73,26 +73,7 @@ jobs: Copy-Item $exe.FullName (Join-Path $outDir "powder_game.exe") -Force - $readme = @( - "Powder Game (Windows 11 x64)", - "", - "Run:", - "- Double-click powder_game.exe", - "", - "Controls:", - "- 1: Sand, 2: Water, 3: Solid, 4: Erase", - "- 5: Smoke, 6: Fire, 7: Wood, 8: Oil", - "- [ / ]: Decrease / increase brush radius (1 to 96)", - "- Left mouse: paint", - "- H: show / hide the on-screen help", - "- F1: normal view; F2-F10: debug views", - "- Esc: quit", - "", - "Notes:", - "- powder_game.exe is self-contained (shaders built in, static runtime); run it from any folder.", - "- Requires OpenGL 4.3 and the resource limits listed in the source README." - ) - $readme | Set-Content -Path (Join-Path $outDir "README.txt") + Copy-Item packaging/README.txt (Join-Path $outDir "README.txt") New-Item -ItemType Directory -Force -Path "dist/win11" | Out-Null Compress-Archive -Path "$outDir/*" -DestinationPath "dist/win11/PowderGame-win11-x64.zip" -Force diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3952ede..5ae5ecf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -45,27 +45,9 @@ jobs: Copy-Item build/_deps/glad_src-src/LICENSE (Join-Path $licenseDir "GLAD-LICENSE") -Recurse Copy-Item build/_deps/glad_src-src/glad/files/khrplatform.h $licenseDir - $readme = @( - "Powder Game $env:GITHUB_REF_NAME (Windows 11 x64)", - "", - "Run:", - "- Double-click powder_game.exe", - "", - "Controls:", - "- 1: Sand, 2: Water, 3: Solid, 4: Erase", - "- 5: Smoke, 6: Fire, 7: Wood, 8: Oil", - "- [ / ]: Decrease / increase brush radius (1 to 96)", - "- Left mouse: paint", - "- H: show / hide the on-screen help", - "- F1: normal view; F2-F10: debug views", - "- Esc: quit", - "", - "Notes:", - "- powder_game.exe is self-contained (shaders built in, static runtime); run it from any folder.", - "- Requires OpenGL 4.3 and the resource limits listed in the source README.", - "- See the release notes and source VALIDATION.md for measured limitations." - ) - $readme | Set-Content -Path (Join-Path $outDir "README.txt") + $readmePath = Join-Path $outDir "README.txt" + Copy-Item packaging/README.txt $readmePath + Add-Content -Path $readmePath -Value "", "Version: $env:GITHUB_REF_NAME" New-Item -ItemType Directory -Force -Path "dist/win11" | Out-Null $binaryZip = "dist/win11/PowderGame-$env:GITHUB_REF_NAME-win11-x64.zip" diff --git a/ROADMAP.md b/ROADMAP.md index 9d09c9a..e5a74ea 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -732,515 +732,4 @@ All red/green and failed timing evidence is retained under `build/goal-baseline/ --- -## Historical initial audit (superseded) - -The remaining text is the preserved audit of the starting implementation. Its -status claims are historical; the completed goal and current handoff above supersede them. - -This roadmap is based on a source audit of the current C++/OpenGL project state. The original plan is directionally good, but several parts are already partially implemented and a few important contracts are currently wrong or stale. The priority is to make the simulation correct and testable before tuning visuals or adding more features. - -## Executive Summary - -The project is a real GPU simulation prototype, not a stub. It already has: - -- Fixed `1/60` simulation dt. -- A mostly centralized `SimulationConfig`. -- Boundary state textures for occupancy, SDFs, and masks. -- Particle water with MAC faces, pressure projection, FLIP blend, reseeding, and derived render fields. -- Half-resolution gas with MAC velocity, scalar fields, MacCormack-style advection, combustion, and a multigrid-like pressure solve. -- Particle/P2G sand with derived occupancy and velocity. -- Tile activity, tile sleep, compacted tile lists, GPU timing queries, replay scenes, and debug counters. - -The project is not yet fully operational. The main blockers are: - -1. The full-resolution boundary SDF/mask path appears broken: `sdf_full` is built from stale `mask_full` instead of fresh `solid_occupancy`. -2. Sand-to-boundary is one frame stale because boundary runs before the current sand rasterization. -3. Water is only an approximate particle/MAC liquid; it does not yet use `liquid_phi` for free-surface pressure classification. -4. Gas/fire is mostly unified, but several coupling and heat/smoke shaders are dead or folded into other passes. -5. Sand is particle/P2G, but not yet an MLS-MPM-lite dry granular model with volume, deformation/plasticity, or a real frictional yield solve. -6. Tile activity is built but only used by coupling; most heavy simulation passes still dispatch globally. -7. Replay validation exists, but it is not deterministic proof, not wired into CI, and misses transient debug counter failures. -8. Docs and shader inventory still describe old cellular sand and old split fire/heat/smoke paths. - -## Current Architecture Assessment - -### Frame Order - -Current order in `src/PowderApp.cpp` is: - -1. Spawn / brush -2. Boundary -3. Tile activity -4. Water -5. Gas -6. Sand -7. Coupling -8. Render extraction -9. Render - -Target order should be: - -1. Brush -2. Boundary -3. Water -4. Gas -5. Sand -6. Coupling -7. Render extraction -8. Render - -The current order is close, but sand occupancy used by boundary is from the previous frame. That can be acceptable only if documented as a one-frame-late coupling decision, but the target says sand occupancy updates next frame boundary while also saying boundary includes dynamic sand rasterization. The implementation should make this contract explicit: - -- Previous-frame `sand_occupancy` is the blocker for this frame's water/gas. -- Current sand pass rasterizes `sand_occupancy_next`. -- Next frame boundary consumes that rasterized field. - -If same-frame sand blocking is required, sand rasterization or a light pre-boundary sand occupancy update must run before boundary. - -### Authoritative Domains - -The intended truth domains are sound: - -- Full-resolution material/static solid + boundary. -- Full-resolution particle/MAC liquid. -- Half-resolution MAC gas/combustion. - -Current code mostly follows this, but old material velocity/stress textures and old cellular sand shaders remain. They should be removed or quarantined once the particle paths are verified. - -## Phase 0 - Make The Current Build Auditable - -Goal: make every future change measurable. - -Tasks: - -- Restore local build validation. The audit shell could not run `cmake` because it was not on PATH. Install or expose CMake in the development shell, or document the exact Visual Studio Developer PowerShell command. -- Add a `VALIDATION.md` or README section with the exact commands for: - - configure - - build - - run app - - run replay scene - - run all replay scenes -- Add a shader compile validation path. Today shaders compile only at runtime through OpenGL program creation. Options: - - Add a headless smoke-test executable that initializes GL and creates all programs. - - Add `glslangValidator` or equivalent if available, but keep OpenGL runtime compile as the authoritative check. -- Wire replay mode into CI where a GL context is available. If CI cannot provide GL, add a local-only documented replay gate and keep CI build-only. -- Add a validation result format that prints scene name, pass/fail metrics, debug counters, particle overflows, and timing aggregates. - -Acceptance: - -- `cmake --build ...` works from documented commands. -- Every shader used by `PowderApp` is compiled by a validation command. -- Replay failures print the metric that failed. -- Audit no longer depends on visual inspection alone. - -## Phase 1 - Fix Boundary As The First Correctness Blocker - -Goal: make solids and sand blockers authoritative and remove stale/self-referential boundary fields. - -Current critical issue: - -- `boundary_build.comp` writes fresh dynamic occupancy to `boundary_state_.solid_occupancy`. -- `RunBoundaryPass()` then builds `sdf_full` from `boundary_state_.mask_full`. -- `mask_full` is regenerated only after `sdf_full`. -- This makes the full boundary SDF/mask stale or self-derived. - -Tasks: - -- Change full SDF build input from `mask_full` to `solid_occupancy`. -- Preserve `static_occupancy -> sdf_static -> mask_static` for static-only collision where needed. -- Define boundary outputs clearly: - - `static_occupancy`: painted solid only. - - `solid_occupancy`: painted solid plus sand occupancy. - - `sdf_static`: static-only SDF. - - `sdf_full`: static plus sand SDF. - - `mask_static`: static-only binary blocker. - - `mask_full`: static plus sand binary blocker for liquid. - - `sdf_gas` and `mask_gas`: downsampled static plus sand blockers for gas. -- Keep water and gas out of all boundary blocker fields. -- Verify `boundary_downsample.comp` reads the intended fresh full occupancy, not a stale mask. -- Add a boundary debug replay scene with: - - thin wall - - corner - - sand pile blocker - - water source above blocker - - gas source near blocker - -Acceptance: - -- Painted solids block water in the first frame after painting. -- Sand blocks water/gas according to the documented one-frame or same-frame contract. -- Water and gas never become blockers in boundary textures. -- Thin wall and corner leakage stay under threshold. - -## Phase 2 - Stabilize Water Into A Real APIC/FLIP Liquid - -Goal: finish the water rewrite so `water_amount` and `water_velocity` are derived outputs from particle/MAC truth. - -Already present: - -- Water particles with position, velocity, mass, and affine slots. -- Safe bounded spawn/reseed allocator with `particleOverflowBlocked`. -- Particle compaction into scratch buffer. -- P2G with quadratic weights to MAC faces. -- MAC face velocity normalization. -- Pressure, divergence, projection. -- FLIP/PIC blend. -- RK2-style advection against SDF. -- `liquid_volume`, `liquid_phi`, `water_amount`, and render velocity outputs. - -Main gaps: - -- `liquid_phi` is derived but not used for pressure/free-surface classification. -- Pressure solves all non-solid cells instead of liquid cells with air/free-surface boundary conditions. -- APIC affine update is approximate: G2P replaces affine with sampled velocity gradient, not a full APIC transfer. -- Reseeding can create mass from smoothed volume if thresholds drift. -- Some spawn/clear paths still write derived `water_amount` / `water_velocity` directly. - -Tasks: - -- Define water particle layout in a shared comment or struct document: - - `state0.xy`: position - - `state0.zw`: velocity - - `state1.x`: live flag - - `state1.y`: mass - - `state1.zw`, `state2.xy`: affine matrix - - remaining slots reserved or removed -- Add explicit liquid cell classification from `liquid_volume` / `liquid_phi`. -- Update water divergence, pressure, and projection shaders to: - - solve only in liquid cells - - use solid SDF/mask for collision - - use air/free-surface boundary where `liquid_phi` indicates non-liquid -- Make P2G/G2P APIC transfer mathematically consistent: - - keep face weights and velocity sums - - compute affine term from weighted face/grid velocity deltas, not only a sampled gradient shortcut - - preserve FLIP blend default at `0.95` -- Make reseeding conservative: - - target 3 particles per under-resolved wet cell - - block overflow and increment `particleOverflowBlocked` - - avoid reseeding from render-smoothed amount - - add mass/particle-count metrics for baseline scenes -- Ensure `water_amount` and `water_velocity` are written only by extraction/finalization/clear paths that are explicitly derived-output maintenance. -- Remove or wire `water_particle_raster.comp`; do not leave dead water shader paths. - -Acceptance: - -- Water source monotonically fills a pool without pressure artifacts in empty air. -- Thin walls and corners do not leak beyond threshold. -- Baseline scenes do not hit particle overflow. -- Replay reports water particle count, amount sum, max velocity, pressure residual, and NaN/Inf count. - -## Phase 3 - Finish Unified Gas, Fire, Heat, And Smoke - -Goal: make gas/fire/heat one coherent half-resolution stack with no split proxy physics. - -Already present: - -- Half-resolution staggered gas `u/v`. -- Centered derived gas velocity. -- Smoke density, temperature, fuel, oxidizer, and reaction textures. -- MacCormack-style scalar advection with limiter. -- MacCormack-style velocity advection/correction. -- Combustion source terms in `fire_rd.comp`. -- Multigrid-like pressure solve. -- Fire render field derived from reaction and temperature. - -Milestone C completed: - -- Unified gas/fire/heat/smoke now runs through the canonical gas stack: - 1. Advect velocity and scalars with MacCormack. - 2. Add buoyancy from temperature and smoke. - 3. Solve gas pressure with configured V-cycle cap/tolerance. - 4. Project staggered gas velocity. - 5. Apply combustion, temperature diffusion/cooling, smoke yield, and reaction decay. - 6. Apply water suppression through canonical `liquid_volume`, reaction, fuel, oxidizer, and temperature fields. -- Fire remains render-derived from reaction rate and temperature. There is no separate fire-state simulation. -- Fire-to-smoke and fire-to-temperature are owned by `fire_rd.comp`; the old standalone gas/fire compatibility shaders were deleted: - - `coupling_smoke.comp` - - `heat_diffuse.comp` - - `spawn_heat.comp` - - `smoke_vorticity.comp` - - `smoke_pressure_jacobi.comp` -- Oxidizer behavior is a closed brush-added system. There is no ambient oxidizer refill path yet, so sustained fire depends on explicitly supplied fuel and oxidizer. -- Gas collision is mask-only from the downsampled boundary field. `sdf_gas` remains available for a later soft-collision pass but is not part of the current gas solver contract. -- Gas pressure residual tolerance and iteration cap are explicit `SimulationConfig` values, not hidden literals. -- Replay accumulates debug counters across the full scripted scene, so gas pressure failures are not lost between frames. - -Acceptance: - -- `POWDER_REPLAY=gas` passes with zero accumulated debug counters. -- Smoke plume rises and dissipates without growing forever in the gas replay. -- Fire burns while brush-supplied fuel/oxidizer are present. -- Water suppression extinguishes reaction within the fixed replay window. -- Fire rendering changes only through reaction and temperature. -- No unused gas/fire compatibility shader remains in the shipped shader directory. - -## Phase 4 - Replace Sand Approximation With MLS-MPM-Lite Dry Granular Sand - -Goal: finish sand as direct particle/grid dry granular simulation and remove old cellular compatibility paths. - -Already present: - -- Particle sand spawn/clear/P2G/grid update/particle step/rasterize. -- Particle state has position, velocity, live flag, mass, and affine slots. -- Full-resolution grid mass and momentum. -- Derived `sand_occupancy` and `sand_velocity`. -- Basic gravity, damping, SDF projection, friction-like velocity adjustment, and water drag. - -Milestone D completed: - -- Sand now uses the direct particle/grid path as the authoritative simulation path. -- Sand particles are compacted each sand step, and `spawn_cursor` is reset to the compacted live count so erased/inactive slots are reused. -- Sand source spawning is density-aware through `sand_occupancy`, preventing baseline replay sources from injecting into already filled cells until particle capacity is hit. -- The sand particle layout is documented by shader state: - - `state0.xy`: position - - `state0.zw`: velocity - - `state1.x`: live flag - - `state1.y`: mass - - `state1.zw` and `state2.xy`: affine velocity term - - `state2.z`: reserved particle volume slot -- Water-to-sand coupling is canonical in `sand_grid_update.comp`, using `liquid_volume` and water velocity during the sand grid update. The redundant post-sand coupling pass was removed. -- Sand self-interaction is grid-density based: compression above `sand_density_yield_threshold` applies a Coulomb/Drucker-Prager-lite velocity yield clamp. Static collision still uses `sdf_static`. -- `sand_occupancy` and `sand_velocity` are rasterized after particle advection for next-frame boundary and rendering. -- Replay sand mass is validated from compacted live particle count rather than filtered render occupancy. -- Old cellular sand shaders and redundant coupling shader were deleted: - - `coupling_sand_drag.comp` - - `sand_prepare.comp` - - `sand_desired.comp` - - `sand_resolve.comp` - - `sand_commit.comp` - - `sand_capture.comp` -- `stress_a_` / `stress_b_` remain as full-res solid/material visual state for existing render paths, not as sand simulation state. - -Acceptance: - -- `POWDER_REPLAY=sand` passes with zero accumulated debug counters. -- `POWDER_REPLAY=combined` passes with zero accumulated debug counters. -- `POWDER_REPLAY=all` passes. -- Sand mass is conserved within `0.5%` in baseline scenes. -- Particle overflow is not hit in baseline scenes. -- Old cellular sand shaders are gone from the shipped shader directory. - -## Phase 5 - Coupling Cleanup - -Goal: make cross-material effects explicit, field-based, and non-circular. - -Milestone E completed: - -- Coupling contracts are explicit in `RunCouplingPass`: - - water -> reaction/fuel/oxidizer/temperature: `liquid_volume` suppresses canonical gas fields. - - fire -> smoke/temperature: owned by `RunFireHeatPass` / `fire_rd.comp`, sourced from `reaction_rate`. - - water -> sand: owned by `RunSandPass` / `sand_grid_update.comp`, sourced from `liquid_volume` and water velocity. - - sand -> boundary: rasterized `sand_occupancy` feeds the next frame boundary build. -- No physics pass binds render-extracted textures as inputs. -- Redundant water-sand coupling was removed; there is one canonical water-to-sand path. -- The combined replay scene exercises water, gas/fire, sand, and coupling together. - -Acceptance: - -- `RunCouplingPass` documents source/output fields. -- `POWDER_REPLAY=combined` passes. -- `inactive_tile_misses` remains zero in replay acceptance. - -## Phase 6 - Tile Activity And Performance - -Goal: make active tiles an actual performance feature, not just a coupling optimization. - -Already present: - -- Full and gas tile activity textures. -- Tile sleep after 8 inactive frames. -- Tile dilation/downsample. -- Compacted tile lists and indirect dispatch buffers. -- `inactiveTileMisses` counter. - -Milestone F completed: - -- Active tile lists remain enabled where safe today: coupling runs through compacted tile lists and indirect dispatch. -- Particle compaction is now present for water and sand, and replay signatures include active particle counts. -- Timing query readback is replay-only. Interactive mode does not block on query or texture readback. -- Replay timing is accumulated per frame and reports per-pass average and max cost instead of last-frame samples. -- Pressure iteration/cycle caps and thresholds are exposed through `SimulationConfig` and environment overrides. -- Tile-list expansion decisions are documented: - - coupling: safe and enabled. - - particle loops: require particle bins beyond current compaction. - - render extraction: not enabled because inactive tiles would need decay/clear semantics to avoid stale render outputs. - - pressure solves: not enabled without active-domain boundary design. - -Acceptance: - -- Combined replay uses average total pass time <= `combined_target_frame_ms` and worst pass <= `combined_worst_frame_ms`. -- Replay output prints per-pass average/max timing. -- Active tile misses stay at zero in acceptance scenes. - -## Phase 7 - Debug Counters And Validation - -Goal: make failures visible and persistent enough to catch. - -Required counters: - -- `nan_inf_detected` -- `particle_overflow_blocked` -- `pressure_nonconverged` -- `inactive_tile_misses` - -Milestone G completed: - -- Debug counters remain per-frame for debug rendering and are accumulated across replay frames for pass/fail validation. -- Replay failure output prints named counters and scene metrics. -- Water and gas pressure convergence checks use configurable thresholds. -- Additional NaN/Inf checks were added to gas correction/combustion/project and sand grid/particle/raster paths. -- Replay runs each requested scene twice by default in one process. -- Determinism is tolerance-based because GPU atomic ordering is not bit-exact. The signature compares: - - derived water amount sum - - liquid volume sum - - smoke density sum - - temperature sum - - reaction sum - - sand occupancy sum - - water and sand live particle counts - -Acceptance: - -- Any transient overflow/nonconvergence/NaN in replay fails the scene. -- Failure output identifies the failed counter and scene. -- Deterministic replay uses documented tolerance metrics from `SimulationConfig`. - -## Phase 8 - Public Configuration And Internal Contracts - -Goal: make solver behavior configurable without hidden constants scattered through shaders and C++. - -Milestone H completed: - -- `SimulationConfig` remains the source of solver defaults. -- `LoadConfigFromEnvironment()` exposes controlled environment overrides for: - - fixed dt - - tile sleep - - water/gas CFL and substep ranges - - APIC/FLIP blend - - water/gas pressure tolerances and iteration caps - - gas combustion, cooling, diffusion, and buoyancy - - sand drag, velocity cap, spawn density, and yield/friction - - replay repeat count and determinism tolerances - - combined replay timing thresholds -- Ambiguous accessors were replaced: - - `CurrentFire()` -> `CurrentReactionRate()` - - `CurrentHeat()` -> `CurrentTemperature()` - - `CurrentSmokeVel()` -> `CurrentGasVelocityCenter()` -- Texture/field contracts: - - boundary: `static_occupancy`, `solid_occupancy`, `sdf_static`, `sdf_full`, `sdf_gas`, and masks. - - water: particles and MAC faces are authoritative; `liquid_volume` / `liquid_phi` classify liquid; `water_amount` / `water_velocity` are derived outputs. - - gas: MAC velocity and pressure plus smoke, temperature, fuel, oxidizer, and reaction are authoritative; render gas/smoke/temp/fire fields are derived outputs. - - sand: particles and grid mass/momentum are authoritative; `sand_occupancy` and `sand_velocity` are derived outputs. - -Acceptance: - -- Solver-critical thresholds/caps touched by Phases 5-8 have matching config values or named constants. -- Debug views and code accessors use canonical field names. -- Field contracts are documented above and in code names. - -## Phase 9 - Documentation And Cleanup - -Goal: remove stale descriptions and make the repo match the implementation. - -Tasks: - -- Replace `PLAN.md` with either: - - historical plan plus status notes, or - - this roadmap as the current canonical plan. -- Update README: - - current architecture - - current controls - - actual frame pipeline - - replay/validation commands - - build commands for Windows and Linux -- Remove stale statements: - - sand prepare/desired/resolve/commit as active path - - active tile culling as if it applies to all heavy work - - split smoke/fire/heat if unified stack is canonical -- Remove unused shaders after each subsystem is validated. -- Keep `dist/` and build directories ignored; do not commit generated outputs unless release packaging requires them. - -Acceptance: - -- README pipeline matches `RunFrame`. -- Shader directory contains only shipped shaders plus clearly named experimental files. -- CI/build docs match the actual developer environment. - -## Suggested Milestones - -### Milestone A - Boundary And Validation Baseline - -- Fix `sdf_full` source. -- Add clear validation commands. -- Improve replay failure output. -- Add accumulated debug counters. - -Exit criteria: - -- Boundary debug scene passes. -- Water hits painted solids correctly. -- Replay failures are actionable. - -### Milestone B - Water Correctness - -- Add liquid cell/free-surface pressure classification. -- Finish APIC/G2P transfer. -- Make reseeding conservative. -- Remove dead water shader path. - -Exit criteria: - -- Water jet, pool, spill, source, and thin-wall scenes pass. -- No baseline particle overflow. - -### Milestone C - Gas/Fire Unification - -- Clean reaction/temperature/smoke contracts. -- Wire or delete unused gas/coupling shaders. -- Decide oxidizer model. -- Improve suppression and smoke metrics. - -Exit criteria: - -- Smoke plume, sustained fire, and water suppression scenes pass. -- Fire remains render-derived. - -### Milestone D - Sand Completion - -- Add sand particle compaction/reuse. -- Add volume and granular yield response. -- Consolidate water-sand coupling. -- Remove old cellular sand shaders/docs. - -Exit criteria: - -- Sand pile/repose/erosion scenes pass. -- Sand mass conserved within `0.5%`. - -### Milestone E - Performance And Shipping Readiness - -- Expand active-tile use where safe. -- Add timing aggregates. -- Wire replay into CI or documented local gate. -- Update README/PLAN. - -Exit criteria: - -- Combined scene meets target FPS range on reference hardware. -- CI/local validation catches shader and replay regressions. -- Documentation matches reality. - -## Known High-Risk Files - -- `src/PowderApp.cpp`: owns frame order, resource binding, replay, timing, and most lifecycle contracts. -- `src/PowderApp.hpp`: owns config/state names and particle/texture contracts. -- `shaders/boundary_*.comp`: highest immediate correctness risk due to stale full boundary path. -- `shaders/water_*.comp`: needs free-surface pressure, true APIC transfer, and conservative reseeding. -- `shaders/smoke_*.comp`, `shaders/gas_*.comp`, `shaders/fire_rd.comp`: mostly implemented but needs contract cleanup. -- `shaders/sand_particle_*.comp`, `shaders/sand_grid_update.comp`, `shaders/sand_rasterize.comp`: particle path is active but not yet full MLS-MPM-lite. -- `shaders/coupling_*.comp`: coupling exists but should be consolidated and audited for persistent writes. -- `README.md` and `PLAN.md`: stale relative to current implementation. - -## Validation Gap From This Audit - -I could not run the local C++ build because `cmake` was not available on PATH in the audit shell. Replay was also not run because it requires a working build and OpenGL runtime context. Treat this roadmap as a static source audit until those validation commands are restored and executed. +The initial audit of the starting implementation used to follow here. It is in git history up to `0bcb329` (v0.7.0). diff --git a/VALIDATION.md b/VALIDATION.md index 6069088..f2f3334 100644 --- a/VALIDATION.md +++ b/VALIDATION.md @@ -144,6 +144,9 @@ This is the current result. The five pass sections that follow it are the work m tree on a GPU shared with the other passes (their timings are noisy; their correctness numbers stand). Everything after them is a historical record; where an older section contradicts this one, this section wins. +Line endings: the repository stores LF only (`.gitattributes`, then a renormalization commit). Shader byte hashes recorded +before it differ from the current ones for `shaders/fullscreen.vert` only by line endings. + Tree: the integration is committed as `12c1343`. The evidence below was measured on the tree before that commit, which was `61e2965` plus the gas scheduling pass (one gas pressure solve split across a tick pair), the water host synchronisation pass (restart from the true residual armed on the GPU), sand pass 5 (hole collapse, per-grain damp diff --git a/build-win11.sh b/build-win11.sh index e36f410..6ec83e8 100755 --- a/build-win11.sh +++ b/build-win11.sh @@ -19,41 +19,7 @@ rm -rf "$DIST_DIR" mkdir -p "$DIST_DIR" cp "$BUILD_DIR/powder_game.exe" "$DIST_DIR/" -cat > "$DIST_DIR/README.txt" <<'TXT' -Powder Game (Windows 11 x64) - -Run: -- Double-click powder_game.exe - -Controls: -- 1: Sand -- 2: Water -- 3: Solid -- 4: Erase -- 5: Smoke -- 6: Fire -- 7: Wood -- 8: Oil -- [ / ]: Decrease / increase brush radius (1 to 96) -- Left mouse: paint -- H: Show / hide the on-screen help -- F1: Normal view -- F2-F10: Debug views (boundary, water, water velocity, gas velocity, - gas pressure, smoke, temperature, fuel/reaction, failure counters) -- Esc: quit - -The window shows a dark cave. A compact inventory (top left) holds the eight -materials, the selected one's name and the brush radius, with a help panel under -it that hides itself after a few seconds. The brush is a ring and a warm lantern -light over the simulation. - -Notes: -- powder_game.exe is self-contained (shaders built in, MinGW runtime linked - statically); run it from any folder. -- Requires OpenGL 4.3 core with at least 18 image units, 18 compute image - uniforms, 19 combined shader output resources, 8 SSBO bindings and 16 - fragment texture units; the app checks the first four at startup. -TXT +cp "$ROOT_DIR/packaging/README.txt" "$DIST_DIR/README.txt" mkdir -p "$(dirname "$ZIP_PATH")" rm -f "$ZIP_PATH" diff --git a/docs/ALGORITHMS.md b/docs/ALGORITHMS.md index a6703c9..86b5848 100644 --- a/docs/ALGORITHMS.md +++ b/docs/ALGORITHMS.md @@ -269,7 +269,8 @@ cells elsewhere (that once deleted water under sand across the map). - The distance field is approximate (jump flooding can pick a non-nearest seed in rare configurations); sweeps use only its sign and normals use its local gradient. - Wood burning away changes the geometry without a readback, so the distance field is refreshed every quarter second - once wood has been painted since the last reset, even after it has all burnt (a marked shortcut in `RunWoodPass`). + while any wood is left. The wood pass counts its cells on the same tick, reads the count at the next refresh through + a fence, and stops once a count comes back zero. --- @@ -1488,7 +1489,7 @@ invocation owns the four material cells it writes: $`T = \max(T, 0.6\, \text{feed})`$, $`\text{flame} = \max(\text{flame}, 0.3\, \text{feed})`$. The gas burns that vapour into flame, heat and smoke, and that heat lights the next wood. -The static distance field is rebuilt every 15 ticks once wood has been painted since the last reset, since burnt cells vanish without a readback. +The static distance field is rebuilt every 15 ticks while wood remains, since burnt cells vanish without a readback; the same tick counts the wood cells, and a zero count ends the rebuilds. The composite draws wood as planks that char to grey ash as fuel goes and glow while burning (11.3). ### 9.2 Why diff --git a/docs/screenshot.png b/docs/screenshot.png index c66bccd..3c6ce7c 100644 Binary files a/docs/screenshot.png and b/docs/screenshot.png differ diff --git a/packaging/README.txt b/packaging/README.txt new file mode 100644 index 0000000..71ca36e --- /dev/null +++ b/packaging/README.txt @@ -0,0 +1,36 @@ +Powder Game (Windows 11 x64) + +Run: +- Double-click powder_game.exe + +Controls: +- 1: Sand +- 2: Water +- 3: Solid +- 4: Erase +- 5: Smoke +- 6: Fire +- 7: Wood +- 8: Oil +- [ / ]: Decrease / increase brush radius (1 to 96) +- Left mouse: paint +- H: Show / hide the on-screen help +- F1: Normal view +- F2-F10: Debug views (boundary, water, water velocity, gas velocity, + gas pressure, smoke, temperature, fuel/reaction, failure counters) +- Esc: quit + +The window shows a dark cave. A compact inventory (top left) holds the eight +materials, the selected one's name and the brush radius, with a help panel under +it that hides itself after a few seconds. The brush is a ring and a warm lantern +light over the simulation. + +Notes: +- powder_game.exe is self-contained (shaders built in, C/C++ runtime linked + statically); run it from any folder. +- Requires OpenGL 4.3 core with at least 18 image units, 18 compute image + uniforms, 19 combined shader output resources, 8 SSBO bindings and 16 + fragment texture units. The game checks the first four at startup and names + a missing one in a dialog. +- Source, documentation and measured limitations (VALIDATION.md): + https://github.com/FueledByRedBull/Powder-Game diff --git a/shaders/fullscreen.vert b/shaders/fullscreen.vert index cb86ace..485a40a 100644 --- a/shaders/fullscreen.vert +++ b/shaders/fullscreen.vert @@ -12,4 +12,4 @@ void main() { vec2 position = positions[gl_VertexID]; uv = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); -} +} diff --git a/shaders/wood_burn.comp b/shaders/wood_burn.comp index 00a4977..9f8812b 100644 --- a/shaders/wood_burn.comp +++ b/shaders/wood_burn.comp @@ -16,8 +16,14 @@ layout(r16f, binding = 3) uniform image2D fuelTex; layout(rg16f, binding = 4) uniform image2D reactionTex; layout(r16f, binding = 5) uniform readonly image2D waterAmountTex; +// On a sample tick (tally 1), mode 0 adds the wood cells left after its update to woodCells (intact, burning or charred). +layout(std430, binding = 0) buffer WoodTally { + uint woodCells; +}; + uniform ivec2 gasSize; uniform int mode; +uniform int tally; uniform uint seed; uniform float ignitionTemperature; uniform float igniteChance; // per tick while hot @@ -52,6 +58,7 @@ void main() { if (imageLoad(gasMaskTex, n).r == 0u) heat = max(heat, imageLoad(temperatureTex, n).x); } } + uint remaining = 0u; for (int i = 0; i < 4; ++i) { ivec2 cell = gas * 2 + ivec2(i & 1, i >> 1); uint material = imageLoad(materialTex, cell).r; @@ -71,7 +78,9 @@ void main() { next = 256u + fuel; } if (next != material) imageStore(materialTex, cell, uvec4(next)); + if (isWood(next)) ++remaining; } + if (tally != 0 && remaining > 0u) atomicAdd(woodCells, remaining); return; } if (imageLoad(gasMaskTex, gas).r != 0u) { diff --git a/src/PowderApp.cpp b/src/PowderApp.cpp index 57f37e2..a65bfa6 100644 --- a/src/PowderApp.cpp +++ b/src/PowderApp.cpp @@ -83,6 +83,17 @@ std::string WithGlfwError(std::string message) { return message; } +#ifdef _WIN32 +// The executable has a console, but a double-clicked build closes it with the process, so a failed start also says why +// in a dialog. +void ShowErrorDialog(const std::string& message) { + const int size = MultiByteToWideChar(CP_UTF8, 0, message.c_str(), -1, nullptr, 0); + std::wstring text(static_cast(std::max(size, 1)), L'\0'); + MultiByteToWideChar(CP_UTF8, 0, message.c_str(), -1, text.data(), size); + MessageBoxW(nullptr, text.c_str(), L"Powder Game", MB_OK | MB_ICONERROR); +} +#endif + } // namespace int PowderApp::Run() { @@ -107,6 +118,17 @@ int PowderApp::Run() { while (glfwWindowShouldClose(window_) == GLFW_FALSE) { glfwPollEvents(); + // Minimized: nothing is drawn or simulated, and the thread sleeps until the next event. The clocks restart + // on return, so the time spent hidden is not simulated as a backlog. + int framebuffer_width = 0; + int framebuffer_height = 0; + glfwGetFramebufferSize(window_, &framebuffer_width, &framebuffer_height); + if (glfwGetWindowAttrib(window_, GLFW_ICONIFIED) == GLFW_TRUE || framebuffer_width == 0 || framebuffer_height == 0) { + glfwWaitEvents(); + previous_time = title_time = glfwGetTime(); + title_frames = 0; + continue; + } UpdateInput(); const double current_time = glfwGetTime(); RunInteractiveFrame(clock, current_time - previous_time); @@ -131,6 +153,9 @@ int PowderApp::Run() { } catch (const std::exception& error) { std::cerr << error.what() << '\n'; Shutdown(); +#ifdef _WIN32 + if (!replay_mode_) ShowErrorDialog(error.what()); // replays stay headless and scriptable +#endif return 1; } } @@ -152,6 +177,7 @@ int PowderApp::RunInteractiveFrame(FixedStepClock& clock, double elapsed) { } void PowderApp::Initialize() { + replay_mode_ = std::getenv("POWDER_REPLAY") != nullptr; // before anything that can throw, so Run() knows config_ = powder_config::LoadConfigFromEnvironment(); glfwSetErrorCallback(GlfwErrorCallback); @@ -162,7 +188,6 @@ void PowderApp::Initialize() { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - replay_mode_ = std::getenv("POWDER_REPLAY") != nullptr; glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // Replays keep the reference 1280x900. Interactive windows take 85% of the work area's height and just enough @@ -303,6 +328,8 @@ void PowderApp::Shutdown() { DeleteProgram(init_state_program_); DeleteBuffer(gas_state_.pressure_check); DeleteBuffer(debug_state_.counters); + DiscardWoodTally(); + DeleteBuffer(wood_tally_.buffer); DeleteBuffer(phase_state_.cell_counts); DeleteBuffer(phase_state_.gas_sources); DeleteBuffer(phase_state_.sinks); @@ -699,6 +726,10 @@ void PowderApp::CreateBuffers() { glBindBuffer(GL_SHADER_STORAGE_BUFFER, debug_state_.counters); glBufferData(GL_SHADER_STORAGE_BUFFER, debug_counter_bytes, nullptr, GL_DYNAMIC_DRAW); + glGenBuffers(1, &wood_tally_.buffer); + glBindBuffer(GL_SHADER_STORAGE_BUFFER, wood_tally_.buffer); + glBufferData(GL_SHADER_STORAGE_BUFFER, 2 * sizeof(GLuint), nullptr, GL_DYNAMIC_DRAW); + glGenBuffers(1, &phase_state_.cell_counts); glBindBuffer(GL_SHADER_STORAGE_BUFFER, phase_state_.cell_counts); glBufferData(GL_SHADER_STORAGE_BUFFER, 2 * water_count_bytes, nullptr, GL_DYNAMIC_DRAW); @@ -843,6 +874,7 @@ void PowderApp::InitializeState() { frame_index_ = 0U; boundary_state_.static_dirty = true; wood_present_ = false; + DiscardWoodTally(); oil_present_ = heat_present_ = false; phase_state_.steam_ping = true; // The gas solve's check schedule follows the last solve, so a stale count makes repeated replays diverge. @@ -1481,7 +1513,10 @@ void PowderApp::RunSpawnFullRes(const BrushConfig& config, const DispatchRegion& return; } if (config.replace_material) boundary_state_.static_dirty = true; - if (config.replace_material && config.material_value == kWoodMaterial) wood_present_ = heat_present_ = true; + if (config.replace_material && config.material_value == kWoodMaterial) { + wood_present_ = heat_present_ = true; + DiscardWoodTally(); // a count taken before this stroke would not include it + } glUseProgram(spawn_full_program_); glUniform2i(CachedUniform(spawn_full_program_, "gridSize"), kGridWidth, kGridHeight); @@ -3160,9 +3195,41 @@ std::array PowderApp::ReadPhaseSinks() const { return sinks; } +void PowderApp::DiscardWoodTally() { + if (wood_tally_.fence != nullptr) glDeleteSync(wood_tally_.fence); + wood_tally_.fence = nullptr; +} + // Wood catches from hot gas, burns down feeding the gas fire, and goes out in water (shaders/wood_burn.comp). +// Burning wood changes the static geometry with no readback, so every 15th tick (a quarter second) the distance field is +// rebuilt and the wood cells are counted. That count is read at the next sample, when its copy finished long ago and +// the read does not stall the GPU; when no wood is left the pass stops running, and the rebuild at the sample that +// counted zero was the last one that was needed. void PowderApp::RunWoodPass() { + const bool sample = frame_index_ % 15U == 0U; + if (sample && wood_tally_.fence != nullptr) { + const GLenum waited = glClientWaitSync(wood_tally_.fence, GL_SYNC_FLUSH_COMMANDS_BIT, GL_TIMEOUT_IGNORED); + if (waited == GL_WAIT_FAILED) throw std::runtime_error("Waiting for the wood count failed."); + GLuint remaining = 0U; + glBindBuffer(GL_SHADER_STORAGE_BUFFER, wood_tally_.buffer); + glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, sizeof(GLuint), sizeof(GLuint), &remaining); + glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); + DiscardWoodTally(); + if (remaining == 0U) { + wood_present_ = false; + return; + } + } + if (sample) { + const GLuint zero = 0U; + glBindBuffer(GL_SHADER_STORAGE_BUFFER, wood_tally_.buffer); + glClearBufferData(GL_SHADER_STORAGE_BUFFER, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT, &zero); + glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); + glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT); + } glUseProgram(wood_burn_program_); + glUniform1i(CachedUniform(wood_burn_program_, "tally"), sample ? 1 : 0); + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, wood_tally_.buffer); glUniform2i(CachedUniform(wood_burn_program_, "gasSize"), kGasWidth, kGasHeight); glUniform1ui(CachedUniform(wood_burn_program_, "seed"), frame_index_ * 2654435761U); glUniform1f(CachedUniform(wood_burn_program_, "ignitionTemperature"), 0.35F); @@ -3179,9 +3246,15 @@ void PowderApp::RunWoodPass() { DispatchGrid(kGasWidth, kGasHeight); glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL_TEXTURE_FETCH_BARRIER_BIT); } - // shortcut: burning wood changes the static geometry with no readback, so the distance field is rebuilt - // every quarter second while wood exists; track burnt-out cells if this shows in profiles. - if (frame_index_ % 15U == 0U) boundary_state_.static_dirty = true; + if (!sample) return; + boundary_state_.static_dirty = true; + glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT | GL_BUFFER_UPDATE_BARRIER_BIT); + glBindBuffer(GL_COPY_READ_BUFFER, wood_tally_.buffer); + glBindBuffer(GL_COPY_WRITE_BUFFER, wood_tally_.buffer); + glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, sizeof(GLuint), sizeof(GLuint)); + glBindBuffer(GL_COPY_READ_BUFFER, 0); + glBindBuffer(GL_COPY_WRITE_BUFFER, 0); + wood_tally_.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); } void PowderApp::RunRenderFieldExtractionPass() { diff --git a/src/PowderApp.hpp b/src/PowderApp.hpp index d977000..6d83327 100644 --- a/src/PowderApp.hpp +++ b/src/PowderApp.hpp @@ -433,8 +433,14 @@ class PowderApp { // Lighting is presentation only. Off, composite.frag draws the plain albedo and no lantern, which is what the // render-modes oracle and the HUD pixel tests compare against. bool lighting_enabled_ = true; - // Wood was painted since the last reset: burning wood changes the static geometry (RunCouplingPass). + // Wood was painted since the last reset and some may remain: burning wood changes the static geometry + // (RunCouplingPass). RunWoodPass counts the wood cells (intact, burning or charred) into word 0 of the tally buffer + // every 15th tick and copies that to word 1 behind a fence; the next sample reads it, and a zero clears the flag. bool wood_present_ = false; + struct WoodTally { + GLuint buffer = 0; + GLsync fence = nullptr; + } wood_tally_; // Oil, or a heat source (fire or wood), was painted since the last reset: only then do the oil drift and the // phase passes (RunPhasePass) run. bool oil_present_ = false; @@ -615,6 +621,7 @@ class PowderApp { void RunFireHeatPass(float dt); void RunCouplingPass(float dt); void RunWoodPass(); + void DiscardWoodTally(); void RunPhasePass(float dt); GLuint CurrentSteam() const; std::array ReadPhaseSinks() const; // evaporated water and burned oil records since the last reset diff --git a/src/main.cpp b/src/main.cpp index 287e85c..be36e89 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3,4 +3,4 @@ int main() { PowderApp app; return app.Run(); -} +} diff --git a/tests/AppLifecycleTests.cpp b/tests/AppLifecycleTests.cpp index 0093f18..c39f4a9 100644 --- a/tests/AppLifecycleTests.cpp +++ b/tests/AppLifecycleTests.cpp @@ -7569,6 +7569,20 @@ struct AppLifecycleTests { Require(far_lit_at > lit_at && far_lit_at < 60 * 20, "fire must spread 260 cells along the beam within 20 s"); Require(beam[3] > 400, "burnt wood must crumble away"); Require(CleanCounters(totals), "burning wood must keep clean counters"); + + // Once nothing is left to burn the wood pass stops and the distance field stops rebuilding. + int cleared_at = -1; + for (int t = 0; t < 60 * 30 && cleared_at < 0; ++t) { + tick(false); + if (!app.wood_present_) cleared_at = t; + } + const auto rest = WoodCensus(app, 300, 200, 700, 210); + std::cout << "wood: pass stopped " << cleared_at / 60.0 << " s later; beam intact/burning/charred=" << rest[0] << '/' + << rest[1] << '/' << rest[2] << '\n'; + Require(cleared_at >= 0, "the wood pass must stop once the beam has burnt away"); + Require(rest[0] + rest[1] + rest[2] == 0, "the wood pass must not stop while wood remains"); + for (int t = 0; t < 30; ++t) tick(false); + Require(!app.boundary_state_.static_dirty, "a burnt-out beam must stop rebuilding the distance field"); } // Sparks and embers are particles (spark_step.comp): live records have life > 0.