csxq0605/where-is-my-codex
Where Is My Codex (Flow Rescue)
Dig through soil to route water into the goal — a Position-Based Fluids puzzle game.
Overview
A computer-graphics course project: a 2D fluid-puzzle game built with Python, Taichi, Position-Based Fluids, GPU/CPU backends, five playable levels, and a Tiled import pipeline.
README
Copied from csxq0605/where-is-my-codex at bac2ec9 on 2026-11-09.
Flow Rescue is a minimal Python + Taichi physics-game demo for the graphics simulation course project. The player digs through soil to route a finite set of water particles into the yellow collection area.
This vertical slice now runs a compact 2D Position-Based Fluids loop behind the stable
FluidSolver.step(dt, terrain) boundary: external forces, predicted positions, uniform-
grid neighbor search, iterative density constraints, terrain projection, and velocity
write-back.
Setup
uv sync
uv run python -m tools.generate_demo_level
The repository pins Python 3.12 in .python-version and locks all dependencies in
uv.lock. uv sync creates the local .venv and installs both runtime and development
dependencies.
The generated assets/levels/demo.png is committed so the demo runs immediately. Run
the generator again after changing the level script.
Author Levels
Tiled maps in assets/levels_src can be imported into the runtime level format:
uv run python -m tools.import_tiled_level \
assets/levels_src/level_02_pipe_rescue.tmj \
--output-dir assets/levels \
--stem level_02_pipe_rescue
The game still loads only generated assets/levels/*.json and *.png files. See
docs/level_editor.md for Tiled layer names, object types, and custom properties.
The player-facing MVP level order and design intent are documented in
docs/playable_levels.md.
See docs/art_direction.md for the GPT, Doubao, and Claude icon-hero sprite states and UI art direction.
Run
uv run python main.py
uv run python main.py --arch cpu
uv run python main.py --arch cpu --mode demo
uv run python main.py --arch cpu --manifest assets/levels/manifest.json
uv run python main.py --arch cpu --level assets/levels/demo.json
uv run python main.py --arch cpu --headless --frames 120
uv run python main.py --arch cpu --level assets/levels/smoke_gameplay_components.json
uv run python main.py --arch cpu --headless --frames 120 --level assets/levels/smoke_gameplay_components.json
uv run python main.py --arch cpu --headless --frames 120 --level assets/levels/smoke_timed_faucet.json
uv run python main.py --arch cpu --headless --frames 120 --level assets/levels/smoke_pipe.json
uv run python main.py --arch cpu --headless --frames 120 --level assets/levels/smoke_hazard_scene.json
uv run python main.py --arch cpu --level assets/levels/smoke_click_faucet.json
The default --arch auto mode asks Taichi for a GPU backend and allows CPU fallback.
Use the CPU command when verifying a machine without a working GPU path.
Without --level, the app loads assets/levels/manifest.json and exposes level
selection in the runtime panel. Use --level to run one level directly for debugging.
--mode debug is the default and shows development panels, smoke levels, and metrics.
--mode demo starts on a player-facing level select screen and filters out manifest entries with
demo_visible: false.
In manifest mode, the runtime UI supports level selection, current-level restart,
previous/next navigation, and a final completion message after the last visible level.
The visible demo sequence includes five levels covering direct digging, pipe transfer,
timed faucets, click-triggered water, and hazard scene markers.
Debug runtime panels show controls, collection progress, FPS, physics timing, active
particles, and optional solver stats such as PBF iterations and neighbor count.
Press T in debug mode to toggle detailed per-phase timing (grid build, constraint
solve, collision, grid overflow); these lines are hidden by default.
Demo gameplay keeps the playfield clear with only a corner pause button; the pause menu offers
exit, retry, and level-select actions. Missing solver stats are shown as n/a so the UI
remains usable before the PBF milestone lands.
Completed demo levels show a star-rating result screen with level-select, retry, and
next-level actions when another level is available.
Controls:
- Left mouse button: interact with click components and dig soil
Up/Down: move the selection on the demo level-select screenSpace: pause or continueR: restart the levelN: next level in manifest modeP: previous level in manifest modeW: switch between particle and continuous water renderingG: toggle occupied Uniform Grid overlay in debug modeC: toggle collider and boundary overlay in debug modeT: toggle detailed profiler timing in debug modeEsc: quit
The click-faucet smoke level is manual: click the top source area to emit water.
Test
uv run pytest
uv run python -m tools.validate_levels assets/levels
uv run python main.py --arch cpu --headless --frames 120
The tests use the CPU backend and cover level loading, coordinate conversion, digging, terrain reset, gravity, rock-floor collision, uniform-grid neighbors, small-scale PBF separation, dense-block stability, boundary clamping, corner collision, narrow-channel flow, goal collection, completion, and restart.
The level validator loads every committed level JSON and PNG pair. Headless runs print backend, particle capacity, active particle count, collected particles, simulated time, wall-clock elapsed time, and per-step profiling breakdown for reports or quick benchmark notes.
Physics Profiling
FluidSolver.step() records per-step timing and exposes it via the fluid.stats
property, which returns a frozen PhysicsStats dataclass (flow_rescue/physics_stats.py).
Available fields
| Field | Unit | Description |
|---|---|---|
physics_total_ms |
ms | Wall-clock time for the entire step() call |
grid_build_ms |
ms | Uniform-grid neighbour construction, summed across all PBF iterations |
constraint_solve_ms |
ms | Density, lambda, and position-delta kernels, summed across all PBF iterations |
collision_ms |
ms | Terrain collision projection during the predict phase |
active_particles |
count | Particles marked active after this step |
pbf_iterations |
count | Number of PBF solver iterations executed |
avg_neighbor_count |
float | Mean neighbour-list length across active particles |
grid_overflow |
count | Particles that could not fit in their grid cell |
Accessing stats
- Debug panel: press
Tto show detailed timing lines (hidden by default). - Headless mode: all fields are printed in a
key=valueline for easy parsing by benchmark scripts. - Programmatic: read
fluid.statsafter anystep()call. The stats are overwritten each step; when multiple sub-steps run per frame, the last step’s stats remain.
Limitations
- Each timing read is preceded by
ti.sync()to ensure GPU kernels have finished. This flushes the command queue on GPU backends and adds a few percent overhead compared to unsynced execution. avg_neighbor_countis computed from host-side numpy data after the final sync, with copy overhead proportional tomax_particles.- All timing is wall-clock (
time.perf_counter). On CPU backends the values are accurate; on GPU backends they include sync overhead but still correctly measure wall-clock cost.
Physics Parameters
Core solver knobs are now grouped in flow_rescue/config.py:
AppConfig.physics:max_particles,grid_cell_capacity,particle_radius,smoothing_radius,gravity_y,velocity_dampingAppConfig.physics.pbf:iterations,rest_density,constraint_epsilon,position_relaxationAppConfig.physics.pbf:artificial_pressure_k,artificial_pressure_delta_qAppConfig.physics.viscosity:velocity_smoothingAppConfig.physics.collision:query_substeps,boundary_epsilon,restitution,soil_restitution,rock_restitutionAppConfig.simulation:fixed_dt,max_frame_dt,max_updates_per_frameAppConfig.render:particle_radius
These defaults are tuned for the demo’s ~480 particles and the CPU-side 2000-particle stability test. The current defaults also add light velocity smoothing, multi-sample collision projection, and material-specific restitution to reduce jitter, corner tunneling, and narrow-channel sticking while keeping rock impacts more responsive than soft soil impacts. Future tuning can still refine kernel calibration and density-kernel calibration without changing the gameplay interface.
For level design workflow and Tiled authoring constraints, see docs/level_editor.md.