1use crate::composite::PixelRect;
17use crate::effect_cost::{ARITHMETIC_UNITS, EffectCost, FETCH_UNITS, TRANSCENDENTAL_UNITS};
18
19pub(crate) const PLANNING_THRESHOLD_UNIT_PIXELS: f64 = 64.0 * 1_048_576.0;
22
23pub(crate) const MAX_BANDS: u32 = 64;
25
26pub(crate) const MAX_TILE_COLUMNS: u32 = 16;
27
28pub(crate) const MAX_FRAME_SUBMISSIONS: u32 = 128;
29
30const SPREAD_SUBMISSIONS: u32 = MAX_FRAME_SUBMISSIONS / 4 * 3;
31
32const _: () = assert!(
33 MAX_FRAME_SUBMISSIONS as usize <= crate::submission_clock::RECENT_SUBMISSIONS_KEPT,
34 "the submission clock keeps every submission of the latest frame"
35);
36
37#[derive(Copy, Clone, Debug, Default, PartialEq)]
39pub struct FrameCost {
40 pub fetches: f64,
42 pub transcendentals: f64,
44 pub arithmetic: f64,
46}
47
48impl FrameCost {
49 #[must_use]
51 #[allow(clippy::cast_precision_loss)]
52 pub fn unit_pixels(&self) -> f64 {
53 self.fetches * FETCH_UNITS as f64
54 + self.transcendentals * TRANSCENDENTAL_UNITS as f64
55 + self.arithmetic * ARITHMETIC_UNITS as f64
56 }
57
58 #[allow(clippy::cast_precision_loss)]
59 pub(crate) fn add(&mut self, cost: EffectCost, pixels: u64) {
60 let pixels = pixels as f64;
61 self.fetches += cost.fetches as f64 * pixels;
62 self.transcendentals += cost.transcendentals as f64 * pixels;
63 self.arithmetic += cost.arithmetic as f64 * pixels;
64 }
65
66 pub(crate) fn of(cost: EffectCost, pixels: u64) -> Self {
67 let mut charge = Self::default();
68 charge.add(cost, pixels);
69 charge
70 }
71
72 pub(crate) fn add_cost(&mut self, other: Self) {
73 self.fetches += other.fetches;
74 self.transcendentals += other.transcendentals;
75 self.arithmetic += other.arithmetic;
76 }
77}
78
79#[derive(Copy, Clone, Debug, Default, PartialEq)]
81pub struct FrameSubmissions {
82 pub submissions: u32,
84 pub predicted_ms: Option<f64>,
86 pub cost: FrameCost,
88}
89
90#[derive(Copy, Clone, Debug, PartialEq, Eq)]
91pub(crate) struct PassPlacement {
92 pub(crate) cut_before: bool,
94 pub(crate) pieces: Pieces,
96 pub(crate) pilot: Option<u32>,
97}
98
99#[derive(Copy, Clone, Debug, PartialEq, Eq)]
102pub(crate) struct Pieces {
103 pub(crate) rows: u32,
104 pub(crate) columns: u32,
105}
106
107impl Pieces {
108 pub(crate) const ONE: Self = Self {
109 rows: 1,
110 columns: 1,
111 };
112
113 fn within(budgets: f64, region: PixelRect) -> Self {
114 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
115 let needed = budgets.ceil().clamp(1.0, f64::from(u32::MAX)) as u32;
116 let rows = needed.min(MAX_BANDS).min(region.height.div_ceil(2)).max(1);
117 let columns = needed
118 .div_ceil(rows)
119 .min(MAX_TILE_COLUMNS)
120 .min(region.width.div_ceil(2))
121 .max(1);
122 Self {
123 rows: rows.min(needed.div_ceil(columns)),
124 columns,
125 }
126 }
127
128 fn at_most(self, most: u32) -> Self {
129 let most = most.max(1);
130 if self.count() <= most {
131 return self;
132 }
133 let rows = self.rows.min(most);
134 Self {
135 rows,
136 columns: (most / rows).clamp(1, self.columns),
137 }
138 }
139
140 pub(crate) const fn count(self) -> u32 {
141 self.rows.saturating_mul(self.columns)
142 }
143
144 pub(crate) fn rect(self, index: u32, region: PixelRect) -> PixelRect {
145 let (y, height) = even_split(region.y, region.height, index / self.columns, self.rows);
146 let (x, width) = even_split(region.x, region.width, index % self.columns, self.columns);
147 PixelRect {
148 x,
149 y,
150 width,
151 height,
152 }
153 }
154}
155
156#[derive(Copy, Clone, Debug)]
157pub(crate) struct Piece {
158 pub(crate) scissor: Option<PixelRect>,
159 pub(crate) first: bool,
160}
161
162impl Piece {
163 pub(crate) const fn first(scissor: Option<PixelRect>) -> Self {
164 Self {
165 scissor,
166 first: true,
167 }
168 }
169}
170
171fn even_split(start: u32, length: u32, part: u32, parts: u32) -> (u32, u32) {
172 let end = start.saturating_add(length);
173 let edge = |index: u32| -> u32 {
174 if index == 0 {
175 return start;
176 }
177 if index >= parts {
178 return end;
179 }
180 let offset = u64::from(length) * u64::from(index) / u64::from(parts);
181 let edge = start.saturating_add(u32::try_from(offset).unwrap_or(length)) & !1;
182 edge.clamp(start, end)
183 };
184 let first = edge(part);
185 (first, edge(part + 1).saturating_sub(first))
186}
187
188#[derive(Debug)]
189pub(crate) struct SubmissionPlan {
190 rate: std::sync::Arc<alpha2_gpu::GpuRate>,
191 ms_per_unit_pixel: f64,
192 budget_ms: f64,
193 predicted_ms: f64,
194 pass_rates: Vec<(alpha2_gpu::PassKey, f64)>,
195}
196
197impl SubmissionPlan {
198 pub(crate) fn new(
199 rate: std::sync::Arc<alpha2_gpu::GpuRate>,
200 ms_per_unit_pixel: f64,
201 budget_ms: f64,
202 predicted_ms: f64,
203 ) -> Self {
204 Self {
205 rate,
206 ms_per_unit_pixel,
207 budget_ms: budget_ms.max(f64::MIN_POSITIVE),
208 predicted_ms,
209 pass_rates: Vec::new(),
210 }
211 }
212
213 pub(crate) fn predict(
214 &mut self,
215 passes: impl IntoIterator<Item = (FrameCost, Option<alpha2_gpu::PassKey>)>,
216 ) {
217 self.predicted_ms = 0.0;
218 for (work, pass) in passes {
219 let rate = self.planning_rate(pass);
220 if let Some(pass) = pass
221 && !self.pass_rates.iter().any(|(kept, _)| *kept == pass)
222 {
223 self.pass_rates.push((pass, rate));
224 }
225 self.predicted_ms += work.unit_pixels() * rate;
226 }
227 }
228
229 fn planning_rate(&self, pass: Option<alpha2_gpu::PassKey>) -> f64 {
230 pass.and_then(|pass| {
231 self.pass_rates
232 .iter()
233 .find_map(|(kept, rate)| (*kept == pass).then_some(*rate))
234 })
235 .unwrap_or_else(|| self.rate.planning_rate(self.ms_per_unit_pixel, pass))
236 }
237}
238
239#[derive(Debug, Default)]
240pub(crate) struct SubmissionPlanner {
241 plan: Option<SubmissionPlan>,
242 current_ms: f64,
244 finished_ms: Vec<f64>,
246 current_effects: Vec<String>,
247 finished_effects: Vec<Vec<String>>,
248 placed_effect: Option<String>,
249 band_ms: f64,
251 cost: FrameCost,
252 placed_ms: f64,
253 device_rated_ms: f64,
254 frame: bool,
256 pilot_rows: Option<u32>,
257}
258
259impl SubmissionPlanner {
260 pub(crate) fn plan(&mut self, plan: SubmissionPlan) {
261 self.plan = Some(plan);
262 }
263
264 pub(crate) const fn mark_frame(&mut self) {
265 self.frame = true;
266 }
267
268 pub(crate) const fn mark_pilot(&mut self, rows: u32) {
269 self.pilot_rows = Some(rows);
270 }
271
272 pub(crate) fn pass(
275 &mut self,
276 work: FrameCost,
277 region: PixelRect,
278 bandable: bool,
279 pass: Option<alpha2_gpu::PassKey>,
280 ) -> PassPlacement {
281 self.cost.add_cost(work);
282 if let (Some(rows), true) = (self.pilot_rows, bandable) {
283 return PassPlacement {
284 cut_before: false,
285 pieces: Pieces::ONE,
286 pilot: Some(rows),
287 };
288 }
289 let Some(plan) = &self.plan else {
290 return PassPlacement {
291 cut_before: false,
292 pieces: Pieces::ONE,
293 pilot: None,
294 };
295 };
296 let rate = plan.planning_rate(pass);
297 let ms = work.unit_pixels() * rate;
298 if rate <= plan.ms_per_unit_pixel {
299 self.device_rated_ms += ms;
300 }
301 let unplaced = plan.predicted_ms - self.placed_ms;
302 let spread = if ms <= unplaced {
303 unplaced / f64::from(self.spread_buffers_left())
304 } else {
305 ms / f64::from(self.quarter_buffers_left())
306 };
307 let budget = if spread.is_finite() {
308 plan.budget_ms.max(spread)
309 } else {
310 plan.budget_ms
311 };
312 self.placed_ms += ms;
313 self.place(ms, budget, bandable.then_some(region))
314 }
315
316 fn spread_buffers_left(&self) -> u32 {
317 (self.buffers_unstarted() * SPREAD_SUBMISSIONS / MAX_FRAME_SUBMISSIONS).max(1)
318 }
319
320 fn quarter_buffers_left(&self) -> u32 {
321 (self.buffers_unstarted() / 4).max(1)
322 }
323
324 fn buffers_unstarted(&self) -> u32 {
325 let finished = u32::try_from(self.finished_ms.len()).unwrap_or(u32::MAX);
326 MAX_FRAME_SUBMISSIONS.saturating_sub(finished)
327 }
328
329 fn place(&mut self, ms: f64, budget: f64, region: Option<PixelRect>) -> PassPlacement {
330 if ms > budget {
331 let cut_before = self.current_ms > 0.0 && self.buffers_left() > 0;
332 if cut_before {
333 self.finish_buffer();
334 }
335 let pieces = region.map_or(Pieces::ONE, |region| {
336 Pieces::within(ms / budget, region).at_most(self.buffers_left() + 1)
337 });
338 let shared = if cut_before { 0.0 } else { self.current_ms };
339 self.band_ms = ms / f64::from(pieces.count());
340 self.current_ms = shared + self.band_ms;
341 return PassPlacement {
342 cut_before,
343 pieces,
344 pilot: None,
345 };
346 }
347 let cut_before =
348 self.current_ms > 0.0 && self.current_ms + ms > budget && self.buffers_left() > 0;
349 if cut_before {
350 self.finish_buffer();
351 self.current_ms = 0.0;
352 }
353 self.current_ms += ms;
354 PassPlacement {
355 cut_before,
356 pieces: Pieces::ONE,
357 pilot: None,
358 }
359 }
360
361 fn buffers_left(&self) -> u32 {
362 let started = u32::try_from(self.finished_ms.len() + 1).unwrap_or(u32::MAX);
363 MAX_FRAME_SUBMISSIONS.saturating_sub(started)
364 }
365
366 pub(crate) fn next_band(&mut self) {
367 self.finish_buffer();
368 self.current_ms = self.band_ms;
369 self.name_current_buffer();
370 }
371
372 fn finish_buffer(&mut self) {
373 self.finished_ms.push(self.current_ms);
374 self.finished_effects
375 .push(std::mem::take(&mut self.current_effects));
376 }
377
378 pub(crate) fn name_placed(&mut self, effect: Option<&crate::EffectId>) {
379 let unchanged = match (&self.placed_effect, effect) {
380 (Some(name), Some(effect)) => names(name, effect),
381 (None, None) => true,
382 _ => false,
383 };
384 if !unchanged {
385 self.placed_effect =
386 effect.map(|effect| format!("{}@{}", effect.as_str(), effect.version()));
387 }
388 self.name_current_buffer();
389 }
390
391 fn name_current_buffer(&mut self) {
392 if let Some(effect) = &self.placed_effect
393 && !self.current_effects.contains(effect)
394 {
395 self.current_effects.push(effect.clone());
396 }
397 }
398
399 pub(crate) fn buffer_effects(&self) -> Vec<Vec<String>> {
400 let mut buffers = self.finished_effects.clone();
401 buffers.push(self.current_effects.clone());
402 buffers
403 }
404
405 pub(crate) const fn is_planned(&self) -> bool {
406 self.plan.is_some()
407 }
408
409 pub(crate) const fn is_frame(&self) -> bool {
410 self.frame
411 }
412
413 pub(crate) const fn cost(&self) -> FrameCost {
414 self.cost
415 }
416
417 pub(crate) const fn device_rated_ms(&self) -> f64 {
418 self.device_rated_ms
419 }
420
421 pub(crate) fn planned_at(&self) -> Option<(f64, f64)> {
422 self.plan
423 .as_ref()
424 .map(|plan| (plan.ms_per_unit_pixel, plan.budget_ms))
425 }
426
427 pub(crate) fn buffer_ms(&self) -> Option<Vec<f64>> {
429 self.plan.as_ref().map(|_| {
430 let mut buffers = self.finished_ms.clone();
431 buffers.push(self.current_ms);
432 buffers
433 })
434 }
435}
436
437const CALIBRATION_SIDE: u32 = 512;
438
439const CALIBRATION_BODY: &str = "\
441fn effect(uv: vec2f, src: vec4f) -> vec4f {
442 var acc = src;
443 for (var i = 0u; i < 64u; i++) {
444 let s = sample_src(fract(uv + vec2f(f32(i) * 0.0019, f32(i) * 0.0007)));
445 acc = vec4f(sin(acc.r * 1.37 + s.g), acc.g, acc.b, acc.a);
446 }
447 return acc;
448}
449";
450
451fn calibration_definition() -> crate::EffectDef {
452 crate::EffectDef {
453 id: "alpha2.internal.calibrate".into(),
454 version: 1,
455 kind: crate::EffectKind::Effect,
456 inputs: Vec::new(),
457 params: Vec::new(),
458 resources: Vec::new(),
459 wgsl_body: CALIBRATION_BODY.into(),
460 tier_min: alpha2_gpu::CapabilityTier::TierB,
461 license: None,
462 }
463}
464
465const CALIBRATION_DRAWS: u32 = 4;
466
467impl crate::Renderer {
468 pub(crate) fn plan_submissions(&self, cost: FrameCost) -> Option<SubmissionPlan> {
473 if cost.unit_pixels() <= PLANNING_THRESHOLD_UNIT_PIXELS {
474 return None;
475 }
476 let rate = self.gpu.rate();
477 if rate.begin_calibration() && self.calibrate().is_err() {
478 rate.abandon_calibration();
479 }
480 let ms_per_unit_pixel = rate
481 .ms_per_unit_pixel()
482 .unwrap_or(alpha2_gpu::UNCALIBRATED_MS_PER_UNIT_PIXEL);
483 Some(SubmissionPlan::new(
484 std::sync::Arc::clone(rate),
485 ms_per_unit_pixel,
486 alpha2_gpu::submission_budget_ms(),
487 cost.unit_pixels() * ms_per_unit_pixel,
488 ))
489 }
490
491 fn calibrate(&self) -> Result<(), crate::RenderError> {
497 let effect = self
498 .calibration
499 .get_or_init(|| crate::registry::registered_effect(calibration_definition()));
500 let id = crate::EffectId::new(effect.definition.id.clone(), effect.definition.version);
501 let size = crate::RenderSize::new(CALIBRATION_SIDE, CALIBRATION_SIDE)?;
502 let format = self.intermediate_format();
503 let params = crate::EffectParams::new();
504 let resources = crate::EffectResources::new();
505 #[allow(clippy::cast_precision_loss)]
506 let unit_pixels =
507 effect.cost.units() as f64 * f64::from(CALIBRATION_SIDE) * f64::from(CALIBRATION_SIDE);
508 #[cfg(not(target_arch = "wasm32"))]
509 let mut fastest: Option<f64> = None;
510 #[cfg(target_arch = "wasm32")]
511 let mut sequences: Option<std::ops::Range<u64>> = None;
512 for draw in 0..CALIBRATION_DRAWS {
513 let mut encoder = self.command_encoder("alpha2 calibration encoder");
514 let source =
515 self.textures
516 .acquire(self.gpu.device(), size, format, "alpha2 calibration source");
517 let target =
518 self.textures
519 .acquire(self.gpu.device(), size, format, "alpha2 calibration target");
520 let mut uniforms = self.uniform_buffers.acquire(self.gpu.device(), 4096);
521 self.encode_registered_pass(
522 &mut encoder,
523 effect,
524 crate::runtime_effect::EffectPass {
525 id: &id,
526 kind: crate::RenderNodeKind::Effect,
527 source_a: source.view(),
528 source_b: None,
529 inputs: &[],
530 size,
531 params: ¶ms,
532 resources: &resources,
533 runtime: crate::EffectRuntime::default(),
534 output: target.view(),
535 },
536 &mut uniforms,
537 )?;
538 uniforms.flush(self.gpu.queue());
539 let submitted = self.submit_measured([encoder.finish()], false)?;
540 uniforms.recycle();
541 #[cfg(not(target_arch = "wasm32"))]
542 {
543 submitted
544 .submission
545 .wait(&self.gpu, self.gpu_wait_timeout)?;
546 if draw > 0
547 && let Some(ms) = self.submission_clock.gpu_ms(submitted.sequences.clone())
548 {
549 fastest = Some(fastest.map_or(ms, |fastest| fastest.min(ms)));
550 }
551 }
552 #[cfg(target_arch = "wasm32")]
553 {
554 let _ = draw;
555 sequences = Some(sequences.map_or(submitted.sequences.clone(), |sequences| {
556 sequences.start..submitted.sequences.end
557 }));
558 }
559 }
560 let rate = std::sync::Arc::clone(self.gpu.rate());
561 #[cfg(not(target_arch = "wasm32"))]
562 match fastest {
563 Some(ms) => rate.seed(ms / unit_pixels),
564 None => rate.abandon_calibration(),
565 }
566 #[cfg(target_arch = "wasm32")]
567 {
568 let clock = std::sync::Arc::clone(&self.submission_clock);
569 let sequences = sequences.expect("calibration draws");
570 self.gpu
571 .on_submitted_work_done(move || match clock.gpu_ms(sequences) {
572 Some(ms) => rate.seed(ms / f64::from(CALIBRATION_DRAWS) / unit_pixels),
573 None => rate.abandon_calibration(),
574 });
575 }
576 Ok(())
577 }
578}
579
580fn names(name: &str, effect: &crate::EffectId) -> bool {
581 name.strip_prefix(effect.as_str())
582 .and_then(|rest| rest.strip_prefix('@'))
583 .is_some_and(|version| version.parse() == Ok(effect.version()))
584}
585
586#[cfg(test)]
587mod tests {
588 use super::*;
589
590 const REGION: PixelRect = PixelRect {
591 x: 0,
592 y: 0,
593 width: 512,
594 height: 288,
595 };
596
597 fn placed(cut_before: bool, rows: u32) -> PassPlacement {
598 PassPlacement {
599 cut_before,
600 pieces: Pieces { rows, columns: 1 },
601 pilot: None,
602 }
603 }
604
605 #[test]
606 fn passes_fill_a_buffer_up_to_the_budget_and_a_heavy_one_is_banded() {
607 let mut planner = SubmissionPlanner::default();
608 let pass = EffectCost {
609 fetches: 0,
610 transcendentals: 0,
611 arithmetic: 10,
612 };
613 assert_eq!(
614 planner
615 .pass(FrameCost::of(pass, 100), REGION, true, None)
616 .pieces,
617 Pieces::ONE
618 );
619 assert_eq!(planner.buffer_ms(), None);
620 planner.plan(SubmissionPlan::new(
621 std::sync::Arc::default(),
622 1.0,
623 2_500.0,
624 0.0,
625 ));
626 assert!(
628 !planner
629 .pass(FrameCost::of(pass, 100), REGION, true, None)
630 .cut_before
631 );
632 assert!(
633 !planner
634 .pass(FrameCost::of(pass, 100), REGION, true, None)
635 .cut_before
636 );
637 assert!(
638 planner
639 .pass(FrameCost::of(pass, 100), REGION, true, None)
640 .cut_before
641 );
642 let placement = planner.pass(FrameCost::of(pass, 1_000), REGION, true, None);
644 assert_eq!(placement, placed(true, 4));
645 for _ in 1..placement.pieces.count() {
646 planner.next_band();
647 }
648 assert_eq!(
649 planner.pass(FrameCost::of(pass, 1_000), REGION, false, None),
650 placed(true, 1)
651 );
652 assert_eq!(
653 planner.buffer_ms(),
654 Some(vec![
655 2_000.0, 1_000.0, 2_500.0, 2_500.0, 2_500.0, 2_500.0, 10_000.0
656 ])
657 );
658 assert!((planner.cost().unit_pixels() - 24_000.0).abs() < 1e-9);
659 assert_eq!(planner.planned_at(), Some((1.0, 2_500.0)));
660 }
661
662 #[test]
663 fn an_effect_placed_again_after_a_cut_names_the_new_buffer_once() {
664 let mut planner = SubmissionPlanner::default();
665 planner.plan(SubmissionPlan::new(
666 std::sync::Arc::default(),
667 1.0,
668 2_500.0,
669 0.0,
670 ));
671 let pass = EffectCost {
672 fetches: 0,
673 transcendentals: 0,
674 arithmetic: 10,
675 };
676 let blur = crate::EffectId::from_static("blur", 2);
677 let _ = planner.pass(FrameCost::of(pass, 100), REGION, false, None);
678 planner.name_placed(Some(&blur));
679 let _ = planner.pass(FrameCost::of(pass, 100), REGION, false, None);
680 planner.name_placed(Some(&blur));
681 let _ = planner.pass(FrameCost::of(pass, 10_000), REGION, false, None);
682 planner.name_placed(Some(&blur));
683 let buffers = planner.buffer_effects();
684 assert!(buffers.len() > 1, "{buffers:?}");
685 for buffer in buffers {
686 assert_eq!(buffer, ["blur@2"]);
687 }
688 }
689
690 #[test]
691 fn effect_names_follow_the_command_buffer_their_pass_is_encoded_into() {
692 let mut planner = SubmissionPlanner::default();
693 planner.plan(SubmissionPlan::new(
694 std::sync::Arc::default(),
695 1.0,
696 2_500.0,
697 0.0,
698 ));
699 let pass = EffectCost {
700 fetches: 0,
701 transcendentals: 0,
702 arithmetic: 10,
703 };
704 let blur = crate::EffectId::from_static("blur", 2);
705 let grain = crate::EffectId::from_static("grain", 1);
706 let _ = planner.pass(FrameCost::of(pass, 100), REGION, true, None);
707 planner.name_placed(Some(&blur));
708 let _ = planner.pass(FrameCost::of(pass, 100), REGION, false, None);
709 planner.name_placed(None);
710 let placement = planner.pass(FrameCost::of(pass, 1_000), REGION, true, None);
711 assert_eq!(placement, placed(true, 4));
712 planner.name_placed(Some(&grain));
713 for _ in 1..placement.pieces.count() {
714 planner.next_band();
715 }
716 let _ = planner.pass(FrameCost::of(pass, 100), REGION, true, None);
717 planner.name_placed(Some(&blur));
718 let names = |names: &[&str]| -> Vec<String> {
719 names.iter().map(|name| (*name).to_owned()).collect()
720 };
721 assert_eq!(
722 planner.buffer_effects(),
723 vec![
724 names(&["blur@2"]),
725 names(&["grain@1"]),
726 names(&["grain@1"]),
727 names(&["grain@1"]),
728 names(&["grain@1"]),
729 names(&["blur@2"]),
730 ]
731 );
732 }
733
734 #[test]
735 fn a_pass_measured_slower_than_the_device_is_banded_at_its_own_rate() {
736 let rate = std::sync::Arc::new(alpha2_gpu::GpuRate::default());
737 rate.seed(0.5);
738 let scattered = alpha2_gpu::PassKey::new(1, 100);
739 rate.record_pass_rate(scattered, 5.0);
740 let mut planner = SubmissionPlanner::default();
741 planner.plan(SubmissionPlan::new(rate, 1.0, 2_500.0, 0.0));
742 let pass = EffectCost {
743 fetches: 0,
744 transcendentals: 0,
745 arithmetic: 10,
746 };
747 assert_eq!(
748 planner.pass(FrameCost::of(pass, 100), REGION, true, None),
749 placed(false, 1)
750 );
751 assert_eq!(
752 planner.pass(FrameCost::of(pass, 100), REGION, true, Some(scattered)),
753 placed(true, 4)
754 );
755 }
756
757 #[test]
758 fn a_pilot_draws_its_rows_alone_and_plans_nothing() {
759 let mut planner = SubmissionPlanner::default();
760 planner.mark_pilot(6);
761 let pass = EffectCost::fixed(1, 0);
762 assert_eq!(
763 planner.pass(FrameCost::of(pass, 100), REGION, true, None),
764 PassPlacement {
765 cut_before: false,
766 pieces: Pieces::ONE,
767 pilot: Some(6)
768 }
769 );
770 assert_eq!(
771 planner.pass(FrameCost::of(pass, 100), REGION, false, None),
772 placed(false, 1)
773 );
774 assert_eq!(planner.buffer_ms(), None);
775 }
776
777 #[test]
778 fn a_pass_past_the_most_bands_is_cut_into_tiles_no_smaller_than_a_quad() {
779 let mut planner = SubmissionPlanner::default();
780 planner.plan(SubmissionPlan::new(
781 std::sync::Arc::default(),
782 1.0,
783 100.0,
784 8_000.0,
785 ));
786 let pass = EffectCost::fixed(0, 0).plus(EffectCost {
787 fetches: 0,
788 transcendentals: 0,
789 arithmetic: 1,
790 });
791 let placement = planner.pass(FrameCost::of(pass, 80 * 100), REGION, true, None);
792 assert_eq!(
793 placement.pieces,
794 Pieces {
795 rows: 40,
796 columns: 2
797 }
798 );
799 let tiny = PixelRect {
800 x: 0,
801 y: 0,
802 width: 5,
803 height: 4,
804 };
805 let placement = planner.pass(FrameCost::of(pass, 1_000 * 100), tiny, true, None);
806 assert_eq!(
807 placement.pieces,
808 Pieces {
809 rows: 2,
810 columns: 3
811 }
812 );
813 }
814
815 #[test]
816 fn a_frame_is_never_cut_into_more_than_its_most_submissions() {
817 let mut planner = SubmissionPlanner::default();
818 planner.plan(SubmissionPlan::new(
819 std::sync::Arc::default(),
820 1.0,
821 1.0,
822 0.0,
823 ));
824 let pass = EffectCost {
825 fetches: 0,
826 transcendentals: 0,
827 arithmetic: 1,
828 };
829 let mut buffers = 1;
830 for _ in 0..60 {
831 let placement = planner.pass(FrameCost::of(pass, 100), REGION, true, None);
832 buffers += u32::from(placement.cut_before);
833 for _ in 1..placement.pieces.count() {
834 planner.next_band();
835 buffers += 1;
836 }
837 }
838 let placement = planner.pass(FrameCost::of(pass, 3), REGION, false, None);
839 assert!(!placement.cut_before, "a full frame starts no buffer");
840 let ms = planner.buffer_ms().expect("planned");
841 assert_eq!(buffers, MAX_FRAME_SUBMISSIONS);
842 assert_eq!(ms.len(), MAX_FRAME_SUBMISSIONS as usize);
843 assert!((ms.iter().sum::<f64>() - 6_003.0).abs() < 1e-9, "{ms:?}");
844 }
845
846 #[test]
847 fn a_frame_predicted_past_its_most_submissions_is_cut_into_longer_ones_evenly() {
848 let mut planner = SubmissionPlanner::default();
849 let budgets = f64::from(MAX_FRAME_SUBMISSIONS) * 4.0;
850 planner.plan(SubmissionPlan::new(
851 std::sync::Arc::default(),
852 1.0,
853 1.0,
854 budgets,
855 ));
856 let pass = EffectCost {
857 fetches: 0,
858 transcendentals: 0,
859 arithmetic: 1,
860 };
861 for _ in 0..4 {
862 let placement = planner.pass(
863 FrameCost::of(pass, u64::from(MAX_FRAME_SUBMISSIONS)),
864 REGION,
865 true,
866 None,
867 );
868 for _ in 1..placement.pieces.count() {
869 planner.next_band();
870 }
871 }
872 let ms = planner.buffer_ms().expect("planned");
873 let spread = budgets / f64::from(SPREAD_SUBMISSIONS);
874 assert!(ms.len() <= MAX_FRAME_SUBMISSIONS as usize, "{ms:?}");
875 assert!(ms.iter().all(|ms| *ms <= spread * (1.0 + 1e-9)), "{ms:?}");
876 }
877
878 #[test]
879 fn a_frame_whose_passes_measured_slower_than_the_device_is_spread_by_their_planned_rate() {
880 use std::sync::Arc;
881 let rate = Arc::new(alpha2_gpu::GpuRate::default());
882 let key = alpha2_gpu::PassKey::new(7, 100);
883 rate.record_pass_rate(key, 25.0);
884 let pass = FrameCost::of(
885 EffectCost {
886 fetches: 0,
887 transcendentals: 0,
888 arithmetic: 1,
889 },
890 100,
891 );
892 let passes = 64;
893 let mut plan = SubmissionPlan::new(Arc::clone(&rate), 1.0, 1.0, f64::from(passes) * 100.0);
894 plan.predict((0..passes).map(|_| (pass, Some(key))));
895 let planned_ms = plan.predicted_ms;
896 rate.record_pass_rate(key, 100.0);
897 let mut planner = SubmissionPlanner::default();
898 planner.plan(plan);
899 for _ in 0..passes {
900 let placement = planner.pass(pass, REGION, true, Some(key));
901 for _ in 1..placement.pieces.count() {
902 planner.next_band();
903 }
904 }
905 let ms = planner.buffer_ms().expect("planned");
906 let spread = planned_ms / f64::from(SPREAD_SUBMISSIONS);
907 assert!(ms.len() <= MAX_FRAME_SUBMISSIONS as usize, "{}", ms.len());
908 assert!(ms.iter().all(|ms| *ms <= spread * (1.0 + 1e-9)), "{ms:?}");
909 }
910
911 #[test]
912 fn pieces_cover_every_pixel_of_their_region_once_on_even_edges() {
913 for (pieces, region) in [
914 (Pieces::ONE, (0, 0, 7, 7)),
915 (
916 Pieces {
917 rows: 3,
918 columns: 1,
919 },
920 (0, 0, 512, 288),
921 ),
922 (
923 Pieces {
924 rows: 7,
925 columns: 1,
926 },
927 (0, 0, 64, 101),
928 ),
929 (
930 Pieces {
931 rows: 64,
932 columns: 1,
933 },
934 (0, 0, 8, 4320),
935 ),
936 (
937 Pieces {
938 rows: 4,
939 columns: 5,
940 },
941 (3, 9, 101, 77),
942 ),
943 ] {
944 let region = PixelRect {
945 x: region.0,
946 y: region.1,
947 width: region.2,
948 height: region.3,
949 };
950 let mut covered = vec![0_u32; (region.width * region.height) as usize];
951 for index in 0..pieces.count() {
952 let piece = pieces.rect(index, region);
953 for (edge, start, end) in [
954 (piece.x, region.x, region.x + region.width),
955 (piece.y, region.y, region.y + region.height),
956 (piece.x + piece.width, region.x, region.x + region.width),
957 (piece.y + piece.height, region.y, region.y + region.height),
958 ] {
959 assert!(edge == start || edge == end || edge % 2 == 0, "{piece:?}");
960 }
961 for y in piece.y..piece.y + piece.height {
962 for x in piece.x..piece.x + piece.width {
963 covered[((y - region.y) * region.width + x - region.x) as usize] += 1;
964 }
965 }
966 }
967 assert!(covered.iter().all(|count| *count == 1), "{pieces:?}");
968 }
969 }
970}