Skip to main content

sim_engine/renderer/frame/
compose.rs

1use super::{
2    FrameComposer, FrameComposerError, FrameItem, FramePassOptions, FrameReport, FrameSourceKind,
3    FrameSourceStatistics, FrameStatistics, RetainedResourceAccounting, RetainedResourceKey,
4    ScalarLutPlan, account_new_retained_resources, retained_arc_key, retained_key,
5    scalar_lut_counts_with_inserted, validate_frame_budget,
6};
7use crate::renderer::{
8    BlendMode, COLOR_MAP_LUT_SIZE, Camera2d, CameraUniform, Color, ColorMap, CompositeUniform,
9    DynamicGpu, DynamicMesh2d, GlyphAtlas2d, GlyphRun2d, HeatmapUniform, Image2d, ImageBatch2d,
10    ImageBatchPlacement, ImageSampling, ImageTexelRect, ImageUniform, ParticleField2d, ParticleGpu,
11    PreparedDrawBatch, PreparedScene, PreparedScreenScene, Rect, RenderTarget2d,
12    ScalarFieldSampling, ScalarFieldTexture, Scene, ScreenScene, Vertex, color_map_lut,
13    prepared_scene_belongs_to, scalar_normalization_is_portable, scalar_value_range_extent,
14};
15
16impl<'frame> FrameComposer<'frame> {
17    /// Adds a streaming world-space scene through its own camera.
18    pub fn draw_scene(
19        &mut self,
20        scene: &'frame Scene,
21        camera: Camera2d,
22        options: FramePassOptions,
23    ) -> Result<(), FrameComposerError> {
24        let statistics = scene.statistics();
25        let work = FrameStatistics {
26            pass_count: 1,
27            command_count: scene.command_count(),
28            vertex_count: statistics.estimated_tessellated_vertices(),
29            streaming_vertex_count: statistics.estimated_tessellated_vertices(),
30            reused_vertex_count: 0,
31            upload_bytes: statistics
32                .estimated_upload_bytes()
33                .saturating_add(std::mem::size_of::<CameraUniform>()),
34            streaming_upload_bytes: statistics.estimated_upload_bytes(),
35            texture_bytes: 0,
36            retained_cpu_bytes: 0,
37            retained_buffer_bytes: 0,
38            draw_calls: statistics.estimated_draw_batches(),
39            source_counts: FrameSourceStatistics::single(FrameSourceKind::StreamingScene),
40        };
41        self.push_accounted_item(
42            &[RetainedResourceAccounting::new(
43                retained_key(scene, 1),
44                scene.allocation_bytes(),
45                0,
46                0,
47            )],
48            work,
49            FrameItem::Scene {
50                scene,
51                camera,
52                options,
53                insertion: self.next_insertion,
54            },
55        )
56    }
57
58    /// Adds a streaming logical-screen scene unaffected by world cameras.
59    pub fn draw_screen_scene(
60        &mut self,
61        scene: &'frame ScreenScene,
62        options: FramePassOptions,
63    ) -> Result<(), FrameComposerError> {
64        let statistics = scene.statistics();
65        let work = FrameStatistics {
66            pass_count: 1,
67            command_count: scene.command_count(),
68            vertex_count: statistics.estimated_tessellated_vertices(),
69            streaming_vertex_count: statistics.estimated_tessellated_vertices(),
70            reused_vertex_count: 0,
71            upload_bytes: statistics
72                .estimated_upload_bytes()
73                .saturating_add(std::mem::size_of::<CameraUniform>()),
74            streaming_upload_bytes: statistics.estimated_upload_bytes(),
75            texture_bytes: 0,
76            retained_cpu_bytes: 0,
77            retained_buffer_bytes: 0,
78            draw_calls: statistics.estimated_draw_batches(),
79            source_counts: FrameSourceStatistics::single(FrameSourceKind::StreamingScene),
80        };
81        self.push_accounted_item(
82            &[RetainedResourceAccounting::new(
83                retained_key(scene, 2),
84                scene.allocation_bytes(),
85                0,
86                0,
87            )],
88            work,
89            FrameItem::ScreenScene {
90                scene,
91                options,
92                insertion: self.next_insertion,
93            },
94        )
95    }
96
97    /// Adds immutable prepared world-space geometry through its own camera.
98    pub fn draw_prepared_scene(
99        &mut self,
100        scene: &'frame PreparedScene,
101        camera: Camera2d,
102        options: FramePassOptions,
103    ) -> Result<(), FrameComposerError> {
104        if !prepared_scene_belongs_to(&self.renderer.renderer_identity, &scene.renderer_identity) {
105            return Err(FrameComposerError::RendererMismatch {
106                source: FrameSourceKind::PreparedScene,
107            });
108        }
109        let work = FrameStatistics {
110            pass_count: 1,
111            command_count: scene.command_count,
112            vertex_count: scene.vertex_count,
113            streaming_vertex_count: 0,
114            reused_vertex_count: scene.vertex_count,
115            upload_bytes: std::mem::size_of::<CameraUniform>(),
116            streaming_upload_bytes: 0,
117            texture_bytes: 0,
118            retained_cpu_bytes: 0,
119            retained_buffer_bytes: 0,
120            draw_calls: scene.draw_batches.len(),
121            source_counts: FrameSourceStatistics::single(FrameSourceKind::PreparedScene),
122        };
123        self.push_accounted_item(
124            &[
125                RetainedResourceAccounting::new(
126                    retained_arc_key(&scene.vertices, 13),
127                    scene
128                        .vertices
129                        .capacity()
130                        .saturating_mul(std::mem::size_of::<Vertex>()),
131                    0,
132                    0,
133                ),
134                RetainedResourceAccounting::new(
135                    retained_arc_key(&scene.vertex_buffer, 3),
136                    0,
137                    scene
138                        .vertex_count
139                        .max(1)
140                        .saturating_mul(std::mem::size_of::<Vertex>()),
141                    0,
142                ),
143                RetainedResourceAccounting::new(
144                    retained_key(&scene.draw_batches, 14),
145                    scene
146                        .draw_batches
147                        .capacity()
148                        .saturating_mul(std::mem::size_of::<PreparedDrawBatch>()),
149                    0,
150                    0,
151                ),
152            ],
153            work,
154            FrameItem::Prepared {
155                scene,
156                camera,
157                options,
158                insertion: self.next_insertion,
159            },
160        )
161    }
162
163    /// Adds immutable prepared logical-screen geometry.
164    pub fn draw_prepared_screen_scene(
165        &mut self,
166        scene: &'frame PreparedScreenScene,
167        options: FramePassOptions,
168    ) -> Result<(), FrameComposerError> {
169        if !prepared_scene_belongs_to(
170            &self.renderer.renderer_identity,
171            &scene.scene.renderer_identity,
172        ) {
173            return Err(FrameComposerError::RendererMismatch {
174                source: FrameSourceKind::PreparedScene,
175            });
176        }
177        let work = FrameStatistics {
178            pass_count: 1,
179            command_count: scene.scene.command_count,
180            vertex_count: scene.scene.vertex_count,
181            streaming_vertex_count: 0,
182            reused_vertex_count: scene.scene.vertex_count,
183            upload_bytes: std::mem::size_of::<CameraUniform>(),
184            streaming_upload_bytes: 0,
185            texture_bytes: 0,
186            retained_cpu_bytes: 0,
187            retained_buffer_bytes: 0,
188            draw_calls: scene.scene.draw_batches.len(),
189            source_counts: FrameSourceStatistics::single(FrameSourceKind::PreparedScene),
190        };
191        self.push_accounted_item(
192            &[
193                RetainedResourceAccounting::new(
194                    retained_arc_key(&scene.scene.vertices, 13),
195                    scene
196                        .scene
197                        .vertices
198                        .capacity()
199                        .saturating_mul(std::mem::size_of::<Vertex>()),
200                    0,
201                    0,
202                ),
203                RetainedResourceAccounting::new(
204                    retained_arc_key(&scene.scene.vertex_buffer, 3),
205                    0,
206                    scene
207                        .scene
208                        .vertex_count
209                        .max(1)
210                        .saturating_mul(std::mem::size_of::<Vertex>()),
211                    0,
212                ),
213                RetainedResourceAccounting::new(
214                    retained_key(&scene.scene.draw_batches, 14),
215                    scene
216                        .scene
217                        .draw_batches
218                        .capacity()
219                        .saturating_mul(std::mem::size_of::<PreparedDrawBatch>()),
220                    0,
221                    0,
222                ),
223            ],
224            work,
225            FrameItem::PreparedScreen {
226                scene,
227                options,
228                insertion: self.next_insertion,
229            },
230        )
231    }
232
233    /// Adds retained dynamic triangles through their own world camera.
234    ///
235    /// Camera-dependent topology is validated by [`FrameComposer::present`],
236    /// which rejects triangles crossing the full target clip volume or having
237    /// an ambiguous projected orientation. Item viewport/scissor clipping is
238    /// axis-aligned fragment clipping and remains supported.
239    pub fn draw_dynamic_mesh(
240        &mut self,
241        mesh: &'frame DynamicMesh2d,
242        camera: Camera2d,
243        options: FramePassOptions,
244    ) -> Result<(), FrameComposerError> {
245        if self.renderer.validate_dynamic_mesh(mesh).is_err() {
246            return Err(FrameComposerError::RendererMismatch {
247                source: FrameSourceKind::DynamicMesh,
248            });
249        }
250        let work = FrameStatistics {
251            pass_count: 1,
252            command_count: usize::from(!mesh.vertices.is_empty()),
253            vertex_count: mesh.vertices.len(),
254            streaming_vertex_count: 0,
255            reused_vertex_count: mesh.vertices.len(),
256            upload_bytes: std::mem::size_of::<CameraUniform>(),
257            streaming_upload_bytes: 0,
258            texture_bytes: 0,
259            retained_cpu_bytes: 0,
260            retained_buffer_bytes: 0,
261            draw_calls: usize::from(!mesh.vertices.is_empty()),
262            source_counts: FrameSourceStatistics::single(FrameSourceKind::DynamicMesh),
263        };
264        self.push_accounted_item(
265            &[RetainedResourceAccounting::new(
266                retained_arc_key(&mesh.vertex_buffer, 4),
267                mesh.recovery_memory_bytes(),
268                mesh.vertex_capacity
269                    .saturating_mul(std::mem::size_of::<DynamicGpu>()),
270                0,
271            )],
272            work,
273            FrameItem::Dynamic {
274                mesh,
275                camera,
276                options,
277                insertion: self.next_insertion,
278            },
279        )
280    }
281
282    /// Adds a budgeted instanced particle field through its own world camera.
283    pub fn draw_particle_field(
284        &mut self,
285        field: &'frame mut ParticleField2d,
286        camera: Camera2d,
287        options: FramePassOptions,
288    ) -> Result<(), FrameComposerError> {
289        if self.renderer.validate_particle_field(field).is_err() {
290            return Err(FrameComposerError::RendererMismatch {
291                source: FrameSourceKind::ParticleField,
292            });
293        }
294        let candidate_count = field
295            .instances
296            .len()
297            .min(field.budget.max_visibility_checks_per_frame)
298            .min(field.budget.instance_limit());
299        self.push_accounted_item(
300            &[RetainedResourceAccounting::new(
301                retained_arc_key(&field.instance_buffer, 5),
302                field.cpu_allocation_bytes(),
303                field.gpu_allocation_bytes(),
304                0,
305            )],
306            FrameStatistics {
307                pass_count: 1,
308                command_count: usize::from(!field.instances.is_empty()),
309                vertex_count: candidate_count.saturating_mul(6),
310                streaming_vertex_count: candidate_count.saturating_mul(6),
311                reused_vertex_count: 0,
312                upload_bytes: candidate_count
313                    .saturating_mul(std::mem::size_of::<ParticleGpu>())
314                    .saturating_add(std::mem::size_of::<CameraUniform>()),
315                streaming_upload_bytes: candidate_count
316                    .saturating_mul(std::mem::size_of::<ParticleGpu>()),
317                texture_bytes: 0,
318                retained_cpu_bytes: 0,
319                retained_buffer_bytes: 0,
320                draw_calls: usize::from(candidate_count > 0),
321                source_counts: FrameSourceStatistics::single(FrameSourceKind::ParticleField),
322            },
323            FrameItem::Particle {
324                field,
325                camera,
326                options,
327                insertion: self.next_insertion,
328            },
329        )
330    }
331
332    /// Adds a retained scalar heatmap scaled into the optional viewport.
333    pub fn draw_scalar_field(
334        &mut self,
335        texture: &'frame ScalarFieldTexture,
336        color_map: &'frame ColorMap,
337        (minimum, maximum): (f32, f32),
338        sampling: ScalarFieldSampling,
339        options: FramePassOptions,
340    ) -> Result<(), FrameComposerError> {
341        if self
342            .renderer
343            .validate_scalar_field_texture(texture)
344            .is_err()
345        {
346            return Err(FrameComposerError::RendererMismatch {
347                source: FrameSourceKind::ScalarField,
348            });
349        }
350        let value_extent = scalar_value_range_extent(minimum, maximum)
351            .ok_or(FrameComposerError::InvalidValueRange { minimum, maximum })?;
352        if !scalar_normalization_is_portable(texture, minimum, value_extent) {
353            return Err(FrameComposerError::InvalidValueRange { minimum, maximum });
354        }
355        let color_map_bytes = COLOR_MAP_LUT_SIZE as usize * 4;
356        let scalar_lut = ScalarLutPlan {
357            sort_key: (options.order(), self.next_insertion),
358            lut: color_map_lut(color_map),
359        };
360        self.scalar_luts
361            .try_reserve(1)
362            .map_err(|_| FrameComposerError::AllocationFailed {
363                requested_bytes: std::mem::size_of::<ScalarLutPlan>(),
364            })?;
365        let insertion = self
366            .scalar_luts
367            .partition_point(|planned| planned.sort_key < scalar_lut.sort_key);
368        let (lut_upload_count, lut_allocation_count) = scalar_lut_counts_with_inserted(
369            &self.scalar_luts,
370            insertion,
371            &scalar_lut.lut,
372            self.renderer
373                .color_map_cache
374                .as_ref()
375                .map(|cached| &cached.lut),
376        );
377        let additional_lut_uploads = lut_upload_count.saturating_sub(self.scalar_lut_upload_count);
378        let additional_lut_allocations =
379            lut_allocation_count.saturating_sub(self.scalar_lut_allocation_count);
380        self.push_accounted_item(
381            &[
382                RetainedResourceAccounting::new(
383                    retained_key(&texture.texture, 6),
384                    texture.recovery_memory_bytes(),
385                    0,
386                    texture.gpu_allocation_bytes(),
387                ),
388                RetainedResourceAccounting::new(
389                    retained_key(color_map, 15),
390                    color_map.allocation_bytes(),
391                    0,
392                    0,
393                ),
394            ],
395            FrameStatistics {
396                pass_count: 1,
397                command_count: 1,
398                vertex_count: 6,
399                streaming_vertex_count: 0,
400                reused_vertex_count: 0,
401                upload_bytes: std::mem::size_of::<HeatmapUniform>()
402                    .saturating_add(additional_lut_uploads.saturating_mul(color_map_bytes)),
403                streaming_upload_bytes: 0,
404                texture_bytes: additional_lut_allocations.saturating_mul(color_map_bytes),
405                retained_cpu_bytes: 0,
406                retained_buffer_bytes: 0,
407                draw_calls: 1,
408                source_counts: FrameSourceStatistics::single(FrameSourceKind::ScalarField),
409            },
410            FrameItem::Scalar {
411                texture,
412                color_map,
413                minimum,
414                maximum,
415                value_extent,
416                sampling,
417                options,
418                insertion: self.next_insertion,
419            },
420        )?;
421        self.scalar_luts.insert(insertion, scalar_lut);
422        self.scalar_lut_upload_count = lut_upload_count;
423        self.scalar_lut_allocation_count = lut_allocation_count;
424        Ok(())
425    }
426
427    /// Adds one image or atlas region scaled into the optional viewport.
428    ///
429    /// With no viewport the image covers the complete logical surface. `tint`
430    /// is normalized straight linear RGBA and multiplies decoded image color.
431    pub fn draw_image(
432        &mut self,
433        image: &'frame Image2d,
434        source: Option<ImageTexelRect>,
435        tint: Color,
436        sampling: ImageSampling,
437        options: FramePassOptions,
438    ) -> Result<(), FrameComposerError> {
439        if self.renderer.validate_image(image).is_err() {
440            return Err(FrameComposerError::RendererMismatch {
441                source: FrameSourceKind::Image,
442            });
443        }
444        if !tint.is_normalized() {
445            return Err(FrameComposerError::InvalidTint);
446        }
447        let source = source.unwrap_or_else(|| image.full_rect());
448        if !source.fits(image.width(), image.height()) {
449            return Err(FrameComposerError::InvalidImageRegion);
450        }
451        self.push_accounted_item(
452            &[RetainedResourceAccounting::new(
453                retained_arc_key(&image.resource_identity, 7),
454                image.recovery_memory_bytes(),
455                0,
456                image.gpu_allocation_bytes(),
457            )],
458            FrameStatistics {
459                pass_count: 1,
460                command_count: 1,
461                vertex_count: 6,
462                streaming_vertex_count: 0,
463                reused_vertex_count: 0,
464                upload_bytes: std::mem::size_of::<ImageUniform>(),
465                streaming_upload_bytes: 0,
466                texture_bytes: 0,
467                retained_cpu_bytes: 0,
468                retained_buffer_bytes: 0,
469                draw_calls: 1,
470                source_counts: FrameSourceStatistics::single(FrameSourceKind::Image),
471            },
472            FrameItem::Image {
473                image,
474                source,
475                tint,
476                sampling,
477                options,
478                insertion: self.next_insertion,
479            },
480        )
481    }
482
483    /// Adds one image or atlas region on an axis-aligned world-space rectangle.
484    ///
485    /// The rectangle follows the supplied camera's zoom, rotation, and
486    /// pseudo-depth projection. Its UV top edge maps to the rectangle's maximum
487    /// world Y edge. The optional frame viewport selects the camera viewport and
488    /// the item remains constrained by that viewport and clip.
489    #[allow(clippy::too_many_arguments)]
490    pub fn draw_world_image(
491        &mut self,
492        image: &'frame Image2d,
493        source: Option<ImageTexelRect>,
494        rectangle: Rect,
495        depth: f32,
496        camera: Camera2d,
497        tint: Color,
498        sampling: ImageSampling,
499        options: FramePassOptions,
500    ) -> Result<(), FrameComposerError> {
501        if self.renderer.validate_image(image).is_err() {
502            return Err(FrameComposerError::RendererMismatch {
503                source: FrameSourceKind::Image,
504            });
505        }
506        if !tint.is_normalized() {
507            return Err(FrameComposerError::InvalidTint);
508        }
509        let source = source.unwrap_or_else(|| image.full_rect());
510        if !source.fits(image.width(), image.height()) {
511            return Err(FrameComposerError::InvalidImageRegion);
512        }
513        let rectangle = rectangle.normalized();
514        if !rectangle.min().is_finite()
515            || !rectangle.max().is_finite()
516            || !rectangle.width().is_finite()
517            || !rectangle.height().is_finite()
518            || rectangle.width() <= 0.0
519            || rectangle.height() <= 0.0
520            || !depth.is_finite()
521        {
522            return Err(FrameComposerError::InvalidWorldImage);
523        }
524        self.push_accounted_item(
525            &[RetainedResourceAccounting::new(
526                retained_arc_key(&image.resource_identity, 7),
527                image.recovery_memory_bytes(),
528                0,
529                image.gpu_allocation_bytes(),
530            )],
531            FrameStatistics {
532                pass_count: 1,
533                command_count: 1,
534                vertex_count: 6,
535                streaming_vertex_count: 0,
536                reused_vertex_count: 0,
537                upload_bytes: std::mem::size_of::<ImageUniform>(),
538                streaming_upload_bytes: 0,
539                texture_bytes: 0,
540                retained_cpu_bytes: 0,
541                retained_buffer_bytes: 0,
542                draw_calls: 1,
543                source_counts: FrameSourceStatistics::single(FrameSourceKind::Image),
544            },
545            FrameItem::WorldImage {
546                image,
547                source,
548                rectangle,
549                depth,
550                camera,
551                tint,
552                sampling,
553                options,
554                insertion: self.next_insertion,
555            },
556        )
557    }
558
559    /// Adds a retained atlas batch as one instanced draw when non-empty.
560    /// Empty batches are valid frame items and emit no draw call.
561    pub fn draw_image_batch(
562        &mut self,
563        image: &'frame Image2d,
564        batch: &'frame ImageBatch2d,
565        sampling: ImageSampling,
566        options: FramePassOptions,
567    ) -> Result<(), FrameComposerError> {
568        self.draw_image_batch_placed(
569            image,
570            batch,
571            ImageBatchPlacement::default(),
572            sampling,
573            options,
574        )
575    }
576
577    /// Draws a retained batch with independent logical translation and tint.
578    /// The pass viewport and clip stay fixed while the content moves; negative
579    /// offsets and partially offscreen content are supported without re-upload.
580    pub fn draw_image_batch_placed(
581        &mut self,
582        image: &'frame Image2d,
583        batch: &'frame ImageBatch2d,
584        placement: ImageBatchPlacement,
585        sampling: ImageSampling,
586        options: FramePassOptions,
587    ) -> Result<(), FrameComposerError> {
588        if self.renderer.validate_image_batch(image, batch).is_err() {
589            return Err(FrameComposerError::RendererMismatch {
590                source: FrameSourceKind::Image,
591            });
592        }
593        self.push_retained_image_batch(
594            image,
595            batch,
596            placement,
597            sampling,
598            options,
599            FrameSourceKind::Image,
600        )
601    }
602
603    /// Adds one host-shaped retained glyph run as one instanced draw when non-empty.
604    ///
605    /// Positions are local logical pixels. Mixed font fallback is represented
606    /// by multiple runs submitted at the same order; stable insertion order is
607    /// preserved between them. An empty run is valid and emits no draw call.
608    pub fn draw_glyph_run(
609        &mut self,
610        atlas: &'frame GlyphAtlas2d,
611        run: &'frame GlyphRun2d,
612        sampling: ImageSampling,
613        options: FramePassOptions,
614    ) -> Result<(), FrameComposerError> {
615        self.draw_glyph_run_placed(
616            atlas,
617            run,
618            ImageBatchPlacement::default(),
619            sampling,
620            options,
621        )
622    }
623
624    /// Draws a shared glyph layout with independent logical translation and tint.
625    /// Glyph bearings and per-glyph tint are preserved; draw tint multiplies them.
626    /// The item clip is not translated. Existing default calls are equivalent
627    /// to zero translation and white tint.
628    pub fn draw_glyph_run_placed(
629        &mut self,
630        atlas: &'frame GlyphAtlas2d,
631        run: &'frame GlyphRun2d,
632        placement: ImageBatchPlacement,
633        sampling: ImageSampling,
634        options: FramePassOptions,
635    ) -> Result<(), FrameComposerError> {
636        if self.renderer.validate_glyph_run(atlas, run).is_err() {
637            return Err(FrameComposerError::RendererMismatch {
638                source: FrameSourceKind::Glyph,
639            });
640        }
641        let image = &atlas.image;
642        let batch = &run.batch;
643        let vertex_count = batch.sprite_count().saturating_mul(6);
644        self.push_accounted_item(
645            &[
646                RetainedResourceAccounting::new(
647                    retained_arc_key(&image.resource_identity, 7),
648                    image.recovery_memory_bytes(),
649                    0,
650                    image.gpu_allocation_bytes(),
651                ),
652                RetainedResourceAccounting::new(
653                    retained_key(atlas, 9),
654                    atlas
655                        .recovery_memory_bytes()
656                        .saturating_sub(image.recovery_memory_bytes()),
657                    0,
658                    0,
659                ),
660                RetainedResourceAccounting::new(
661                    retained_key(run, 10),
662                    run.recovery_memory_bytes(),
663                    run.gpu_allocation_bytes(),
664                    0,
665                ),
666            ],
667            FrameStatistics {
668                pass_count: 1,
669                command_count: usize::from(batch.sprite_count() > 0),
670                vertex_count,
671                streaming_vertex_count: 0,
672                reused_vertex_count: vertex_count,
673                upload_bytes: std::mem::size_of::<ImageUniform>(),
674                streaming_upload_bytes: 0,
675                texture_bytes: 0,
676                retained_cpu_bytes: 0,
677                retained_buffer_bytes: 0,
678                draw_calls: usize::from(batch.sprite_count() > 0),
679                source_counts: FrameSourceStatistics::single(FrameSourceKind::Glyph),
680            },
681            FrameItem::ImageBatch {
682                image,
683                batch,
684                placement,
685                sampling,
686                options,
687                insertion: self.next_insertion,
688            },
689        )
690    }
691
692    fn push_retained_image_batch(
693        &mut self,
694        image: &'frame Image2d,
695        batch: &'frame ImageBatch2d,
696        placement: ImageBatchPlacement,
697        sampling: ImageSampling,
698        options: FramePassOptions,
699        source: FrameSourceKind,
700    ) -> Result<(), FrameComposerError> {
701        let vertex_count = batch.sprite_count().saturating_mul(6);
702        self.push_accounted_item(
703            &[
704                RetainedResourceAccounting::new(
705                    retained_arc_key(&image.resource_identity, 7),
706                    image.recovery_memory_bytes(),
707                    0,
708                    image.gpu_allocation_bytes(),
709                ),
710                RetainedResourceAccounting::new(
711                    retained_key(batch, 8),
712                    batch.recovery_memory_bytes(),
713                    batch.gpu_allocation_bytes(),
714                    0,
715                ),
716            ],
717            FrameStatistics {
718                pass_count: 1,
719                command_count: usize::from(batch.sprite_count() > 0),
720                vertex_count,
721                streaming_vertex_count: 0,
722                reused_vertex_count: vertex_count,
723                upload_bytes: std::mem::size_of::<ImageUniform>(),
724                streaming_upload_bytes: 0,
725                texture_bytes: 0,
726                retained_cpu_bytes: 0,
727                retained_buffer_bytes: 0,
728                draw_calls: usize::from(batch.sprite_count() > 0),
729                source_counts: FrameSourceStatistics::single(source),
730            },
731            FrameItem::ImageBatch {
732                image,
733                batch,
734                placement,
735                sampling,
736                options,
737                insertion: self.next_insertion,
738            },
739        )
740    }
741
742    /// Adds an offscreen target, scaled into the optional logical viewport.
743    pub fn draw_render_target(
744        &mut self,
745        target: &'frame RenderTarget2d,
746        blend_mode: BlendMode,
747        opacity: f32,
748        options: FramePassOptions,
749    ) -> Result<(), FrameComposerError> {
750        if self.renderer.validate_render_target(target).is_err() {
751            return Err(FrameComposerError::RendererMismatch {
752                source: FrameSourceKind::RenderTarget,
753            });
754        }
755        if !opacity.is_finite() || !(0.0..=1.0).contains(&opacity) {
756            return Err(FrameComposerError::InvalidOpacity);
757        }
758        self.push_accounted_item(
759            &[RetainedResourceAccounting::new(
760                retained_arc_key(&target.resource_identity, 11),
761                0,
762                0,
763                target.allocation_bytes,
764            )],
765            FrameStatistics {
766                pass_count: 1,
767                command_count: 1,
768                vertex_count: 6,
769                streaming_vertex_count: 0,
770                reused_vertex_count: 0,
771                upload_bytes: std::mem::size_of::<CompositeUniform>(),
772                streaming_upload_bytes: 0,
773                texture_bytes: 0,
774                retained_cpu_bytes: 0,
775                retained_buffer_bytes: 0,
776                draw_calls: 1,
777                source_counts: FrameSourceStatistics::single(FrameSourceKind::RenderTarget),
778            },
779            FrameItem::Target {
780                target,
781                blend_mode,
782                opacity,
783                options,
784                insertion: self.next_insertion,
785            },
786        )
787    }
788
789    /// Returns conservative work accepted so far without presenting it.
790    pub const fn planned_statistics(&self) -> FrameStatistics {
791        self.planned
792    }
793
794    /// Validates, orders, encodes, submits, and presents the complete frame.
795    pub fn present(self) -> Result<FrameReport, FrameComposerError> {
796        super::present::present_frame(self)
797    }
798
799    fn push_item(
800        &mut self,
801        work: FrameStatistics,
802        item: FrameItem<'frame>,
803    ) -> Result<(), FrameComposerError> {
804        let planned = self.planned.adding(work);
805        validate_frame_budget(self.budget, planned)?;
806        self.items
807            .try_reserve(1)
808            .map_err(|_| FrameComposerError::AllocationFailed {
809                requested_bytes: std::mem::size_of::<FrameItem<'frame>>(),
810            })?;
811        self.items.push(item);
812        self.planned = planned;
813        self.next_insertion = self.next_insertion.saturating_add(1);
814        Ok(())
815    }
816
817    fn push_accounted_item(
818        &mut self,
819        resources: &[RetainedResourceAccounting],
820        mut work: FrameStatistics,
821        item: FrameItem<'frame>,
822    ) -> Result<(), FrameComposerError> {
823        let (accounted_work, missing) =
824            account_new_retained_resources(&self.retained_resources, resources, work);
825        work = accounted_work;
826        self.retained_resources.try_reserve(missing).map_err(|_| {
827            FrameComposerError::AllocationFailed {
828                requested_bytes: missing.saturating_mul(std::mem::size_of::<RetainedResourceKey>()),
829            }
830        })?;
831        self.push_item(work, item)?;
832        for resource in resources {
833            if !self.retained_resources.contains(&resource.key) {
834                self.retained_resources.push(resource.key);
835            }
836        }
837        Ok(())
838    }
839}