← All projects

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 screen
  • Space: pause or continue
  • R: restart the level
  • N: next level in manifest mode
  • P: previous level in manifest mode
  • W: switch between particle and continuous water rendering
  • G: toggle occupied Uniform Grid overlay in debug mode
  • C: toggle collider and boundary overlay in debug mode
  • T: toggle detailed profiler timing in debug mode
  • Esc: 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 T to show detailed timing lines (hidden by default).
  • Headless mode: all fields are printed in a key=value line for easy parsing by benchmark scripts.
  • Programmatic: read fluid.stats after any step() 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_count is computed from host-side numpy data after the final sync, with copy overhead proportional to max_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_damping
  • AppConfig.physics.pbf: iterations, rest_density, constraint_epsilon, position_relaxation
  • AppConfig.physics.pbf: artificial_pressure_k, artificial_pressure_delta_q
  • AppConfig.physics.viscosity: velocity_smoothing
  • AppConfig.physics.collision: query_substeps, boundary_epsilon, restitution, soil_restitution, rock_restitution
  • AppConfig.simulation: fixed_dt, max_frame_dt, max_updates_per_frame
  • AppConfig.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.

Homepage

About meIntroduction Research interestAgents, scientific workflows, embodied AI NewsRecent updates EducationPeking University ExperienceResearch and engineering ProjectsCards with README HonorsScholarships and competitions

Repositories

NexgentDesktop agent team that learns · GitHub ManySelvesRecoverable runtime for agent teams · GitHub Tiny PyTorchCUDA deep-learning framework · GitHub Where Is My CodexFluid-puzzle game in Taichi · GitHub

Pages

CVEnglish and Chinese PDF World notebookFootprints and visitors A little mechanicsDamped oscillator you can play with MUNer personality test31 questions, in Chinese