vello_encoding/config.rs
1// Copyright 2023 the Vello Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use crate::SegmentCount;
5
6use super::{
7 BinHeader, Clip, ClipBbox, ClipBic, ClipElement, DrawBbox, DrawMonoid, Layout, LineSoup, Path,
8 PathBbox, PathMonoid, PathSegment, Tile,
9};
10use bytemuck::{Pod, Zeroable};
11
12const TILE_WIDTH: u32 = 16;
13const TILE_HEIGHT: u32 = 16;
14
15// TODO: Obtain these from the vello_shaders crate
16pub(crate) const PATH_REDUCE_WG: u32 = 256;
17const PATH_BBOX_WG: u32 = 256;
18const FLATTEN_WG: u32 = 256;
19const CLIP_REDUCE_WG: u32 = 256;
20
21/// Counters for tracking dynamic allocation on the GPU.
22///
23/// This must be kept in sync with the struct in `shader/shared/bump.wgsl`
24#[derive(Clone, Copy, Debug, Default, Zeroable, Pod)]
25#[repr(C)]
26pub struct BumpAllocators {
27 pub failed: u32,
28 // Final needed dynamic size of the buffers. If any of these are larger
29 // than the corresponding `_size` element reallocation needs to occur.
30 pub binning: u32,
31 pub ptcl: u32,
32 pub tile: u32,
33 pub seg_counts: u32,
34 pub segments: u32,
35 pub blend: u32,
36 pub lines: u32,
37}
38
39#[derive(Default)]
40pub struct BumpAllocatorMemory {
41 pub total: u32,
42 pub binning: BufferSize<u32>,
43 pub ptcl: BufferSize<u32>,
44 pub tile: BufferSize<Tile>,
45 pub seg_counts: BufferSize<SegmentCount>,
46 pub segments: BufferSize<PathSegment>,
47 pub lines: BufferSize<LineSoup>,
48}
49
50impl BumpAllocators {
51 pub fn memory(&self) -> BumpAllocatorMemory {
52 let binning = BufferSize::new(self.binning);
53 let ptcl = BufferSize::new(self.ptcl);
54 let tile = BufferSize::new(self.tile);
55 let seg_counts = BufferSize::new(self.seg_counts);
56 let segments = BufferSize::new(self.segments);
57 let lines = BufferSize::new(self.lines);
58 BumpAllocatorMemory {
59 total: binning.size_in_bytes()
60 + ptcl.size_in_bytes()
61 + tile.size_in_bytes()
62 + seg_counts.size_in_bytes()
63 + segments.size_in_bytes()
64 + lines.size_in_bytes(),
65 binning,
66 ptcl,
67 tile,
68 seg_counts,
69 segments,
70 lines,
71 }
72 }
73}
74
75impl std::fmt::Display for BumpAllocatorMemory {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 write!(
78 f,
79 "\n \
80 \tTotal:\t\t\t{} bytes ({:.2} KB | {:.2} MB)\n\
81 \tBinning\t\t\t{} elements ({} bytes)\n\
82 \tPTCL\t\t\t{} elements ({} bytes)\n\
83 \tTile:\t\t\t{} elements ({} bytes)\n\
84 \tSegment Counts:\t\t{} elements ({} bytes)\n\
85 \tSegments:\t\t{} elements ({} bytes)\n\
86 \tLines:\t\t\t{} elements ({} bytes)",
87 self.total,
88 self.total as f32 / (1 << 10) as f32,
89 self.total as f32 / (1 << 20) as f32,
90 self.binning.len(),
91 self.binning.size_in_bytes(),
92 self.ptcl.len(),
93 self.ptcl.size_in_bytes(),
94 self.tile.len(),
95 self.tile.size_in_bytes(),
96 self.seg_counts.len(),
97 self.seg_counts.size_in_bytes(),
98 self.segments.len(),
99 self.segments.size_in_bytes(),
100 self.lines.len(),
101 self.lines.size_in_bytes()
102 )
103 }
104}
105
106/// Storage of indirect dispatch size values.
107///
108/// The original plan was to reuse [`BumpAllocators`], but the WebGPU compatible
109/// usage list rules forbid that being used as indirect counts while also
110/// bound as writable.
111#[derive(Clone, Copy, Debug, Default, Zeroable, Pod)]
112#[repr(C)]
113pub struct IndirectCount {
114 pub count_x: u32,
115 pub count_y: u32,
116 pub count_z: u32,
117 pub pad0: u32,
118}
119
120/// Uniform render configuration data used by all GPU stages.
121///
122/// This data structure must be kept in sync with the definition in
123/// `shaders/shared/config.wgsl`.
124#[derive(Clone, Copy, Debug, Default, Zeroable, Pod)]
125#[repr(C)]
126pub struct ConfigUniform {
127 /// Width of the scene in tiles.
128 pub width_in_tiles: u32,
129 /// Height of the scene in tiles.
130 pub height_in_tiles: u32,
131 /// Width of the target in pixels.
132 pub target_width: u32,
133 /// Height of the target in pixels.
134 pub target_height: u32,
135 /// The base background color applied to the target before any blends.
136 pub base_color: u32,
137 /// Layout of packed scene data.
138 pub layout: Layout,
139 /// Size of line soup buffer allocation (in [`LineSoup`]s)
140 pub lines_size: u32,
141 /// Size of binning buffer allocation (in `u32`s).
142 pub binning_size: u32,
143 /// Size of tile buffer allocation (in [`Tile`]s).
144 pub tiles_size: u32,
145 /// Size of segment count buffer allocation (in [`SegmentCount`]s).
146 pub seg_counts_size: u32,
147 /// Size of segment buffer allocation (in [`PathSegment`]s).
148 pub segments_size: u32,
149 /// Size of blend spill buffer (in `u32` pixels).
150 // TODO: Maybe store in TILE_WIDTH * TILE_HEIGHT blocks of pixels instead?
151 pub blend_size: u32,
152 /// Size of per-tile command list buffer allocation (in `u32`s).
153 pub ptcl_size: u32,
154}
155
156/// CPU side setup and configuration.
157#[derive(Default)]
158pub struct RenderConfig {
159 /// GPU side configuration.
160 pub gpu: ConfigUniform,
161 /// Workgroup counts for all compute pipelines.
162 pub workgroup_counts: WorkgroupCounts,
163 /// Sizes of all buffer resources.
164 pub buffer_sizes: BufferSizes,
165}
166
167impl RenderConfig {
168 pub fn new(
169 layout: &Layout,
170 width: u32,
171 height: u32,
172 base_color: &peniko::Color,
173 budget: &BumpBudget,
174 ) -> Self {
175 let new_width = width.next_multiple_of(TILE_WIDTH);
176 let new_height = height.next_multiple_of(TILE_HEIGHT);
177 let width_in_tiles = new_width / TILE_WIDTH;
178 let height_in_tiles = new_height / TILE_HEIGHT;
179 let n_path_tags = layout.path_tags_size();
180 let workgroup_counts =
181 WorkgroupCounts::new(layout, width_in_tiles, height_in_tiles, n_path_tags);
182 let buffer_sizes = BufferSizes::new(
183 layout,
184 &workgroup_counts,
185 width_in_tiles,
186 height_in_tiles,
187 budget,
188 );
189 Self {
190 gpu: ConfigUniform {
191 width_in_tiles,
192 height_in_tiles,
193 target_width: width,
194 target_height: height,
195 base_color: base_color.premultiply().to_rgba8().to_u32(),
196 lines_size: buffer_sizes.lines.len(),
197 binning_size: buffer_sizes.bin_data.len() - layout.bin_data_start,
198 tiles_size: buffer_sizes.tiles.len(),
199 seg_counts_size: buffer_sizes.seg_counts.len(),
200 segments_size: buffer_sizes.segments.len(),
201 blend_size: buffer_sizes.blend_spill.len(),
202 ptcl_size: buffer_sizes.ptcl.len(),
203 layout: *layout,
204 },
205 workgroup_counts,
206 buffer_sizes,
207 }
208 }
209}
210
211/// Type alias for a workgroup size.
212pub type WorkgroupSize = (u32, u32, u32);
213
214/// Computed sizes for all dispatches.
215#[derive(Copy, Clone, Debug, Default)]
216pub struct WorkgroupCounts {
217 pub use_large_path_scan: bool,
218 pub path_reduce: WorkgroupSize,
219 pub path_reduce2: WorkgroupSize,
220 pub path_scan1: WorkgroupSize,
221 pub path_scan: WorkgroupSize,
222 pub bbox_clear: WorkgroupSize,
223 pub flatten: WorkgroupSize,
224 pub draw_reduce: WorkgroupSize,
225 pub draw_leaf: WorkgroupSize,
226 pub clip_reduce: WorkgroupSize,
227 pub clip_leaf: WorkgroupSize,
228 pub binning: WorkgroupSize,
229 pub tile_alloc: WorkgroupSize,
230 pub path_count_setup: WorkgroupSize,
231 // Note: `path_count` must use an indirect dispatch
232 pub backdrop: WorkgroupSize,
233 pub coarse: WorkgroupSize,
234 pub path_tiling_setup: WorkgroupSize,
235 // Note: `path_tiling` must use an indirect dispatch
236 pub fine: WorkgroupSize,
237}
238
239impl WorkgroupCounts {
240 pub fn new(
241 layout: &Layout,
242 width_in_tiles: u32,
243 height_in_tiles: u32,
244 n_path_tags: u32,
245 ) -> Self {
246 let n_paths = layout.n_paths;
247 let n_draw_objects = layout.n_draw_objects;
248 let n_clips = layout.n_clips;
249 let path_tag_padded = align_up(n_path_tags, 4 * PATH_REDUCE_WG);
250 let path_tag_wgs = path_tag_padded / (4 * PATH_REDUCE_WG);
251 let use_large_path_scan = path_tag_wgs > PATH_REDUCE_WG;
252 let reduced_size = if use_large_path_scan {
253 align_up(path_tag_wgs, PATH_REDUCE_WG)
254 } else {
255 path_tag_wgs
256 };
257 let draw_object_wgs = n_draw_objects.div_ceil(PATH_BBOX_WG);
258 let draw_monoid_wgs = draw_object_wgs.min(PATH_BBOX_WG);
259 let flatten_wgs = n_path_tags.div_ceil(FLATTEN_WG);
260 let clip_reduce_wgs = n_clips.saturating_sub(1) / CLIP_REDUCE_WG;
261 let clip_wgs = n_clips.div_ceil(CLIP_REDUCE_WG);
262 let path_wgs = n_paths.div_ceil(PATH_BBOX_WG);
263 let width_in_bins = width_in_tiles.div_ceil(16);
264 let height_in_bins = height_in_tiles.div_ceil(16);
265 Self {
266 use_large_path_scan,
267 path_reduce: (path_tag_wgs, 1, 1),
268 path_reduce2: (PATH_REDUCE_WG, 1, 1),
269 path_scan1: (reduced_size / PATH_REDUCE_WG, 1, 1),
270 path_scan: (path_tag_wgs, 1, 1),
271 bbox_clear: (draw_object_wgs, 1, 1),
272 flatten: (flatten_wgs, 1, 1),
273 draw_reduce: (draw_monoid_wgs, 1, 1),
274 draw_leaf: (draw_monoid_wgs, 1, 1),
275 clip_reduce: (clip_reduce_wgs, 1, 1),
276 clip_leaf: (clip_wgs, 1, 1),
277 binning: (draw_object_wgs, 1, 1),
278 tile_alloc: (path_wgs, 1, 1),
279 path_count_setup: (1, 1, 1),
280 backdrop: (path_wgs, 1, 1),
281 coarse: (width_in_bins, height_in_bins, 1),
282 path_tiling_setup: (1, 1, 1),
283 fine: (width_in_tiles, height_in_tiles, 1),
284 }
285 }
286}
287
288/// Typed buffer size primitive.
289#[derive(Copy, Clone, Eq, Default, Debug)]
290pub struct BufferSize<T: Sized> {
291 len: u32,
292 _phantom: std::marker::PhantomData<T>,
293}
294
295impl<T: Sized> BufferSize<T> {
296 /// Creates a new buffer size from number of elements.
297 pub const fn new(len: u32) -> Self {
298 Self {
299 // Each buffer binding must be large enough to hold at least one element to avoid
300 // triggering validation errors.
301 //
302 // Note: not using `Ord::max` here because it doesn't support const eval yet (except
303 // in nightly)
304 len: if len > 0 { len } else { 1 },
305 _phantom: std::marker::PhantomData,
306 }
307 }
308
309 /// Creates a new buffer size from size in bytes.
310 pub const fn from_size_in_bytes(size: u32) -> Self {
311 Self::new(size / size_of::<T>() as u32)
312 }
313
314 /// Returns the number of elements.
315 #[expect(clippy::len_without_is_empty, reason = "The buffer can never be empty")]
316 pub const fn len(self) -> u32 {
317 self.len
318 }
319
320 /// Returns the size in bytes.
321 pub const fn size_in_bytes(self) -> u32 {
322 size_of::<T>() as u32 * self.len
323 }
324
325 /// Returns the size in bytes aligned up to the given value.
326 pub const fn aligned_in_bytes(self, alignment: u32) -> u32 {
327 align_up(self.size_in_bytes(), alignment)
328 }
329}
330
331impl<T: Sized> PartialEq for BufferSize<T> {
332 fn eq(&self, other: &Self) -> bool {
333 self.len == other.len
334 }
335}
336
337impl<T: Sized> PartialOrd for BufferSize<T> {
338 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
339 self.len.partial_cmp(&other.len)
340 }
341}
342
343/// Computed sizes for all buffers.
344#[derive(Copy, Clone, Debug, Default)]
345pub struct BufferSizes {
346 // Known size buffers
347 pub path_reduced: BufferSize<PathMonoid>,
348 pub path_reduced2: BufferSize<PathMonoid>,
349 pub path_reduced_scan: BufferSize<PathMonoid>,
350 pub path_monoids: BufferSize<PathMonoid>,
351 pub path_bboxes: BufferSize<PathBbox>,
352 pub draw_reduced: BufferSize<DrawMonoid>,
353 pub draw_monoids: BufferSize<DrawMonoid>,
354 pub info: BufferSize<u32>,
355 pub clip_inps: BufferSize<Clip>,
356 pub clip_els: BufferSize<ClipElement>,
357 pub clip_bics: BufferSize<ClipBic>,
358 pub clip_bboxes: BufferSize<ClipBbox>,
359 pub draw_bboxes: BufferSize<DrawBbox>,
360 pub bump_alloc: BufferSize<BumpAllocators>,
361 pub indirect_count: BufferSize<IndirectCount>,
362 pub bin_headers: BufferSize<BinHeader>,
363 pub paths: BufferSize<Path>,
364 // Bump allocated buffers
365 pub lines: BufferSize<LineSoup>,
366 pub bin_data: BufferSize<u32>,
367 pub tiles: BufferSize<Tile>,
368 pub seg_counts: BufferSize<SegmentCount>,
369 pub segments: BufferSize<PathSegment>,
370 pub blend_spill: BufferSize<u32>,
371 pub ptcl: BufferSize<u32>,
372}
373
374impl BufferSizes {
375 /// Sizes for a scene of this `layout`, at a viewport of
376 /// `width_in_tiles` x `height_in_tiles`, given a `budget` of
377 /// bump-allocated scratch.
378 ///
379 /// The known-size buffers are functions of the scene and are
380 /// upstream's own code. The bump-allocated ones are the reservation
381 /// this fork exists to change: see [`BumpBudget`].
382 pub fn new(
383 layout: &Layout,
384 workgroups: &WorkgroupCounts,
385 width_in_tiles: u32,
386 height_in_tiles: u32,
387 budget: &BumpBudget,
388 ) -> Self {
389 let n_paths = layout.n_paths;
390 let n_draw_objects = layout.n_draw_objects;
391 let n_clips = layout.n_clips;
392 let path_tag_wgs = workgroups.path_reduce.0;
393 let reduced_size = if workgroups.use_large_path_scan {
394 align_up(path_tag_wgs, PATH_REDUCE_WG)
395 } else {
396 path_tag_wgs
397 };
398 let path_reduced = BufferSize::new(reduced_size);
399 let path_reduced2 = BufferSize::new(PATH_REDUCE_WG);
400 let path_reduced_scan = BufferSize::new(reduced_size);
401 let path_monoids = BufferSize::new(path_tag_wgs * PATH_REDUCE_WG);
402 let path_bboxes = BufferSize::new(n_paths);
403 let binning_wgs = workgroups.binning.0;
404 let draw_monoid_wgs = workgroups.draw_reduce.0;
405 let draw_reduced = BufferSize::new(draw_monoid_wgs);
406 let draw_monoids = BufferSize::new(n_draw_objects);
407 let info = BufferSize::new(layout.bin_data_start);
408 let clip_inps = BufferSize::new(n_clips);
409 let clip_els = BufferSize::new(n_clips);
410 let clip_bics = BufferSize::new(n_clips / CLIP_REDUCE_WG);
411 let clip_bboxes = BufferSize::new(n_clips);
412 let draw_bboxes = BufferSize::new(n_paths);
413 let bump_alloc = BufferSize::new(1);
414 let indirect_count = BufferSize::new(1);
415 let bin_headers = BufferSize::new(binning_wgs * 256);
416 let n_paths_aligned = align_up(n_paths, 256);
417 let paths = BufferSize::new(n_paths_aligned);
418
419 // The following buffer sizes have been hand picked to accommodate the vello test scenes as
420 // well as paris-30k. These should instead get derived from the scene layout using
421 // reasonable heuristics.
422 //
423 // ---- Tilo: derived from the scene, and then from measurement ----
424 //
425 // Upstream's own comment above says these constants are picked
426 // for a 30,000-path stress scene and ought to be derived. They
427 // come to about 165 MB, per renderer, and a renderer is per
428 // process -- so a file manager showing four rows reserves what a
429 // street map of Paris would, and a session of a dozen such
430 // applications is two gigabytes of an integrated GPU's shared
431 // memory before anything is drawn. On this machine, whose window
432 // onto that memory is 16404 MB, it was four hard freezes in an
433 // evening.
434 //
435 // So they come from the `budget` instead, and the budget is
436 // measured: `BumpAllocators` -- which the GPU already writes and
437 // `Renderer` reads back when adaptive sizing needs a sample -- says
438 // what the frame used, and `BumpBudget::observe` grows to cover it.
439 //
440 // What the budget may not do is go below what the *viewport*
441 // structurally requires, which is the floor applied here:
442 //
443 // * `ptcl` is indexed as `tile_ix * PTCL_INITIAL_ALLOC` before
444 // any bump allocation happens (`coarse.wgsl`), so the first
445 // `n_tiles * 64` words are spoken for whatever the scene is.
446 // Measured usage never counts them, and that is exactly how a
447 // blind fraction of upstream's constant goes wrong: at 3840x2160
448 // the floor alone is 2.07M words inside a `1 << 21` buffer,
449 // leaving 23k words to allocate from and dropping most of the
450 // screen's commands silently.
451 // * `tiles` takes one entry per tile per path covering it, so a
452 // single full-screen rectangle is already `n_tiles` of them.
453 // * `bin_data` shares its buffer with the draw-info region: the
454 // config's `binning_size` is `bin_data - bin_data_start`,
455 // which on a u32 underflows to near four billion if the buffer
456 // is ever sized below the scene's own info block.
457 //
458 // Neither floor nor budget may exceed the largest binding the device
459 // accepts: WebGPU rejects the bind group and the device error ends
460 // the renderer, where a clamped buffer only drops geometry the shaders
461 // already detect and report through `BumpAllocators::failed`.
462 let n_tiles = width_in_tiles.max(1) * height_in_tiles.max(1);
463 let floor = BumpBudget::floor_for_scene(n_tiles, layout.path_tags_size());
464 let bin_data = BufferSize::new(
465 layout
466 .bin_data_start
467 .saturating_add(budget.binning.max(floor.binning))
468 .min(budget.binding_capacity::<u32>())
469 // `binning_size` is `bin_data - bin_data_start` on a u32.
470 .max(layout.bin_data_start.saturating_add(1)),
471 );
472 let tiles = BufferSize::new(
473 budget
474 .tiles
475 .max(floor.tiles)
476 .min(budget.binding_capacity::<Tile>()),
477 );
478 let lines = BufferSize::new(
479 budget
480 .lines
481 .max(floor.lines)
482 .min(budget.binding_capacity::<LineSoup>()),
483 );
484 let seg_counts = BufferSize::new(
485 budget
486 .seg_counts
487 .max(floor.seg_counts)
488 .min(budget.binding_capacity::<SegmentCount>()),
489 );
490 // Every crossing `path_count` counts becomes one segment, and no
491 // stage reports running out of segments: a frame whose counts fit
492 // must find room for all of them.
493 let segments = BufferSize::new(
494 budget
495 .segments
496 .max(floor.segments)
497 .max(seg_counts.len())
498 .min(budget.binding_capacity::<PathSegment>()),
499 );
500 // One blend spill occupies 16 * 16 words.
501 let blend_spill = BufferSize::new(
502 budget
503 .blend_spill
504 .max(floor.blend_spill)
505 .min(budget.binding_capacity::<u32>()),
506 );
507 let ptcl = BufferSize::new(
508 n_tiles
509 .saturating_mul(PTCL_INITIAL_ALLOC)
510 .saturating_add(budget.ptcl.max(floor.ptcl))
511 .min(budget.binding_capacity::<u32>()),
512 );
513 Self {
514 path_reduced,
515 path_reduced2,
516 path_reduced_scan,
517 path_monoids,
518 path_bboxes,
519 draw_reduced,
520 draw_monoids,
521 info,
522 clip_inps,
523 clip_els,
524 clip_bics,
525 clip_bboxes,
526 draw_bboxes,
527 bump_alloc,
528 indirect_count,
529 lines,
530 bin_headers,
531 paths,
532 bin_data,
533 tiles,
534 seg_counts,
535 segments,
536 blend_spill,
537 ptcl,
538 }
539 }
540}
541
542/// A counter at or above this did not count anything. The largest binding
543/// holds 2^25 words, and a counter bumps once per element it tries to
544/// place, so no frame reaches 2^31; values up there are what a counter
545/// read back from an aborted pass wraps to.
546const CORRUPT_COUNT: u32 = 1 << 31;
547
548/// Words of `ptcl` reserved per tile before any allocation happens, from
549/// `PTCL_INITIAL_ALLOC` in `shader/shared/ptcl.wgsl`. Kept in step by
550/// hand, like the other shader constants in this file.
551const PTCL_INITIAL_ALLOC: u32 = 64;
552
553/// Floors for the measured buffers, in elements.
554///
555/// The budget grows to fit, but growth is a frame behind, so the floor
556/// is what the *first* frame gets — and a first frame is the compositor
557/// painting a whole desktop, not a blank window. These come from
558/// measurement rather than taste: the shell's scene catalogue, all 28
559/// scenes, rendered with the counters logged.
560///
561/// | buffer | peak at 1920x1080 | per tile | peak at 3840x2160 | per tile |
562/// |------------|-------------------|----------|-------------------|----------|
563/// | lines | 27943 | - | 29377 | - |
564/// | binning | 1833 | 0.22 | 5592 | 0.17 |
565/// | tiles | 115406 | 14.1 | 439039 | 13.5 |
566/// | `seg_counts` | 54177 | 6.6 | 123122 | 3.8 |
567/// | segments | 54177 | - | 123122 | - |
568/// | blend | 0 | - | 0 | - |
569/// | ptcl (dyn) | 659200 | 80.8 | 1361664 | 42.0 |
570///
571/// So the ones that track screen area are written per tile, while the ones
572/// that track how much *stuff* is on screen also carry measured flat floors.
573/// With the later foreign-surface, complete-app-capture and late-shell-chrome
574/// workloads below included, 1920x1080 reserves about 22 MiB against
575/// upstream's 167 MiB. At 3840x2160 it is about 71 MiB, where viewport-scaled
576/// floors dominate and upstream's flat ptcl constant is itself smaller than
577/// the measured per-tile requirement.
578///
579/// The 28-scene catalogue above has no *foreign* surface in it, and a
580/// composited Wayland client is not a flat fill: `foreign.rs` draws it
581/// as `push_layer(rounded-rect clip) + draw_image + pop_layer`, and a
582/// blend layer around a sampled image costs far more per-tile `ptcl`
583/// than the vector UI the catalogue was measured from. Compositing a
584/// client for the first time -- `client_buffer_pixels_are_composited_
585/// into_the_tab_rect` in `shell/tests/foreign_surface_compositing.rs`,
586/// a 1310x768 tab in a 1600x900 (5700-tile) viewport -- asked for
587/// 1,085,696 `ptcl` words, ~190/tile against every tile in the
588/// viewport, more than the old floor's 96/tile reserved in total. That
589/// is the first frame a client ever presents: there is no prior frame
590/// for growth to have learned from, so the floor is the only thing
591/// standing between that frame and a silently missing window. Chrome
592/// (the sidebar, the top bar) is permanent screen furniture in this
593/// shell, so a maximized single tab cannot exceed roughly the 70% tile
594/// coverage this measurement already has; 320/tile keeps clear of it
595/// with room over both measurement noise and a second simultaneous
596/// composited surface.
597/// Path segments scale with how much is drawn, so this floor scales with the
598/// viewport like the tile-indexed ones. A flat constant cannot cover a large or
599/// high-DPI surface: a subtree cache at scale 2 measured 105,450 lines against
600/// the old flat 65,536, and the overflow drops geometry silently.
601// Semantic whole-app capture is a different first-frame workload from the
602// on-screen catalogue: the shell renders a complete, potentially off-screen
603// app into a second target while still painting the desktop and picker. A
604// 1310x1188 Notes capture measured 137,812 lines in the 1600x900 compositor
605// target (24.2/viewport tile), but that extra work is scene complexity rather
606// than screen-area coverage. Model it as a 160K flat floor; the existing
607// 16/tile term takes over again on genuinely large/high-DPI targets. This
608// avoids multiplying one 1600x900 measurement across every future display.
609const FLOOR_LINES_PER_TILE: u32 = 16;
610const FLOOR_LINES_MIN: u32 = 10 << 14;
611// Flattening can emit more than one line for an encoded path tag. Dashed
612// strokes are the sharpest case in the test corpus: `longpathdash_butt`
613// encodes 503,706 segments and emits 1,054,848 lines on its first frame.
614// Three lines per tag covers that expansion without giving every small
615// scene the old fixed two-million-line reservation.
616const FLOOR_LINES_PER_PATH_TAG: u32 = 3;
617const FLOOR_BINNING: u32 = 1 << 14;
618const FLOOR_BLEND_SPILL: u32 = 1 << 14;
619// The same desktop + complete-app picker measured 102,091 tile allocations.
620// Model that cold-scene complexity as a flat 120K floor, while 16/tile takes
621// over on larger outputs. This keeps useful headroom without multiplying its
622// app complexity by display area.
623const FLOOR_TILES_PER_TILE: u32 = 16;
624const FLOOR_TILES_MIN: u32 = 30 << 12;
625const FLOOR_SEG_COUNTS_PER_TILE: u32 = 8;
626// The same complete-app render measured 144,180 segment counts and segments
627// in its off-screen target. Keep both paired buffers above that real workload;
628// a flat 128K floor made the saved pixels drop before adaptive growth arrived.
629const FLOOR_SEG_COUNTS_MIN: u32 = 10 << 14;
630const FLOOR_PTCL_PER_TILE: u32 = 320;
631// A/B isolation with `VELLO_BUMP_BUDGET=ptcl` found a second real shape the
632// per-tile catalogue misses: dense shell chrome appended after a full desktop
633// scene. At 1600x900 the recording pill could disappear on a later frame even
634// though `bump.ptcl` reported only ~156k dynamic words and `failed == 0`; pinning
635// only ptcl to upstream made every frame stable. A direct A/B threshold run
636// then showed 2M still dropped the settled paused pill while 2.5M kept every
637// pause and saved-receipt frame intact. This flat 2.5M-word floor covers
638// that unreported command-list pressure without carrying upstream's 8M words,
639// and it adds nothing at sufficiently large viewports where the measured
640// 320-words-per-tile floor already wins.
641const FLOOR_PTCL_MIN: u32 = 5 << 19;
642
643/// How much bump-allocated scratch a renderer reserves, in elements.
644///
645/// Every field here is a count the GPU also reports back through
646/// [`BumpAllocators`], which is what makes the reservation measurable
647/// rather than guessed: [`BumpBudget::observe`] takes what a frame asked
648/// for and grows the budget to cover it.
649///
650/// Growth is one-way within a process. A window that once drew a map
651/// keeps room to draw a map, on the grounds that it probably will again,
652/// and that handing the memory back costs a reallocation of every buffer
653/// at the moment the user is busiest. A renderer that opts in
654/// (`Renderer::set_shrink_scratch` in `vello`) hands it back once its
655/// scene has stayed much lighter for a while.
656#[derive(Copy, Clone, Debug, PartialEq, Eq)]
657pub struct BumpBudget {
658 /// Flattened line segments ([`LineSoup`]).
659 pub lines: u32,
660 /// Words of per-bin draw-object lists, not counting the draw-info
661 /// region they share a buffer with.
662 pub binning: u32,
663 /// Per-path tile allocations ([`Tile`]).
664 pub tiles: u32,
665 /// Line/tile crossings counted by `path_count` ([`SegmentCount`]).
666 pub seg_counts: u32,
667 /// Per-tile path segments ([`PathSegment`]).
668 pub segments: u32,
669 /// Words of spilled blend scratch.
670 pub blend_spill: u32,
671 /// Words of per-tile command list beyond the structural
672 /// `n_tiles * PTCL_INITIAL_ALLOC` floor.
673 pub ptcl: u32,
674 /// Bytes of the largest buffer the device can bind. No bump-allocated
675 /// buffer, floors included, is sized past it. WebGPU's default is
676 /// 128 MiB, below [`Self::CEILING`] for lines and segments.
677 pub max_binding_bytes: u32,
678}
679
680impl BumpBudget {
681 /// Upstream vello's constants, kept for reference and as the scale
682 /// the ceiling below is expressed in.
683 pub const UPSTREAM: Self = Self {
684 lines: 1 << 21,
685 binning: 1 << 18,
686 tiles: 1 << 21,
687 seg_counts: 1 << 21,
688 segments: 1 << 21,
689 blend_spill: 1 << 20,
690 ptcl: 1 << 23,
691 max_binding_bytes: u32::MAX,
692 };
693
694 /// What a renderer starts from, before it has seen a frame: zero,
695 /// with [`BufferSizes`] applying the viewport floor underneath. A
696 /// renderer that never draws anything reserves what the floor says
697 /// and no more.
698 pub const INITIAL: Self = Self {
699 lines: 0,
700 binning: 0,
701 tiles: 0,
702 seg_counts: 0,
703 segments: 0,
704 blend_spill: 0,
705 ptcl: 0,
706 max_binding_bytes: u32::MAX,
707 };
708
709 /// The least a viewport of `n_tiles` can be rendered with, per the
710 /// measurements at the constants above.
711 pub fn floor_for_viewport(n_tiles: u32) -> Self {
712 Self::floor_for_scene(n_tiles, 0)
713 }
714
715 /// The viewport floor, extended by the encoded path stream's known
716 /// first-frame complexity.
717 ///
718 /// Most buffers scale with screen area. Flattened lines also scale with
719 /// the amount of path data, especially for dashed strokes, and there is
720 /// no previous frame from which to learn on the first render.
721 pub fn floor_for_scene(n_tiles: u32, n_path_tags: u32) -> Self {
722 Self {
723 lines: n_tiles
724 .saturating_mul(FLOOR_LINES_PER_TILE)
725 .max(FLOOR_LINES_MIN)
726 .max(n_path_tags.saturating_mul(FLOOR_LINES_PER_PATH_TAG)),
727 binning: FLOOR_BINNING,
728 tiles: n_tiles
729 .saturating_mul(FLOOR_TILES_PER_TILE)
730 .max(FLOOR_TILES_MIN),
731 seg_counts: n_tiles
732 .saturating_mul(FLOOR_SEG_COUNTS_PER_TILE)
733 .max(FLOOR_SEG_COUNTS_MIN),
734 segments: n_tiles
735 .saturating_mul(FLOOR_SEG_COUNTS_PER_TILE)
736 .max(FLOOR_SEG_COUNTS_MIN),
737 blend_spill: FLOOR_BLEND_SPILL,
738 ptcl: n_tiles
739 .saturating_mul(FLOOR_PTCL_PER_TILE)
740 .max(FLOOR_PTCL_MIN),
741 max_binding_bytes: u32::MAX,
742 }
743 }
744
745 /// This budget with every buffer limited to `bytes` per binding.
746 #[must_use]
747 pub fn with_max_binding_bytes(self, bytes: u32) -> Self {
748 let mut budget = Self {
749 max_binding_bytes: bytes,
750 ..self
751 };
752 budget.clamp_to_binding();
753 budget
754 }
755
756 /// Elements of `T` that fit in one binding.
757 pub fn binding_capacity<T>(&self) -> u32 {
758 self.max_binding_bytes / size_of::<T>() as u32
759 }
760
761 fn clamp_to_binding(&mut self) {
762 self.lines = self.lines.min(self.binding_capacity::<LineSoup>());
763 self.binning = self.binning.min(self.binding_capacity::<u32>());
764 self.tiles = self.tiles.min(self.binding_capacity::<Tile>());
765 self.seg_counts = self.seg_counts.min(self.binding_capacity::<SegmentCount>());
766 self.segments = self.segments.min(self.binding_capacity::<PathSegment>());
767 self.blend_spill = self.blend_spill.min(self.binding_capacity::<u32>());
768 self.ptcl = self.ptcl.min(self.binding_capacity::<u32>());
769 }
770
771 /// Nothing grows past this -- four times upstream's reservation. No
772 /// user interface reaches it; a scene that did would have rendered
773 /// wrong on upstream too, and this way the renderer can say so
774 /// instead of reserving without limit.
775 pub const CEILING: Self = Self {
776 lines: Self::UPSTREAM.lines << 2,
777 binning: Self::UPSTREAM.binning << 2,
778 tiles: Self::UPSTREAM.tiles << 2,
779 seg_counts: Self::UPSTREAM.seg_counts << 2,
780 segments: Self::UPSTREAM.segments << 2,
781 blend_spill: Self::UPSTREAM.blend_spill << 2,
782 ptcl: Self::UPSTREAM.ptcl << 2,
783 max_binding_bytes: u32::MAX,
784 };
785
786 /// Grow to cover what a frame reported using, with headroom.
787 ///
788 /// Returns `true` if anything changed, which is the caller's cue to
789 /// drop pooled buffers of the sizes that are no longer asked for.
790 ///
791 /// The headroom matters because feedback arrives after the render that
792 /// produced it: reserving exactly the previous usage would repeatedly
793 /// under-provision a growing scene. A failure may prevent later stages
794 /// from reporting their final demand, so convergence is not guaranteed
795 /// in a single subsequent render.
796 ///
797 /// A counter that has wrapped (see [`CORRUPT_COUNT`]) is ignored rather
798 /// than believed: growing from it would pin a binding's worth of memory
799 /// per buffer for the rest of the process on one bad readback.
800 pub fn observe(&mut self, used: &BumpAllocators) -> bool {
801 self.observe_within(used, &Self::CEILING)
802 }
803
804 /// [`BumpBudget::observe`], growing no field past `ceiling`.
805 pub fn observe_within(&mut self, used: &BumpAllocators, ceiling: &Self) -> bool {
806 let before = *self;
807 let grow = |field: &mut u32, used: u32, ceiling: u32| {
808 if used < CORRUPT_COUNT {
809 *field = (*field).max(used.saturating_mul(2).min(ceiling));
810 }
811 };
812 grow(&mut self.lines, used.lines, ceiling.lines);
813 grow(&mut self.binning, used.binning, ceiling.binning);
814 grow(&mut self.tiles, used.tile, ceiling.tiles);
815 grow(&mut self.seg_counts, used.seg_counts, ceiling.seg_counts);
816 // A frame that ran out of segment counts never reached the stage
817 // that allocates segments, so its counts are the segments the next
818 // frame needs.
819 grow(
820 &mut self.segments,
821 used.segments.max(used.seg_counts),
822 ceiling.segments,
823 );
824 grow(&mut self.blend_spill, used.blend, ceiling.blend_spill);
825 grow(&mut self.ptcl, used.ptcl, ceiling.ptcl);
826 self.clamp_to_binding();
827 *self != before
828 }
829
830 /// Shrink every reservation by the same factor until the whole budget
831 /// fits in `max_bytes`. A browser's GPU process has a hard memory limit
832 /// (Safari's is 600 MB); seven buffers each allowed a full binding reach
833 /// most of a gigabyte, and a GPU process killed there mid-frame took the
834 /// macOS window server down with it.
835 #[allow(
836 clippy::cast_possible_truncation,
837 clippy::cast_sign_loss,
838 clippy::cast_precision_loss,
839 reason = "each field is scaled down from a u32 by a factor below one"
840 )]
841 pub fn fit_total_bytes(&mut self, max_bytes: u64) {
842 let size = self.size_in_bytes();
843 if size <= max_bytes {
844 return;
845 }
846 let scale = max_bytes as f64 / size as f64;
847 for field in [
848 &mut self.lines,
849 &mut self.binning,
850 &mut self.tiles,
851 &mut self.seg_counts,
852 &mut self.segments,
853 &mut self.blend_spill,
854 &mut self.ptcl,
855 ] {
856 *field = (f64::from(*field) * scale) as u32;
857 }
858 }
859
860 /// The most a viewport of `n_tiles` may grow to.
861 ///
862 /// [`BumpBudget::CEILING`] is flat, and upstream's constants it is
863 /// scaled from were picked at 1080p. The floors beneath it scale with
864 /// the viewport, so on a large enough target a flat ceiling sits below
865 /// what the viewport structurally needs: blend spill, in particular, is
866 /// `TILE_WIDTH * TILE_HEIGHT` words per tile per nesting level past the
867 /// on-chip stack, and a 5120x2880 desktop with one spilled level
868 /// everywhere asks for 14.7M words against a flat ceiling of 4.2M. A
869 /// frame like that overflows, observes, is refused growth, and
870 /// overflows again, forever -- a black screen that looks like progress.
871 /// The device's binding limit still applies on top.
872 pub fn ceiling_for_viewport(n_tiles: u32) -> Self {
873 let floor = Self::floor_for_viewport(n_tiles);
874 let scaled =
875 |ceiling: u32, floor: u32| ceiling.max(floor.saturating_mul(CEILING_OVER_FLOOR));
876 Self {
877 lines: scaled(Self::CEILING.lines, floor.lines),
878 binning: scaled(Self::CEILING.binning, floor.binning),
879 tiles: scaled(Self::CEILING.tiles, floor.tiles),
880 seg_counts: scaled(Self::CEILING.seg_counts, floor.seg_counts),
881 segments: scaled(Self::CEILING.segments, floor.segments),
882 blend_spill: Self::CEILING.blend_spill.max(
883 n_tiles.saturating_mul(BLEND_SPILL_WORDS_PER_LEVEL * CEILING_BLEND_SPILL_LEVELS),
884 ),
885 ptcl: scaled(Self::CEILING.ptcl, floor.ptcl),
886 max_binding_bytes: u32::MAX,
887 }
888 }
889
890 /// Bytes this budget reserves, not counting the viewport floors.
891 pub fn size_in_bytes(&self) -> u64 {
892 u64::from(self.lines) * size_of::<LineSoup>() as u64
893 + u64::from(self.binning) * 4
894 + u64::from(self.tiles) * size_of::<Tile>() as u64
895 + u64::from(self.seg_counts) * size_of::<SegmentCount>() as u64
896 + u64::from(self.segments) * size_of::<PathSegment>() as u64
897 + u64::from(self.blend_spill) * 4
898 + u64::from(self.ptcl) * 4
899 }
900}
901
902impl Default for BumpBudget {
903 fn default() -> Self {
904 Self::INITIAL
905 }
906}
907
908/// How far [`BumpBudget::ceiling_for_viewport`] lets a viewport-scaled
909/// field grow past its first-frame floor.
910const CEILING_OVER_FLOOR: u32 = 4;
911/// Words of blend scratch one tile spills per nesting level past the
912/// on-chip stack: `TILE_WIDTH * TILE_HEIGHT` in `coarse.wgsl`.
913const BLEND_SPILL_WORDS_PER_LEVEL: u32 = TILE_WIDTH * TILE_HEIGHT;
914/// Spilled nesting levels the blend ceiling covers on every tile at once.
915const CEILING_BLEND_SPILL_LEVELS: u32 = 4;
916
917const fn align_up(len: u32, alignment: u32) -> u32 {
918 len + (len.wrapping_neg() & (alignment - 1))
919}
920
921#[cfg(test)]
922mod tests {
923 use super::{
924 BLEND_SPILL_WORDS_PER_LEVEL, BufferSizes, BumpAllocators, BumpBudget, CORRUPT_COUNT,
925 PTCL_INITIAL_ALLOC, RenderConfig,
926 };
927 use crate::{Layout, LineSoup, WorkgroupCounts};
928
929 /// `failed=0x10` from a 5120x2880 desktop whose windows nest one layer
930 /// past the on-chip blend stack on every tile. Against the flat
931 /// ceiling the budget grew to 4.2M words, the frame asked for 14.7M,
932 /// and every retry overflowed the same way: the session never
933 /// presented a frame.
934 #[test]
935 fn blend_spill_can_grow_to_cover_a_spilled_5k_desktop() {
936 let n_tiles = 5120_u32.div_ceil(16) * 2880_u32.div_ceil(16);
937 let used = BumpAllocators {
938 failed: 0x10,
939 blend: n_tiles * BLEND_SPILL_WORDS_PER_LEVEL,
940 ..BumpAllocators::default()
941 };
942 let mut budget = BumpBudget::INITIAL;
943 budget.observe_within(&used, &BumpBudget::ceiling_for_viewport(n_tiles));
944 assert!(
945 budget.blend_spill >= used.blend,
946 "grew to {} blend words, the frame needs {}: it would overflow on every retry",
947 budget.blend_spill,
948 used.blend,
949 );
950 assert_eq!(
951 BumpBudget::ceiling_for_viewport(1),
952 BumpBudget::CEILING,
953 "a one-tile viewport keeps the flat ceiling"
954 );
955 }
956
957 /// Marching ants (thousands of dashes) first ran out of segment counts
958 /// (`failed=0x8`), which stops the frame before any segment is
959 /// allocated. The counts grew; segments, having reported none, stayed at
960 /// the floor, and the next frame wrote 3.6M segments into room for 164K.
961 /// No stage reports running out of segments, so that frame showed with
962 /// geometry missing and said it fit.
963 #[test]
964 fn segments_cover_every_count_a_frame_may_make() {
965 let (width, height) = (480_u32, 320_u32);
966 let n_tiles = width.div_ceil(16) * height.div_ceil(16);
967 let used = BumpAllocators {
968 failed: 0x8,
969 lines: 3_310_659,
970 binning: 642,
971 tile: 82_223,
972 seg_counts: 3_602_928,
973 ..BumpAllocators::default()
974 };
975 let mut budget = BumpBudget::INITIAL;
976 budget.observe_within(&used, &BumpBudget::ceiling_for_viewport(n_tiles));
977 assert!(budget.segments >= used.seg_counts);
978 // Whatever the budget says, the buffers keep the pair in step.
979 let lopsided = BumpBudget {
980 seg_counts: 7_205_856,
981 ..BumpBudget::INITIAL
982 };
983 let s = sizes(width, height, &lopsided);
984 assert!(
985 s.segments.len() >= s.seg_counts.len(),
986 "{} segments for {} counts",
987 s.segments.len(),
988 s.seg_counts.len(),
989 );
990 }
991
992 /// A layout with nothing in it. The bump-allocated sizes do not
993 /// depend on the scene, only on the viewport and the budget, so this
994 /// is enough to exercise them.
995 fn sizes(width: u32, height: u32, budget: &BumpBudget) -> BufferSizes {
996 let layout = Layout {
997 bin_data_start: 4096,
998 ..Layout::default()
999 };
1000 let (w_tiles, h_tiles) = (width.div_ceil(16), height.div_ceil(16));
1001 let wgs = WorkgroupCounts::new(&layout, w_tiles, h_tiles, 0);
1002 BufferSizes::new(&layout, &wgs, w_tiles, h_tiles, budget)
1003 }
1004
1005 /// `coarse.wgsl` indexes ptcl as `tile_ix * PTCL_INITIAL_ALLOC`
1006 /// before it allocates anything, so that much of the buffer is
1007 /// spoken for whatever the scene is. Sizing the buffer as a fraction
1008 /// of a constant -- rather than from the viewport -- leaves a 4K
1009 /// screen with a few thousand words to draw a desktop from, and the
1010 /// overflow is silent.
1011 #[test]
1012 fn ptcl_has_room_to_allocate_from_at_every_resolution() {
1013 for (w, h) in [(800, 600), (1920, 1080), (2560, 1440), (3840, 2160)] {
1014 let s = sizes(w, h, &BumpBudget::INITIAL);
1015 let structural = w.div_ceil(16) * h.div_ceil(16) * PTCL_INITIAL_ALLOC;
1016 let dynamic = s.ptcl.len() - structural;
1017 assert!(
1018 dynamic >= structural / 2,
1019 "{w}x{h}: {dynamic} words to allocate from, under a floor of {structural}",
1020 );
1021 }
1022 }
1023
1024 /// A composited Wayland client is not a flat fill: the compositor
1025 /// draws it as `push_layer(rounded-rect clip) + draw_image +
1026 /// pop_layer`, which costs far more `ptcl` per tile than the vector
1027 /// UI the floor's per-tile constant was calibrated from. This is
1028 /// the exact ask a real first frame of `shell`'s
1029 /// `foreign_buffers_are_composited_once_into_visible_tabs_only` made
1030 /// (`VELLO_BUMP_LOG=1`, a 1310x768 tab in a 1600x900 viewport): a
1031 /// regression test, not a synthetic bound, because a synthetic one
1032 /// would have missed this exact shape of scene the way the
1033 /// catalogue did the first time.
1034 ///
1035 /// The first frame a client ever presents has no earlier frame for
1036 /// `BumpBudget::observe` to have grown from, so the static floor is
1037 /// the only thing standing between that frame and a client's
1038 /// window rendering with its content silently missing. Below the
1039 /// floor this raised, that is exactly what happened: `failed=0x10`
1040 /// (the `ptcl` bit), and the composited pixels never reached the
1041 /// screen.
1042 #[test]
1043 fn ptcl_floor_covers_a_clipped_foreign_surface_composite_first_frame() {
1044 let width_in_tiles = 1600_u32.div_ceil(16);
1045 let height_in_tiles = 900_u32.div_ceil(16);
1046 let n_tiles = width_in_tiles * height_in_tiles;
1047 // BumpAllocators.ptcl measured on that frame; already excludes
1048 // the structural `n_tiles * PTCL_INITIAL_ALLOC` term (see
1049 // `ptcl_reserves_the_structural_floor_on_top_of_the_heuristic_one`),
1050 // so it compares directly against the heuristic floor alone.
1051 let measured_ptcl_words = 1_085_696;
1052 let floor = BumpBudget::floor_for_viewport(n_tiles);
1053 assert!(
1054 floor.ptcl >= measured_ptcl_words,
1055 "floor of {} ptcl words does not cover the {measured_ptcl_words} a real clipped \
1056 client composite asked for at {n_tiles} tiles -- the first frame a client \
1057 presents would overflow ptcl and render with its pixels silently missing",
1058 floor.ptcl,
1059 );
1060 }
1061
1062 /// Dense shell chrome is appended after the desktop scene so it is the
1063 /// first geometry lost when command-list pressure is under-reported. The
1064 /// active-recorder sequence (start, pause, settled pause, saved receipt)
1065 /// A/B'd at 1600x900: 2M words still dropped the pill, while 2.5M kept all
1066 /// frames intact. Unlike the foreign-surface case, the GPU counter stayed
1067 /// far below both values and did not set `failed`, so this must remain an
1068 /// explicit measured floor until the shader exposes that pressure.
1069 #[test]
1070 fn ptcl_floor_keeps_dense_late_shell_chrome_stable() {
1071 let n_tiles = 1600u32.div_ceil(16) * 900u32.div_ceil(16);
1072 let floor = BumpBudget::floor_for_viewport(n_tiles);
1073 assert!(
1074 floor.ptcl >= 2_621_440,
1075 "floor of {} ptcl words is below the measured 2.5M stability threshold for late shell chrome",
1076 floor.ptcl,
1077 );
1078 }
1079
1080 /// A cached subtree redrawn at scale 2 measured 105,450 lines against
1081 /// a flat floor of 65,536, overflowed (`failed=0x4`) and lost geometry.
1082 ///
1083 /// The lesson is the shape of the floor rather than its size: every other
1084 /// floor here scales with `n_tiles` and this one did not. Segment count
1085 /// follows how much is drawn, so a flat constant covers a small window and
1086 /// silently under-provisions a large or high-DPI one -- the case least
1087 /// likely to be measured and most likely to be somebody's actual desktop.
1088 #[test]
1089 fn lines_floor_scales_with_the_viewport_it_has_to_cover() {
1090 let n_tiles = 3840u32.div_ceil(16) * 2160u32.div_ceil(16);
1091 let measured_lines = 105_450;
1092 let floor = BumpBudget::floor_for_viewport(n_tiles);
1093 assert!(
1094 floor.lines >= measured_lines,
1095 "floor of {} lines does not cover the {measured_lines} a subtree cache at \
1096 scale 2 asked for at {n_tiles} tiles",
1097 floor.lines,
1098 );
1099 // Once a viewport outgrows the scene-complexity minimum, area must take
1100 // over: a 4K desktop reserves more than a small window rather than
1101 // leaving the per-tile term flat in disguise.
1102 let small = BumpBudget::floor_for_viewport(320u32.div_ceil(16) * 240u32.div_ceil(16));
1103 assert!(
1104 floor.lines > small.lines,
1105 "a 4K desktop reserves {} lines and a 320x240 window {} -- the floor is not \
1106 scaling with the viewport",
1107 floor.lines,
1108 small.lines,
1109 );
1110 }
1111
1112 /// Selecting a complete semantic app creates two cold renderer workloads:
1113 /// the desktop plus picker at 1600x900, and the app's complete 1310x1188
1114 /// off-screen target. Logged first frames measured 137,812 / 126,771 lines;
1115 /// the latter then needed 144,180 segment counts and segments. These are
1116 /// exactly the frames users inspect before trusting a beyond-screen save,
1117 /// so adaptive repair on frame two is too late.
1118 #[test]
1119 fn floors_cover_first_frame_of_complete_offscreen_app_capture() {
1120 let desktop = BumpBudget::floor_for_viewport(1600u32.div_ceil(16) * 900u32.div_ceil(16));
1121 assert!(desktop.lines >= 137_812);
1122 assert!(desktop.tiles >= 102_091);
1123
1124 let complete_app =
1125 BumpBudget::floor_for_viewport(1310u32.div_ceil(16) * 1188u32.div_ceil(16));
1126 assert!(complete_app.lines >= 126_771);
1127 assert!(complete_app.seg_counts >= 144_180);
1128 assert!(complete_app.segments >= 144_180);
1129 }
1130
1131 /// A heavily dashed path expands to more flattened lines than its tiny
1132 /// viewport predicts. This is the first-frame ask from the upstream
1133 /// `longpathdash_butt` snapshot that exposed the missing scene term.
1134 #[test]
1135 fn lines_floor_covers_dashed_path_expansion_on_the_first_frame() {
1136 let n_tiles = 440_u32.div_ceil(16) * 80_u32.div_ceil(16);
1137 let encoded_path_tags = 503_706;
1138 let measured_lines = 1_054_848;
1139 let floor = BumpBudget::floor_for_scene(n_tiles, encoded_path_tags);
1140 assert!(
1141 floor.lines >= measured_lines,
1142 "floor of {} lines does not cover the {measured_lines} emitted by a dashed path",
1143 floor.lines,
1144 );
1145 assert!(
1146 floor.lines < BumpBudget::UPSTREAM.lines,
1147 "scene-derived floor {} fell back to upstream's fixed reservation",
1148 floor.lines,
1149 );
1150 }
1151
1152 /// The structural `n_tiles * PTCL_INITIAL_ALLOC` term is reserved on
1153 /// top of the budget/floor, not folded into it.
1154 ///
1155 /// `floor_for_viewport`'s own per-tile headroom happens to be 1.5x
1156 /// `PTCL_INITIAL_ALLOC`, so at the `INITIAL` budget the test above
1157 /// still passes -- at exactly zero margin -- even with the
1158 /// structural term removed entirely. This isolates the claim: the
1159 /// reservation must clear the heuristic floor *plus* the structural
1160 /// one, which only holding both terms produces.
1161 #[test]
1162 fn ptcl_reserves_the_structural_floor_on_top_of_the_heuristic_one() {
1163 for (w, h) in [(800, 600), (1920, 1080), (3840, 2160)] {
1164 let s = sizes(w, h, &BumpBudget::INITIAL);
1165 let n_tiles = w.div_ceil(16) * h.div_ceil(16);
1166 let structural = n_tiles * PTCL_INITIAL_ALLOC;
1167 let heuristic_floor = BumpBudget::floor_for_viewport(n_tiles).ptcl;
1168 assert!(
1169 s.ptcl.len() >= structural + heuristic_floor,
1170 "{w}x{h}: reserved {}, expected the structural floor {structural} \
1171 plus the heuristic one {heuristic_floor} = {}",
1172 s.ptcl.len(),
1173 structural + heuristic_floor,
1174 );
1175 }
1176 }
1177
1178 /// The config hands the shaders `bin_data - bin_data_start` as the
1179 /// binning size. On a u32 that underflows to near four billion if
1180 /// the buffer is ever smaller than the scene's own draw-info block,
1181 /// and the shaders then believe they have unlimited room.
1182 #[test]
1183 fn bin_data_always_clears_the_info_block() {
1184 let layout = Layout {
1185 bin_data_start: 1 << 20,
1186 ..Layout::default()
1187 };
1188 let wgs = WorkgroupCounts::new(&layout, 120, 68, 0);
1189 let s = BufferSizes::new(&layout, &wgs, 120, 68, &BumpBudget::INITIAL);
1190 assert!(
1191 s.bin_data.len() > layout.bin_data_start,
1192 "bin_data {} does not clear bin_data_start {}",
1193 s.bin_data.len(),
1194 layout.bin_data_start,
1195 );
1196 let cfg = RenderConfig::new(
1197 &layout,
1198 1920,
1199 1080,
1200 &peniko::Color::BLACK,
1201 &BumpBudget::INITIAL,
1202 );
1203 assert!(
1204 cfg.gpu.binning_size < s.bin_data.len(),
1205 "binning_size {} underflowed",
1206 cfg.gpu.binning_size,
1207 );
1208 }
1209
1210 /// Growth covers what a frame asked for, including the part that did
1211 /// not fit -- the shaders bump the counter first and check after, so
1212 /// the reported count is the need, not the fit.
1213 #[test]
1214 fn growth_covers_an_overflowed_frame() {
1215 let mut budget = BumpBudget::INITIAL;
1216 let overflowed = BumpAllocators {
1217 failed: 0x2,
1218 binning: 4_000,
1219 ptcl: 700_000,
1220 tile: 500_000,
1221 seg_counts: 90_000,
1222 segments: 90_000,
1223 blend: 0,
1224 lines: 40_000,
1225 };
1226 assert!(budget.observe(&overflowed), "should have grown");
1227 assert!(budget.tiles >= overflowed.tile);
1228 assert!(budget.ptcl >= overflowed.ptcl);
1229 assert!(budget.lines >= overflowed.lines);
1230 // And it settles: a second frame like the first asks for nothing
1231 // more, so the buffers stop being reallocated.
1232 assert!(
1233 !budget.observe(&overflowed),
1234 "a repeat of the same frame should not grow again"
1235 );
1236 }
1237
1238 /// Growth is one-way and bounded.
1239 #[test]
1240 fn growth_stops_at_the_ceiling() {
1241 let mut budget = BumpBudget::INITIAL;
1242 // The largest count still believed; above it is a wrapped readback.
1243 let most = CORRUPT_COUNT - 1;
1244 let huge = BumpAllocators {
1245 failed: 0x1f,
1246 binning: most,
1247 ptcl: most,
1248 tile: most,
1249 seg_counts: most,
1250 segments: most,
1251 blend: most,
1252 lines: most,
1253 };
1254 budget.observe(&huge);
1255 assert_eq!(budget.tiles, BumpBudget::CEILING.tiles);
1256 assert_eq!(budget.ptcl, BumpBudget::CEILING.ptcl);
1257 let quiet = BumpAllocators::default();
1258 assert!(
1259 !budget.observe(&quiet),
1260 "a quiet frame must not shrink the reservation mid-session"
1261 );
1262 }
1263
1264 /// WebGPU's default `maxStorageBufferBindingSize`. The ceiling's lines and
1265 /// segments (8M x 24 bytes = 192 MiB) exceed it, and a bind group past it
1266 /// fails the device.
1267 const WEBGPU_DEFAULT_BINDING: u32 = 128 << 20;
1268
1269 fn assert_bump_buffers_bindable(s: &BufferSizes, limit: u32) {
1270 for (name, bytes) in [
1271 ("lines", s.lines.size_in_bytes()),
1272 ("bin_data", s.bin_data.size_in_bytes()),
1273 ("tiles", s.tiles.size_in_bytes()),
1274 ("seg_counts", s.seg_counts.size_in_bytes()),
1275 ("segments", s.segments.size_in_bytes()),
1276 ("blend_spill", s.blend_spill.size_in_bytes()),
1277 ("ptcl", s.ptcl.size_in_bytes()),
1278 ] {
1279 assert!(bytes <= limit, "{name} is {bytes} bytes, past {limit}");
1280 }
1281 }
1282
1283 /// Opening Search at 5K overflowed blend spill; the readback from the
1284 /// aborted pass reported 2.4e9 segments and 4.3e9 blend words against
1285 /// a real 1e5. Believing it pinned a binding per buffer for the session.
1286 #[test]
1287 fn a_wrapped_counter_does_not_grow_the_budget() {
1288 let mut budget = BumpBudget::INITIAL.with_max_binding_bytes(WEBGPU_DEFAULT_BINDING);
1289 let wrapped = BumpAllocators {
1290 failed: 0x10,
1291 segments: 2_373_742_623,
1292 blend: 4_293_529_600,
1293 lines: 38_037,
1294 ..BumpAllocators::default()
1295 };
1296 assert!(wrapped.segments >= CORRUPT_COUNT && wrapped.blend >= CORRUPT_COUNT);
1297 assert!(
1298 budget.observe(&wrapped),
1299 "the plausible lines count still grows"
1300 );
1301 assert_eq!(budget.lines, 2 * 38_037);
1302 assert_eq!(budget.segments, BumpBudget::INITIAL.segments);
1303 assert_eq!(budget.blend_spill, BumpBudget::INITIAL.blend_spill);
1304 }
1305
1306 #[test]
1307 fn growth_never_passes_a_total_memory_limit() {
1308 let mut budget = BumpBudget::INITIAL.with_max_binding_bytes(WEBGPU_DEFAULT_BINDING);
1309 let huge = BumpAllocators {
1310 lines: u32::MAX / 2,
1311 binning: u32::MAX / 2,
1312 tile: u32::MAX / 2,
1313 seg_counts: u32::MAX / 2,
1314 segments: u32::MAX / 2,
1315 blend: u32::MAX / 2,
1316 ptcl: u32::MAX / 2,
1317 ..Default::default()
1318 };
1319 budget.observe(&huge);
1320 assert!(
1321 budget.size_in_bytes() > 512 << 20,
1322 "{}",
1323 budget.size_in_bytes()
1324 );
1325 budget.fit_total_bytes(128 << 20);
1326 assert!(
1327 budget.size_in_bytes() <= 128 << 20,
1328 "{}",
1329 budget.size_in_bytes()
1330 );
1331 assert!(budget.ptcl > 0 && budget.lines > 0);
1332 let fitted = budget;
1333 budget.fit_total_bytes(128 << 20);
1334 assert_eq!(budget, fitted, "a budget within the limit is left alone");
1335 }
1336
1337 #[test]
1338 fn growth_never_passes_the_device_binding_limit() {
1339 let mut budget = BumpBudget::INITIAL.with_max_binding_bytes(WEBGPU_DEFAULT_BINDING);
1340 // A crowded desktop: four million lines doubles to the ceiling.
1341 let crowded = BumpAllocators {
1342 failed: 0x1f,
1343 lines: 4 << 20,
1344 segments: 4 << 20,
1345 ..BumpAllocators::default()
1346 };
1347 assert!(budget.observe(&crowded));
1348 assert_eq!(
1349 budget.lines,
1350 WEBGPU_DEFAULT_BINDING / size_of::<LineSoup>() as u32
1351 );
1352 assert!(!budget.observe(&crowded), "a saturated budget is stable");
1353 for (w, h) in [(1920, 1080), (3840, 2160), (7680, 4320)] {
1354 assert_bump_buffers_bindable(&sizes(w, h, &budget), WEBGPU_DEFAULT_BINDING);
1355 }
1356 let mut unlimited = BumpBudget::INITIAL;
1357 unlimited.observe(&crowded);
1358 assert_eq!(unlimited.lines, BumpBudget::CEILING.lines);
1359 }
1360
1361 #[test]
1362 fn scene_floors_never_pass_the_device_binding_limit() {
1363 let layout = Layout {
1364 bin_data_start: 4096,
1365 ..Layout::default()
1366 };
1367 let budget = BumpBudget::CEILING.with_max_binding_bytes(WEBGPU_DEFAULT_BINDING);
1368 let (w_tiles, h_tiles) = (7680_u32.div_ceil(16), 4320_u32.div_ceil(16));
1369 let wgs = WorkgroupCounts::new(&layout, w_tiles, h_tiles, 0);
1370 let mut s = BufferSizes::new(&layout, &wgs, w_tiles, h_tiles, &budget);
1371 assert_bump_buffers_bindable(&s, WEBGPU_DEFAULT_BINDING);
1372 // A dense scene's lines floor (three per path tag) is unbounded.
1373 let dense = Layout {
1374 path_tag_base: 0,
1375 path_data_base: 64 << 20,
1376 ..layout
1377 };
1378 s = BufferSizes::new(&dense, &wgs, w_tiles, h_tiles, &budget);
1379 assert!(dense.path_tags_size() >= 16 << 20);
1380 assert_bump_buffers_bindable(&s, WEBGPU_DEFAULT_BINDING);
1381 }
1382
1383 /// The whole point: a desktop-sized viewport reserves a fraction of what
1384 /// upstream's constants do. The complete off-screen-app and late-shell-
1385 /// chrome floors are real first-frame correctness requirements, so the
1386 /// bound is sevenfold rather than rewarding a broken frame to preserve the
1387 /// earlier eightfold figure.
1388 #[test]
1389 fn a_desktop_viewport_reserves_far_less_than_upstream() {
1390 let ours = sizes(1920, 1080, &BumpBudget::INITIAL);
1391 let theirs = sizes(1920, 1080, &BumpBudget::UPSTREAM);
1392 let bytes = |s: &BufferSizes| -> u64 {
1393 u64::from(s.lines.size_in_bytes())
1394 + u64::from(s.bin_data.size_in_bytes())
1395 + u64::from(s.tiles.size_in_bytes())
1396 + u64::from(s.seg_counts.size_in_bytes())
1397 + u64::from(s.segments.size_in_bytes())
1398 + u64::from(s.blend_spill.size_in_bytes())
1399 + u64::from(s.ptcl.size_in_bytes())
1400 };
1401 let (ours, theirs) = (bytes(&ours), bytes(&theirs));
1402 assert!(
1403 ours * 7 < theirs,
1404 "reserved {ours} bytes against upstream's {theirs}; expected at least a sevenfold reduction",
1405 );
1406 }
1407}