cntrl/docs/PERF_HANDOFF.md

149 lines
7.7 KiB
Markdown

# Performance work — handoff for next session (P1)
## Where we are
Goal: stable **60 FPS @ 1920x1080** on this machine (AMD Ryzen 5 4500U / Renoir
Vega iGPU, 6 CU, shared memory, Mesa 26.2.7). The goal is **met**. P0 is done and
committed. Continue with **P1** below if more headroom is wanted (e.g. for
`--post-fx`, bigger hordes, or weaker GPUs).
### Measured results
| Scenario | Before | Now |
|---|---|---|
| 1834x1032, 17 enemies, raw | 40 FPS, GPU 20.1 ms, 230 draws | 60 FPS, GPU ~7.6 ms, 163 draws |
| 1920x1080 fullscreen, raw | — | 60 FPS, GPU 7.9 ms, 184 draws |
| 58 s horde (24 enemies, 12 proj, 35 shards) | — | 59 FPS, GPU 5.4 ms, 246 draws |
| Trilinear concrete filter | — | 60 FPS, GPU 2.6 ms |
| Aniso 8x concrete filter (`--aniso 8`) | — | 19 FPS, GPU 40.0 ms (leave off on this GPU) |
**Uncapped headroom (`--uncapped`, removes the 60 FPS target via `SetTargetFPS(0)`):**
| Scenario | FPS | Frame | GPU |
|---|---|---|---|
| 1400x900 dev default, 17 enemies | 337 | 4.0 ms | 1.2 ms |
| 1920x1080 fullscreen, raw | 259 | 3.2 ms | 2.4 ms |
| 1920x1080 fullscreen, `--post-fx` | 172 | 5.6 ms | 2.9 ms |
The overlay title shows `UNCAPPED`; `Present` drops to ~0.3 ms because VSync
waiting is gone, so these numbers show real per-frame cost. Even with the full
bloom chain at 1080p there is ~2.8x headroom over the 60 FPS budget.
CPU section times are tiny: Sim 0.03 ms, Scene ~1.2 ms, UI ~1.5 ms. `Present`
(~14 ms) is `EndDrawing()` waiting for VSync — not a cost to optimize.
## Tooling (already in place)
- **F10** toggles the profiler overlay: CPU bars (Sim/Scene/Post/UI/Present), GPU
time, draw calls, entity counts. Code: `src/render/profiler.{hpp,cpp}`.
- GPU time uses two alternating `GL_TIME_ELAPSED` queries loaded via
`glXGetProcAddress`. Mesa's `GL_QUERY_RESULT_AVAILABLE` check always returned
false here, so `begin_gpu()` does a **blocking read of the query from two frames
ago** (`profiler.cpp:88`) — safe and accurate, do not "fix" it back.
- Draw-call counting is via macros wrapping `DrawCube`/`DrawCylinder` in
`presenter.cpp`, `models.cpp`, `debris.cpp`, plus manual `PROF_DRAW_CALL()` in
`concrete.cpp`, `aura.cpp` and `main.cpp`'s post chain.
### How to measure reproducibly
```sh
cmake --build build -j6
# 10 s sample at the default dev resolution (1400x900), 17-ish enemies:
timeout 16 ./build/cntrl --seed 42 --bot --no-damage \
--screenshot /tmp/opencode/p1_sample.png --screenshot-at 10
# performance/visual test resolutions: add --720p or --1080p
# true 1080p fullscreen: add --1080p --fullscreen
# late horde: add --screenshot-at 58 and raise timeout to 70
# post-FX chain (bloom only runs here): add --post-fx
# headroom: add --uncapped (removes the 60 FPS target via SetTargetFPS(0))
```
Read the overlay in the PNG (crop top 280x240 and enlarge). The in-game bottom
HUD FPS line is a second sanity check. With `--uncapped` the overlay title shows
`UNCAPPED` and FPS exceeds 60 — that gap is the headroom. GPU time is the number
that matters most: at 60 FPS the frame must stay under 16.6 ms.
## What was done in P0
1. **Concrete triplanar -> baked UVs.** `write_box` in `src/render/concrete.cpp:49`
bakes one planar UV per axis-aligned face; `concrete.vs/fs` do 3 texture fetches
instead of 9 and dropped a per-vertex matrix inverse. Textures got explicit
mipmaps. This alone halved GPU time.
2. **Static prop culling.** `ViewCull` (`presenter.cpp:53`) is now passed into the
office suite, plaza, floor props and doors via `draw_environment(game, cull)`.
3. **FX batching.** `QuadBatch` (`presenter.cpp:212`) merges all blob shadows and
camera-facing glows into two `RL_QUADS` draws instead of one per particle.
4. **Graphics option plumbing.** `src/render/graphics_settings.{hpp,cpp}` holds
`gfx::graphics_settings().concrete_filter` (Trilinear default / Aniso 4x / 8x).
`--aniso 0|4|8` selects it; `ConcreteMaterial::apply_texture_filter()`
(`concrete.cpp:196`) + `Presenter::apply_graphics_settings()`
(`presenter.cpp:485`) are the runtime hook for the M8 menu. Roadmap M8 records
the deferred menu UI.
5. **Backface culling on the static mesh.** The winding baked by
`StaticMeshBuilder` is outward-facing, so the two
`rlDisableBackfaceCulling()` calls were unnecessary and shaded both sides of
every baked box. Replaced with `rlEnableBackfaceCulling()` before the draw.
6. **Debris batching.** `src/render/box_batch.{hpp,cpp}` provides `BoxBatch`, a
dynamic mesh that accumulates rotated, tinted unit cubes into **one draw**.
`PaperDebris` (including ink lines and red stamps) and `ConcreteDebris` now
use it instead of one `DrawCube` per shard. Capacity 1024 boxes each, so
debris counts can be raised safely. Verified with `--aoe-test`: 21 debris
items render as 2 draws.
## P1 work (next, in priority order)
1. **Bake Hiss fluid noise to a texture — biggest remaining GPU cost.**
`assets/shaders/actor.fs:99-124` runs several `vnoise()` calls (each = 4
`hash21`), domain-warp sin/cos, ridges and extra hashes **per Hiss pixel**.
Generate a small scrolling 2-channel noise texture once at init (CPU or a
Blender bake) and replace the block with 2 texture fetches + a few ALU. Keep a
cheap 1-noise fallback for low quality. The `uHiss > 0.001` branch is uniform
per draw, so clean actors already skip it. Touch `src/render/models.cpp:56-132`
and `models.hpp` to own the texture. Validate with `--hiss-test` (close-up of a
buffed Hiss Brute) and a late horde.
2. **Cheaper bloom (only active with `--post-fx`).**
`main.cpp:269-270` uses half-res bloom buffers; `bloom_blur.fs` is 9-tap.
Options: quarter-res buffers (4x less blur work), 5-tap bilinear-paired blur,
fold the bright pass into the first blur to remove one full-screen pass, or
skip blur on alternate frames. `post_fx.fs:19-21` also uses a `sin()` hash —
swap in the trig-free `hash21` from `actor.fs:29-34`.
3. **Uniform / bind reduction for actors.**
`ModelBank::draw` (`src/render/models.cpp:165-215`) issues ~11 `SetShaderValue`
calls *per actor* and `DrawModelEx` rebinds material maps every draw. Cache the
last value per uniform (rig/glow/hiss are constant per model type), group draws
by model type, or pack per-actor data into one UBO update per frame.
## P2 — scalability switches (optional)
- `--render-scale 0.75` internal render target upscaled in the final pass,
auto-enabled on iGPUs.
- `--quality low|high` preset bundling filter, bloom, render scale and Hiss detail.
- Draw translucent glow cylinders with `rlDisableDepthMask()` last to cut overdraw.
## P3 — deeper batching (partly done)
- **Remaining:** `ScorchDecals::draw` (`debris.cpp`) still issues 5 draws per
decal (2 cylinders + 3 cubes); `CorruptionAura::draw_ground_waves`
(`aura.cpp:108`) is one draw per wave, up to 16. Both can use batch helpers.
- **Done:** paper/concrete debris (BoxBatch), glows/shadows (QuadBatch).
## P4 — assets
- Concrete maps are still 2048x2048 (~7.6 MB raw); 1K with mipmaps would likely
hold the stylized look and help cache behaviour on shared-memory iGPUs.
- Optional distance LOD for enemy meshes.
## Gotchas
- Default dev window is 1400x900 (fits under the 1080p desktop chrome without
being clamped). The window clamp only bites for `--1080p` on a 1080p monitor —
add `--fullscreen` for a true 1920x1080 capture.
- With the 60 FPS cap on, the `Present` section includes VSync waiting, so its
number is not a cost to optimize. Use `--uncapped` to see real per-frame cost.
- `--post-fx` is opt-in; without it the bloom chain does not run, so P1 bloom
work must be measured with that flag.
- Keep Trilinear as the default filter. Aniso 8x is a user-facing *option* for
stronger GPUs, not a default.
- Do not add comments unless asked; existing code style is `snake_case`,
`PascalCase` types, `kConstant`.