Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3bd49f61c0 | ||
|
|
dc66203259 | ||
|
|
95723af6a5 | ||
|
|
5e4758ce16 | ||
|
|
7a04cdaa8b | ||
|
|
c49302d90c | ||
|
|
1388c818f4 | ||
|
|
cd29426bbe |
@@ -0,0 +1,208 @@
|
||||
# Add configurable internal render scale to improve fill-bound FPS
|
||||
|
||||
## Summary
|
||||
|
||||
Complete-frame benchmarks show that the current sprite renderer is primarily
|
||||
pixel/fill bound on Vulkan/Lavapipe, not CPU draw-preparation bound. Rendering
|
||||
the world into a smaller offscreen color target and nearest-blitting it to the
|
||||
native swapchain produced the largest measured FPS improvement.
|
||||
|
||||
This should be an opt-in render-quality setting with a native-resolution
|
||||
fallback. For pixel art, a 50% scale is especially useful because it maps to an
|
||||
exact 2× nearest-neighbor upscale.
|
||||
|
||||
## Evidence
|
||||
|
||||
Environment:
|
||||
|
||||
- Commit `dc66203259e92ce39291556f7b6c26c8dd999b84`
|
||||
- Odin `dev-2026-05-nightly:ea5175d`
|
||||
- `-debug -o:speed`
|
||||
- SDL 3.4.12, Vulkan/Lavapipe, immediate present
|
||||
- 800×600 swapchain
|
||||
- Five 150-frame trials per invocation after 50 warm-up frames
|
||||
- Order-balanced baseline/candidate invocations
|
||||
- GPU idle wait included before stopping each trial timer
|
||||
|
||||
### Fill and overdraw scaling
|
||||
|
||||
The committed `perf-frame` harness produced:
|
||||
|
||||
| Workload | Median frame time | Median FPS |
|
||||
| --- | ---: | ---: |
|
||||
| 1 visible sprite | 0.592 ms | 1,690 |
|
||||
| 24 visible sprites | 2.249 ms | 445 |
|
||||
| 64 visible sprites | 4.017 ms | 249 |
|
||||
| 128 visible sprites | 6.255 ms | 160 |
|
||||
| 128 stacked sprites | 7.692 ms | 130 |
|
||||
|
||||
Stacking the same 128 sprites increased frame time by approximately 23%,
|
||||
confirming that overdraw matters.
|
||||
|
||||
With one centered sprite, render-target scaling produced:
|
||||
|
||||
| Window size | Pixels | Median frame time |
|
||||
| --- | ---: | ---: |
|
||||
| 400×300 | 120,000 | 0.268 ms |
|
||||
| 800×600 | 480,000 | 0.545 ms |
|
||||
| 1600×1200 | 1,920,000 | 2.075 ms |
|
||||
|
||||
The near-linear increase at larger sizes is further evidence of a pixel-bound
|
||||
workload.
|
||||
|
||||
### Internal render-scale prototype
|
||||
|
||||
The temporary candidate kept the physical swapchain at 800×600, rendered
|
||||
sprites into a smaller `COLOR_TARGET | SAMPLER` texture, and used
|
||||
`BlitGPUTexture` with nearest filtering to upscale into the swapchain.
|
||||
|
||||
Aggregate medians across ten trials per mode:
|
||||
|
||||
| Workload | Native | 75% scale | 50% scale |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 128 spread sprites | 6.082 ms / 164 FPS | 4.082 ms / 245 FPS | 3.082 ms / 325 FPS |
|
||||
| 128 stacked sprites | 7.912 ms / 126 FPS | 5.116 ms / 195 FPS | 3.034 ms / 330 FPS |
|
||||
|
||||
Compared with native resolution:
|
||||
|
||||
- 75% reduced frame time by 33–35% and increased FPS by 49–55%.
|
||||
- 50% reduced frame time by 49–62% and increased FPS by 97–161%.
|
||||
|
||||
A visual smoke test confirmed that the 50% path rendered the complete scene at
|
||||
the correct orientation and 800×600 output size. It was visibly coarser, as
|
||||
expected. A 75% scale at 800×600 does not produce an integer upscale and can
|
||||
create uneven pixel sizing with nearest filtering.
|
||||
|
||||
## Reproduction harness
|
||||
|
||||
Native spread and stacked workloads:
|
||||
|
||||
```bash
|
||||
make perf-frame \
|
||||
PERF_FRAME_SCENARIO=0 \
|
||||
PERF_FRAME_SPRITES=128 \
|
||||
PERF_FRAME_WIDTH=800 \
|
||||
PERF_FRAME_HEIGHT=600
|
||||
|
||||
make perf-frame \
|
||||
PERF_FRAME_SCENARIO=3 \
|
||||
PERF_FRAME_SPRITES=128 \
|
||||
PERF_FRAME_WIDTH=800 \
|
||||
PERF_FRAME_HEIGHT=600
|
||||
```
|
||||
|
||||
Run the same commands on the candidate branch with internal render scale set to
|
||||
75% and 50%. Keep every `PERF_FRAME_*` value unchanged between comparisons.
|
||||
|
||||
## Suggested fix
|
||||
|
||||
Add explicit logical/output and internal-render dimensions to `App`:
|
||||
|
||||
```odin
|
||||
Render_Scale :: enum {
|
||||
Native,
|
||||
Three_Quarter,
|
||||
Half,
|
||||
}
|
||||
|
||||
App :: struct {
|
||||
// Existing swapchain fields remain the logical/output dimensions.
|
||||
swapchain_texture: ^sdl.GPUTexture,
|
||||
swapchain_w: u32,
|
||||
swapchain_h: u32,
|
||||
|
||||
render_scale: Render_Scale,
|
||||
scene_texture: ^sdl.GPUTexture,
|
||||
scene_w: u32,
|
||||
scene_h: u32,
|
||||
}
|
||||
```
|
||||
|
||||
Create the offscreen target with the swapchain format and both usages required
|
||||
by SDL's blit path:
|
||||
|
||||
```odin
|
||||
app.scene_texture = sdl.CreateGPUTexture(
|
||||
app.device,
|
||||
{
|
||||
type = .D2,
|
||||
format = sdl.GetGPUSwapchainTextureFormat(app.device, app.window),
|
||||
usage = {.COLOR_TARGET, .SAMPLER},
|
||||
width = app.scene_w,
|
||||
height = app.scene_h,
|
||||
layer_count_or_depth = 1,
|
||||
num_levels = 1,
|
||||
sample_count = ._1,
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
Render the sprite pass into `scene_texture`. Continue using the logical
|
||||
swapchain dimensions for camera and clip-space calculations so world layout
|
||||
does not change with render scale:
|
||||
|
||||
```odin
|
||||
color_info := sdl.GPUColorTargetInfo {
|
||||
texture = app.scene_texture,
|
||||
clear_color = app.clear_color,
|
||||
load_op = .CLEAR,
|
||||
store_op = .STORE,
|
||||
cycle = true,
|
||||
}
|
||||
```
|
||||
|
||||
After ending the render pass, upscale into the full swapchain:
|
||||
|
||||
```odin
|
||||
blit := sdl.GPUBlitInfo {
|
||||
source = {
|
||||
texture = app.scene_texture,
|
||||
w = app.scene_w,
|
||||
h = app.scene_h,
|
||||
},
|
||||
destination = {
|
||||
texture = app.swapchain_texture,
|
||||
w = app.swapchain_w,
|
||||
h = app.swapchain_h,
|
||||
},
|
||||
load_op = .DONT_CARE,
|
||||
filter = .NEAREST,
|
||||
}
|
||||
sdl.BlitGPUTexture(app.cmd, blit)
|
||||
```
|
||||
|
||||
Use the existing direct-to-swapchain path at native scale to avoid an
|
||||
unnecessary blit. Recreate the offscreen texture whenever the swapchain size,
|
||||
format, or render-scale setting changes. If native-resolution UI or text is
|
||||
added later, render it after the world blit in a separate swapchain pass.
|
||||
|
||||
## Rejected experiment: fragment alpha discard
|
||||
|
||||
Approximately 49.7% of pixels inside the baked frame rectangles have exact
|
||||
alpha zero. A temporary fragment shader discarded those texels:
|
||||
|
||||
```glsl
|
||||
vec4 texel = texture(u_tex, v_uv);
|
||||
if (texel.a == 0.0) {
|
||||
discard;
|
||||
}
|
||||
out_color = texel;
|
||||
```
|
||||
|
||||
Despite the high transparent coverage, this regressed frame time by roughly
|
||||
5–6% in both spread and stacked workloads. Do not add alpha discard without
|
||||
contradictory hardware-GPU evidence.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- Native, 75%, and 50% internal render-scale settings are available.
|
||||
- Native scale retains the current direct-to-swapchain path.
|
||||
- The scene target is recreated safely on resize, format change, or scale
|
||||
change and released during shutdown.
|
||||
- Camera/world coordinates remain stable when render scale changes.
|
||||
- Nearest filtering is used for pixel-art output.
|
||||
- Add screenshot-based checks for output orientation, viewport coverage, and
|
||||
stable sprite placement at every scale.
|
||||
- Benchmark spread and stacked scenarios on at least one hardware GPU.
|
||||
- Document the quality tradeoff and recommend integer upscale ratios for pixel
|
||||
art.
|
||||
@@ -0,0 +1,218 @@
|
||||
# Add deterministic CPU and frame benchmarks for sprite rendering
|
||||
|
||||
## Summary
|
||||
|
||||
The current `make flame` workflow is valuable for finding call stacks, but it
|
||||
does not provide a reproducible performance metric:
|
||||
|
||||
- `examples/crowd` draws only 24 sprites.
|
||||
- `MAX_SPRITES` limits the renderer to 128 sprites.
|
||||
- Recording starts an interactive application and asks the user to play for
|
||||
10–20 seconds before quitting.
|
||||
- The two checked-in reports contain only 499 and 469 samples.
|
||||
- CPU queue construction and GPU submission are combined in one profile.
|
||||
- The profiler currently builds unoptimized code.
|
||||
|
||||
These limitations make it difficult to tell whether a change made
|
||||
`draw_sprite` faster, changed driver behavior, or merely changed sampling noise.
|
||||
|
||||
## Evidence
|
||||
|
||||
A temporary deterministic benchmark exposed two very different results:
|
||||
|
||||
1. CPU-only `draw_sprite`, two million calls and seven trials:
|
||||
- `-debug`: median 192.560 ns/draw
|
||||
- `-debug -o:speed`: median 19.154 ns/draw
|
||||
2. Full 128-sprite frames through SDL GPU on Lavapipe, 1,000 measured frames
|
||||
and five trials:
|
||||
- `-debug`: median 2.486 ms/frame
|
||||
- `-debug -o:speed`: median 2.447 ms/frame
|
||||
|
||||
At the current cap, optimized CPU queue construction is approximately 3.2
|
||||
microseconds for 128 sprites. The full software-rendered frame is around 2.45
|
||||
milliseconds, so optimizing `draw_sprite` cannot materially improve that
|
||||
specific end-to-end workload. A hardware GPU or a larger future sprite limit
|
||||
may have a different balance.
|
||||
|
||||
This split also explains why percentages from the current unoptimized
|
||||
flamegraphs overstate small helper functions.
|
||||
|
||||
### Follow-up enhancement benchmarks
|
||||
|
||||
Six proposed renderer changes were implemented temporarily and measured before
|
||||
being discarded. Full-frame tests used:
|
||||
|
||||
- Odin `dev-2026-05-nightly:ea5175d`
|
||||
- `-debug -o:speed`
|
||||
- SDL 3.4.12 with Vulkan/Lavapipe
|
||||
- 128 animated sprites using real baked toad metadata and textures
|
||||
- Warm-up before measurement
|
||||
- Paired baseline/change samples on the same device with alternating order
|
||||
- Ten 400-frame samples per mode, except culling, which used seven 750-frame
|
||||
samples per mode
|
||||
|
||||
Each row is a separate paired run, so absolute frame times should only be
|
||||
compared within that row.
|
||||
|
||||
| Enhancement | Baseline median | Changed median | Result |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Viewport culling, all visible | 4.845 ms | 4.822 ms | 0.5% faster |
|
||||
| Viewport culling, 50% offscreen | 2.856 ms | 2.878 ms | 0.8% slower |
|
||||
| SDL transfer and vertex buffer cycling | 4.869 ms | 4.834 ms | 0.7% faster |
|
||||
| Contiguous vertex queue and one upload-side copy | 4.793 ms | 4.809 ms | 0.3% slower |
|
||||
| Four-vertex indexed quads | 4.745 ms | 4.830 ms | 1.8% slower |
|
||||
| GPU instancing with 32-byte instance records | 5.527 ms | 5.467 ms | 1.1% faster |
|
||||
| Texture sorting, including sort cost, 128 runs to 2 | 5.765 ms | 5.654 ms | 1.9% faster |
|
||||
|
||||
Interpretation:
|
||||
|
||||
- Viewport culling is neutral at the current cap. The GPU already clips
|
||||
offscreen triangles, and the sprites remain in one batched draw.
|
||||
- SDL buffer cycling is a small performance improvement and is also the
|
||||
documented way to avoid overwriting resources still bound by prior frames.
|
||||
- Repacking the CPU queue does not help at 128 sprites; extra dynamic-array
|
||||
work offsets the saved small-copy loop.
|
||||
- Indexed quads regress performance despite reducing dynamic vertex data.
|
||||
- Instancing reduces per-sprite upload data from 96 to 32 bytes, but the 1.1%
|
||||
gain does not justify a second pipeline and shader path at the current cap.
|
||||
- Texture sorting has the largest full-frame gain, but unrestricted sorting can
|
||||
change alpha compositing. It is only safe within compatible layer/order
|
||||
groups.
|
||||
|
||||
The recommended order is:
|
||||
|
||||
1. Profile optimized builds and establish the deterministic benchmark.
|
||||
2. Apply the clip-space math simplification documented in the related issue.
|
||||
3. Enable SDL buffer cycling for correct cross-frame resource reuse.
|
||||
4. Consider layer-aware texture grouping if a 1.9% workload-specific gain is
|
||||
worth the ordering complexity.
|
||||
5. Defer culling, queue repacking, indexed quads, and instancing until the
|
||||
sprite limit or measured workload grows substantially.
|
||||
|
||||
These results are from a software Vulkan backend. Hardware drivers may have a
|
||||
different balance, which is another reason to keep the benchmark reproducible
|
||||
and report backend details.
|
||||
|
||||
## Suggested fix
|
||||
|
||||
Add a non-interactive benchmark target with two explicitly separate workloads.
|
||||
|
||||
The committed harnesses are:
|
||||
|
||||
```make
|
||||
PERF_ODIN_FLAGS ?= -debug -o:speed
|
||||
|
||||
perf-draw:
|
||||
odin run benchmarks/draw_sprite \
|
||||
-collection:pkg=. \
|
||||
$(PERF_ODIN_FLAGS) \
|
||||
-define:PERF_ITERATIONS=$(PERF_DRAW_ITERATIONS)
|
||||
|
||||
perf-frame:
|
||||
odin run benchmarks/sprite_frame \
|
||||
-collection:pkg=. \
|
||||
$(PERF_ODIN_FLAGS) \
|
||||
-define:PERF_FRAMES=$(PERF_FRAME_FRAMES) \
|
||||
-define:PERF_SCENARIO=$(PERF_FRAME_SCENARIO)
|
||||
```
|
||||
|
||||
Run the standard workloads with:
|
||||
|
||||
```bash
|
||||
# CPU-only draw preparation.
|
||||
make perf-draw
|
||||
|
||||
# Complete frame: 128 visible sprites sharing one texture.
|
||||
make perf-frame PERF_FRAME_SCENARIO=0
|
||||
|
||||
# Complete frame: every second sprite is fully offscreen.
|
||||
make perf-frame PERF_FRAME_SCENARIO=1
|
||||
|
||||
# Complete frame: 128 sprites alternate between two texture objects.
|
||||
make perf-frame PERF_FRAME_SCENARIO=2
|
||||
```
|
||||
|
||||
Every invocation prints the Git commit, Odin version, compiler flags, workload
|
||||
configuration, every trial, and the median. `perf-frame` waits for GPU idle
|
||||
after warm-up and after each measured frame batch so outstanding work is
|
||||
included.
|
||||
|
||||
### CPU queue benchmark
|
||||
|
||||
- Construct `App`, `Character_Data`, and `Sprite` with real baked metadata.
|
||||
- Use safe fake non-null GPU handles; `draw_sprite` only checks/stores these.
|
||||
- Preallocate the draw list.
|
||||
- Clear the queue whenever it reaches `MAX_SPRITES`.
|
||||
- Vary sprite position between calls so the compiler cannot hoist the work.
|
||||
- Warm up before timing.
|
||||
- Run at least one million calls and report nanoseconds per draw.
|
||||
- Build with `-o:speed` by default.
|
||||
|
||||
The measured loop should clear the queue at its cap, vary input to prevent
|
||||
compiler hoisting, and report time per draw:
|
||||
|
||||
```odin
|
||||
PERF_ITERATIONS :: #config(PERF_ITERATIONS, 2_000_000)
|
||||
|
||||
start := sdl.GetTicksNS()
|
||||
for i in 0 ..< PERF_ITERATIONS {
|
||||
if len(app.draw_list) == eng.MAX_SPRITES {
|
||||
clear(&app.draw_list)
|
||||
}
|
||||
sprite.position.x = f32(i & 1023)
|
||||
eng.draw_sprite(&app, &sprite)
|
||||
}
|
||||
elapsed := sdl.GetTicksNS() - start
|
||||
|
||||
fmt.printfln(
|
||||
"%.3f ns/draw",
|
||||
f64(elapsed) / f64(PERF_ITERATIONS),
|
||||
)
|
||||
```
|
||||
|
||||
### Full-frame benchmark
|
||||
|
||||
- Use a real SDL GPU device and baked texture.
|
||||
- Warm up before timing.
|
||||
- Run a fixed number of frames without interactive input.
|
||||
- Report milliseconds per frame and sprites per second.
|
||||
- Record GPU backend, present mode, compiler version, compiler flags, and sprite
|
||||
count.
|
||||
|
||||
Use a fixed frame count rather than an interactive quit time:
|
||||
|
||||
```odin
|
||||
PERF_FRAMES :: #config(PERF_FRAMES, 1_000)
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
draw_benchmark_frame(&app, sprites[:]) // warm-up
|
||||
}
|
||||
|
||||
start := sdl.GetTicksNS()
|
||||
for _ in 0 ..< PERF_FRAMES {
|
||||
draw_benchmark_frame(&app, sprites[:])
|
||||
}
|
||||
elapsed := sdl.GetTicksNS() - start
|
||||
|
||||
fmt.printfln(
|
||||
"%.3f ms/frame",
|
||||
f64(elapsed) / f64(PERF_FRAMES) / 1_000_000.0,
|
||||
)
|
||||
```
|
||||
|
||||
The CPU benchmark should be available without a display or GPU. The full-frame
|
||||
benchmark may remain opt-in where a suitable GPU backend is unavailable.
|
||||
|
||||
Do not add a strict CI regression threshold initially; hosted runner variance
|
||||
will make a single threshold flaky. CI can still compile the benchmark and
|
||||
verify that it completes.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- A Makefile target runs the optimized CPU benchmark non-interactively.
|
||||
- Results include compiler flags, iteration count, median, and per-trial values.
|
||||
- CPU queue time is reported separately from complete frame time.
|
||||
- Sprite positions or frames vary during the measured loop.
|
||||
- The draw list never silently exceeds `MAX_SPRITES`.
|
||||
- The benchmark has documented commands for repeatable local comparison.
|
||||
- `make check` and `make test` continue to pass.
|
||||
@@ -0,0 +1,116 @@
|
||||
# Add opt-in order-safe texture batching
|
||||
|
||||
## Summary
|
||||
|
||||
`end_frame` batches only consecutive sprites that use the same texture.
|
||||
Alternating two textures therefore produces one sampler bind and draw call per
|
||||
sprite even when some sprites could safely be regrouped.
|
||||
|
||||
Globally sorting transparent sprites by texture is not correct: overlapping
|
||||
sprites may blend differently when submission order changes. Batching should
|
||||
therefore be opt-in within explicit groups whose members are safe to reorder.
|
||||
|
||||
## Evidence
|
||||
|
||||
A temporary paired benchmark used:
|
||||
|
||||
- Odin `dev-2026-05-nightly:ea5175d` with `-debug -o:speed`
|
||||
- SDL 3.4.12 and Vulkan/Lavapipe
|
||||
- 128 animated sprites alternating between two equivalent textures
|
||||
- Sorting cost included in the measured frame
|
||||
- Ten order-alternated samples of 400 frames per mode
|
||||
|
||||
| Mode | Texture runs | Median frame time |
|
||||
| --- | ---: | ---: |
|
||||
| Submission order | 128 | 5.765 ms |
|
||||
| Texture grouped | 2 | 5.654 ms |
|
||||
|
||||
Sorting and grouping improved median frame time by approximately **1.9%**.
|
||||
Hardware drivers with higher draw-call overhead may show a different result.
|
||||
|
||||
## Reproduction harness
|
||||
|
||||
Run the committed alternating-texture workload on the baseline and candidate
|
||||
commits:
|
||||
|
||||
```bash
|
||||
make perf-frame \
|
||||
PERF_FRAME_SCENARIO=2 \
|
||||
PERF_ODIN_FLAGS="-debug -o:speed"
|
||||
```
|
||||
|
||||
Keep all `PERF_FRAME_*` values unchanged. The baseline should produce one
|
||||
texture run per sprite; the candidate should reduce runs only inside explicit
|
||||
reorder-safe groups. Compare `median_ms_per_frame` and verify rendered output.
|
||||
|
||||
## Suggested fix
|
||||
|
||||
Add an explicit batch group to queued sprites. Group `0` keeps strict submission
|
||||
order; nonzero groups may be reordered only when the caller guarantees that
|
||||
their members are order-independent.
|
||||
|
||||
```odin
|
||||
Queued_Sprite :: struct {
|
||||
texture: ^sdl.GPUTexture,
|
||||
verts: [SPRITE_VERT_COUNT]Vertex,
|
||||
batch_group: u32, // 0 = strict order; nonzero = caller permits regrouping
|
||||
}
|
||||
```
|
||||
|
||||
Sort each contiguous, nonzero group by texture immediately before upload:
|
||||
|
||||
```odin
|
||||
group_texture_runs :: proc(list: []Queued_Sprite) {
|
||||
start := 0
|
||||
for start < len(list) {
|
||||
group := list[start].batch_group
|
||||
if group == 0 {
|
||||
start += 1
|
||||
continue
|
||||
}
|
||||
|
||||
end := start + 1
|
||||
for end < len(list) && list[end].batch_group == group {
|
||||
end += 1
|
||||
}
|
||||
|
||||
// Stable insertion sort is sufficient while MAX_SPRITES is 128.
|
||||
for i in start + 1 ..< end {
|
||||
item := list[i]
|
||||
j := i
|
||||
for j > start {
|
||||
if uintptr(list[j - 1].texture) <= uintptr(item.texture) {
|
||||
break
|
||||
}
|
||||
list[j] = list[j - 1]
|
||||
j -= 1
|
||||
}
|
||||
list[j] = item
|
||||
}
|
||||
start = end
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Call it after all sprites are queued and before the transfer-buffer copy:
|
||||
|
||||
```odin
|
||||
group_texture_runs(app.draw_list[:])
|
||||
```
|
||||
|
||||
Expose batching through a separate API or explicit parameter so existing
|
||||
`draw_sprite` calls remain strict-order by default:
|
||||
|
||||
```odin
|
||||
draw_sprite_batched(&app, &sprite, batch_group = 1)
|
||||
```
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- Existing `draw_sprite` behavior preserves exact submission order.
|
||||
- Reordering requires an explicit nonzero batch group.
|
||||
- Sorting never moves a sprite across a strict-order entry or group boundary.
|
||||
- Add tests for strict order, group boundaries, stable same-texture ordering,
|
||||
and reduced texture-run count.
|
||||
- Add a visual overlap test confirming default alpha compositing is unchanged.
|
||||
- Benchmark sorting cost and draw-call reduction on a hardware GPU.
|
||||
@@ -0,0 +1,83 @@
|
||||
# Enable SDL GPU buffer cycling for per-frame sprite uploads
|
||||
|
||||
## Summary
|
||||
|
||||
`end_frame` overwrites the same transfer buffer and vertex buffer every frame,
|
||||
but both SDL calls currently pass `cycle = false`:
|
||||
|
||||
```odin
|
||||
sdl.MapGPUTransferBuffer(app.device, app.transfer_buffer, false)
|
||||
sdl.UploadToGPUBuffer(copy_pass, src, dst, false)
|
||||
```
|
||||
|
||||
SDL documents cycling as the mechanism that rotates to an unbound internal
|
||||
resource when the previous frame still references the current one. Enabling it
|
||||
avoids an unnecessary resource dependency and makes the overwrite pattern
|
||||
explicitly safe.
|
||||
|
||||
## Evidence
|
||||
|
||||
A temporary paired benchmark used:
|
||||
|
||||
- Odin `dev-2026-05-nightly:ea5175d` with `-debug -o:speed`
|
||||
- SDL 3.4.12 and Vulkan/Lavapipe
|
||||
- 128 animated sprites
|
||||
- Ten order-alternated samples of 400 frames per mode
|
||||
|
||||
| Mode | Median frame time |
|
||||
| --- | ---: |
|
||||
| Cycling disabled | 4.869 ms |
|
||||
| Cycling enabled | 4.834 ms |
|
||||
|
||||
Cycling improved median frame time by approximately **0.7%**. This is a small
|
||||
performance change, but it also follows SDL's documented resource-reuse model.
|
||||
|
||||
## Reproduction harness
|
||||
|
||||
Run the committed full-frame harness on the baseline commit and candidate
|
||||
commit:
|
||||
|
||||
```bash
|
||||
make perf-frame \
|
||||
PERF_FRAME_SCENARIO=0 \
|
||||
PERF_ODIN_FLAGS="-debug -o:speed"
|
||||
```
|
||||
|
||||
Keep all `PERF_FRAME_*` values unchanged. Compare `median_ms_per_frame`; the
|
||||
harness waits for GPU idle before stopping each trial timer.
|
||||
|
||||
## Suggested fix
|
||||
|
||||
Cycle both resources that are fully overwritten each frame:
|
||||
|
||||
```odin
|
||||
map_ptr := sdl.MapGPUTransferBuffer(
|
||||
app.device,
|
||||
app.transfer_buffer,
|
||||
true, // rotate if the previous frame still binds this transfer buffer
|
||||
)
|
||||
|
||||
// Write the complete [0, n * SPRITE_VERTS_SIZE) range, then unmap.
|
||||
sdl.UnmapGPUTransferBuffer(app.device, app.transfer_buffer)
|
||||
|
||||
copy_pass := sdl.BeginGPUCopyPass(cmd)
|
||||
sdl.UploadToGPUBuffer(
|
||||
copy_pass,
|
||||
src,
|
||||
dst,
|
||||
true, // rotate the destination vertex buffer if it is still bound
|
||||
)
|
||||
sdl.EndGPUCopyPass(copy_pass)
|
||||
```
|
||||
|
||||
Cycling makes previous contents undefined, so this remains correct only because
|
||||
the renderer writes the complete vertex range used by the frame before drawing.
|
||||
Do not enable cycling for partial updates that depend on untouched data.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- Both `MapGPUTransferBuffer` and `UploadToGPUBuffer` use `cycle = true`.
|
||||
- The complete submitted vertex range is rewritten every frame.
|
||||
- Existing engine tests and examples continue to pass.
|
||||
- A full-frame benchmark confirms no regression on a hardware GPU backend.
|
||||
- Add a comment explaining why cycling is safe for this full-overwrite path.
|
||||
@@ -0,0 +1,98 @@
|
||||
# Profile optimized sprite builds instead of unoptimized debug code
|
||||
|
||||
## Summary
|
||||
|
||||
`make flame-build` currently compiles the selected example with `-debug` but
|
||||
without an optimization mode:
|
||||
|
||||
```make
|
||||
odin build examples/$(FLAME_EXAMPLE) -collection:pkg=. -out:$(FLAME_BIN) -debug
|
||||
```
|
||||
|
||||
This makes the flamegraph useful for debugging but misleading for performance
|
||||
decisions. The current profiles largely describe code that will disappear or
|
||||
be inlined in an optimized build.
|
||||
|
||||
## Evidence
|
||||
|
||||
The two checked-in `crowd` profiles were captured from this unoptimized binary.
|
||||
They report:
|
||||
|
||||
- `engine::draw_sprite`: 9.56% and 12.22% self time
|
||||
- `engine::to_clip`: 5.33% and 5.51% self time
|
||||
- `engine::sprite_feet_quad`: 3.98% and 3.30% self time
|
||||
- Additional time in string hashing/map lookup, bounds checks, and dynamic
|
||||
array append helpers
|
||||
|
||||
A CPU-only benchmark using the real `draw_sprite`, real baked toad metadata,
|
||||
preallocated draw list, changing sprite positions, and two million draws per
|
||||
trial produced:
|
||||
|
||||
| Build | Median time per draw | Trials |
|
||||
| --- | ---: | ---: |
|
||||
| `-debug` (current Makefile behavior) | 192.560 ns | 7 |
|
||||
| `-debug -o:speed` | 19.154 ns | 7 |
|
||||
|
||||
The optimized build is about **10.1x faster** without an engine code change.
|
||||
|
||||
An end-to-end 128-sprite benchmark on SDL 3.4.12 with Lavapipe showed only a
|
||||
small full-frame difference (median 2.486 ms debug versus 2.447 ms optimized)
|
||||
because software GPU/driver work dominated. This does not invalidate the CPU
|
||||
result; it shows why CPU queue time and full-frame time must be reported
|
||||
separately.
|
||||
|
||||
Environment:
|
||||
|
||||
- Odin `dev-2026-05-nightly:ea5175d` (the version pinned by CI)
|
||||
- SDL 3.4.12
|
||||
- Linux x86-64
|
||||
|
||||
## Suggested fix
|
||||
|
||||
Compile profiling binaries with optimization while retaining symbols:
|
||||
|
||||
```make
|
||||
FLAME_ODIN_FLAGS ?= -debug -o:speed
|
||||
|
||||
flame-build:
|
||||
odin build examples/$(FLAME_EXAMPLE) \
|
||||
-collection:pkg=. \
|
||||
-out:$(FLAME_BIN) \
|
||||
$(FLAME_ODIN_FLAGS)
|
||||
```
|
||||
|
||||
Keeping the flags configurable allows an explicitly unoptimized diagnostic run
|
||||
without making it the performance default.
|
||||
|
||||
Example usage:
|
||||
|
||||
```bash
|
||||
# Representative performance profile: optimized code with debug symbols.
|
||||
make flame FLAME_EXAMPLE=crowd
|
||||
|
||||
# Explicitly profile unoptimized code when investigating debug-only behavior.
|
||||
make flame FLAME_EXAMPLE=crowd FLAME_ODIN_FLAGS="-debug -o:none"
|
||||
```
|
||||
|
||||
Reproduce the isolated build-mode comparison with the committed CPU harness:
|
||||
|
||||
```bash
|
||||
make perf-draw PERF_ODIN_FLAGS="-debug -o:none"
|
||||
make perf-draw PERF_ODIN_FLAGS="-debug -o:speed"
|
||||
```
|
||||
|
||||
Both runs print the Git commit, Odin version, compiler flags, every trial, and
|
||||
the median nanoseconds per draw.
|
||||
|
||||
Consider applying an explicit optimization mode to performance-oriented example
|
||||
runs as well. Plain `odin run` currently uses Odin's unoptimized default.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- `make flame-build` produces an optimized binary with debug symbols.
|
||||
- `FLAME_ODIN_FLAGS` can override the default for diagnostic builds.
|
||||
- `make check` and `make test` continue to pass.
|
||||
- A new `crowd` profile records the exact compiler flags in its report or
|
||||
accompanying documentation.
|
||||
- Performance conclusions distinguish CPU `draw_sprite` cost from complete
|
||||
frame/GPU submission cost.
|
||||
@@ -0,0 +1,139 @@
|
||||
# Prototype instanced sprite rendering for larger batches
|
||||
|
||||
## Summary
|
||||
|
||||
The renderer currently generates and uploads six complete vertices per sprite:
|
||||
|
||||
```text
|
||||
6 vertices × (position float2 + UV float2) = 96 bytes/sprite/frame
|
||||
```
|
||||
|
||||
Instancing can keep one immutable six-corner unit quad on the GPU and upload one
|
||||
rectangle/UV record per sprite:
|
||||
|
||||
```text
|
||||
clip rectangle float4 + UV rectangle float4 = 32 bytes/sprite/frame
|
||||
```
|
||||
|
||||
This reduces dynamic upload volume by two thirds, but requires another pipeline
|
||||
and backend-specific vertex shader. At the current 128-sprite cap, the measured
|
||||
gain is too small to justify enabling it unconditionally.
|
||||
|
||||
## Evidence
|
||||
|
||||
A complete temporary instanced path was implemented with:
|
||||
|
||||
- A static six-corner vertex buffer
|
||||
- A 32-byte per-instance buffer
|
||||
- Vertex-rate and instance-rate pipeline inputs
|
||||
- One instanced draw per texture run
|
||||
- Validated SPIR-V and SDL's debug GPU device
|
||||
|
||||
The paired benchmark used ten order-alternated samples of 400 frames:
|
||||
|
||||
| Mode | Median frame time |
|
||||
| --- | ---: |
|
||||
| Six dynamic vertices per sprite | 5.527 ms |
|
||||
| 32-byte instance per sprite | 5.467 ms |
|
||||
|
||||
Instancing improved median frame time by approximately **1.1%** on
|
||||
Vulkan/Lavapipe with 128 sprites.
|
||||
|
||||
## Reproduction harness
|
||||
|
||||
Run the committed visible full-frame workload on baseline and candidate commits:
|
||||
|
||||
```bash
|
||||
make perf-frame \
|
||||
PERF_FRAME_SCENARIO=0 \
|
||||
PERF_FRAME_SPRITES=128 \
|
||||
PERF_ODIN_FLAGS="-debug -o:speed"
|
||||
```
|
||||
|
||||
Keep all other `PERF_FRAME_*` values unchanged and compare
|
||||
`median_ms_per_frame`. To test 512 or more sprites, first raise the engine's
|
||||
`MAX_SPRITES` and associated buffer capacities on the candidate branch, then
|
||||
set `PERF_FRAME_SPRITES` to the same value.
|
||||
|
||||
## Suggested fix
|
||||
|
||||
Treat this as a prototype gated by larger sprite counts or a demonstrated
|
||||
hardware bottleneck, not as an immediate replacement.
|
||||
|
||||
Define the compact instance payload:
|
||||
|
||||
```odin
|
||||
Sprite_Instance :: struct {
|
||||
clip_rect: [4]f32, // left, top, right, bottom
|
||||
uv_rect: [4]f32, // u0, v0, u1, v1
|
||||
}
|
||||
```
|
||||
|
||||
Queue one record after the existing quad and UV calculations:
|
||||
|
||||
```odin
|
||||
instance := Sprite_Instance {
|
||||
clip_rect = {p0.x, p0.y, p2.x, p2.y},
|
||||
uv_rect = {u0, v0, u1, v1},
|
||||
}
|
||||
append(&app.instance_list, instance)
|
||||
```
|
||||
|
||||
Use a static unit quad:
|
||||
|
||||
```odin
|
||||
UNIT_QUAD := [6]Vec2 {
|
||||
{0, 0}, {1, 0}, {1, 1},
|
||||
{0, 0}, {1, 1}, {0, 1},
|
||||
}
|
||||
```
|
||||
|
||||
The instanced vertex shader reconstructs position and UV:
|
||||
|
||||
```glsl
|
||||
#version 450
|
||||
|
||||
layout(location = 0) in vec2 in_corner;
|
||||
layout(location = 1) in vec4 in_clip_rect;
|
||||
layout(location = 2) in vec4 in_uv_rect;
|
||||
|
||||
layout(location = 0) out vec2 v_uv;
|
||||
|
||||
void main() {
|
||||
vec2 position = mix(in_clip_rect.xy, in_clip_rect.zw, in_corner);
|
||||
v_uv = mix(in_uv_rect.xy, in_uv_rect.zw, in_corner);
|
||||
gl_Position = vec4(position, 0.0, 1.0);
|
||||
}
|
||||
```
|
||||
|
||||
Configure slot 0 as vertex-rate and slot 1 as instance-rate, then draw each
|
||||
texture run with six vertices and `run` instances:
|
||||
|
||||
```odin
|
||||
vb_descs := [2]sdl.GPUVertexBufferDescription {
|
||||
{slot = 0, pitch = u32(size_of(Vec2)), input_rate = .VERTEX},
|
||||
{slot = 1, pitch = u32(size_of(Sprite_Instance)), input_rate = .INSTANCE},
|
||||
}
|
||||
|
||||
sdl.DrawGPUPrimitives(
|
||||
app.render_pass,
|
||||
6, // unit-quad vertices
|
||||
u32(run), // sprite instances in this texture run
|
||||
0,
|
||||
0,
|
||||
)
|
||||
```
|
||||
|
||||
Keep the current path as a fallback until the instanced implementation exists
|
||||
for Vulkan, D3D12, and Metal and demonstrates a meaningful hardware win.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- Benchmark at 128, 512, 2,048, and 10,000 sprites or the highest supported
|
||||
counts.
|
||||
- Report CPU queue time, bytes uploaded, and complete frame time separately.
|
||||
- Require a meaningful hardware improvement before changing the default path.
|
||||
- Supply equivalent Vulkan, D3D12, and Metal shaders.
|
||||
- Preserve texture-run batching and sprite flip/trim behavior.
|
||||
- Add visual equivalence tests for position, UVs, animation frames, and flip.
|
||||
- Retain the existing six-vertex path as a fallback during evaluation.
|
||||
@@ -0,0 +1,130 @@
|
||||
# Reduce repeated clip-space work in `draw_sprite`
|
||||
|
||||
## Summary
|
||||
|
||||
`draw_sprite` calls `to_clip` four times for an axis-aligned quad:
|
||||
|
||||
```odin
|
||||
p0 := to_clip(x0_px, y0_px, sw, sh)
|
||||
p1 := to_clip(x1_px, y0_px, sw, sh)
|
||||
p2 := to_clip(x1_px, y1_px, sw, sh)
|
||||
p3 := to_clip(x0_px, y1_px, sw, sh)
|
||||
```
|
||||
|
||||
This repeats the same divisions and converts duplicate x/y coordinates. An
|
||||
axis-aligned sprite has only two unique x values and two unique y values.
|
||||
|
||||
This is a measurable optimization, but it is low priority at the current
|
||||
128-sprite limit because the absolute saving is small.
|
||||
|
||||
## Evidence
|
||||
|
||||
The checked-in unoptimized profiles report `engine::to_clip` at 5.33% and 5.51%
|
||||
self time. Those percentages are inflated by the unoptimized profiling build,
|
||||
so the change was also measured with `-debug -o:speed`.
|
||||
|
||||
A temporary benchmark used the real baked toad metadata, changed sprite
|
||||
position on every iteration, preallocated the queue, and performed two million
|
||||
draws per mode over seven trials:
|
||||
|
||||
| Mode | Median time per draw |
|
||||
| --- | ---: |
|
||||
| Current `draw_sprite` | 25.128 ns |
|
||||
| Precomputed clip scale and reused coordinates | 21.531 ns |
|
||||
| Same math plus cached `Frame_Def` | 21.778 ns |
|
||||
|
||||
Simplifying the math improved isolated draw time by approximately **14.3%**.
|
||||
Caching the resolved frame did not provide an additional benefit and should not
|
||||
be included without new evidence.
|
||||
|
||||
At `MAX_SPRITES == 128`, the measured math saving is only about 0.46
|
||||
microseconds per completely full frame. GPU/driver work dominated the
|
||||
end-to-end benchmark, so this should follow the profiling and deterministic
|
||||
benchmark improvements.
|
||||
|
||||
Follow-up paired full-frame experiments at the 128-sprite cap found no larger
|
||||
renderer-architecture win: buffer cycling improved median frame time by 0.7%,
|
||||
GPU instancing by 1.1%, and texture sorting by 1.9%, while culling, queue
|
||||
repacking, and indexed quads were neutral or slower. The clip-space change
|
||||
therefore remains the strongest measured optimization specifically inside
|
||||
`draw_sprite`, although its absolute frame impact is still small.
|
||||
|
||||
Environment:
|
||||
|
||||
- Odin `dev-2026-05-nightly:ea5175d`
|
||||
- Optimized with `-debug -o:speed`
|
||||
- Linux x86-64
|
||||
|
||||
## Reproduction harness
|
||||
|
||||
Run the committed CPU harness on the baseline commit and again after applying
|
||||
the suggested fix:
|
||||
|
||||
```bash
|
||||
make perf-draw PERF_ODIN_FLAGS="-debug -o:speed"
|
||||
```
|
||||
|
||||
Keep `PERF_DRAW_ITERATIONS`, `PERF_DRAW_WARMUP`, and `PERF_DRAW_TRIALS`
|
||||
unchanged between commits. Compare `median_ns_per_draw`.
|
||||
|
||||
## Suggested fix
|
||||
|
||||
Compute clip scaling once and construct corners from the unique coordinates:
|
||||
|
||||
```odin
|
||||
sprite_quad_to_clip :: proc(x0, y0, x1, y1, sw, sh: f32) -> [4]Vec2 {
|
||||
sx := 2.0 / sw
|
||||
sy := 2.0 / sh
|
||||
|
||||
left := x0 * sx - 1
|
||||
right := x1 * sx - 1
|
||||
top := 1 - y0 * sy
|
||||
bottom := 1 - y1 * sy
|
||||
|
||||
return {
|
||||
{left, top},
|
||||
{right, top},
|
||||
{right, bottom},
|
||||
{left, bottom},
|
||||
}
|
||||
}
|
||||
|
||||
points := sprite_quad_to_clip(x0_px, y0_px, x1_px, y1_px, sw, sh)
|
||||
p0, p1, p2, p3 := points[0], points[1], points[2], points[3]
|
||||
```
|
||||
|
||||
Keep `to_clip` for general callers and its existing tests; this change only
|
||||
specializes quad construction inside `draw_sprite`.
|
||||
|
||||
Add an equivalence test before replacing the current calls:
|
||||
|
||||
```odin
|
||||
@(test)
|
||||
sprite_quad_clip_math_matches_to_clip :: proc(t: ^testing.T) {
|
||||
x0, y0 := f32(125), f32(80)
|
||||
x1, y1 := f32(325), f32(280)
|
||||
sw, sh := f32(800), f32(600)
|
||||
|
||||
expected := [4]Vec2 {
|
||||
to_clip(x0, y0, sw, sh),
|
||||
to_clip(x1, y0, sw, sh),
|
||||
to_clip(x1, y1, sw, sh),
|
||||
to_clip(x0, y1, sw, sh),
|
||||
}
|
||||
actual := sprite_quad_to_clip(x0, y0, x1, y1, sw, sh)
|
||||
|
||||
for i in 0 ..< 4 {
|
||||
testing.expect_value(t, actual[i], expected[i])
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- Existing sprite geometry, camera, UV, and batching tests pass.
|
||||
- Add or extend a test that compares all four generated corners against
|
||||
`to_clip` for representative viewport and sprite coordinates.
|
||||
- Flipped and unflipped sprites produce identical vertices to the current code.
|
||||
- An optimized deterministic benchmark shows at least a 10% improvement in
|
||||
isolated `draw_sprite` time under comparable conditions.
|
||||
- Do not add a per-sprite frame cache as part of this issue.
|
||||
@@ -1,5 +1,6 @@
|
||||
.PHONY: shaders-vulkan shaders-d3d12 shaders-metal shaders-all bake toad hello_sprite crowd camera_sandbox clips check test help
|
||||
.PHONY: flame flame-build flame-record flame-svg flame-report flame-tools
|
||||
.PHONY: perf-draw perf-frame
|
||||
|
||||
# Flamegraph profiling (needs: pacman -S perf). Example: make flame or make flame FLAME_EXAMPLE=toad
|
||||
FLAME_EXAMPLE ?= crowd
|
||||
@@ -12,6 +13,19 @@ FLAME_STAMP := $(shell date +%Y%m%d-%H%M%S)
|
||||
endif
|
||||
FLAME_PREFIX := $(FLAME_OUT_DIR)/$(FLAME_EXAMPLE)-$(FLAME_STAMP)
|
||||
|
||||
PERF_DRAW_ITERATIONS ?= 2000000
|
||||
PERF_DRAW_WARMUP ?= 10000
|
||||
PERF_DRAW_TRIALS ?= 7
|
||||
PERF_ODIN_FLAGS ?= -debug -o:speed
|
||||
PERF_FRAME_SPRITES ?= 128
|
||||
PERF_FRAME_FRAMES ?= 400
|
||||
PERF_FRAME_WARMUP ?= 100
|
||||
PERF_FRAME_TRIALS ?= 10
|
||||
# 0=visible, 1=half offscreen, 2=alternating textures, 3=stacked
|
||||
PERF_FRAME_SCENARIO ?= 0
|
||||
PERF_FRAME_WIDTH ?= 800
|
||||
PERF_FRAME_HEIGHT ?= 600
|
||||
|
||||
help:
|
||||
@echo "Targets:"
|
||||
@echo " bake Bake all characters under content/characters/"
|
||||
@@ -31,6 +45,8 @@ help:
|
||||
@echo " flame-record perf record (play, then quit)"
|
||||
@echo " flame-svg Convert perf.data -> $(FLAME_PREFIX).svg/.jpg"
|
||||
@echo " flame-report Convert perf.data -> $(FLAME_PREFIX)-report.txt"
|
||||
@echo " perf-draw Deterministic CPU draw benchmark"
|
||||
@echo " perf-frame Deterministic SDL GPU frame benchmark (scenario 0/1/2/3)"
|
||||
|
||||
bake:
|
||||
./scripts/bake_all.sh
|
||||
@@ -57,6 +73,28 @@ check:
|
||||
odin check examples/camera_sandbox -collection:pkg=.
|
||||
odin check examples/clips -collection:pkg=.
|
||||
|
||||
perf-draw:
|
||||
@echo "git_commit=$$(git rev-parse HEAD)"
|
||||
@echo "odin_version=$$(odin version)"
|
||||
@echo "odin_flags=$(PERF_ODIN_FLAGS)"
|
||||
odin run benchmarks/draw_sprite -collection:pkg=. $(PERF_ODIN_FLAGS) \
|
||||
-define:PERF_ITERATIONS=$(PERF_DRAW_ITERATIONS) \
|
||||
-define:PERF_WARMUP=$(PERF_DRAW_WARMUP) \
|
||||
-define:PERF_TRIALS=$(PERF_DRAW_TRIALS)
|
||||
|
||||
perf-frame:
|
||||
@echo "git_commit=$$(git rev-parse HEAD)"
|
||||
@echo "odin_version=$$(odin version)"
|
||||
@echo "odin_flags=$(PERF_ODIN_FLAGS)"
|
||||
odin run benchmarks/sprite_frame -collection:pkg=. $(PERF_ODIN_FLAGS) \
|
||||
-define:PERF_SPRITES=$(PERF_FRAME_SPRITES) \
|
||||
-define:PERF_FRAMES=$(PERF_FRAME_FRAMES) \
|
||||
-define:PERF_WARMUP_FRAMES=$(PERF_FRAME_WARMUP) \
|
||||
-define:PERF_TRIALS=$(PERF_FRAME_TRIALS) \
|
||||
-define:PERF_SCENARIO=$(PERF_FRAME_SCENARIO) \
|
||||
-define:PERF_WIDTH=$(PERF_FRAME_WIDTH) \
|
||||
-define:PERF_HEIGHT=$(PERF_FRAME_HEIGHT)
|
||||
|
||||
toad:
|
||||
odin run examples/toad -collection:pkg=.
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package main
|
||||
|
||||
import "core:fmt"
|
||||
import "core:os"
|
||||
import eng "pkg:engine"
|
||||
import sdl "vendor:sdl3"
|
||||
|
||||
PERF_ITERATIONS :: #config(PERF_ITERATIONS, 2_000_000)
|
||||
PERF_WARMUP :: #config(PERF_WARMUP, 10_000)
|
||||
PERF_TRIALS :: #config(PERF_TRIALS, 7)
|
||||
|
||||
@(private)
|
||||
median :: proc(values: []f64) -> f64 {
|
||||
for i in 1 ..< len(values) {
|
||||
value := values[i]
|
||||
j := i
|
||||
for j > 0 {
|
||||
if values[j - 1] <= value do break
|
||||
values[j] = values[j - 1]
|
||||
j -= 1
|
||||
}
|
||||
values[j] = value
|
||||
}
|
||||
|
||||
middle := len(values) / 2
|
||||
if len(values) & 1 == 1 do return values[middle]
|
||||
return (values[middle - 1] + values[middle]) / 2
|
||||
}
|
||||
|
||||
@(private)
|
||||
run_draws :: proc(app: ^eng.App, sprite: ^eng.Sprite, iterations: int) -> u64 {
|
||||
clear(&app.draw_list)
|
||||
start := sdl.GetTicksNS()
|
||||
for i in 0 ..< iterations {
|
||||
if len(app.draw_list) >= eng.MAX_SPRITES {
|
||||
clear(&app.draw_list)
|
||||
}
|
||||
|
||||
// Vary an input so optimized builds cannot hoist the draw calculations.
|
||||
sprite.position.x = f32(i & 1023)
|
||||
eng.draw_sprite(app, sprite)
|
||||
}
|
||||
return sdl.GetTicksNS() - start
|
||||
}
|
||||
|
||||
main :: proc() {
|
||||
#assert(PERF_ITERATIONS > 0)
|
||||
#assert(PERF_WARMUP > 0)
|
||||
#assert(PERF_TRIALS > 0)
|
||||
|
||||
file_data, err := os.read_entire_file(
|
||||
"assets_baked/characters/toad/toad.char.json",
|
||||
context.allocator,
|
||||
)
|
||||
if err != nil {
|
||||
fmt.eprintfln("benchmark asset read failed: %v", err)
|
||||
return
|
||||
}
|
||||
defer delete(file_data)
|
||||
|
||||
def, ok := eng.parse_char_def(file_data)
|
||||
if !ok do return
|
||||
|
||||
data := eng.Character_Data {
|
||||
def = def,
|
||||
texture = cast(^sdl.GPUTexture)uintptr(1),
|
||||
width = 1911,
|
||||
height = 1526,
|
||||
}
|
||||
app := eng.App {
|
||||
cmd = cast(^sdl.GPUCommandBuffer)uintptr(1),
|
||||
swapchain_texture = cast(^sdl.GPUTexture)uintptr(2),
|
||||
swapchain_w = 800,
|
||||
swapchain_h = 600,
|
||||
camera = eng.camera_default(),
|
||||
draw_list = make(
|
||||
[dynamic]eng.Queued_Sprite,
|
||||
0,
|
||||
eng.MAX_SPRITES,
|
||||
),
|
||||
}
|
||||
defer delete(app.draw_list)
|
||||
|
||||
sprite := eng.spawn_sprite(&data, {400, 400}, "walk", 4)
|
||||
_ = run_draws(&app, &sprite, PERF_WARMUP)
|
||||
|
||||
samples: [PERF_TRIALS]f64
|
||||
fmt.printfln(
|
||||
"benchmark=draw_sprite iterations=%d warmup=%d trials=%d sprites_per_queue=%d",
|
||||
PERF_ITERATIONS,
|
||||
PERF_WARMUP,
|
||||
PERF_TRIALS,
|
||||
eng.MAX_SPRITES,
|
||||
)
|
||||
for trial in 0 ..< PERF_TRIALS {
|
||||
elapsed := run_draws(&app, &sprite, PERF_ITERATIONS)
|
||||
samples[trial] = f64(elapsed) / f64(PERF_ITERATIONS)
|
||||
fmt.printfln("trial=%d ns_per_draw=%.3f", trial + 1, samples[trial])
|
||||
}
|
||||
|
||||
fmt.printfln("median_ns_per_draw=%.3f", median(samples[:]))
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package main
|
||||
|
||||
import "core:fmt"
|
||||
import eng "pkg:engine"
|
||||
import sdl "vendor:sdl3"
|
||||
|
||||
PERF_SPRITES :: #config(PERF_SPRITES, 128)
|
||||
PERF_FRAMES :: #config(PERF_FRAMES, 400)
|
||||
PERF_WARMUP_FRAMES :: #config(PERF_WARMUP_FRAMES, 100)
|
||||
PERF_TRIALS :: #config(PERF_TRIALS, 10)
|
||||
PERF_SCENARIO :: #config(PERF_SCENARIO, 0)
|
||||
PERF_WIDTH :: #config(PERF_WIDTH, 800)
|
||||
PERF_HEIGHT :: #config(PERF_HEIGHT, 600)
|
||||
|
||||
Scenario :: enum {
|
||||
Visible,
|
||||
Half_Offscreen,
|
||||
Alternating_Textures,
|
||||
Stacked,
|
||||
}
|
||||
|
||||
@(private)
|
||||
median :: proc(values: []f64) -> f64 {
|
||||
for i in 1 ..< len(values) {
|
||||
value := values[i]
|
||||
j := i
|
||||
for j > 0 {
|
||||
if values[j - 1] <= value do break
|
||||
values[j] = values[j - 1]
|
||||
j -= 1
|
||||
}
|
||||
values[j] = value
|
||||
}
|
||||
|
||||
middle := len(values) / 2
|
||||
if len(values) & 1 == 1 do return values[middle]
|
||||
return (values[middle - 1] + values[middle]) / 2
|
||||
}
|
||||
|
||||
@(private)
|
||||
scenario_name :: proc(scenario: Scenario) -> string {
|
||||
switch scenario {
|
||||
case .Visible:
|
||||
return "visible"
|
||||
case .Half_Offscreen:
|
||||
return "half_offscreen"
|
||||
case .Alternating_Textures:
|
||||
return "alternating_textures"
|
||||
case .Stacked:
|
||||
return "stacked"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
@(private)
|
||||
present_mode_name :: proc(app: ^eng.App) -> string {
|
||||
if sdl.WindowSupportsGPUPresentMode(app.device, app.window, .IMMEDIATE) {
|
||||
return "immediate"
|
||||
}
|
||||
if sdl.WindowSupportsGPUPresentMode(app.device, app.window, .MAILBOX) {
|
||||
return "mailbox"
|
||||
}
|
||||
return "vsync"
|
||||
}
|
||||
|
||||
@(private)
|
||||
draw_frame :: proc(app: ^eng.App, sprites: []eng.Sprite) {
|
||||
for &sprite in sprites {
|
||||
eng.update_sprite(&sprite, 1.0 / 60.0)
|
||||
}
|
||||
|
||||
eng.begin_frame(app)
|
||||
for &sprite in sprites {
|
||||
eng.draw_sprite(app, &sprite)
|
||||
}
|
||||
eng.end_frame(app)
|
||||
}
|
||||
|
||||
main :: proc() {
|
||||
#assert(PERF_SPRITES > 0)
|
||||
#assert(PERF_SPRITES <= eng.MAX_SPRITES)
|
||||
#assert(PERF_FRAMES > 0)
|
||||
#assert(PERF_WARMUP_FRAMES > 0)
|
||||
#assert(PERF_TRIALS > 0)
|
||||
#assert(PERF_SCENARIO >= 0 && PERF_SCENARIO <= 3)
|
||||
#assert(PERF_WIDTH > 0)
|
||||
#assert(PERF_HEIGHT > 0)
|
||||
|
||||
scenario := Scenario(PERF_SCENARIO)
|
||||
|
||||
app: eng.App
|
||||
if !eng.init(&app, "sprite frame benchmark", PERF_WIDTH, PERF_HEIGHT) {
|
||||
return
|
||||
}
|
||||
defer eng.shutdown(&app)
|
||||
|
||||
path := "assets_baked/characters/toad/toad.char.json"
|
||||
data_a, ok := eng.load_character_data(&app, path)
|
||||
if !ok do return
|
||||
defer eng.destroy_character_data(&app, &data_a)
|
||||
|
||||
data_b: eng.Character_Data
|
||||
data_b, ok = eng.load_character_data(&app, path)
|
||||
if !ok do return
|
||||
defer eng.destroy_character_data(&app, &data_b)
|
||||
|
||||
sprites: [PERF_SPRITES]eng.Sprite
|
||||
for i in 0 ..< PERF_SPRITES {
|
||||
data := &data_a
|
||||
if scenario == .Alternating_Textures && (i & 1) == 1 {
|
||||
data = &data_b
|
||||
}
|
||||
|
||||
position := eng.Vec2 {
|
||||
f32(40 + (i % 16) * 48),
|
||||
f32(120 + (i / 16) * 60),
|
||||
}
|
||||
if scenario == .Half_Offscreen && (i & 1) == 1 {
|
||||
position = {-10_000, -10_000}
|
||||
} else if scenario == .Stacked {
|
||||
position = {f32(PERF_WIDTH / 2), f32(PERF_HEIGHT / 2)}
|
||||
}
|
||||
sprites[i] = eng.spawn_sprite(data, position, "walk", i % 17)
|
||||
}
|
||||
|
||||
for _ in 0 ..< PERF_WARMUP_FRAMES {
|
||||
draw_frame(&app, sprites[:])
|
||||
}
|
||||
if !sdl.WaitForGPUIdle(app.device) {
|
||||
fmt.eprintfln("GPU wait failed after warm-up: %s", sdl.GetError())
|
||||
return
|
||||
}
|
||||
|
||||
fmt.printfln(
|
||||
"benchmark=sprite_frame scenario=%s sprites=%d resolution=%dx%d frames=%d warmup=%d trials=%d backend=%v driver=%s present=%s",
|
||||
scenario_name(scenario),
|
||||
PERF_SPRITES,
|
||||
PERF_WIDTH,
|
||||
PERF_HEIGHT,
|
||||
PERF_FRAMES,
|
||||
PERF_WARMUP_FRAMES,
|
||||
PERF_TRIALS,
|
||||
app.shader.backend,
|
||||
sdl.GetGPUDeviceDriver(app.device),
|
||||
present_mode_name(&app),
|
||||
)
|
||||
|
||||
samples: [PERF_TRIALS]f64
|
||||
for trial in 0 ..< PERF_TRIALS {
|
||||
start := sdl.GetTicksNS()
|
||||
for _ in 0 ..< PERF_FRAMES {
|
||||
draw_frame(&app, sprites[:])
|
||||
}
|
||||
if !sdl.WaitForGPUIdle(app.device) {
|
||||
fmt.eprintfln("GPU wait failed after trial %d: %s", trial + 1, sdl.GetError())
|
||||
return
|
||||
}
|
||||
elapsed := sdl.GetTicksNS() - start
|
||||
samples[trial] = f64(elapsed) / f64(PERF_FRAMES) / 1_000_000.0
|
||||
fmt.printfln(
|
||||
"trial=%d ms_per_frame=%.3f fps=%.1f",
|
||||
trial + 1,
|
||||
samples[trial],
|
||||
1_000.0 / samples[trial],
|
||||
)
|
||||
}
|
||||
|
||||
median_ms := median(samples[:])
|
||||
fmt.printfln(
|
||||
"median_ms_per_frame=%.3f median_fps=%.1f",
|
||||
median_ms,
|
||||
1_000.0 / median_ms,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user