Skip to main content

sim_engine/renderer/
mod.rs

1use std::{
2    borrow::Cow,
3    error::Error,
4    fmt,
5    ops::Range,
6    sync::{Arc, Mutex},
7    time::{Duration, Instant},
8};
9
10use crate::{
11    Camera2d, Circle, Color, ColorMap, DrawCommand, Fill, Line, LogicalScreenPosition,
12    LogicalViewport, LogicalViewportRegion, ParticleInstance2d, PhysicalPerLogical,
13    PhysicalScreenPosition, Polyline, PrimitiveCommandCounts, Rect, ScalarField, Scene,
14    SceneBudgetResource, ScreenClipRect, ScreenScene, Shadow, ShapeStyle, Stroke, Vec2,
15    scene::{CIRCLE_SEGMENTS, CORNER_SEGMENTS, ROUND_CAP_SEGMENTS, TESSELLATED_VERTEX_BYTES},
16    screen::screen_camera,
17};
18use config::select_surface_present_mode;
19
20const INITIAL_VERTEX_CAPACITY: usize = 4096;
21const PREFERRED_SAMPLE_COUNT: u32 = 4;
22const COLOR_MAP_LUT_SIZE: u32 = 256;
23// Stay inside the WGSL division accuracy domain and reject denormal geometric
24// operands. This deliberately narrow transform envelope is shared by every GPU path.
25const MAX_PORTABLE_SHADER_VALUE: f32 = f32::from_bits((247_u32) << 23); // 2^120
26
27fn is_portable_shader_source(value: f32) -> bool {
28    value.is_finite()
29        && value.abs() <= MAX_PORTABLE_SHADER_VALUE
30        && (value == 0.0 || value.abs() >= f32::MIN_POSITIVE)
31}
32
33#[repr(C)]
34#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
35struct Vertex {
36    world_position: [f32; 2],
37    depth: f32,
38    world_offset: [f32; 2],
39    screen_offset: [f32; 2],
40    previous_direction: [f32; 2],
41    next_direction: [f32; 2],
42    normal_distance: f32,
43    tangent_distance: f32,
44    miter_limit: f32,
45    stroke_role: f32,
46    stroke_parameter: f32,
47    color: [f32; 4],
48}
49
50const _: () = assert!(std::mem::size_of::<Vertex>() == TESSELLATED_VERTEX_BYTES);
51
52#[repr(C)]
53#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
54struct DynamicGpu {
55    world_position: [f32; 2],
56    depth: f32,
57    color: [f32; 4],
58}
59
60#[repr(C)]
61#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
62struct CameraUniform {
63    camera_center: [f32; 4],
64    world_to_screen_x: [f32; 4],
65    world_to_screen_y: [f32; 4],
66    screen_to_clip: [f32; 4],
67}
68
69#[repr(C)]
70#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
71struct HeatmapUniform {
72    value_range: [f32; 4],
73    dimensions: [u32; 4],
74    destination: [f32; 4],
75}
76
77impl HeatmapUniform {
78    fn new(
79        minimum: f32,
80        value_extent: f32,
81        width: usize,
82        height: usize,
83        sampling: ScalarFieldSampling,
84    ) -> Self {
85        Self {
86            value_range: [minimum, value_extent, 0.0, 0.0],
87            dimensions: [width as u32, height as u32, sampling.shader_value(), 0],
88            destination: [1.0, 1.0, 0.0, 0.0],
89        }
90    }
91
92    fn in_region(mut self, region: LogicalViewportRegion, target: LogicalViewport) -> Option<Self> {
93        let destination = CompositeUniform::in_region(1.0, region, target)?.destination;
94        self.destination = destination;
95        Some(self)
96    }
97}
98
99#[repr(C)]
100#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
101struct CompositeUniform {
102    opacity: [f32; 4],
103    destination: [f32; 4],
104}
105
106impl CompositeUniform {
107    const fn full_surface(opacity: f32) -> Self {
108        Self {
109            opacity: [opacity, 0.0, 0.0, 0.0],
110            destination: [1.0, 1.0, 0.0, 0.0],
111        }
112    }
113
114    fn in_region(
115        opacity: f32,
116        region: LogicalViewportRegion,
117        target: LogicalViewport,
118    ) -> Option<Self> {
119        let origin = region.origin().to_vec2();
120        let viewport = region.viewport();
121        let scale_x = viewport.width() / target.width();
122        let scale_y = viewport.height() / target.height();
123        let offset_x = (origin.x.mul_add(2.0, viewport.width())) / target.width() - 1.0;
124        let offset_y = 1.0 - (origin.y.mul_add(2.0, viewport.height())) / target.height();
125        [scale_x, scale_y, offset_x, offset_y]
126            .into_iter()
127            .all(f32::is_finite)
128            .then_some(Self {
129                opacity: [opacity, 0.0, 0.0, 0.0],
130                destination: [scale_x, scale_y, offset_x, offset_y],
131            })
132    }
133}
134
135/// Scalar-field sampling mode used by heatmap rendering.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
137pub enum ScalarFieldSampling {
138    /// Select one exact source texel for each output fragment.
139    #[default]
140    Nearest,
141    /// Bilinearly interpolate neighboring source texels in shader math.
142    Linear,
143}
144
145impl ScalarFieldSampling {
146    fn shader_value(self) -> u32 {
147        match self {
148            Self::Nearest => 0,
149            Self::Linear => 1,
150        }
151    }
152}
153
154/// How a render target is combined with the presentation surface.
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
156pub enum BlendMode {
157    /// Standard source-alpha compositing.
158    #[default]
159    Alpha,
160    /// Adds source light to the existing destination, useful for glow and trails.
161    Additive,
162    /// Replaces destination pixels with the source target.
163    Replace,
164}
165
166/// How a target-rendering pass initializes its destination pixels.
167#[derive(Debug, Clone, Copy, PartialEq)]
168pub enum RenderTargetLoad {
169    /// Preserve existing target pixels and blend new geometry over them.
170    Load,
171    /// Clear the target to normalized finite straight-linear RGBA before drawing.
172    Clear(Color),
173}
174
175#[derive(Debug, Clone, Copy)]
176struct GeometryExtents {
177    world_min: Vec2,
178    world_max: Vec2,
179    world_offset_min: Vec2,
180    world_offset_max: Vec2,
181    depth_min: f32,
182    depth_max: f32,
183    direction_min: Vec2,
184    direction_max: Vec2,
185    screen_offset_max_abs: Vec2,
186    normal_distance_max_abs: f32,
187    tangent_distance_max_abs: f32,
188    miter_limit_max: f32,
189    vertex_count: usize,
190    empty: bool,
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194struct ScissorRect {
195    x: u32,
196    y: u32,
197    width: u32,
198    height: u32,
199}
200
201#[derive(Debug, Clone, Copy)]
202struct ParticleDrawPreparation {
203    camera_uniform: CameraUniform,
204    visible_count: usize,
205    statistics: ParticleStatistics,
206}
207
208#[derive(Debug, Clone, PartialEq)]
209struct PreparedDrawBatch {
210    vertex_range: Range<u32>,
211    screen_clip: Option<ScreenClipRect>,
212}
213
214/// Outcome of converting accepted scene commands into GPU vertices.
215///
216/// A dropped command had finite source fields but produced no finite triangle
217/// vertices, usually because arithmetic overflowed while expanding geometry.
218/// Hosts can surface this separately from presentation success.
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
220pub struct TessellationStats {
221    command_count: usize,
222    rendered_command_count: usize,
223    dropped_command_count: usize,
224    command_counts: PrimitiveCommandCounts,
225    rendered_counts: PrimitiveCommandCounts,
226    dropped_counts: PrimitiveCommandCounts,
227    vertex_count: usize,
228    draw_batch_count: usize,
229    upload_bytes: usize,
230}
231
232impl TessellationStats {
233    /// Returns accepted source commands examined by the tessellator.
234    pub fn command_count(self) -> usize {
235        self.command_count
236    }
237
238    /// Returns source commands that emitted finite triangle vertices.
239    pub fn rendered_command_count(self) -> usize {
240        self.rendered_command_count
241    }
242
243    /// Returns source commands discarded because tessellation emitted no valid geometry.
244    pub fn dropped_command_count(self) -> usize {
245        self.dropped_command_count
246    }
247
248    /// Returns accepted commands examined, grouped by primitive category.
249    pub const fn command_counts(self) -> PrimitiveCommandCounts {
250        self.command_counts
251    }
252
253    /// Returns commands that emitted geometry, grouped by primitive category.
254    pub const fn rendered_counts(self) -> PrimitiveCommandCounts {
255        self.rendered_counts
256    }
257
258    /// Returns commands that emitted no geometry, grouped by primitive category.
259    pub const fn dropped_counts(self) -> PrimitiveCommandCounts {
260        self.dropped_counts
261    }
262
263    /// Returns finite triangle-list vertices generated for this scene.
264    pub fn vertex_count(self) -> usize {
265        self.vertex_count
266    }
267
268    /// Returns draw batches generated after compatible adjacent commands merge.
269    pub fn draw_batch_count(self) -> usize {
270        self.draw_batch_count
271    }
272
273    /// Returns bytes required to upload the generated vertices.
274    pub fn upload_bytes(self) -> usize {
275        self.upload_bytes
276    }
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280enum TessellationError {
281    AllocationFailed {
282        requested_bytes: usize,
283    },
284    CapacityTooLarge,
285    BudgetExceeded {
286        resource: SceneBudgetResource,
287        limit: usize,
288        actual: usize,
289    },
290}
291
292impl Vertex {
293    const ATTRIBUTES: [wgpu::VertexAttribute; 12] = wgpu::vertex_attr_array![
294        0 => Float32x2,
295        1 => Float32,
296        2 => Float32x2,
297        3 => Float32x2,
298        4 => Float32x2,
299        5 => Float32x2,
300        6 => Float32,
301        7 => Float32,
302        8 => Float32,
303        9 => Float32,
304        10 => Float32,
305        11 => Float32x4
306    ];
307
308    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
309        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
310        step_mode: wgpu::VertexStepMode::Vertex,
311        attributes: &Self::ATTRIBUTES,
312    };
313
314    fn is_finite(self) -> bool {
315        self.world_position.iter().all(|value| value.is_finite())
316            && self.depth.is_finite()
317            && self.world_offset.iter().all(|value| value.is_finite())
318            && self.screen_offset.iter().all(|value| value.is_finite())
319            && self
320                .previous_direction
321                .iter()
322                .all(|value| value.is_finite())
323            && self.next_direction.iter().all(|value| value.is_finite())
324            && self.normal_distance.is_finite()
325            && self.tangent_distance.is_finite()
326            && self.miter_limit.is_finite()
327            && self.stroke_role.is_finite()
328            && self.stroke_parameter.is_finite()
329            && self.color.iter().all(|value| value.is_finite())
330    }
331}
332
333impl DynamicGpu {
334    const ATTRIBUTES: [wgpu::VertexAttribute; 3] =
335        wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32, 2 => Float32x4];
336
337    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
338        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
339        step_mode: wgpu::VertexStepMode::Vertex,
340        attributes: &Self::ATTRIBUTES,
341    };
342}
343
344#[repr(C)]
345#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
346struct ParticleUnitVertex {
347    direction: [f32; 2],
348}
349
350impl ParticleUnitVertex {
351    const ATTRIBUTES: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![0 => Float32x2];
352
353    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
354        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
355        step_mode: wgpu::VertexStepMode::Vertex,
356        attributes: &Self::ATTRIBUTES,
357    };
358}
359
360#[repr(C)]
361#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
362struct ParticleGpu {
363    world_position: [f32; 2],
364    depth: f32,
365    radius: f32,
366    color: [f32; 4],
367}
368
369impl ParticleGpu {
370    const ATTRIBUTES: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
371        1 => Float32x2,
372        2 => Float32,
373        3 => Float32,
374        4 => Float32x4
375    ];
376
377    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
378        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
379        step_mode: wgpu::VertexStepMode::Instance,
380        attributes: &Self::ATTRIBUTES,
381    };
382
383    #[cfg(test)]
384    fn screen_position(self, camera: CameraUniform) -> Vec2 {
385        let relative_x = self.world_position[0] - camera.camera_center[0];
386        let relative_y = self.world_position[1] - camera.camera_center[1];
387        Vec2::new(
388            camera.world_to_screen_x[0] * relative_x
389                + camera.world_to_screen_x[1] * relative_y
390                + camera.world_to_screen_x[2] * self.depth
391                + camera.world_to_screen_x[3],
392            camera.world_to_screen_y[0] * relative_x
393                + camera.world_to_screen_y[1] * relative_y
394                + camera.world_to_screen_y[2] * self.depth
395                + camera.world_to_screen_y[3],
396        )
397    }
398
399    fn is_safe_for(self, camera: CameraUniform, viewport: LogicalViewport) -> bool {
400        self.validated_viewport_intersection(camera, viewport)
401            .is_some()
402    }
403
404    fn transform_sources_are_portable(self) -> bool {
405        self.world_position
406            .into_iter()
407            .chain([self.depth, self.radius])
408            .all(is_portable_shader_source)
409    }
410
411    fn projected_screen_bounds(self, camera: CameraUniform) -> Option<((f64, f64), (f64, f64))> {
412        let center = self.projected_screen_center_bounds(camera)?;
413        let radius = f64::from(self.radius);
414        Some((
415            shader_interval_sum_range([center.0, (-radius, radius)])?,
416            shader_interval_sum_range([center.1, (-radius, radius)])?,
417        ))
418    }
419
420    fn projected_screen_center_bounds(
421        self,
422        camera: CameraUniform,
423    ) -> Option<((f64, f64), (f64, f64))> {
424        let relative_x = shader_relative_component_bounds(
425            self.world_position[0],
426            self.world_position[0],
427            camera.camera_center[0],
428            0.0,
429            0.0,
430        )?;
431        let relative_y = shader_relative_component_bounds(
432            self.world_position[1],
433            self.world_position[1],
434            camera.camera_center[1],
435            0.0,
436            0.0,
437        )?;
438        let relative_minimum = [relative_x.0, relative_y.0];
439        let relative_maximum = [relative_x.1, relative_y.1];
440        Some((
441            shader_world_dot_range(
442                camera.world_to_screen_x,
443                relative_minimum,
444                relative_maximum,
445                self.depth,
446                self.depth,
447            )?,
448            shader_world_dot_range(
449                camera.world_to_screen_y,
450                relative_minimum,
451                relative_maximum,
452                self.depth,
453                self.depth,
454            )?,
455        ))
456    }
457
458    fn screen_bounds_intersect_viewport(
459        bounds: ((f64, f64), (f64, f64)),
460        viewport: LogicalViewport,
461    ) -> bool {
462        bounds.0.1 >= 0.0
463            && bounds.0.0 <= f64::from(viewport.width())
464            && bounds.1.1 >= 0.0
465            && bounds.1.0 <= f64::from(viewport.height())
466    }
467
468    fn validated_viewport_intersection(
469        self,
470        camera: CameraUniform,
471        viewport: LogicalViewport,
472    ) -> Option<bool> {
473        if !self.transform_sources_are_portable() || !camera.sources_are_portable() {
474            return None;
475        }
476        let center = self.projected_screen_center_bounds(camera)?;
477        if !self.clip_expansion_is_stable(center, camera) {
478            return None;
479        }
480        let radius = f64::from(self.radius);
481        let width = f64::from(viewport.width());
482        let height = f64::from(viewport.height());
483        let wholly_outside = center.0.1 + radius < 0.0
484            || center.0.0 - radius > width
485            || center.1.1 + radius < 0.0
486            || center.1.0 - radius > height;
487        if wholly_outside {
488            return Some(false);
489        }
490        // Every permitted dot/FMA association must leave a positive-area
491        // portion of the quad inside the viewport. If visibility itself can
492        // change between legal shader lowerings, fail closed before upload.
493        let always_intersects = center.0.0 + radius > 0.0
494            && center.0.1 - radius < width
495            && center.1.0 + radius > 0.0
496            && center.1.1 - radius < height;
497        always_intersects.then_some(true)
498    }
499
500    fn clip_expansion_is_stable(
501        self,
502        center: ((f64, f64), (f64, f64)),
503        camera: CameraUniform,
504    ) -> bool {
505        (0..2).all(|axis| {
506            let center_clip = rounded_f32_product_range(
507                center_axis(center, axis),
508                (
509                    f64::from(camera.screen_to_clip[axis]),
510                    f64::from(camera.screen_to_clip[axis]),
511                ),
512            )
513            .and_then(|scaled| {
514                rounded_f32_add_range(
515                    scaled,
516                    (
517                        f64::from(camera.screen_to_clip[axis + 2]),
518                        f64::from(camera.screen_to_clip[axis + 2]),
519                    ),
520                    false,
521                )
522            });
523            let extent = rounded_f32_product_range(
524                (f64::from(self.radius), f64::from(self.radius)),
525                (
526                    f64::from(camera.screen_to_clip[axis].abs()),
527                    f64::from(camera.screen_to_clip[axis].abs()),
528                ),
529            );
530            let (Some(center_clip), Some(extent)) = (center_clip, extent) else {
531                return false;
532            };
533            if extent.0 < f64::from(f32::MIN_POSITIVE) {
534                return false;
535            }
536            let Some(negative) = rounded_f32_add_range(center_clip, extent, true) else {
537                return false;
538            };
539            let Some(positive) = rounded_f32_add_range(center_clip, extent, false) else {
540                return false;
541            };
542            positive.0 - negative.1 >= f64::from(f32::MIN_POSITIVE)
543        })
544    }
545
546    fn intersects_viewport(self, camera: CameraUniform, viewport: LogicalViewport) -> bool {
547        // Validation precedes production culling. If this helper is called on
548        // an invalid instance, keep it conservatively instead of silently
549        // dropping geometry based on one CPU association of the shader dot.
550        self.projected_screen_bounds(camera)
551            .is_none_or(|bounds| Self::screen_bounds_intersect_viewport(bounds, viewport))
552    }
553}
554
555fn center_axis(center: ((f64, f64), (f64, f64)), axis: usize) -> (f64, f64) {
556    if axis == 0 { center.0 } else { center.1 }
557}
558
559impl CameraUniform {
560    fn new(camera: Camera2d, viewport: LogicalViewport) -> Option<Self> {
561        Self::new_in_region(camera, viewport, Vec2::ZERO, viewport)
562    }
563
564    fn new_in_region(
565        camera: Camera2d,
566        viewport: LogicalViewport,
567        target_origin: Vec2,
568        target_viewport: LogicalViewport,
569    ) -> Option<Self> {
570        let projection_cosine = camera.projection().tilt().cos();
571        let rotation_cosine = camera.rotation().cos();
572        let rotation_sine = camera.rotation().sin();
573        let zoom = camera.zoom();
574        let center = camera.center();
575        let projection_sine = camera.projection().tilt().sin();
576        let depth_scale = camera.projection().depth_scale();
577
578        let horizontal_x = zoom * rotation_cosine;
579        let horizontal_y = -zoom * rotation_sine * projection_cosine;
580        let vertical_x = -zoom * rotation_sine;
581        let vertical_y = -zoom * rotation_cosine * projection_cosine;
582        let horizontal_depth =
583            zoom * depth_scale * projection_sine * (rotation_cosine * 0.5 - rotation_sine);
584        let vertical_depth =
585            -zoom * depth_scale * projection_sine * (rotation_sine * 0.5 + rotation_cosine);
586
587        let uniform = Self {
588            camera_center: [center.x, center.y, 0.0, 0.0],
589            world_to_screen_x: [
590                horizontal_x,
591                horizontal_y,
592                horizontal_depth,
593                target_origin.x + viewport.width() * 0.5,
594            ],
595            world_to_screen_y: [
596                vertical_x,
597                vertical_y,
598                vertical_depth,
599                target_origin.y + viewport.height() * 0.5,
600            ],
601            screen_to_clip: [
602                2.0 / target_viewport.width(),
603                -2.0 / target_viewport.height(),
604                -1.0,
605                1.0,
606            ],
607        };
608        (uniform.is_finite() && uniform.sources_are_portable()).then_some(uniform)
609    }
610
611    fn sources_are_portable(self) -> bool {
612        self.camera_center
613            .into_iter()
614            .chain(self.world_to_screen_x)
615            .chain(self.world_to_screen_y)
616            .chain(self.screen_to_clip)
617            .all(is_portable_shader_source)
618    }
619
620    fn is_finite(self) -> bool {
621        self.camera_center
622            .iter()
623            .chain(self.world_to_screen_x.iter())
624            .chain(self.world_to_screen_y.iter())
625            .chain(self.screen_to_clip.iter())
626            .all(|value| value.is_finite())
627    }
628
629    fn world_to_screen(self, world: Vec2, depth: f32) -> Vec2 {
630        let relative = world - Vec2::new(self.camera_center[0], self.camera_center[1]);
631        Vec2::new(
632            self.world_to_screen_x[0] * relative.x
633                + self.world_to_screen_x[1] * relative.y
634                + self.world_to_screen_x[2] * depth
635                + self.world_to_screen_x[3],
636            self.world_to_screen_y[0] * relative.x
637                + self.world_to_screen_y[1] * relative.y
638                + self.world_to_screen_y[2] * depth
639                + self.world_to_screen_y[3],
640        )
641    }
642
643    #[cfg(test)]
644    fn direction_to_screen(self, direction: Vec2) -> Vec2 {
645        Vec2::new(
646            self.world_to_screen_x[0] * direction.x + self.world_to_screen_x[1] * direction.y,
647            self.world_to_screen_y[0] * direction.x + self.world_to_screen_y[1] * direction.y,
648        )
649    }
650}
651
652impl GeometryExtents {
653    fn empty(is_empty: bool) -> Self {
654        Self {
655            world_min: Vec2::splat(f32::INFINITY),
656            world_max: Vec2::splat(f32::NEG_INFINITY),
657            world_offset_min: Vec2::splat(f32::INFINITY),
658            world_offset_max: Vec2::splat(f32::NEG_INFINITY),
659            depth_min: f32::INFINITY,
660            depth_max: f32::NEG_INFINITY,
661            direction_min: Vec2::splat(f32::INFINITY),
662            direction_max: Vec2::splat(f32::NEG_INFINITY),
663            screen_offset_max_abs: Vec2::ZERO,
664            normal_distance_max_abs: 0.0,
665            tangent_distance_max_abs: 0.0,
666            miter_limit_max: 1.0,
667            vertex_count: 0,
668            empty: is_empty,
669        }
670    }
671
672    fn include(&mut self, vertex: Vertex) {
673        self.vertex_count += 1;
674        let world = Vec2::new(vertex.world_position[0], vertex.world_position[1]);
675        self.world_min.x = self.world_min.x.min(world.x);
676        self.world_min.y = self.world_min.y.min(world.y);
677        self.world_max.x = self.world_max.x.max(world.x);
678        self.world_max.y = self.world_max.y.max(world.y);
679        let world_offset = Vec2::new(vertex.world_offset[0], vertex.world_offset[1]);
680        self.world_offset_min.x = self.world_offset_min.x.min(world_offset.x);
681        self.world_offset_min.y = self.world_offset_min.y.min(world_offset.y);
682        self.world_offset_max.x = self.world_offset_max.x.max(world_offset.x);
683        self.world_offset_max.y = self.world_offset_max.y.max(world_offset.y);
684        self.depth_min = self.depth_min.min(vertex.depth);
685        self.depth_max = self.depth_max.max(vertex.depth);
686
687        for direction in [vertex.previous_direction, vertex.next_direction] {
688            self.direction_min.x = self.direction_min.x.min(direction[0]);
689            self.direction_min.y = self.direction_min.y.min(direction[1]);
690            self.direction_max.x = self.direction_max.x.max(direction[0]);
691            self.direction_max.y = self.direction_max.y.max(direction[1]);
692        }
693
694        self.screen_offset_max_abs.x = self
695            .screen_offset_max_abs
696            .x
697            .max(vertex.screen_offset[0].abs());
698        self.screen_offset_max_abs.y = self
699            .screen_offset_max_abs
700            .y
701            .max(vertex.screen_offset[1].abs());
702        self.normal_distance_max_abs = self
703            .normal_distance_max_abs
704            .max(vertex.normal_distance.abs());
705        self.tangent_distance_max_abs = self
706            .tangent_distance_max_abs
707            .max(vertex.tangent_distance.abs());
708        self.miter_limit_max = self.miter_limit_max.max(vertex.miter_limit);
709    }
710
711    fn include_dynamic(&mut self, vertex: DynamicGpu) {
712        self.vertex_count += 1;
713        let world = Vec2::new(vertex.world_position[0], vertex.world_position[1]);
714        self.world_min.x = self.world_min.x.min(world.x);
715        self.world_min.y = self.world_min.y.min(world.y);
716        self.world_max.x = self.world_max.x.max(world.x);
717        self.world_max.y = self.world_max.y.max(world.y);
718        self.world_offset_min = Vec2::ZERO;
719        self.world_offset_max = Vec2::ZERO;
720        self.depth_min = self.depth_min.min(vertex.depth);
721        self.depth_max = self.depth_max.max(vertex.depth);
722        self.direction_min = Vec2::ZERO;
723        self.direction_max = Vec2::ZERO;
724    }
725
726    fn from_dynamic_vertices(vertices: &[DynamicGpu]) -> Self {
727        let mut extents = Self::empty(vertices.is_empty());
728        for vertex in vertices {
729            extents.include_dynamic(*vertex);
730        }
731        extents
732    }
733
734    fn from_vertices(vertices: &[Vertex]) -> Self {
735        let mut extents = Self::empty(vertices.is_empty());
736        for vertex in vertices {
737            extents.include(*vertex);
738        }
739
740        extents
741    }
742
743    fn is_safe_for(self, uniform: CameraUniform) -> bool {
744        if self.empty {
745            return true;
746        }
747        let center = Vec2::new(uniform.camera_center[0], uniform.camera_center[1]);
748        // Match the vertex shader's split-anchor operation order. Generated
749        // local offsets are projected separately so they cannot disappear
750        // when their world anchor is much larger than the local geometry.
751        let Some(relative_horizontal) = shader_relative_component_bounds(
752            self.world_min.x,
753            self.world_max.x,
754            center.x,
755            0.0,
756            0.0,
757        ) else {
758            return false;
759        };
760        let Some(relative_vertical) = shader_relative_component_bounds(
761            self.world_min.y,
762            self.world_max.y,
763            center.y,
764            0.0,
765            0.0,
766        ) else {
767            return false;
768        };
769        let relative_minimum = [relative_horizontal.0, relative_vertical.0];
770        let relative_maximum = [relative_horizontal.1, relative_vertical.1];
771        let Some(projected_world_horizontal) = shader_world_dot_range(
772            uniform.world_to_screen_x,
773            relative_minimum,
774            relative_maximum,
775            self.depth_min,
776            self.depth_max,
777        ) else {
778            return false;
779        };
780        let Some(projected_world_vertical) = shader_world_dot_range(
781            uniform.world_to_screen_y,
782            relative_minimum,
783            relative_maximum,
784            self.depth_min,
785            self.depth_max,
786        ) else {
787            return false;
788        };
789        let Some(projected_offset_horizontal) = shader_direction_dot_range(
790            uniform.world_to_screen_x,
791            self.world_offset_min,
792            self.world_offset_max,
793        ) else {
794            return false;
795        };
796        let Some(projected_offset_vertical) = shader_direction_dot_range(
797            uniform.world_to_screen_y,
798            self.world_offset_min,
799            self.world_offset_max,
800        ) else {
801            return false;
802        };
803        let Some(world_horizontal) =
804            shader_interval_sum_range([projected_world_horizontal, projected_offset_horizontal])
805        else {
806            return false;
807        };
808        let Some(world_vertical) =
809            shader_interval_sum_range([projected_world_vertical, projected_offset_vertical])
810        else {
811            return false;
812        };
813        let Some(direction_horizontal) = shader_direction_dot_range(
814            uniform.world_to_screen_x,
815            self.direction_min,
816            self.direction_max,
817        ) else {
818            return false;
819        };
820        let Some(direction_vertical) = shader_direction_dot_range(
821            uniform.world_to_screen_y,
822            self.direction_min,
823            self.direction_max,
824        ) else {
825            return false;
826        };
827        if [
828            self.screen_offset_max_abs.x,
829            self.screen_offset_max_abs.y,
830            self.normal_distance_max_abs,
831            self.tangent_distance_max_abs,
832        ]
833        .into_iter()
834        .any(is_nonzero_subnormal)
835        {
836            return false;
837        }
838        let Some(horizontal_bounds) = shader_stroke_screen_bounds(
839            world_horizontal,
840            self.screen_offset_max_abs.x,
841            self.normal_distance_max_abs,
842            self.tangent_distance_max_abs,
843            self.miter_limit_max,
844        ) else {
845            return false;
846        };
847        let Some(vertical_bounds) = shader_stroke_screen_bounds(
848            world_vertical,
849            self.screen_offset_max_abs.y,
850            self.normal_distance_max_abs,
851            self.tangent_distance_max_abs,
852            self.miter_limit_max,
853        ) else {
854            return false;
855        };
856
857        if !shader_clip_interval_is_safe(
858            horizontal_bounds.0,
859            horizontal_bounds.1,
860            uniform.screen_to_clip[0],
861            uniform.screen_to_clip[2],
862        ) || !shader_clip_interval_is_safe(
863            vertical_bounds.0,
864            vertical_bounds.1,
865            uniform.screen_to_clip[1],
866            uniform.screen_to_clip[3],
867        ) {
868            return false;
869        }
870
871        [
872            world_horizontal.0,
873            world_horizontal.1,
874            world_vertical.0,
875            world_vertical.1,
876            direction_horizontal.0,
877            direction_horizontal.1,
878            direction_vertical.0,
879            direction_vertical.1,
880            horizontal_bounds.0,
881            horizontal_bounds.1,
882            vertical_bounds.0,
883            vertical_bounds.1,
884        ]
885        .into_iter()
886        .all(|value| value.is_finite() && value.abs() <= f32::MAX as f64)
887    }
888}
889
890fn shader_stroke_screen_bounds(
891    world_screen: (f64, f64),
892    screen_offset_max_abs: f32,
893    normal_distance_max_abs: f32,
894    tangent_distance_max_abs: f32,
895    miter_limit_max: f32,
896) -> Option<(f64, f64)> {
897    // `safe_unit` and the miter path are backend-selected inverse-square-root
898    // arithmetic. A component of a mathematically unit vector is at most one;
899    // two is a deliberately loose portable bound that also contains its
900    // permitted approximation error. Propagate the shader's two additions
901    // separately so a tiny later clip scale cannot hide screen-space overflow.
902    const UNIT_COMPONENT_BOUND: f64 = 2.0;
903    let normal = f64::from(normal_distance_max_abs);
904    let tangent = f64::from(tangent_distance_max_abs);
905    let miter = normal * f64::from(miter_limit_max.max(1.0));
906    let normal_component = UNIT_COMPONENT_BOUND * normal.max(miter);
907    let tangent_component = UNIT_COMPONENT_BOUND * tangent;
908    let extrusion = shader_interval_sum_range([
909        (-normal_component, normal_component),
910        (-tangent_component, tangent_component),
911    ])?;
912    let offset = f64::from(screen_offset_max_abs);
913    shader_interval_sum_range([world_screen, extrusion, (-offset, offset)])
914}
915
916#[derive(Clone, Copy)]
917enum GeometryValidationSource<'a> {
918    Tessellated(&'a [Vertex]),
919    Dynamic(&'a [DynamicGpu]),
920}
921
922const GEOMETRY_VALIDATION_CACHE_CAPACITY: usize = 8;
923
924#[derive(Clone, Copy)]
925struct GeometryValidationCacheEntry {
926    uniform: CameraUniform,
927    safe: bool,
928}
929
930struct GeometryValidationCacheState {
931    entries: [Option<GeometryValidationCacheEntry>; GEOMETRY_VALIDATION_CACHE_CAPACITY],
932    next: usize,
933}
934
935impl Default for GeometryValidationCacheState {
936    fn default() -> Self {
937        Self {
938            entries: [None; GEOMETRY_VALIDATION_CACHE_CAPACITY],
939            next: 0,
940        }
941    }
942}
943
944#[derive(Default)]
945struct GeometryValidationCache {
946    state: Mutex<GeometryValidationCacheState>,
947}
948
949impl GeometryValidationCache {
950    fn validate(
951        &self,
952        extents: GeometryExtents,
953        source: GeometryValidationSource<'_>,
954        uniform: CameraUniform,
955    ) -> bool {
956        {
957            let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
958            if let Some(entry) = state
959                .entries
960                .iter()
961                .flatten()
962                .find(|entry| entry.uniform == uniform)
963            {
964                return entry.safe;
965            }
966        }
967
968        let safe = geometry_is_safe_for(extents, source, uniform);
969        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
970        if let Some(entry) = state
971            .entries
972            .iter()
973            .flatten()
974            .find(|entry| entry.uniform == uniform)
975        {
976            return entry.safe;
977        }
978        let next = state.next;
979        state.entries[next] = Some(GeometryValidationCacheEntry { uniform, safe });
980        state.next = (next + 1) % GEOMETRY_VALIDATION_CACHE_CAPACITY;
981        safe
982    }
983
984    fn clear(&mut self) {
985        let state = self
986            .state
987            .get_mut()
988            .unwrap_or_else(|error| error.into_inner());
989        *state = GeometryValidationCacheState::default();
990    }
991}
992
993fn geometry_is_safe_for_cached(
994    cache: Option<&GeometryValidationCache>,
995    extents: GeometryExtents,
996    source: GeometryValidationSource<'_>,
997    uniform: CameraUniform,
998) -> bool {
999    cache.map_or_else(
1000        || geometry_is_safe_for(extents, source, uniform),
1001        |cache| cache.validate(extents, source, uniform),
1002    )
1003}
1004
1005fn geometry_is_safe_for(
1006    extents: GeometryExtents,
1007    source: GeometryValidationSource<'_>,
1008    uniform: CameraUniform,
1009) -> bool {
1010    geometry_sources_are_portable(source)
1011        && match source {
1012            GeometryValidationSource::Tessellated(vertices) => {
1013                geometry::tessellated_topology_is_portable(vertices, uniform)
1014                    && vertices
1015                        .iter()
1016                        .all(|vertex| logical_stroke_branches_are_stable(*vertex, uniform))
1017            }
1018            GeometryValidationSource::Dynamic(vertices) => {
1019                // The triangle proof projects every vertex itself, so do not
1020                // duplicate the same per-vertex dot envelopes first.
1021                dynamic_triangle_topology_is_portable(vertices, uniform)
1022            }
1023        }
1024        && uniform.sources_are_portable()
1025        && extents.is_safe_for(uniform)
1026}
1027
1028fn dynamic_triangle_topology_is_portable(vertices: &[DynamicGpu], uniform: CameraUniform) -> bool {
1029    if !vertices.len().is_multiple_of(3) {
1030        return false;
1031    }
1032    let minimum_normal = f64::from(f32::MIN_POSITIVE);
1033    for triangle in vertices.chunks_exact(3) {
1034        let Some(first) = dynamic_vertex_clip_ranges(triangle[0], uniform) else {
1035            return false;
1036        };
1037        let Some(second) = dynamic_vertex_clip_ranges(triangle[1], uniform) else {
1038            return false;
1039        };
1040        let Some(third) = dynamic_vertex_clip_ranges(triangle[2], uniform) else {
1041            return false;
1042        };
1043        let clip = [first, second, third];
1044        if clip_triangle_is_wholly_outside(clip) {
1045            continue;
1046        }
1047        if !clip_triangle_is_wholly_inside(clip) {
1048            // v0.2 does not yet carry conservative interval polygons through
1049            // hardware clipping. Reject partially clipped dynamic triangles
1050            // rather than permit backend-selected topology.
1051            return false;
1052        }
1053        if !clip_triangle_has_stable_signed_area(clip, minimum_normal) {
1054            return false;
1055        }
1056    }
1057    true
1058}
1059
1060// Frozen pre-optimization topology reference for differential regression tests.
1061#[cfg(test)]
1062fn tessellated_triangle_topology_is_portable(vertices: &[Vertex], uniform: CameraUniform) -> bool {
1063    if !vertices.len().is_multiple_of(3) {
1064        return false;
1065    }
1066    let minimum_normal = f64::from(f32::MIN_POSITIVE);
1067    for triangle in vertices.chunks_exact(3) {
1068        let has_shader_extrusion = !triangle.iter().all(|vertex| {
1069            vertex.normal_distance == 0.0
1070                && vertex.tangent_distance == 0.0
1071                && vertex.stroke_role >= 0.0
1072        });
1073        if has_shader_extrusion {
1074            let Some(first) = logical_stroke_vertex_screen_ranges(triangle[0], uniform) else {
1075                return false;
1076            };
1077            let Some(second) = logical_stroke_vertex_screen_ranges(triangle[1], uniform) else {
1078                return false;
1079            };
1080            let Some(third) = logical_stroke_vertex_screen_ranges(triangle[2], uniform) else {
1081                return false;
1082            };
1083            if [first, second, third].iter().all(|output| output.1)
1084                && triangle_position_sources_equal(triangle)
1085            {
1086                continue;
1087            }
1088            let Some(first) = screen_ranges_to_clip(first.0, uniform) else {
1089                return false;
1090            };
1091            let Some(second) = screen_ranges_to_clip(second.0, uniform) else {
1092                return false;
1093            };
1094            let Some(third) = screen_ranges_to_clip(third.0, uniform) else {
1095                return false;
1096            };
1097            let clip = [first, second, third];
1098            if !clip_triangle_is_wholly_outside(clip)
1099                && !clip_triangle_has_stable_signed_area(clip, minimum_normal)
1100            {
1101                return false;
1102            }
1103            continue;
1104        }
1105        let Some(first) = tessellated_vertex_clip_ranges(triangle[0], uniform) else {
1106            return false;
1107        };
1108        let Some(second) = tessellated_vertex_clip_ranges(triangle[1], uniform) else {
1109            return false;
1110        };
1111        let Some(third) = tessellated_vertex_clip_ranges(triangle[2], uniform) else {
1112            return false;
1113        };
1114        let clip = [first, second, third];
1115        if clip_triangle_is_wholly_outside(clip) {
1116            continue;
1117        }
1118        if !clip_triangle_has_stable_signed_area(clip, minimum_normal) {
1119            return false;
1120        }
1121    }
1122    true
1123}
1124
1125fn clip_triangle_is_wholly_outside(clip: [[(f64, f64); 2]; 3]) -> bool {
1126    (0..2).any(|axis| {
1127        clip.iter().all(|point| point[axis].1 < -1.0)
1128            || clip.iter().all(|point| point[axis].0 > 1.0)
1129    })
1130}
1131
1132fn clip_triangle_is_wholly_inside(clip: [[(f64, f64); 2]; 3]) -> bool {
1133    clip.iter()
1134        .all(|point| point.iter().all(|axis| axis.0 >= -1.0 && axis.1 <= 1.0))
1135}
1136
1137fn clip_triangle_has_stable_signed_area(
1138    clip: [[(f64, f64); 2]; 3],
1139    minimum_magnitude: f64,
1140) -> bool {
1141    let Some(first_x) = shader_interval_difference(clip[1][0], clip[0][0]) else {
1142        return false;
1143    };
1144    let Some(first_y) = shader_interval_difference(clip[2][1], clip[0][1]) else {
1145        return false;
1146    };
1147    let Some(second_y) = shader_interval_difference(clip[1][1], clip[0][1]) else {
1148        return false;
1149    };
1150    let Some(second_x) = shader_interval_difference(clip[2][0], clip[0][0]) else {
1151        return false;
1152    };
1153    let Some(positive) = shader_interval_product(first_x, first_y) else {
1154        return false;
1155    };
1156    let Some(negative) = shader_interval_product(second_y, second_x) else {
1157        return false;
1158    };
1159    let Some(area) = shader_interval_difference(positive, negative) else {
1160        return false;
1161    };
1162    area.0 >= minimum_magnitude || area.1 <= -minimum_magnitude
1163}
1164
1165fn dynamic_vertex_clip_ranges(
1166    vertex: DynamicGpu,
1167    uniform: CameraUniform,
1168) -> Option<[(f64, f64); 2]> {
1169    let relative_x = shader_relative_component_bounds(
1170        vertex.world_position[0],
1171        vertex.world_position[0],
1172        uniform.camera_center[0],
1173        0.0,
1174        0.0,
1175    )?;
1176    let relative_y = shader_relative_component_bounds(
1177        vertex.world_position[1],
1178        vertex.world_position[1],
1179        uniform.camera_center[1],
1180        0.0,
1181        0.0,
1182    )?;
1183    let minimum = [relative_x.0, relative_y.0];
1184    let maximum = [relative_x.1, relative_y.1];
1185    let screen = [
1186        shader_world_dot_range(
1187            uniform.world_to_screen_x,
1188            minimum,
1189            maximum,
1190            vertex.depth,
1191            vertex.depth,
1192        )?,
1193        shader_world_dot_range(
1194            uniform.world_to_screen_y,
1195            minimum,
1196            maximum,
1197            vertex.depth,
1198            vertex.depth,
1199        )?,
1200    ];
1201    screen_ranges_to_clip(screen, uniform)
1202}
1203
1204#[cfg(test)]
1205fn tessellated_vertex_clip_ranges(
1206    vertex: Vertex,
1207    uniform: CameraUniform,
1208) -> Option<[(f64, f64); 2]> {
1209    screen_ranges_to_clip(tessellated_vertex_screen_ranges(vertex, uniform)?, uniform)
1210}
1211
1212#[cfg(test)]
1213fn tessellated_vertex_screen_ranges(
1214    vertex: Vertex,
1215    uniform: CameraUniform,
1216) -> Option<[(f64, f64); 2]> {
1217    let base = tessellated_vertex_base_screen_ranges(vertex, uniform)?;
1218    Some([
1219        rounded_f32_add_range(
1220            base[0],
1221            (
1222                f64::from(vertex.screen_offset[0]),
1223                f64::from(vertex.screen_offset[0]),
1224            ),
1225            false,
1226        )?,
1227        rounded_f32_add_range(
1228            base[1],
1229            (
1230                f64::from(vertex.screen_offset[1]),
1231                f64::from(vertex.screen_offset[1]),
1232            ),
1233            false,
1234        )?,
1235    ])
1236}
1237
1238fn tessellated_vertex_base_screen_ranges(
1239    vertex: Vertex,
1240    uniform: CameraUniform,
1241) -> Option<[(f64, f64); 2]> {
1242    let relative_x = shader_relative_component_bounds(
1243        vertex.world_position[0],
1244        vertex.world_position[0],
1245        uniform.camera_center[0],
1246        0.0,
1247        0.0,
1248    )?;
1249    let relative_y = shader_relative_component_bounds(
1250        vertex.world_position[1],
1251        vertex.world_position[1],
1252        uniform.camera_center[1],
1253        0.0,
1254        0.0,
1255    )?;
1256    let minimum = [relative_x.0, relative_y.0];
1257    let maximum = [relative_x.1, relative_y.1];
1258    let world_offset = Vec2::new(vertex.world_offset[0], vertex.world_offset[1]);
1259    Some([
1260        shader_interval_sum_range([
1261            shader_world_dot_range(
1262                uniform.world_to_screen_x,
1263                minimum,
1264                maximum,
1265                vertex.depth,
1266                vertex.depth,
1267            )?,
1268            shader_direction_dot_range(uniform.world_to_screen_x, world_offset, world_offset)?,
1269        ])?,
1270        shader_interval_sum_range([
1271            shader_world_dot_range(
1272                uniform.world_to_screen_y,
1273                minimum,
1274                maximum,
1275                vertex.depth,
1276                vertex.depth,
1277            )?,
1278            shader_direction_dot_range(uniform.world_to_screen_y, world_offset, world_offset)?,
1279        ])?,
1280    ])
1281}
1282
1283fn triangle_position_sources_equal(triangle: &[Vertex]) -> bool {
1284    triangle.windows(2).all(|pair| {
1285        pair[0].world_position == pair[1].world_position
1286            && pair[0].depth == pair[1].depth
1287            && pair[0].world_offset == pair[1].world_offset
1288            && pair[0].screen_offset == pair[1].screen_offset
1289    })
1290}
1291
1292fn logical_stroke_vertex_screen_ranges(
1293    vertex: Vertex,
1294    uniform: CameraUniform,
1295) -> Option<([(f64, f64); 2], bool)> {
1296    if vertex.stroke_role < 0.0 {
1297        return exact_markers::vertex_screen_ranges(vertex, uniform);
1298    }
1299    let base = tessellated_vertex_base_screen_ranges(vertex, uniform)?;
1300    let previous_source = Vec2::new(vertex.previous_direction[0], vertex.previous_direction[1]);
1301    let next_source = Vec2::new(vertex.next_direction[0], vertex.next_direction[1]);
1302    let previous_projected = [
1303        shader_direction_dot_range(uniform.world_to_screen_x, previous_source, previous_source)?,
1304        shader_direction_dot_range(uniform.world_to_screen_y, previous_source, previous_source)?,
1305    ];
1306    let next_projected = if vertex.previous_direction == vertex.next_direction {
1307        previous_projected
1308    } else {
1309        [
1310            shader_direction_dot_range(uniform.world_to_screen_x, next_source, next_source)?,
1311            shader_direction_dot_range(uniform.world_to_screen_y, next_source, next_source)?,
1312        ]
1313    };
1314    let previous_tangent = stroke_safe_unit_range(previous_projected)?;
1315    let next_tangent = if vertex.previous_direction == vertex.next_direction {
1316        previous_tangent
1317    } else {
1318        stroke_safe_unit_range(next_projected)?
1319    };
1320    let previous_normal = [range_negate(previous_tangent[1]), previous_tangent[0]];
1321    let next_normal = [range_negate(next_tangent[1]), next_tangent[0]];
1322    let turn = if vertex.previous_direction == vertex.next_direction {
1323        (0.0, 0.0)
1324    } else {
1325        rounded_f32_add_range(
1326            rounded_f32_product_range(previous_tangent[0], next_tangent[1])?,
1327            rounded_f32_product_range(previous_tangent[1], next_tangent[0])?,
1328            true,
1329        )?
1330    };
1331    let turn_sign = if turn.0 > 0.0 {
1332        1.0
1333    } else if turn.1 < 0.0 {
1334        -1.0
1335    } else if vertex.previous_direction == vertex.next_direction {
1336        0.0
1337    } else {
1338        return None;
1339    };
1340    let combined_normal = [
1341        rounded_f32_add_range(previous_normal[0], next_normal[0], false)?,
1342        rounded_f32_add_range(previous_normal[1], next_normal[1], false)?,
1343    ];
1344    let miter = stroke_safe_unit_range(combined_normal);
1345    let miter_state = miter.and_then(|miter| {
1346        let denominator = range_dot(miter, next_normal)?;
1347        if denominator.0 <= 0.001 && denominator.1 >= -0.001 {
1348            return None;
1349        }
1350        let reciprocal = rounded_f32_division_range((1.0, 1.0), denominator)?;
1351        let multiple = range_abs(reciprocal);
1352        let limit = f64::from(vertex.miter_limit);
1353        let within_limit = if multiple.1 <= limit {
1354            true
1355        } else if multiple.0 > limit {
1356            false
1357        } else {
1358            return None;
1359        };
1360        let scalar = rounded_f32_product_range(
1361            reciprocal,
1362            (
1363                f64::from(vertex.normal_distance),
1364                f64::from(vertex.normal_distance),
1365            ),
1366        )?;
1367        Some((range_vector_scale(miter, scalar)?, within_limit))
1368    });
1369    let normal_scalar = (
1370        f64::from(vertex.normal_distance),
1371        f64::from(vertex.normal_distance),
1372    );
1373    let tangent_scalar = (
1374        f64::from(vertex.tangent_distance),
1375        f64::from(vertex.tangent_distance),
1376    );
1377    let next_normal_offset = range_vector_scale(next_normal, normal_scalar)?;
1378    let previous_normal_offset = range_vector_scale(previous_normal, normal_scalar)?;
1379    let tangent_offset = range_vector_scale(next_tangent, tangent_scalar)?;
1380    let mut inactive_candidate = false;
1381    let mut extrusion = range_vector_add(next_normal_offset, tangent_offset)?;
1382    if (1.0..=3.0).contains(&vertex.stroke_role) {
1383        if turn_sign == 0.0 {
1384            extrusion = next_normal_offset;
1385        } else {
1386            let side = vertex.normal_distance.signum();
1387            let outer_side = -turn_sign;
1388            if side * outer_side <= 0.0 {
1389                extrusion = miter_state
1390                    .filter(|state| state.1)
1391                    .map_or([(0.0, 0.0); 2], |state| state.0);
1392            } else if vertex.stroke_role == 2.0 && miter_state.is_some_and(|state| state.1) {
1393                extrusion = miter_state?.0;
1394            } else if vertex.stroke_parameter < 0.0 {
1395                extrusion = previous_normal_offset;
1396            } else {
1397                extrusion = next_normal_offset;
1398            }
1399        }
1400        extrusion = range_vector_add(extrusion, tangent_offset)?;
1401    } else if vertex.stroke_role >= 4.0 {
1402        let inner = matches!(vertex.stroke_role as i32, 5 | 7 | 9);
1403        let side = vertex.normal_distance.signum();
1404        let candidate_side = if inner { -side } else { side };
1405        let mut active = turn_sign != 0.0 && candidate_side * -turn_sign > 0.0;
1406        if matches!(vertex.stroke_role as i32, 6 | 7) {
1407            active &= miter_state.is_none_or(|state| !state.1);
1408        }
1409        if !active {
1410            inactive_candidate = true;
1411            extrusion = [(0.0, 0.0); 2];
1412        } else if inner {
1413            extrusion = miter_state
1414                .filter(|state| state.1)
1415                .map_or([(0.0, 0.0); 2], |state| state.0);
1416        } else if vertex.stroke_role == 8.0 {
1417            let side_range = (f64::from(candidate_side), f64::from(candidate_side));
1418            let start = range_vector_scale(previous_normal, side_range)?;
1419            let finish = range_vector_scale(next_normal, side_range)?;
1420            let amount = f64::from(vertex.stroke_parameter);
1421            let mixed = range_vector_add(
1422                range_vector_scale(start, (1.0 - amount, 1.0 - amount))?,
1423                range_vector_scale(finish, (amount, amount))?,
1424            )?;
1425            extrusion = range_vector_scale(
1426                stroke_safe_unit_range(mixed)?,
1427                (
1428                    f64::from(vertex.normal_distance.abs()),
1429                    f64::from(vertex.normal_distance.abs()),
1430                ),
1431            )?;
1432        } else if vertex.stroke_parameter < 0.0 {
1433            extrusion = previous_normal_offset;
1434        } else {
1435            extrusion = next_normal_offset;
1436        }
1437    } else if miter_state.is_some_and(|state| state.1) {
1438        extrusion = range_vector_add(miter_state?.0, tangent_offset)?;
1439    }
1440    let screen = range_vector_add(base, extrusion)?;
1441    let screen_offset = [
1442        (
1443            f64::from(vertex.screen_offset[0]),
1444            f64::from(vertex.screen_offset[0]),
1445        ),
1446        (
1447            f64::from(vertex.screen_offset[1]),
1448            f64::from(vertex.screen_offset[1]),
1449        ),
1450    ];
1451    Some((range_vector_add(screen, screen_offset)?, inactive_candidate))
1452}
1453
1454fn range_vector_add(left: [(f64, f64); 2], right: [(f64, f64); 2]) -> Option<[(f64, f64); 2]> {
1455    Some([
1456        rounded_f32_add_range(left[0], right[0], false)?,
1457        rounded_f32_add_range(left[1], right[1], false)?,
1458    ])
1459}
1460
1461fn range_vector_scale(vector: [(f64, f64); 2], scalar: (f64, f64)) -> Option<[(f64, f64); 2]> {
1462    Some([
1463        rounded_f32_product_range(vector[0], scalar)?,
1464        rounded_f32_product_range(vector[1], scalar)?,
1465    ])
1466}
1467
1468fn range_dot(left: [(f64, f64); 2], right: [(f64, f64); 2]) -> Option<(f64, f64)> {
1469    rounded_f32_add_range(
1470        rounded_f32_product_range(left[0], right[0])?,
1471        rounded_f32_product_range(left[1], right[1])?,
1472        false,
1473    )
1474}
1475
1476fn range_negate(value: (f64, f64)) -> (f64, f64) {
1477    (-value.1, -value.0)
1478}
1479
1480fn range_abs(value: (f64, f64)) -> (f64, f64) {
1481    if value.0 <= 0.0 && value.1 >= 0.0 {
1482        (0.0, value.0.abs().max(value.1.abs()))
1483    } else {
1484        (
1485            value.0.abs().min(value.1.abs()),
1486            value.0.abs().max(value.1.abs()),
1487        )
1488    }
1489}
1490
1491fn stroke_safe_unit_range(direction: [(f64, f64); 2]) -> Option<[(f64, f64); 2]> {
1492    let horizontal_abs = range_abs(direction[0]);
1493    let vertical_abs = range_abs(direction[1]);
1494    let scale = (
1495        horizontal_abs.0.max(vertical_abs.0),
1496        horizontal_abs.1.max(vertical_abs.1),
1497    );
1498    if scale.0 < f64::from(f32::MIN_POSITIVE) {
1499        return None;
1500    }
1501    let scaled = [
1502        rounded_f32_division_range(direction[0], scale)?,
1503        rounded_f32_division_range(direction[1], scale)?,
1504    ];
1505    let length_squared = range_dot(scaled, scaled)?;
1506    if length_squared.0 < f64::from(f32::MIN_POSITIVE) {
1507        return None;
1508    }
1509    let mut inverse_length =
1510        rounded_f32_range(1.0 / length_squared.1.sqrt(), 1.0 / length_squared.0.sqrt())?;
1511    // WGSL permits two ULP error for inverseSqrt. Add two outward neighbours;
1512    // an inexact endpoint may already carry one additional rounding neighbour.
1513    for _ in 0..2 {
1514        inverse_length = (
1515            f64::from(next_f32_down(inverse_length.0 as f32)?),
1516            f64::from(next_f32_up(inverse_length.1 as f32)?),
1517        );
1518    }
1519    range_vector_scale(scaled, inverse_length)
1520}
1521
1522fn rounded_f32_division_range(
1523    numerator: (f64, f64),
1524    denominator: (f64, f64),
1525) -> Option<(f64, f64)> {
1526    if denominator.0 <= 0.0 && denominator.1 >= 0.0 {
1527        return None;
1528    }
1529    let quotients = [
1530        numerator.0 / denominator.0,
1531        numerator.0 / denominator.1,
1532        numerator.1 / denominator.0,
1533        numerator.1 / denominator.1,
1534    ];
1535    let mut range = rounded_f32_range(
1536        quotients.into_iter().fold(f64::INFINITY, f64::min),
1537        quotients.into_iter().fold(f64::NEG_INFINITY, f64::max),
1538    )?;
1539    // WGSL permits 2.5 ULP division error. Three outward neighbours cover it;
1540    // an inexact endpoint may already carry one additional rounding neighbour.
1541    for _ in 0..3 {
1542        range = (
1543            f64::from(next_f32_down(range.0 as f32)?),
1544            f64::from(next_f32_up(range.1 as f32)?),
1545        );
1546    }
1547    Some(range)
1548}
1549
1550fn rounded_f32_product_range(left: (f64, f64), right: (f64, f64)) -> Option<(f64, f64)> {
1551    let products = [
1552        left.0 * right.0,
1553        left.0 * right.1,
1554        left.1 * right.0,
1555        left.1 * right.1,
1556    ];
1557    rounded_f32_range(
1558        products.into_iter().fold(f64::INFINITY, f64::min),
1559        products.into_iter().fold(f64::NEG_INFINITY, f64::max),
1560    )
1561}
1562
1563fn rounded_f32_add_range(
1564    left: (f64, f64),
1565    right: (f64, f64),
1566    subtract: bool,
1567) -> Option<(f64, f64)> {
1568    let (minimum, maximum) = if subtract {
1569        (left.0 - right.1, left.1 - right.0)
1570    } else {
1571        (left.0 + right.0, left.1 + right.1)
1572    };
1573    rounded_f32_range(minimum, maximum)
1574}
1575
1576fn rounded_f32_range(minimum: f64, maximum: f64) -> Option<(f64, f64)> {
1577    if !minimum.is_finite()
1578        || !maximum.is_finite()
1579        || minimum < -f64::from(MAX_PORTABLE_SHADER_VALUE)
1580        || maximum > f64::from(MAX_PORTABLE_SHADER_VALUE)
1581    {
1582        return None;
1583    }
1584    if minimum == maximum && f64::from(minimum as f32) == minimum {
1585        return Some((minimum, maximum));
1586    }
1587    let mut minimum = f64::from(next_f32_down(minimum as f32)?);
1588    let mut maximum = f64::from(next_f32_up(maximum as f32)?);
1589    let minimum_normal = f64::from(f32::MIN_POSITIVE);
1590    if maximum > 0.0 && minimum < minimum_normal {
1591        minimum = minimum.min(0.0);
1592    }
1593    if minimum < 0.0 && maximum > -minimum_normal {
1594        maximum = maximum.max(0.0);
1595    }
1596    Some((minimum, maximum))
1597}
1598
1599fn next_f32_down(value: f32) -> Option<f32> {
1600    if !value.is_finite() {
1601        return None;
1602    }
1603    let next = if value == 0.0 {
1604        -f32::from_bits(1)
1605    } else if value > 0.0 {
1606        f32::from_bits(value.to_bits().checked_sub(1)?)
1607    } else {
1608        f32::from_bits(value.to_bits().checked_add(1)?)
1609    };
1610    next.is_finite().then_some(next)
1611}
1612
1613fn next_f32_up(value: f32) -> Option<f32> {
1614    if !value.is_finite() {
1615        return None;
1616    }
1617    let next = if value == 0.0 {
1618        f32::from_bits(1)
1619    } else if value > 0.0 {
1620        f32::from_bits(value.to_bits().checked_add(1)?)
1621    } else {
1622        f32::from_bits(value.to_bits().checked_sub(1)?)
1623    };
1624    next.is_finite().then_some(next)
1625}
1626
1627fn screen_ranges_to_clip(
1628    screen: [(f64, f64); 2],
1629    uniform: CameraUniform,
1630) -> Option<[(f64, f64); 2]> {
1631    Some([
1632        shader_interval_sum_range([
1633            interval_products_f64(uniform.screen_to_clip[0], screen[0].0, screen[0].1),
1634            (
1635                f64::from(uniform.screen_to_clip[2]),
1636                f64::from(uniform.screen_to_clip[2]),
1637            ),
1638        ])?,
1639        shader_interval_sum_range([
1640            interval_products_f64(uniform.screen_to_clip[1], screen[1].0, screen[1].1),
1641            (
1642                f64::from(uniform.screen_to_clip[3]),
1643                f64::from(uniform.screen_to_clip[3]),
1644            ),
1645        ])?,
1646    ])
1647}
1648
1649fn shader_interval_difference(left: (f64, f64), right: (f64, f64)) -> Option<(f64, f64)> {
1650    shader_interval_sum_range([left, (-right.1, -right.0)])
1651}
1652
1653fn shader_interval_product(left: (f64, f64), right: (f64, f64)) -> Option<(f64, f64)> {
1654    let products = [
1655        left.0 * right.0,
1656        left.0 * right.1,
1657        left.1 * right.0,
1658        left.1 * right.1,
1659    ];
1660    shader_interval_sum_range([(
1661        products.into_iter().fold(f64::INFINITY, f64::min),
1662        products.into_iter().fold(f64::NEG_INFINITY, f64::max),
1663    )])
1664}
1665
1666#[cfg(test)]
1667fn geometry_vertex_centers_are_portable(
1668    source: GeometryValidationSource<'_>,
1669    uniform: CameraUniform,
1670) -> bool {
1671    let dynamic_center_is_portable = |world: [f32; 2], depth: f32| {
1672        let Some(relative_x) = shader_relative_component_bounds(
1673            world[0],
1674            world[0],
1675            uniform.camera_center[0],
1676            0.0,
1677            0.0,
1678        ) else {
1679            return false;
1680        };
1681        let Some(relative_y) = shader_relative_component_bounds(
1682            world[1],
1683            world[1],
1684            uniform.camera_center[1],
1685            0.0,
1686            0.0,
1687        ) else {
1688            return false;
1689        };
1690        let minimum = [relative_x.0, relative_y.0];
1691        let maximum = [relative_x.1, relative_y.1];
1692        shader_world_dot_range(uniform.world_to_screen_x, minimum, maximum, depth, depth).is_some()
1693            && shader_world_dot_range(uniform.world_to_screen_y, minimum, maximum, depth, depth)
1694                .is_some()
1695    };
1696    match source {
1697        GeometryValidationSource::Tessellated(vertices) => vertices
1698            .iter()
1699            .all(|vertex| tessellated_vertex_clip_ranges(*vertex, uniform).is_some()),
1700        GeometryValidationSource::Dynamic(vertices) => vertices
1701            .iter()
1702            .all(|vertex| dynamic_center_is_portable(vertex.world_position, vertex.depth)),
1703    }
1704}
1705
1706fn geometry_sources_are_portable(source: GeometryValidationSource<'_>) -> bool {
1707    match source {
1708        GeometryValidationSource::Tessellated(vertices) => vertices.iter().all(|vertex| {
1709            vertex
1710                .world_position
1711                .into_iter()
1712                .chain(vertex.world_offset)
1713                .chain(vertex.screen_offset)
1714                .chain(vertex.previous_direction)
1715                .chain(vertex.next_direction)
1716                .chain([
1717                    vertex.depth,
1718                    vertex.normal_distance,
1719                    vertex.tangent_distance,
1720                    vertex.miter_limit,
1721                ])
1722                .all(is_portable_shader_source)
1723        }),
1724        GeometryValidationSource::Dynamic(vertices) => vertices.iter().all(|vertex| {
1725            vertex
1726                .world_position
1727                .into_iter()
1728                .chain([vertex.depth])
1729                .all(is_portable_shader_source)
1730        }),
1731    }
1732}
1733
1734fn logical_stroke_branches_are_stable(vertex: Vertex, uniform: CameraUniform) -> bool {
1735    if vertex.normal_distance == 0.0 && vertex.tangent_distance == 0.0 {
1736        return true;
1737    }
1738    let project = |direction: [f32; 2]| {
1739        [
1740            f64::from(uniform.world_to_screen_x[0]) * f64::from(direction[0])
1741                + f64::from(uniform.world_to_screen_x[1]) * f64::from(direction[1]),
1742            f64::from(uniform.world_to_screen_y[0]) * f64::from(direction[0])
1743                + f64::from(uniform.world_to_screen_y[1]) * f64::from(direction[1]),
1744        ]
1745    };
1746    let stable_projected_direction = |direction: [f32; 2]| {
1747        let direction = Vec2::new(direction[0], direction[1]);
1748        let horizontal =
1749            shader_direction_dot_range(uniform.world_to_screen_x, direction, direction)?;
1750        let vertical = shader_direction_dot_range(uniform.world_to_screen_y, direction, direction)?;
1751        let fixed = project([direction.x, direction.y]);
1752        let component_minimum_magnitude = |range: (f64, f64)| {
1753            if range.0 > 0.0 {
1754                range.0
1755            } else if range.1 < 0.0 {
1756                -range.1
1757            } else {
1758                0.0
1759            }
1760        };
1761        let lower_length =
1762            component_minimum_magnitude(horizontal).hypot(component_minimum_magnitude(vertical));
1763        let fixed_length = fixed[0].hypot(fixed[1]);
1764        let uncertainty = (horizontal.0 - fixed[0])
1765            .abs()
1766            .max((horizontal.1 - fixed[0]).abs())
1767            .hypot(
1768                (vertical.0 - fixed[1])
1769                    .abs()
1770                    .max((vertical.1 - fixed[1]).abs()),
1771            );
1772        let minimum_normal = f64::from(f32::MIN_POSITIVE);
1773        (lower_length >= minimum_normal
1774            && fixed_length.is_finite()
1775            && uncertainty.is_finite()
1776            && uncertainty <= fixed_length * 1.0e-6)
1777            .then_some(fixed)
1778    };
1779    let Some(previous_projected) = stable_projected_direction(vertex.previous_direction) else {
1780        return false;
1781    };
1782    let Some(next_projected) = stable_projected_direction(vertex.next_direction) else {
1783        return false;
1784    };
1785    if vertex.previous_direction == vertex.next_direction {
1786        // The shader detects source equality and reuses one projection and
1787        // normalization result, so identical directions cannot acquire a
1788        // backend-dependent artificial turn.
1789        return true;
1790    }
1791
1792    let normalize = |value: [f64; 2]| {
1793        let scale = value[0].abs().max(value[1].abs());
1794        if !scale.is_finite() || scale <= 0.0 {
1795            return None;
1796        }
1797        let scaled = [value[0] / scale, value[1] / scale];
1798        let length = scaled[0].hypot(scaled[1]);
1799        (length.is_finite() && length > 0.0).then_some([scaled[0] / length, scaled[1] / length])
1800    };
1801    let Some(previous) = normalize(previous_projected) else {
1802        return false;
1803    };
1804    let Some(next) = normalize(next_projected) else {
1805        return false;
1806    };
1807    let turn = previous[0] * next[1] - previous[1] * next[0];
1808    let tangent_dot = previous[0] * next[0] + previous[1] * next[1];
1809    if !turn.is_finite() || !tangent_dot.is_finite() {
1810        return false;
1811    }
1812    // Keep every topology-changing comparison far outside WGSL's permitted
1813    // normal-operation error. Exact repeated directions took the fast path.
1814    if turn.abs() <= 1.0e-4 || tangent_dot <= -0.999_9 {
1815        return false;
1816    }
1817
1818    let previous_normal = [-previous[1], previous[0]];
1819    let next_normal = [-next[1], next[0]];
1820    let combined = [
1821        previous_normal[0] + next_normal[0],
1822        previous_normal[1] + next_normal[1],
1823    ];
1824    let Some(miter) = normalize(combined) else {
1825        return false;
1826    };
1827    let denominator = miter[0] * next_normal[0] + miter[1] * next_normal[1];
1828    if !denominator.is_finite() || denominator.abs() <= 0.002 {
1829        return false;
1830    }
1831    let miter_multiple = 1.0 / denominator.abs();
1832    let limit = f64::from(vertex.miter_limit);
1833    let comparison_margin = 1.0e-4 * miter_multiple.abs().max(limit.abs()).max(1.0);
1834    (miter_multiple - limit).abs() > comparison_margin
1835}
1836
1837fn shader_clip_interval_is_safe(
1838    screen_minimum: f64,
1839    screen_maximum: f64,
1840    scale: f32,
1841    offset: f32,
1842) -> bool {
1843    if ((is_nonzero_subnormal_f64(screen_minimum) || is_nonzero_subnormal_f64(screen_maximum))
1844        && scale != 0.0)
1845        || (is_nonzero_subnormal(scale) && (screen_minimum != 0.0 || screen_maximum != 0.0))
1846    {
1847        return false;
1848    }
1849    shader_interval_sum_range([
1850        interval_products_f64(scale, screen_minimum, screen_maximum),
1851        (f64::from(offset), f64::from(offset)),
1852    ])
1853    .is_some()
1854}
1855
1856fn shader_relative_component_bounds(
1857    world_minimum: f32,
1858    world_maximum: f32,
1859    camera_center: f32,
1860    offset_minimum: f32,
1861    offset_maximum: f32,
1862) -> Option<(f64, f64)> {
1863    // Exact equal f32 operands subtract to exact zero on every backend. Keep
1864    // that important camera-relative case tight so separately projected local
1865    // tessellation offsets remain usable at large world anchors.
1866    let subtraction = if world_minimum == camera_center && world_maximum == camera_center {
1867        (0.0, 0.0)
1868    } else {
1869        shader_interval_sum_range([
1870            (f64::from(world_minimum), f64::from(world_maximum)),
1871            (-f64::from(camera_center), -f64::from(camera_center)),
1872        ])?
1873    };
1874    if offset_minimum == 0.0 && offset_maximum == 0.0 {
1875        Some(subtraction)
1876    } else {
1877        shader_interval_sum_range([
1878            subtraction,
1879            (f64::from(offset_minimum), f64::from(offset_maximum)),
1880        ])
1881    }
1882}
1883
1884fn shader_world_dot_range(
1885    row: [f32; 4],
1886    minimum: [f64; 2],
1887    maximum: [f64; 2],
1888    depth_minimum: f32,
1889    depth_maximum: f32,
1890) -> Option<(f64, f64)> {
1891    if (is_nonzero_subnormal(row[0]) && (minimum[0] != 0.0 || maximum[0] != 0.0))
1892        || (is_nonzero_subnormal(row[1]) && (minimum[1] != 0.0 || maximum[1] != 0.0))
1893        || (is_nonzero_subnormal(row[2]) && (depth_minimum != 0.0 || depth_maximum != 0.0))
1894        || ((is_nonzero_subnormal_f64(minimum[0]) || is_nonzero_subnormal_f64(maximum[0]))
1895            && row[0] != 0.0)
1896        || ((is_nonzero_subnormal_f64(minimum[1]) || is_nonzero_subnormal_f64(maximum[1]))
1897            && row[1] != 0.0)
1898        || ((is_nonzero_subnormal(depth_minimum) || is_nonzero_subnormal(depth_maximum))
1899            && row[2] != 0.0)
1900    {
1901        return None;
1902    }
1903    shader_interval_sum_range([
1904        interval_products_f64(row[0], minimum[0], maximum[0]),
1905        interval_products_f64(row[1], minimum[1], maximum[1]),
1906        interval_products(row[2], depth_minimum, depth_maximum),
1907        (f64::from(row[3]), f64::from(row[3])),
1908    ])
1909}
1910
1911fn shader_direction_dot_range(row: [f32; 4], minimum: Vec2, maximum: Vec2) -> Option<(f64, f64)> {
1912    if (is_nonzero_subnormal(row[0]) && (minimum.x != 0.0 || maximum.x != 0.0))
1913        || (is_nonzero_subnormal(row[1]) && (minimum.y != 0.0 || maximum.y != 0.0))
1914        || ((is_nonzero_subnormal(minimum.x) || is_nonzero_subnormal(maximum.x)) && row[0] != 0.0)
1915        || ((is_nonzero_subnormal(minimum.y) || is_nonzero_subnormal(maximum.y)) && row[1] != 0.0)
1916    {
1917        return None;
1918    }
1919    shader_interval_sum_range([
1920        interval_products(row[0], minimum.x, maximum.x),
1921        interval_products(row[1], minimum.y, maximum.y),
1922    ])
1923}
1924
1925#[cfg(test)]
1926fn shader_interval_sum_is_safe<const N: usize>(terms: [(f64, f64); N]) -> bool {
1927    shader_interval_sum_range(terms).is_some()
1928}
1929
1930#[cfg(test)]
1931#[path = "shader_interval_sum_tests.rs"]
1932mod shader_interval_sum_tests;
1933
1934fn shader_interval_sum_range<const N: usize>(terms: [(f64, f64); N]) -> Option<(f64, f64)> {
1935    // WGSL's `dot` may be lowered with a backend-selected association or FMA
1936    // pattern. Bound all multiplication/addition rounding as well as every
1937    // same-sign partial sum, then return the complete finite output interval.
1938    // Keeping that interval is essential when a later shader stage multiplies
1939    // a cancellation residual by another large coefficient.
1940    let maximum = f64::from(MAX_PORTABLE_SHADER_VALUE);
1941    let mut positive_sum = 0.0;
1942    let mut negative_sum = 0.0;
1943    let mut minimum_sum = 0.0;
1944    let mut maximum_sum = 0.0;
1945    let mut magnitude_sum = 0.0;
1946    let mut active_terms = 0usize;
1947    let mut inexact_products = 0usize;
1948    let mut active_term = (0.0, 0.0);
1949    for term in terms {
1950        // WGSL permits implementations to flush subnormal arithmetic to zero.
1951        // A flushed product can become visually significant after a later
1952        // large camera or clip multiplier, so reject it structurally.
1953        if is_nonzero_subnormal_f64(term.0)
1954            || is_nonzero_subnormal_f64(term.1)
1955            || !term.0.is_finite()
1956            || !term.1.is_finite()
1957            || term.0 < -maximum
1958            || term.1 > maximum
1959        {
1960            return None;
1961        }
1962        positive_sum += term.1.max(0.0);
1963        negative_sum += term.0.min(0.0);
1964        minimum_sum += term.0;
1965        maximum_sum += term.1;
1966        magnitude_sum += term.0.abs().max(term.1.abs());
1967        if term.0 != 0.0 || term.1 != 0.0 {
1968            active_terms += 1;
1969            active_term = term;
1970        }
1971        inexact_products += usize::from(term.0 != term.1 || f64::from(term.0 as f32) != term.0);
1972    }
1973
1974    // Exact zero terms do not participate in any association, and an isolated
1975    // exactly representable product needs no rounding allowance. This keeps
1976    // component-selection rows tight inside the portability envelope while
1977    // retaining a conservative margin for operations which can round.
1978    if active_terms == 1 {
1979        let term = active_term;
1980        // A single interval term has no association ambiguity. When both
1981        // endpoints are already representable f32 values, they also prove
1982        // that the producing multiply rounded exactly at the extrema; adding
1983        // the remaining exact zero terms cannot enlarge the range. This is
1984        // important for a later dot row which merely selects or negates one
1985        // component from an earlier association envelope.
1986        if [term.0, term.1]
1987            .into_iter()
1988            .all(|value| f64::from(value as f32) == value)
1989        {
1990            return Some(term);
1991        }
1992    }
1993    let operation_count = inexact_products + active_terms.saturating_sub(1);
1994    // WGSL correctly-rounded operations may select either adjacent f32 value;
1995    // use the directed-rounding bound rather than Rust's round-to-nearest.
1996    // Compute the original formula at compile time for all N<=8 operation
1997    // counts. No decimal approximation or reduced rounding allowance is used.
1998    const GAMMA: [f64; 16] = {
1999        let unit_roundoff = f32::EPSILON as f64;
2000        let mut values = [0.0; 16];
2001        let mut index = 0;
2002        while index < values.len() {
2003            let count = index as f64;
2004            values[index] = count * unit_roundoff / (1.0 - count * unit_roundoff);
2005            index += 1;
2006        }
2007        values
2008    };
2009    let gamma = GAMMA.get(operation_count).copied().unwrap_or_else(|| {
2010        let count = operation_count as f64;
2011        let unit_roundoff = f64::from(f32::EPSILON);
2012        count * unit_roundoff / (1.0 - count * unit_roundoff)
2013    });
2014    let operation_count = operation_count as f64;
2015    let subnormal_margin = if magnitude_sum > 0.0 {
2016        operation_count * f64::from(f32::MIN_POSITIVE)
2017    } else {
2018        0.0
2019    };
2020    let rounding_margin = gamma * magnitude_sum + subnormal_margin;
2021    let minimum_output = minimum_sum - rounding_margin;
2022    let maximum_output = maximum_sum + rounding_margin;
2023    if !positive_sum.is_finite()
2024        || !negative_sum.is_finite()
2025        || !minimum_output.is_finite()
2026        || !maximum_output.is_finite()
2027        || positive_sum + rounding_margin > maximum
2028        || negative_sum - rounding_margin < -maximum
2029        || minimum_output < -maximum
2030        || maximum_output > maximum
2031    {
2032        return None;
2033    }
2034    Some((minimum_output, maximum_output))
2035}
2036
2037fn is_nonzero_subnormal(value: f32) -> bool {
2038    value != 0.0 && value.abs() < f32::MIN_POSITIVE
2039}
2040
2041fn is_nonzero_subnormal_f64(value: f64) -> bool {
2042    value != 0.0 && value.abs() < f64::from(f32::MIN_POSITIVE)
2043}
2044
2045fn interval_products(coefficient: f32, minimum: f32, maximum: f32) -> (f64, f64) {
2046    interval_products_f64(coefficient, f64::from(minimum), f64::from(maximum))
2047}
2048
2049fn interval_products_f64(coefficient: f32, minimum: f64, maximum: f64) -> (f64, f64) {
2050    let first = f64::from(coefficient) * minimum;
2051    let second = f64::from(coefficient) * maximum;
2052    (first.min(second), first.max(second))
2053}
2054
2055/// Result of attempting to draw a frame.
2056#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2057pub enum RenderStatus {
2058    /// Commands were submitted successfully. Surface paths also requested
2059    /// presentation; offscreen paths completed their target submission only.
2060    Drawn,
2061    /// The frame was skipped because the window surface was temporarily unavailable.
2062    Skipped(RendererSurfaceStatus),
2063}
2064
2065/// CPU-side durations measured while preparing and submitting one renderer frame.
2066///
2067/// These values do not measure GPU execution or the monitor scanout timestamp.
2068/// FIFO presentation back-pressure normally appears in `surface_acquire` because
2069/// `wgpu` blocks frame acquisition when the presentation queue is full.
2070#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2071pub struct RendererFrameMetrics {
2072    tessellation: Duration,
2073    upload: Duration,
2074    camera_uniform_upload: Duration,
2075    surface_acquire: Duration,
2076    encode_submit_present: Duration,
2077    total_cpu: Duration,
2078    geometry_reused: bool,
2079    geometry_streamed: bool,
2080    tessellation_stats: TessellationStats,
2081}
2082
2083impl RendererFrameMetrics {
2084    /// Returns CPU time spent preparing visual work before GPU uploads.
2085    ///
2086    /// For an ordinary streaming scene this is validation and tessellation.
2087    /// A heterogeneous [`FrameComposer`](crate::FrameComposer) frame also
2088    /// includes viewport and source validation, particle visibility selection,
2089    /// scalar LUT generation, and preparation of retained image/glyph draws.
2090    pub fn tessellation(self) -> Duration {
2091        self.tessellation
2092    }
2093
2094    /// Returns CPU time spent preparing and enqueueing non-camera per-frame GPU data.
2095    ///
2096    /// Depending on the rendering path this includes transient vertex or
2097    /// instance writes, scalar LUT and pass-uniform uploads, and creation of
2098    /// the per-frame bindings needed by image, glyph, scalar, particle, or
2099    /// composition passes. The camera-only write remains separately available
2100    /// through [`Self::camera_uniform_upload`]. This is CPU preparation/enqueue
2101    /// time, not GPU execution time. An ordinary streaming frame can include
2102    /// pre-acquire transient buffer
2103    /// capacity creation here, so a skipped report may have a non-zero duration
2104    /// even though it performed no queue write and reports zero uploaded bytes.
2105    pub fn upload(self) -> Duration {
2106        self.upload
2107    }
2108
2109    /// Returns CPU time spent updating the small per-frame camera uniform.
2110    pub fn camera_uniform_upload(self) -> Duration {
2111        self.camera_uniform_upload
2112    }
2113
2114    /// Returns CPU time spent acquiring the next presentation surface texture.
2115    ///
2116    /// In FIFO modes this includes queue back-pressure and is the closest CPU-side
2117    /// approximation to VSync wait exposed by `wgpu`.
2118    pub fn surface_acquire(self) -> Duration {
2119        self.surface_acquire
2120    }
2121
2122    /// Returns CPU time spent encoding, submitting, and dispatching present.
2123    ///
2124    /// Present dispatch does not mean the monitor has already scanned out the
2125    /// frame; `wgpu` does not expose that timestamp here.
2126    pub fn encode_submit_present(self) -> Duration {
2127        self.encode_submit_present
2128    }
2129
2130    /// Returns total CPU time inside the profiled render call.
2131    pub fn total_cpu(self) -> Duration {
2132        self.total_cpu
2133    }
2134
2135    /// Returns whether this frame referenced retained visual geometry.
2136    ///
2137    /// This includes prepared scenes and retained sprite/glyph batches. It is
2138    /// a broad workload-classification hint rather than a statement that the
2139    /// frame performed no uploads, and it can be true together with
2140    /// [`Self::geometry_streamed`].
2141    pub fn geometry_reused(self) -> bool {
2142        self.geometry_reused
2143    }
2144
2145    /// Returns whether this frame contained dynamically supplied visual work.
2146    ///
2147    /// This includes dynamic meshes, particle visibility instances, and scalar
2148    /// field passes. It is a broad workload-classification hint rather than an
2149    /// allocation or upload guarantee, and it can be true together with
2150    /// [`Self::geometry_reused`].
2151    pub fn geometry_streamed(self) -> bool {
2152        self.geometry_streamed
2153    }
2154
2155    /// Returns command-level tessellation results for this frame.
2156    pub fn tessellation_stats(self) -> TessellationStats {
2157        self.tessellation_stats
2158    }
2159}
2160
2161/// Status and CPU timing breakdown for one renderer frame.
2162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2163pub struct RenderReport {
2164    status: RenderStatus,
2165    metrics: RendererFrameMetrics,
2166}
2167
2168impl RenderReport {
2169    /// Returns whether the frame was drawn or skipped by the surface.
2170    pub fn status(self) -> RenderStatus {
2171        self.status
2172    }
2173
2174    /// Returns CPU-side stage durations for the render call.
2175    pub fn metrics(self) -> RendererFrameMetrics {
2176        self.metrics
2177    }
2178}
2179
2180/// Recoverable or fatal state reported by the presentation surface.
2181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2182pub enum RendererSurfaceStatus {
2183    /// Acquiring the next frame timed out; try again on a later frame.
2184    Timeout,
2185    /// The surface is occluded or minimized; rendering can be skipped.
2186    Occluded,
2187    /// The surface configuration is stale; resizing or reconfiguring is needed.
2188    Outdated,
2189    /// The surface was lost and should be recreated by the host application.
2190    Lost,
2191    /// `wgpu` reported a validation error while acquiring the frame.
2192    Validation,
2193}
2194
2195/// Fatal failure while preparing or submitting one frame.
2196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2197pub enum RendererFrameError {
2198    /// The presentation surface was lost or rejected frame acquisition.
2199    Surface(RendererSurfaceStatus),
2200    /// Camera, geometry, stroke arithmetic, or dynamic-triangle topology
2201    /// cannot be proven portable on the GPU.
2202    ///
2203    /// This includes nonzero subnormal or excessively large shader sources,
2204    /// transform ranges that may overflow under permitted GPU arithmetic, and
2205    /// stroke branch decisions that are ambiguous after projection, every
2206    /// dynamic triangle requiring partial frustum clipping, and projected
2207    /// triangle orientation that may change with legal shader association.
2208    InvalidGeometryTransform,
2209    /// A logical viewport is outside the active surface or render target.
2210    InvalidViewport,
2211    /// Tessellated geometry exceeds the active device's vertex-buffer limit.
2212    GeometryCapacityTooLarge,
2213    /// CPU storage for scene tessellation could not be reserved.
2214    SceneAllocationFailed {
2215        /// Minimum additional bytes requested by the failed reservation.
2216        requested_bytes: usize,
2217    },
2218    /// CPU storage for the camera-visible particle subset could not be reserved.
2219    ParticleAllocationFailed {
2220        /// Bytes requested for the rejected visible-instance vector.
2221        requested_bytes: usize,
2222    },
2223    /// Actual renderer work exceeded a scene's explicit limit.
2224    SceneBudgetExceeded {
2225        /// Work category whose post-tessellation limit was exceeded.
2226        resource: SceneBudgetResource,
2227        /// Configured maximum for the category.
2228        limit: usize,
2229        /// Actual renderer work observed.
2230        actual: usize,
2231    },
2232}
2233
2234impl fmt::Display for RendererFrameError {
2235    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2236        match self {
2237            Self::Surface(status) => write!(formatter, "renderer surface failed: {status:?}"),
2238            Self::InvalidGeometryTransform => {
2239                write!(
2240                    formatter,
2241                    "camera, geometry, or dynamic topology is outside the portable GPU envelope"
2242                )
2243            }
2244            Self::InvalidViewport => {
2245                write!(
2246                    formatter,
2247                    "logical viewport lies outside the active render target"
2248                )
2249            }
2250            Self::GeometryCapacityTooLarge => {
2251                write!(formatter, "geometry exceeds the GPU vertex-buffer limit")
2252            }
2253            Self::SceneAllocationFailed { requested_bytes } => write!(
2254                formatter,
2255                "could not reserve {requested_bytes} additional bytes for scene tessellation"
2256            ),
2257            Self::ParticleAllocationFailed { requested_bytes } => write!(
2258                formatter,
2259                "could not reserve {requested_bytes} bytes for visible particle instances"
2260            ),
2261            Self::SceneBudgetExceeded {
2262                resource,
2263                limit,
2264                actual,
2265            } => write!(
2266                formatter,
2267                "scene {resource:?} work exceeded its limit {limit} after tessellation: {actual}"
2268            ),
2269        }
2270    }
2271}
2272
2273impl Error for RendererFrameError {}
2274
2275/// Errors that can happen while creating the `wgpu` renderer.
2276#[derive(Debug)]
2277pub enum RendererInitError {
2278    /// Surface creation failed for the provided window or canvas target.
2279    CreateSurface(wgpu::CreateSurfaceError),
2280    /// No compatible GPU adapter could be selected.
2281    RequestAdapter(wgpu::RequestAdapterError),
2282    /// A logical GPU device and queue could not be created.
2283    RequestDevice(wgpu::RequestDeviceError),
2284    /// The surface did not expose a usable default configuration.
2285    NoSurfaceConfig,
2286    /// Requested physical dimensions exceed the selected device limit.
2287    SurfaceDimensionsTooLarge {
2288        /// Rejected physical width.
2289        width: u32,
2290        /// Rejected physical height.
2291        height: u32,
2292        /// Device maximum for either dimension.
2293        limit: u32,
2294    },
2295    /// The bounded previous-device quarantine is full.
2296    RecoveryLimitReached {
2297        /// Configured maximum number of quarantined logical devices.
2298        limit: usize,
2299    },
2300    /// CPU storage for quarantining the previous device could not be reserved.
2301    RecoveryAllocationFailed {
2302        /// Additional bytes requested for one quarantine entry.
2303        requested_bytes: usize,
2304    },
2305}
2306
2307impl fmt::Display for RendererInitError {
2308    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2309        match self {
2310            Self::CreateSurface(error) => write!(formatter, "failed to create surface: {error}"),
2311            Self::RequestAdapter(error) => write!(formatter, "failed to request adapter: {error}"),
2312            Self::RequestDevice(error) => write!(formatter, "failed to request device: {error}"),
2313            Self::NoSurfaceConfig => write!(formatter, "surface has no supported default config"),
2314            Self::SurfaceDimensionsTooLarge {
2315                width,
2316                height,
2317                limit,
2318            } => write!(
2319                formatter,
2320                "surface dimensions {width}x{height} exceed device limit {limit}"
2321            ),
2322            Self::RecoveryLimitReached { limit } => write!(
2323                formatter,
2324                "device recovery limit reached with {limit} quarantined devices"
2325            ),
2326            Self::RecoveryAllocationFailed { requested_bytes } => write!(
2327                formatter,
2328                "could not reserve {requested_bytes} bytes for device recovery quarantine"
2329            ),
2330        }
2331    }
2332}
2333
2334impl Error for RendererInitError {}
2335
2336/// Invalid runtime or initialization configuration for [`WgpuRenderer`].
2337#[derive(Debug, Clone, Copy, PartialEq)]
2338pub enum RendererConfigurationError {
2339    /// Logical-to-physical scale must keep all surface transforms normal and finite.
2340    InvalidScaleFactor {
2341        /// Rejected physical pixels per logical screen pixel.
2342        scale_factor: f64,
2343    },
2344    /// Previous-device quarantine must remain inside the supported bounded range.
2345    InvalidRecoveryLimit {
2346        /// Rejected maximum retained-device count.
2347        limit: usize,
2348    },
2349    /// Requested physical dimensions exceed the active device limit.
2350    SurfaceDimensionsTooLarge {
2351        /// Rejected physical width.
2352        width: u32,
2353        /// Rejected physical height.
2354        height: u32,
2355        /// Device maximum for either dimension.
2356        limit: u32,
2357    },
2358}
2359
2360impl fmt::Display for RendererConfigurationError {
2361    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2362        match self {
2363            Self::InvalidScaleFactor { scale_factor } => write!(
2364                formatter,
2365                "renderer scale factor must be finite, representable as f32, and keep every u32 surface transform in the normal f32 range, got {scale_factor}"
2366            ),
2367            Self::InvalidRecoveryLimit { limit } => write!(
2368                formatter,
2369                "renderer recovery quarantine must retain between 1 and 8 devices, got {limit}"
2370            ),
2371            Self::SurfaceDimensionsTooLarge {
2372                width,
2373                height,
2374                limit,
2375            } => write!(
2376                formatter,
2377                "surface dimensions {width}x{height} exceed device limit {limit}"
2378            ),
2379        }
2380    }
2381}
2382
2383impl Error for RendererConfigurationError {}
2384
2385/// Failure while converting between logical and physical screen coordinates.
2386#[derive(Debug, Clone, Copy, PartialEq)]
2387pub enum RendererCoordinateError {
2388    /// The source position is non-finite or the scaled result cannot be represented as `f32`.
2389    NonFiniteConversion,
2390}
2391
2392impl fmt::Display for RendererCoordinateError {
2393    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2394        write!(
2395            formatter,
2396            "screen coordinate conversion produced a non-finite result"
2397        )
2398    }
2399}
2400
2401impl Error for RendererCoordinateError {}
2402
2403/// Failure while uploading or restoring immutable prepared-scene geometry.
2404#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2405pub enum PreparedSceneError {
2406    /// Tessellated geometry exceeds the active device's vertex-buffer limit.
2407    CapacityTooLarge,
2408    /// Command sources or derived tessellated vertices are outside the
2409    /// portable GPU input envelope.
2410    InvalidGeometrySources,
2411    /// CPU storage for scene tessellation could not be reserved.
2412    AllocationFailed {
2413        /// Minimum additional bytes requested by the failed reservation.
2414        requested_bytes: usize,
2415    },
2416    /// Actual prepared-scene work exceeded an explicit scene limit.
2417    BudgetExceeded {
2418        /// Work category whose post-tessellation limit was exceeded.
2419        resource: SceneBudgetResource,
2420        /// Configured maximum for the category.
2421        limit: usize,
2422        /// Actual renderer work observed.
2423        actual: usize,
2424    },
2425}
2426
2427impl fmt::Display for PreparedSceneError {
2428    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2429        match self {
2430            Self::CapacityTooLarge => {
2431                write!(
2432                    formatter,
2433                    "prepared scene exceeds the GPU vertex-buffer limit"
2434                )
2435            }
2436            Self::InvalidGeometrySources => write!(
2437                formatter,
2438                "prepared scene contains non-portable GPU geometry sources"
2439            ),
2440            Self::AllocationFailed { requested_bytes } => write!(
2441                formatter,
2442                "could not reserve {requested_bytes} additional bytes for prepared-scene tessellation"
2443            ),
2444            Self::BudgetExceeded {
2445                resource,
2446                limit,
2447                actual,
2448            } => write!(
2449                formatter,
2450                "prepared scene {resource:?} work exceeded its limit {limit}: {actual}"
2451            ),
2452        }
2453    }
2454}
2455
2456impl From<TessellationError> for RendererFrameError {
2457    fn from(error: TessellationError) -> Self {
2458        match error {
2459            TessellationError::AllocationFailed { requested_bytes } => {
2460                Self::SceneAllocationFailed { requested_bytes }
2461            }
2462            TessellationError::CapacityTooLarge => Self::GeometryCapacityTooLarge,
2463            TessellationError::BudgetExceeded {
2464                resource,
2465                limit,
2466                actual,
2467            } => Self::SceneBudgetExceeded {
2468                resource,
2469                limit,
2470                actual,
2471            },
2472        }
2473    }
2474}
2475
2476impl From<TessellationError> for PreparedSceneError {
2477    fn from(error: TessellationError) -> Self {
2478        match error {
2479            TessellationError::AllocationFailed { requested_bytes } => {
2480                Self::AllocationFailed { requested_bytes }
2481            }
2482            TessellationError::CapacityTooLarge => Self::CapacityTooLarge,
2483            TessellationError::BudgetExceeded {
2484                resource,
2485                limit,
2486                actual,
2487            } => Self::BudgetExceeded {
2488                resource,
2489                limit,
2490                actual,
2491            },
2492        }
2493    }
2494}
2495
2496impl Error for PreparedSceneError {}
2497
2498/// Failure to draw geometry prepared by [`WgpuRenderer::prepare_scene`].
2499#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2500pub enum PreparedSceneRenderError {
2501    /// The prepared geometry belongs to a different renderer and GPU device.
2502    RendererMismatch,
2503    /// Frame rendering failed after prepared-scene ownership validation.
2504    Frame(RendererFrameError),
2505}
2506
2507impl fmt::Display for PreparedSceneRenderError {
2508    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2509        match self {
2510            Self::RendererMismatch => {
2511                write!(formatter, "prepared scene belongs to a different renderer")
2512            }
2513            Self::Frame(error) => write!(formatter, "prepared frame failed: {error}"),
2514        }
2515    }
2516}
2517
2518impl Error for PreparedSceneRenderError {}
2519
2520/// Immutable scene geometry tessellated and uploaded once for repeated drawing.
2521///
2522/// Camera movement, zoom, rotation, projection tilt, viewport resizing, and DPI
2523/// changes do not invalidate prepared geometry. Shape, style, gradient, layer,
2524/// or clip changes require preparing a replacement. A prepared scene can only be
2525/// rendered by the [`WgpuRenderer`] that created it. Use
2526/// [`WgpuRenderer::restore_prepared_scene`] to recreate its GPU buffer for a
2527/// replacement renderer after device loss. Portable shader arithmetic is proved
2528/// once per exact camera/viewport uniform and retained in a bounded cache.
2529pub struct PreparedScene {
2530    renderer_identity: Arc<()>,
2531    background: Color,
2532    vertex_buffer: Arc<wgpu::Buffer>,
2533    vertices: Arc<Vec<Vertex>>,
2534    command_count: usize,
2535    vertex_count: usize,
2536    geometry_extents: GeometryExtents,
2537    draw_batches: Vec<PreparedDrawBatch>,
2538    tessellation: TessellationStats,
2539    geometry_validation_cache: GeometryValidationCache,
2540}
2541
2542/// Immutable prepared geometry whose positions are logical screen pixels.
2543///
2544/// This distinct wrapper prevents a world camera from being supplied to fixed
2545/// UI geometry. It is created by [`WgpuRenderer::prepare_screen_scene`].
2546pub struct PreparedScreenScene {
2547    scene: PreparedScene,
2548}
2549
2550/// One world-space vertex in a dynamic triangle-list mesh.
2551///
2552/// Dynamic meshes use plain filled triangles. Positions are measured in world
2553/// units, `depth` uses the active camera projection, and colors are linear RGBA.
2554#[derive(Debug, Clone, Copy, PartialEq)]
2555pub struct DynamicVertex2d {
2556    world_position: Vec2,
2557    depth: f32,
2558    color: Color,
2559}
2560
2561impl DynamicVertex2d {
2562    /// Builds a finite dynamic vertex.
2563    pub fn new(world_position: Vec2, depth: f32, color: Color) -> Result<Self, DynamicMeshError> {
2564        if !world_position.is_finite() || !depth.is_finite() || !color.is_normalized() {
2565            return Err(DynamicMeshError::InvalidVertex);
2566        }
2567        Ok(Self {
2568            world_position,
2569            depth,
2570            color,
2571        })
2572    }
2573
2574    /// Returns the world-space triangle position.
2575    pub fn world_position(self) -> Vec2 {
2576        self.world_position
2577    }
2578
2579    /// Returns pseudo-depth in caller-defined units.
2580    pub fn depth(self) -> f32 {
2581        self.depth
2582    }
2583
2584    /// Returns the linear RGBA vertex color.
2585    pub fn color(self) -> Color {
2586        self.color
2587    }
2588}
2589
2590/// Validation or ownership failure while changing a dynamic mesh.
2591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2592pub enum DynamicMeshError {
2593    /// Triangle-list vertex counts must be divisible by three.
2594    InvalidVertexCount,
2595    /// A position/depth is outside the portable shader envelope or a color is invalid.
2596    InvalidVertex,
2597    /// A partial update lies outside the mesh's current vertex range.
2598    UpdateRangeOutOfBounds,
2599    /// The mesh belongs to a different renderer and GPU device.
2600    RendererMismatch,
2601    /// The mesh capacity exceeds the current device's vertex-buffer limit.
2602    CapacityTooLarge,
2603    /// At least one complete triangle must fit in every configured limit.
2604    InvalidBudget,
2605    /// A bounded mesh operation exceeded a host-selected limit.
2606    BudgetExceeded {
2607        /// Work category that exceeded its ceiling.
2608        resource: DynamicMeshBudgetResource,
2609        /// Configured upper bound.
2610        limit: usize,
2611        /// Required work for the requested mesh state.
2612        actual: usize,
2613    },
2614    /// CPU recovery storage could not be reserved without changing the mesh.
2615    AllocationFailed {
2616        /// Bytes requested by the failed reservation.
2617        requested_bytes: usize,
2618    },
2619}
2620
2621impl fmt::Display for DynamicMeshError {
2622    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2623        match self {
2624            Self::InvalidVertexCount => write!(
2625                formatter,
2626                "dynamic mesh vertex count must be divisible by three"
2627            ),
2628            Self::InvalidVertex => write!(
2629                formatter,
2630                "dynamic mesh positions/depth must be portable and colors normalized"
2631            ),
2632            Self::UpdateRangeOutOfBounds => write!(
2633                formatter,
2634                "dynamic mesh update range is outside the current mesh"
2635            ),
2636            Self::RendererMismatch => {
2637                write!(formatter, "dynamic mesh belongs to a different renderer")
2638            }
2639            Self::CapacityTooLarge => {
2640                write!(
2641                    formatter,
2642                    "dynamic mesh exceeds the GPU vertex-buffer limit"
2643                )
2644            }
2645            Self::InvalidBudget => write!(formatter, "dynamic mesh budget must fit one triangle"),
2646            Self::BudgetExceeded {
2647                resource,
2648                limit,
2649                actual,
2650            } => write!(
2651                formatter,
2652                "dynamic mesh {resource:?} work {actual} exceeds limit {limit}"
2653            ),
2654            Self::AllocationFailed { requested_bytes } => write!(
2655                formatter,
2656                "could not reserve {requested_bytes} bytes for dynamic mesh recovery data"
2657            ),
2658        }
2659    }
2660}
2661
2662impl Error for DynamicMeshError {}
2663
2664/// Host-selected work category constrained by [`DynamicMeshBudget`].
2665#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2666pub enum DynamicMeshBudgetResource {
2667    /// Triangle-list vertex count.
2668    Vertices,
2669    /// CPU bytes retained for exact recovery.
2670    RetainedBytes,
2671    /// GPU bytes uploaded by a full replacement.
2672    UploadBytes,
2673}
2674
2675/// Explicit retained and upload limits for caller-provided colored triangles.
2676#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2677pub struct DynamicMeshBudget {
2678    max_vertices: usize,
2679    max_retained_bytes: usize,
2680    max_upload_bytes: usize,
2681}
2682
2683impl DynamicMeshBudget {
2684    /// Creates limits large enough for at least one complete triangle.
2685    pub fn new(
2686        max_vertices: usize,
2687        max_retained_bytes: usize,
2688        max_upload_bytes: usize,
2689    ) -> Result<Self, DynamicMeshError> {
2690        let triangle_bytes = 3 * std::mem::size_of::<DynamicGpu>();
2691        if max_vertices < 3
2692            || max_retained_bytes < triangle_bytes
2693            || max_upload_bytes < triangle_bytes
2694        {
2695            return Err(DynamicMeshError::InvalidBudget);
2696        }
2697        Ok(Self {
2698            max_vertices,
2699            max_retained_bytes,
2700            max_upload_bytes,
2701        })
2702    }
2703
2704    /// Returns the maximum retained triangle-list vertex count.
2705    pub const fn max_vertices(self) -> usize {
2706        self.max_vertices
2707    }
2708
2709    /// Returns the maximum exact CPU recovery bytes.
2710    pub const fn max_retained_bytes(self) -> usize {
2711        self.max_retained_bytes
2712    }
2713
2714    /// Returns the maximum bytes uploaded by one complete replacement.
2715    pub const fn max_upload_bytes(self) -> usize {
2716        self.max_upload_bytes
2717    }
2718}
2719
2720impl Default for DynamicMeshBudget {
2721    fn default() -> Self {
2722        Self {
2723            max_vertices: 1_000_000,
2724            max_retained_bytes: 64 * 1024 * 1024,
2725            max_upload_bytes: 64 * 1024 * 1024,
2726        }
2727    }
2728}
2729
2730/// Mutable GPU triangle-list geometry for high-frequency simulation visuals.
2731///
2732/// A mesh retains its CPU vertices for validation and recreates its GPU buffer
2733/// only when a replacement exceeds its current capacity. Use
2734/// [`WgpuRenderer::update_dynamic_mesh_range`] for in-place partial updates.
2735/// Its bounded camera-validation cache is cleared by every successful mutation.
2736pub struct DynamicMesh2d {
2737    renderer_identity: Arc<()>,
2738    vertex_buffer: Arc<wgpu::Buffer>,
2739    vertices: Vec<DynamicGpu>,
2740    vertex_capacity: usize,
2741    geometry_extents: GeometryExtents,
2742    geometry_validation_cache: GeometryValidationCache,
2743    budget: Option<DynamicMeshBudget>,
2744}
2745
2746impl DynamicMesh2d {
2747    /// Returns the number of triangle-list vertices currently stored.
2748    pub fn vertex_count(&self) -> usize {
2749        self.vertices.len()
2750    }
2751
2752    /// Returns the number of vertices that fit without reallocating its GPU buffer.
2753    pub fn vertex_capacity(&self) -> usize {
2754        self.vertex_capacity
2755    }
2756
2757    /// Returns retained CPU memory used for validation and future updates.
2758    pub fn recovery_memory_bytes(&self) -> usize {
2759        self.vertices
2760            .capacity()
2761            .saturating_mul(std::mem::size_of::<DynamicGpu>())
2762    }
2763
2764    /// Returns explicit limits, or `None` for the compatibility constructor.
2765    pub const fn budget(&self) -> Option<DynamicMeshBudget> {
2766        self.budget
2767    }
2768}
2769
2770/// CPU-side outcome of one dynamic mesh update.
2771#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2772pub struct DynamicMeshUpdateReport {
2773    vertex_count: usize,
2774    upload: Duration,
2775    reallocated: bool,
2776}
2777
2778impl DynamicMeshUpdateReport {
2779    /// Returns the current triangle-list vertex count after the update.
2780    pub fn vertex_count(self) -> usize {
2781        self.vertex_count
2782    }
2783
2784    /// Returns CPU time spent validating, allocating when needed, and writing GPU data.
2785    pub fn upload(self) -> Duration {
2786        self.upload
2787    }
2788
2789    /// Returns whether this update grew and replaced the mesh GPU buffer.
2790    pub fn reallocated(self) -> bool {
2791        self.reallocated
2792    }
2793}
2794
2795/// Counts associated with one particle-field update or draw.
2796#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2797pub struct ParticleStatistics {
2798    submitted: usize,
2799    visibility_checked: usize,
2800    visible: usize,
2801    culled: usize,
2802    budget_limited: usize,
2803    dropped: usize,
2804    rendered: usize,
2805}
2806
2807impl ParticleStatistics {
2808    /// Returns instances supplied by the host.
2809    pub fn submitted(self) -> usize {
2810        self.submitted
2811    }
2812
2813    /// Returns instances tested against the camera viewport this frame.
2814    pub fn visibility_checked(self) -> usize {
2815        self.visibility_checked
2816    }
2817
2818    /// Returns checked instances that intersect the camera viewport.
2819    pub fn visible(self) -> usize {
2820        self.visible
2821    }
2822
2823    /// Returns instances outside the current camera viewport.
2824    pub fn culled(self) -> usize {
2825        self.culled
2826    }
2827
2828    /// Returns unchecked or camera-visible instances omitted by the render budget.
2829    pub fn budget_limited(self) -> usize {
2830        self.budget_limited
2831    }
2832
2833    /// Returns instances rejected before GPU submission.
2834    pub fn dropped(self) -> usize {
2835        self.dropped
2836    }
2837
2838    /// Returns instances submitted to the particle draw call.
2839    pub fn rendered(self) -> usize {
2840        self.rendered
2841    }
2842}
2843
2844/// Hard steady-state per-field limits for bounding particle visualization.
2845///
2846/// Atomic replacement temporarily retains the old and fully prepared new
2847/// state together. Its CPU/GPU peak is therefore bounded by the sum of the old
2848/// and new budgets, while every committed field stays within its own budget.
2849#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2850pub struct ParticleRenderBudget {
2851    max_visible_instances: usize,
2852    max_retained_bytes: usize,
2853    max_gpu_bytes: usize,
2854    max_upload_bytes_per_frame: usize,
2855    max_visibility_checks_per_frame: usize,
2856}
2857
2858impl ParticleRenderBudget {
2859    /// Bytes used by one retained or visibility-staging particle slot.
2860    pub const INSTANCE_BYTES: usize = std::mem::size_of::<ParticleGpu>();
2861
2862    /// No application-level cap beyond active-device allocation limits.
2863    pub const UNBOUNDED: Self = Self {
2864        max_visible_instances: usize::MAX,
2865        max_retained_bytes: usize::MAX,
2866        max_gpu_bytes: usize::MAX,
2867        max_upload_bytes_per_frame: usize::MAX,
2868        max_visibility_checks_per_frame: usize::MAX,
2869    };
2870
2871    /// Creates explicit visible-instance, retained-CPU, GPU-memory, and
2872    /// per-frame upload caps.
2873    pub fn new(
2874        max_visible_instances: usize,
2875        max_retained_bytes: usize,
2876        max_gpu_bytes: usize,
2877        max_upload_bytes_per_frame: usize,
2878    ) -> Result<Self, ParticleBudgetError> {
2879        let minimum_bytes = Self::INSTANCE_BYTES;
2880        let minimum_retained_bytes = minimum_bytes.saturating_mul(2);
2881        if max_visible_instances == 0
2882            || max_visible_instances > u32::MAX as usize
2883            || max_retained_bytes < minimum_retained_bytes
2884            || max_gpu_bytes < minimum_bytes
2885            || max_upload_bytes_per_frame < minimum_bytes
2886        {
2887            return Err(ParticleBudgetError::InvalidLimit);
2888        }
2889        Ok(Self {
2890            max_visible_instances,
2891            max_retained_bytes,
2892            max_gpu_bytes,
2893            max_upload_bytes_per_frame,
2894            max_visibility_checks_per_frame: usize::MAX,
2895        })
2896    }
2897
2898    /// Caps camera visibility checks while sampling candidates uniformly across
2899    /// the retained field. The cap must fit the effective visible-instance cap.
2900    pub fn with_max_visibility_checks(
2901        mut self,
2902        max_visibility_checks_per_frame: usize,
2903    ) -> Result<Self, ParticleBudgetError> {
2904        if max_visibility_checks_per_frame < self.instance_limit() {
2905            return Err(ParticleBudgetError::InvalidLimit);
2906        }
2907        self.max_visibility_checks_per_frame = max_visibility_checks_per_frame;
2908        Ok(self)
2909    }
2910
2911    /// Returns the maximum camera-visible instances considered for drawing.
2912    pub const fn max_visible_instances(self) -> usize {
2913        self.max_visible_instances
2914    }
2915
2916    /// Returns the maximum steady-state engine-owned particle allocation in bytes.
2917    pub const fn max_retained_bytes(self) -> usize {
2918        self.max_retained_bytes
2919    }
2920
2921    /// Returns the maximum particle instance-buffer allocation in bytes.
2922    pub const fn max_gpu_bytes(self) -> usize {
2923        self.max_gpu_bytes
2924    }
2925
2926    /// Returns the maximum particle bytes uploaded by one render call.
2927    pub const fn max_upload_bytes_per_frame(self) -> usize {
2928        self.max_upload_bytes_per_frame
2929    }
2930
2931    /// Returns the maximum retained instances checked against the viewport.
2932    pub const fn max_visibility_checks_per_frame(self) -> usize {
2933        self.max_visibility_checks_per_frame
2934    }
2935
2936    fn instance_limit(self) -> usize {
2937        self.max_visible_instances
2938            .min(self.max_gpu_bytes / std::mem::size_of::<ParticleGpu>())
2939            .min(self.max_upload_bytes_per_frame / std::mem::size_of::<ParticleGpu>())
2940    }
2941}
2942
2943impl Default for ParticleRenderBudget {
2944    fn default() -> Self {
2945        Self::UNBOUNDED
2946    }
2947}
2948
2949/// Invalid particle visualization resource budget.
2950#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2951pub enum ParticleBudgetError {
2952    /// CPU retention must fit one source plus one staging slot; GPU/upload
2953    /// limits must each fit at least one visible particle instance.
2954    InvalidLimit,
2955}
2956
2957impl fmt::Display for ParticleBudgetError {
2958    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2959        write!(
2960            formatter,
2961            "particle budget must fit one retained instance, its visibility staging slot, and one visible GPU upload"
2962        )
2963    }
2964}
2965
2966impl Error for ParticleBudgetError {}
2967
2968/// Renderer-owned instanced particles for high-volume simulation visuals.
2969///
2970/// The field retains its validated CPU instances so it can be recreated after
2971/// device loss. Its GPU instance buffer grows only when a replacement exceeds
2972/// the current capacity.
2973pub struct ParticleField2d {
2974    renderer_identity: Arc<()>,
2975    instance_buffer: Arc<wgpu::Buffer>,
2976    instances: Vec<ParticleGpu>,
2977    visible_instances: Vec<ParticleGpu>,
2978    instance_capacity: usize,
2979    budget: ParticleRenderBudget,
2980    statistics: ParticleStatistics,
2981}
2982
2983impl ParticleField2d {
2984    /// Returns the number of particle instances currently stored.
2985    pub fn instance_count(&self) -> usize {
2986        self.instances.len()
2987    }
2988
2989    /// Returns the number of instances that fit without reallocating GPU memory.
2990    pub fn instance_capacity(&self) -> usize {
2991        self.instance_capacity
2992    }
2993
2994    /// Returns the most recent update or draw counts.
2995    pub fn statistics(&self) -> ParticleStatistics {
2996        self.statistics
2997    }
2998
2999    /// Returns the hard visualization budget applied by rendering.
3000    pub fn budget(&self) -> ParticleRenderBudget {
3001        self.budget
3002    }
3003
3004    /// Returns retained CPU memory used for recovery and validation.
3005    pub fn recovery_memory_bytes(&self) -> usize {
3006        self.instances
3007            .capacity()
3008            .saturating_mul(std::mem::size_of::<ParticleGpu>())
3009    }
3010
3011    /// Returns currently reserved CPU bytes for retained and culled instance lists.
3012    pub fn cpu_allocation_bytes(&self) -> usize {
3013        self.instances
3014            .capacity()
3015            .saturating_add(self.visible_instances.capacity())
3016            .saturating_mul(std::mem::size_of::<ParticleGpu>())
3017    }
3018
3019    /// Returns allocated GPU instance-buffer bytes.
3020    pub fn gpu_allocation_bytes(&self) -> usize {
3021        self.instance_capacity
3022            .saturating_mul(std::mem::size_of::<ParticleGpu>())
3023    }
3024}
3025
3026/// Failure while creating or updating a [`ParticleField2d`].
3027#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3028pub enum ParticleFieldError {
3029    /// An input instance violates the portable particle contract.
3030    InvalidInstance,
3031    /// A partial update lies outside the field's current instance range.
3032    UpdateRangeOutOfBounds,
3033    /// The field belongs to another renderer and GPU device.
3034    RendererMismatch,
3035    /// The instance capacity exceeds the current device's buffer limit.
3036    CapacityTooLarge,
3037    /// The retained CPU allocation exceeds the host-selected hard ceiling.
3038    RetainedBudgetExceeded {
3039        /// Configured retained-allocation ceiling.
3040        limit: usize,
3041        /// Required or actually reserved retained bytes.
3042        actual: usize,
3043    },
3044    /// Particle retention, replacement, or visibility-staging storage could
3045    /// not be reserved without panicking.
3046    AllocationFailed {
3047        /// Bytes requested by the failed particle-storage reservation.
3048        requested_bytes: usize,
3049    },
3050}
3051
3052impl fmt::Display for ParticleFieldError {
3053    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3054        match self {
3055            Self::InvalidInstance => write!(
3056                formatter,
3057                "particle field positions, depth, and radius must be portable and colors valid"
3058            ),
3059            Self::UpdateRangeOutOfBounds => {
3060                write!(
3061                    formatter,
3062                    "particle update range is outside the current field"
3063                )
3064            }
3065            Self::RendererMismatch => {
3066                write!(formatter, "particle field belongs to a different renderer")
3067            }
3068            Self::CapacityTooLarge => {
3069                write!(
3070                    formatter,
3071                    "particle field exceeds the GPU instance-buffer limit"
3072                )
3073            }
3074            Self::RetainedBudgetExceeded { limit, actual } => write!(
3075                formatter,
3076                "particle retained CPU allocation {actual} bytes exceeds limit {limit}"
3077            ),
3078            Self::AllocationFailed { requested_bytes } => write!(
3079                formatter,
3080                "could not reserve {requested_bytes} bytes for particle storage"
3081            ),
3082        }
3083    }
3084}
3085
3086impl Error for ParticleFieldError {}
3087
3088/// CPU-side outcome of one particle-field update.
3089#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3090pub struct ParticleFieldUpdateReport {
3091    statistics: ParticleStatistics,
3092    preparation: Duration,
3093    reallocated: bool,
3094}
3095
3096impl ParticleFieldUpdateReport {
3097    /// Returns submitted, visible, dropped, and rendered instance counts.
3098    pub fn statistics(self) -> ParticleStatistics {
3099        self.statistics
3100    }
3101
3102    /// Returns CPU time spent validating and retaining the new visual state.
3103    ///
3104    /// GPU upload is deferred until rendering, after camera culling has selected
3105    /// the compact visible set.
3106    pub fn preparation(self) -> Duration {
3107        self.preparation
3108    }
3109
3110    /// Backward-compatible alias for [`ParticleFieldUpdateReport::preparation`].
3111    #[deprecated(note = "particle GPU upload is deferred to render; use preparation()")]
3112    pub fn upload(self) -> Duration {
3113        self.preparation
3114    }
3115
3116    /// Returns whether this update grew and replaced the GPU instance buffer.
3117    pub fn reallocated(self) -> bool {
3118        self.reallocated
3119    }
3120}
3121
3122/// Failure while rendering a [`ParticleField2d`].
3123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3124pub enum ParticleFieldRenderError {
3125    /// The field belongs to another renderer and GPU device.
3126    RendererMismatch,
3127    /// The clear color is not normalized linear RGBA.
3128    InvalidBackground,
3129    /// Particle projection cannot be proven inside the portable GPU envelope.
3130    InvalidGeometryTransform,
3131    /// Surface acquisition or presentation failed.
3132    Frame(RendererFrameError),
3133}
3134
3135impl fmt::Display for ParticleFieldRenderError {
3136    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3137        match self {
3138            Self::RendererMismatch => {
3139                write!(formatter, "particle field belongs to a different renderer")
3140            }
3141            Self::InvalidBackground => {
3142                write!(formatter, "particle field background must be normalized")
3143            }
3144            Self::InvalidGeometryTransform => {
3145                write!(formatter, "particle field geometry transform is invalid")
3146            }
3147            Self::Frame(error) => write!(formatter, "particle field frame failed: {error}"),
3148        }
3149    }
3150}
3151
3152impl Error for ParticleFieldRenderError {}
3153
3154/// Renderer-owned scalar texture retaining its validated source field.
3155pub struct ScalarFieldTexture {
3156    renderer_identity: Arc<()>,
3157    texture: wgpu::Texture,
3158    field: ScalarField,
3159    source_minimum: f32,
3160    source_maximum: f32,
3161}
3162
3163impl ScalarFieldTexture {
3164    /// Returns the current grid width in texels.
3165    pub fn width(&self) -> usize {
3166        self.field.width()
3167    }
3168
3169    /// Returns the current grid height in texels.
3170    pub fn height(&self) -> usize {
3171        self.field.height()
3172    }
3173
3174    /// Returns retained CPU scalar data used for recovery and uploads.
3175    pub fn field(&self) -> &ScalarField {
3176        &self.field
3177    }
3178
3179    /// Returns retained CPU scalar bytes used for device-loss recovery.
3180    pub fn recovery_memory_bytes(&self) -> usize {
3181        self.field.value_allocation_bytes()
3182    }
3183
3184    /// Returns nominal `R32Float` texel-storage bytes requested from the GPU,
3185    /// excluding backend row/tile/page alignment and metadata.
3186    pub fn gpu_allocation_bytes(&self) -> usize {
3187        self.field
3188            .values()
3189            .len()
3190            .saturating_mul(std::mem::size_of::<f32>())
3191    }
3192}
3193
3194/// A renderer-owned offscreen color target in physical texture pixels.
3195///
3196/// Targets preserve GPU pixels only; a host must redraw them after device
3197/// recreation. Use the renderer's physical [`WgpuRenderer::size`] when a
3198/// target should match the presentation surface exactly.
3199pub struct RenderTarget2d {
3200    renderer_identity: Arc<()>,
3201    resource_identity: Arc<()>,
3202    _texture: wgpu::Texture,
3203    view: wgpu::TextureView,
3204    width: u32,
3205    height: u32,
3206    allocation_bytes: usize,
3207}
3208
3209/// A pair of offscreen targets used for bounded temporal accumulation.
3210///
3211/// Each accumulation retains a caller-selected amount of the previous frame
3212/// and then composites a distinct source target over it. The buffer owns no
3213/// domain state and can therefore serve particles, scalar fields, or any later
3214/// target-rendering producer.
3215pub struct TrailBuffer2d {
3216    renderer_identity: Arc<()>,
3217    front: RenderTarget2d,
3218    back: RenderTarget2d,
3219}
3220
3221impl TrailBuffer2d {
3222    /// Returns trail-buffer width in physical texture pixels.
3223    pub fn width(&self) -> u32 {
3224        self.front.width()
3225    }
3226
3227    /// Returns trail-buffer height in physical texture pixels.
3228    pub fn height(&self) -> u32 {
3229        self.front.height()
3230    }
3231
3232    /// Returns trail-buffer physical dimensions.
3233    pub fn size(&self) -> (u32, u32) {
3234        self.front.size()
3235    }
3236
3237    /// Returns nominal texel-storage bytes for both ping-pong textures.
3238    pub fn allocation_bytes(&self) -> usize {
3239        self.front
3240            .allocation_bytes()
3241            .saturating_add(self.back.allocation_bytes())
3242    }
3243}
3244
3245impl RenderTarget2d {
3246    /// Returns target width in physical texture pixels.
3247    pub fn width(&self) -> u32 {
3248        self.width
3249    }
3250
3251    /// Returns target height in physical texture pixels.
3252    pub fn height(&self) -> u32 {
3253        self.height
3254    }
3255
3256    /// Returns the physical texture dimensions.
3257    pub fn size(&self) -> (u32, u32) {
3258        (self.width, self.height)
3259    }
3260
3261    /// Returns nominal single-level texel-storage bytes implied by its format.
3262    /// Backend row/tile/page alignment and resource metadata are not observable
3263    /// through wgpu and are therefore excluded.
3264    pub fn allocation_bytes(&self) -> usize {
3265        self.allocation_bytes
3266    }
3267}
3268
3269/// Failure while creating or composing a [`RenderTarget2d`].
3270#[derive(Debug, Clone, Copy, PartialEq)]
3271pub enum RenderTargetError {
3272    /// Target dimensions must both be non-zero.
3273    ZeroDimension,
3274    /// Dimensions exceed the current device's supported target size or allocation range.
3275    DimensionsTooLarge,
3276    /// The target belongs to another renderer and GPU device.
3277    RendererMismatch,
3278    /// Opacity must be finite and within `0.0..=1.0`.
3279    InvalidOpacity,
3280    /// A temporal source must not be one of its destination ping-pong targets.
3281    SourceAliasesDestination,
3282    /// The destination clear color was not normalized linear RGBA.
3283    InvalidBackground,
3284    /// Surface acquisition or presentation failed.
3285    Frame(RendererFrameError),
3286}
3287
3288impl fmt::Display for RenderTargetError {
3289    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3290        match self {
3291            Self::ZeroDimension => write!(formatter, "render target dimensions must be non-zero"),
3292            Self::DimensionsTooLarge => {
3293                write!(formatter, "render target dimensions exceed device limits")
3294            }
3295            Self::RendererMismatch => {
3296                write!(formatter, "render target belongs to a different renderer")
3297            }
3298            Self::InvalidOpacity => write!(
3299                formatter,
3300                "render target opacity must be finite and in 0.0..=1.0"
3301            ),
3302            Self::SourceAliasesDestination => {
3303                write!(
3304                    formatter,
3305                    "trail source must be distinct from its destination targets"
3306                )
3307            }
3308            Self::InvalidBackground => {
3309                write!(formatter, "render target background must be normalized")
3310            }
3311            Self::Frame(error) => write!(formatter, "render target frame failed: {error}"),
3312        }
3313    }
3314}
3315
3316impl Error for RenderTargetError {}
3317
3318/// Failure while creating or updating a [`ScalarFieldTexture`].
3319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3320pub enum ScalarFieldTextureError {
3321    /// The texture belongs to another renderer and GPU device.
3322    RendererMismatch,
3323    /// Grid dimensions exceed the addressable `wgpu` texture range.
3324    DimensionsTooLarge,
3325    /// A region does not fit inside the current scalar texture.
3326    UpdateRegionOutOfBounds,
3327    /// Region values did not match the region dimensions.
3328    InvalidUpdateValueCount,
3329    /// A region value was NaN or infinite.
3330    NonFiniteUpdateValue,
3331    /// A finite scalar source lies outside the portable GPU arithmetic envelope.
3332    NonPortableValue,
3333    /// CPU recovery storage could not be reserved.
3334    AllocationFailed {
3335        /// Bytes requested for the rejected retained scalar copy.
3336        requested_bytes: usize,
3337    },
3338}
3339
3340impl fmt::Display for ScalarFieldTextureError {
3341    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3342        match self {
3343            Self::RendererMismatch => write!(
3344                formatter,
3345                "scalar field texture belongs to a different renderer"
3346            ),
3347            Self::DimensionsTooLarge => write!(
3348                formatter,
3349                "scalar field dimensions exceed GPU texture limits"
3350            ),
3351            Self::UpdateRegionOutOfBounds => {
3352                write!(formatter, "scalar texture update region is out of bounds")
3353            }
3354            Self::InvalidUpdateValueCount => {
3355                write!(
3356                    formatter,
3357                    "scalar texture update values do not match the region"
3358                )
3359            }
3360            Self::NonFiniteUpdateValue => {
3361                write!(formatter, "scalar texture update values must be finite")
3362            }
3363            Self::NonPortableValue => write!(
3364                formatter,
3365                "scalar values must be normal-or-zero and remain inside the portable GPU arithmetic envelope"
3366            ),
3367            Self::AllocationFailed { requested_bytes } => write!(
3368                formatter,
3369                "could not reserve {requested_bytes} bytes for scalar field recovery data"
3370            ),
3371        }
3372    }
3373}
3374
3375impl Error for ScalarFieldTextureError {}
3376
3377/// Failure while rendering a scalar texture as a heatmap.
3378#[derive(Debug, Clone, Copy, PartialEq)]
3379pub enum ScalarFieldRenderError {
3380    /// The texture belongs to another renderer and GPU device.
3381    RendererMismatch,
3382    /// The scalar range was non-finite or did not have positive extent.
3383    InvalidValueRange {
3384        /// Lower bound supplied by the caller.
3385        minimum: f32,
3386        /// Upper bound supplied by the caller.
3387        maximum: f32,
3388    },
3389    /// The clear color is not normalized linear RGBA.
3390    InvalidBackground,
3391    /// Surface acquisition or presentation failed.
3392    Frame(RendererFrameError),
3393}
3394
3395impl fmt::Display for ScalarFieldRenderError {
3396    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3397        match self {
3398            Self::RendererMismatch => write!(
3399                formatter,
3400                "scalar field texture belongs to a different renderer"
3401            ),
3402            Self::InvalidValueRange { minimum, maximum } => {
3403                write!(formatter, "invalid scalar value range {minimum}..{maximum}")
3404            }
3405            Self::InvalidBackground => {
3406                write!(formatter, "scalar field background must be normalized")
3407            }
3408            Self::Frame(error) => write!(formatter, "scalar field frame failed: {error}"),
3409        }
3410    }
3411}
3412
3413impl Error for ScalarFieldRenderError {}
3414
3415/// CPU-side outcome of one scalar-field texture upload.
3416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3417pub struct ScalarFieldUploadReport {
3418    upload: Duration,
3419    reallocated: bool,
3420}
3421
3422impl ScalarFieldUploadReport {
3423    /// Returns CPU time spent allocating when needed and enqueuing the upload.
3424    pub fn upload(self) -> Duration {
3425        self.upload
3426    }
3427
3428    /// Returns whether differing dimensions recreated the GPU texture.
3429    pub fn reallocated(self) -> bool {
3430        self.reallocated
3431    }
3432}
3433
3434/// Failure while rendering a [`DynamicMesh2d`].
3435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3436pub enum DynamicMeshRenderError {
3437    /// The mesh belongs to another renderer and GPU device.
3438    RendererMismatch,
3439    /// The clear color is not normalized linear RGBA.
3440    InvalidBackground,
3441    /// Frame rendering failed after dynamic-mesh ownership validation.
3442    Frame(RendererFrameError),
3443}
3444
3445impl fmt::Display for DynamicMeshRenderError {
3446    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3447        match self {
3448            Self::RendererMismatch => {
3449                write!(formatter, "dynamic mesh belongs to a different renderer")
3450            }
3451            Self::InvalidBackground => {
3452                write!(formatter, "dynamic mesh background must be normalized")
3453            }
3454            Self::Frame(error) => write!(formatter, "dynamic mesh frame failed: {error}"),
3455        }
3456    }
3457}
3458
3459impl Error for DynamicMeshRenderError {}
3460
3461impl PreparedScene {
3462    /// Returns the number of accepted source scene commands.
3463    pub fn command_count(&self) -> usize {
3464        self.command_count
3465    }
3466
3467    /// Returns the number of triangle-list vertices stored in the GPU buffer.
3468    pub fn vertex_count(&self) -> usize {
3469        self.vertex_count
3470    }
3471
3472    /// Returns the number of clip-compatible draw batches.
3473    pub fn draw_batch_count(&self) -> usize {
3474        self.draw_batches.len()
3475    }
3476
3477    /// Returns currently allocated CPU recovery bytes for vertices and draw batches.
3478    pub fn recovery_memory_bytes(&self) -> usize {
3479        self.vertices
3480            .capacity()
3481            .saturating_mul(std::mem::size_of::<Vertex>())
3482            .saturating_add(
3483                self.draw_batches
3484                    .capacity()
3485                    .saturating_mul(std::mem::size_of::<PreparedDrawBatch>()),
3486            )
3487    }
3488
3489    /// Returns command-level tessellation results captured during preparation.
3490    pub fn tessellation_stats(&self) -> TessellationStats {
3491        self.tessellation
3492    }
3493}
3494
3495impl PreparedScreenScene {
3496    /// Returns the number of accepted source screen commands.
3497    pub fn command_count(&self) -> usize {
3498        self.scene.command_count()
3499    }
3500
3501    /// Returns the retained triangle-list vertex count.
3502    pub fn vertex_count(&self) -> usize {
3503        self.scene.vertex_count()
3504    }
3505
3506    /// Returns the number of clip-compatible draw batches.
3507    pub fn draw_batch_count(&self) -> usize {
3508        self.scene.draw_batch_count()
3509    }
3510
3511    /// Returns retained CPU bytes available for device-loss recovery.
3512    pub fn recovery_memory_bytes(&self) -> usize {
3513        self.scene.recovery_memory_bytes()
3514    }
3515
3516    /// Returns preparation-time tessellation statistics.
3517    pub fn tessellation_stats(&self) -> TessellationStats {
3518        self.scene.tessellation_stats()
3519    }
3520}
3521
3522/// `wgpu` backend that renders [`Scene`] commands into a presentation surface.
3523///
3524/// The renderer owns the GPU device, queue, surface, pipeline, and transient
3525/// vertex buffer. Window creation stays outside the library so each application
3526/// can choose its own windowing framework.
3527pub struct WgpuRenderer {
3528    renderer_identity: Arc<()>,
3529    _instance: wgpu::Instance,
3530    surface: wgpu::Surface<'static>,
3531    _adapter: wgpu::Adapter,
3532    adapter_info: wgpu::AdapterInfo,
3533    device: wgpu::Device,
3534    queue: wgpu::Queue,
3535    config: wgpu::SurfaceConfiguration,
3536    requested_present_mode: RendererPresentMode,
3537    surface_present_mode: RendererSurfacePresentMode,
3538    pre_present_notify: Option<Arc<dyn Fn() + Send + Sync>>,
3539    scale_factor: f64,
3540    pipeline: wgpu::RenderPipeline,
3541    target_pipeline: wgpu::RenderPipeline,
3542    dynamic_pipeline: wgpu::RenderPipeline,
3543    particle_pipeline: wgpu::RenderPipeline,
3544    target_particle_pipeline: wgpu::RenderPipeline,
3545    heatmap_pipeline: wgpu::RenderPipeline,
3546    target_heatmap_pipeline: wgpu::RenderPipeline,
3547    composition_pipelines: CompositionPipelines,
3548    target_composition_pipelines: CompositionPipelines,
3549    image_renderer: ImageRenderer,
3550    mesh3d_renderer: Mesh3dRenderer,
3551    gpu_timing: gpu_timing::GpuTimingCollector,
3552    gpu_timing_requested: bool,
3553    camera_uniform_buffer: wgpu::Buffer,
3554    camera_bind_group: wgpu::BindGroup,
3555    camera_bind_group_layout: wgpu::BindGroupLayout,
3556    heatmap_uniform_buffer: wgpu::Buffer,
3557    heatmap_bind_group_layout: wgpu::BindGroupLayout,
3558    color_map_cache: Option<CachedColorMap>,
3559    frame_cache: frame::FrameCache,
3560    vertex_buffer: Arc<wgpu::Buffer>,
3561    particle_unit_buffer: wgpu::Buffer,
3562    vertex_capacity: usize,
3563    multisample_target: Option<MultisampleTarget>,
3564    sample_count: u32,
3565    vertices: Vec<Vertex>,
3566    draw_batches: Vec<PreparedDrawBatch>,
3567    retired_devices: Vec<RetiredDevice>,
3568    max_quarantined_devices: usize,
3569}
3570
3571struct RetiredDevice {
3572    _adapter: wgpu::Adapter,
3573    _device: wgpu::Device,
3574    _queue: wgpu::Queue,
3575}
3576
3577impl WgpuRenderer {
3578    /// Creates a renderer for a window or canvas surface target.
3579    ///
3580    /// `width` and `height` are physical surface pixels. Zero sizes are clamped
3581    /// to one pixel because `wgpu` surfaces cannot be configured at zero size.
3582    /// This convenience constructor assumes a display scale factor of `1.0`;
3583    /// HiDPI hosts should use [`WgpuRenderer::new_with_options`].
3584    pub async fn new(
3585        surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
3586        width: u32,
3587        height: u32,
3588    ) -> Result<Self, RendererInitError> {
3589        Self::new_with_options(
3590            surface_target,
3591            width,
3592            height,
3593            WgpuRendererOptions::default(),
3594        )
3595        .await
3596    }
3597
3598    /// Creates a renderer with explicit options.
3599    ///
3600    /// Use this when measuring renderer throughput or when the host application
3601    /// needs control over presentation behavior or display scale.
3602    pub async fn new_with_options(
3603        surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
3604        width: u32,
3605        height: u32,
3606        options: WgpuRendererOptions,
3607    ) -> Result<Self, RendererInitError> {
3608        let instance =
3609            wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
3610        let surface = instance
3611            .create_surface(surface_target)
3612            .map_err(RendererInitError::CreateSurface)?;
3613        let adapter = instance
3614            .request_adapter(&wgpu::RequestAdapterOptions {
3615                power_preference: wgpu::PowerPreference::HighPerformance,
3616                force_fallback_adapter: false,
3617                compatible_surface: Some(&surface),
3618                apply_limit_buckets: false,
3619            })
3620            .await
3621            .map_err(RendererInitError::RequestAdapter)?;
3622        let adapter_info = adapter.get_info();
3623
3624        let (device, queue) = adapter
3625            .request_device(&wgpu::DeviceDescriptor {
3626                label: Some("sim-engine device"),
3627                required_features: gpu_timing::requested_features(
3628                    adapter.features(),
3629                    options.gpu_timing(),
3630                ),
3631                required_limits: wgpu::Limits::default(),
3632                experimental_features: wgpu::ExperimentalFeatures::disabled(),
3633                memory_hints: wgpu::MemoryHints::Performance,
3634                trace: wgpu::Trace::Off,
3635            })
3636            .await
3637            .map_err(RendererInitError::RequestDevice)?;
3638
3639        let width = width.max(1);
3640        let height = height.max(1);
3641        let dimension_limit = device.limits().max_texture_dimension_2d;
3642        if width > dimension_limit || height > dimension_limit {
3643            return Err(RendererInitError::SurfaceDimensionsTooLarge {
3644                width,
3645                height,
3646                limit: dimension_limit,
3647            });
3648        }
3649        let surface_capabilities = surface.get_capabilities(&adapter);
3650        let mut config = surface
3651            .get_default_config(&adapter, width, height)
3652            .ok_or(RendererInitError::NoSurfaceConfig)?;
3653        let surface_present_mode = select_surface_present_mode(
3654            options.present_mode(),
3655            &surface_capabilities.present_modes,
3656        );
3657        config.present_mode = surface_present_mode.to_wgpu();
3658        surface.configure(&device, &config);
3659
3660        let sample_count = preferred_sample_count(&adapter, config.format);
3661        let PipelineResources {
3662            pipeline,
3663            target_pipeline,
3664            dynamic_pipeline,
3665            particle_pipeline,
3666            target_particle_pipeline,
3667            heatmap_pipeline,
3668            target_heatmap_pipeline,
3669            composition_pipelines,
3670            target_composition_pipelines,
3671            camera_uniform_buffer,
3672            camera_bind_group,
3673            camera_bind_group_layout,
3674            heatmap_uniform_buffer,
3675            heatmap_bind_group_layout,
3676        } = create_pipeline(&device, config.format, sample_count);
3677        let vertex_buffer = Arc::new(create_vertex_buffer(&device, INITIAL_VERTEX_CAPACITY));
3678        let particle_unit_buffer = create_submitted_particle_unit_buffer(&device, &queue);
3679        let multisample_target = create_multisample_target(&device, &config, sample_count);
3680        let image_renderer = ImageRenderer::new(&device, config.format, sample_count);
3681        let mesh3d_renderer = Mesh3dRenderer::new(&device, config.format);
3682        let gpu_timing = gpu_timing::GpuTimingCollector::new(&device, &queue, options.gpu_timing());
3683
3684        Ok(Self {
3685            renderer_identity: Arc::new(()),
3686            _instance: instance,
3687            surface,
3688            _adapter: adapter,
3689            adapter_info,
3690            device,
3691            queue,
3692            config,
3693            requested_present_mode: options.present_mode(),
3694            surface_present_mode,
3695            pre_present_notify: None,
3696            scale_factor: options.scale_factor(),
3697            pipeline,
3698            target_pipeline,
3699            dynamic_pipeline,
3700            particle_pipeline,
3701            target_particle_pipeline,
3702            heatmap_pipeline,
3703            target_heatmap_pipeline,
3704            composition_pipelines,
3705            target_composition_pipelines,
3706            image_renderer,
3707            mesh3d_renderer,
3708            gpu_timing,
3709            gpu_timing_requested: options.gpu_timing(),
3710            camera_uniform_buffer,
3711            camera_bind_group,
3712            camera_bind_group_layout,
3713            heatmap_uniform_buffer,
3714            heatmap_bind_group_layout,
3715            color_map_cache: None,
3716            frame_cache: frame::FrameCache::default(),
3717            vertex_buffer,
3718            particle_unit_buffer,
3719            vertex_capacity: INITIAL_VERTEX_CAPACITY,
3720            multisample_target,
3721            sample_count,
3722            vertices: Vec::new(),
3723            draw_batches: Vec::new(),
3724            retired_devices: Vec::new(),
3725            max_quarantined_devices: options.max_quarantined_devices(),
3726        })
3727    }
3728
3729    /// Returns the configured surface size in physical pixels.
3730    pub fn size(&self) -> (u32, u32) {
3731        (self.config.width, self.config.height)
3732    }
3733
3734    /// Returns optional GPU-query availability, bounded resources and losses.
3735    /// These diagnostics are independent of frame CPU timings and scene uploads.
3736    pub fn gpu_timing_statistics(&self) -> GpuTimingStatistics {
3737        self.gpu_timing.statistics()
3738    }
3739
3740    /// Collects at most eight completed GPU pass intervals without waiting.
3741    ///
3742    /// Call regularly when timing is enabled; uncollected samples occupy the
3743    /// fixed ring and eventually cause new samples to be dropped. Match sample
3744    /// IDs to submitted reports when excluding warmup or unrelated work. A call
3745    /// performs one nonblocking device poll and reports its CPU overhead. Device
3746    /// recovery discards pending old-device samples and resets the counters.
3747    pub fn collect_gpu_timings(&mut self) -> GpuTimingBatch {
3748        self.gpu_timing.collect(&self.device)
3749    }
3750
3751    /// Returns the render viewport size in logical screen pixels.
3752    ///
3753    /// Scene clipping, stroke widths, shadows, and camera zoom use this logical
3754    /// coordinate space so their visual size remains stable across display DPI.
3755    pub fn logical_size(&self) -> (f32, f32) {
3756        let scale_factor = self.scale_factor as f32;
3757        (
3758            self.config.width as f32 / scale_factor,
3759            self.config.height as f32 / scale_factor,
3760        )
3761    }
3762
3763    /// Returns the current camera viewport in logical screen pixels.
3764    pub fn logical_viewport(&self) -> Result<LogicalViewport, crate::LogicalViewportError> {
3765        let (width, height) = self.logical_size();
3766        LogicalViewport::new(width, height)
3767    }
3768
3769    /// Converts a physical surface position into logical screen pixels.
3770    pub fn physical_to_logical_screen(
3771        &self,
3772        position: PhysicalScreenPosition,
3773    ) -> Result<LogicalScreenPosition, RendererCoordinateError> {
3774        physical_to_logical_screen(position, self.scale_factor as f32)
3775    }
3776
3777    /// Converts a logical screen position into physical surface pixels.
3778    pub fn logical_to_physical_screen(
3779        &self,
3780        position: LogicalScreenPosition,
3781    ) -> Result<PhysicalScreenPosition, RendererCoordinateError> {
3782        logical_to_physical_screen(position, self.scale_factor as f32)
3783    }
3784
3785    /// Returns physical surface pixels per logical screen pixel.
3786    pub fn scale_factor(&self) -> f64 {
3787        self.scale_factor
3788    }
3789
3790    /// Returns the concrete presentation mode selected for the active surface.
3791    ///
3792    /// `RendererPresentMode::NoVsync` prefers Immediate, then Mailbox, then
3793    /// FIFO. This method reveals which supported fallback was configured. The
3794    /// desktop compositor may still pace host redraw callbacks independently.
3795    pub fn surface_present_mode(&self) -> RendererSurfacePresentMode {
3796        self.surface_present_mode
3797    }
3798
3799    /// Installs a host callback invoked immediately before synchronized
3800    /// surface presentation.
3801    ///
3802    /// A winit host should capture its `Arc<Window>` and call
3803    /// `Window::pre_present_notify` from this callback. The renderer invokes
3804    /// it after command submission and immediately before `Queue::present`,
3805    /// but only when the concrete surface mode is Mailbox, FIFO, or
3806    /// FIFO-relaxed. Immediate presentation deliberately remains uncapped.
3807    pub fn set_pre_present_notify(&mut self, notify: impl Fn() + Send + Sync + 'static) {
3808        self.pre_present_notify = Some(Arc::new(notify));
3809    }
3810
3811    /// Removes the synchronized-presentation callback, if one is installed.
3812    pub fn clear_pre_present_notify(&mut self) {
3813        self.pre_present_notify = None;
3814    }
3815
3816    fn notify_before_present(&self) {
3817        invoke_pre_present_notify(
3818            self.surface_present_mode,
3819            self.pre_present_notify.as_deref(),
3820        );
3821    }
3822
3823    /// Returns the active graphics adapter's human-readable name.
3824    pub fn adapter_name(&self) -> &str {
3825        &self.adapter_info.name
3826    }
3827
3828    /// Returns the active graphics API backend as a stable lowercase name.
3829    pub fn adapter_backend(&self) -> &'static str {
3830        self.adapter_info.backend.to_str()
3831    }
3832
3833    /// Returns the PCI vendor identifier reported for the active adapter.
3834    pub fn adapter_vendor_id(&self) -> u32 {
3835        self.adapter_info.vendor
3836    }
3837
3838    /// Returns the device identifier reported for the active adapter.
3839    pub fn adapter_device_id(&self) -> u32 {
3840        self.adapter_info.device
3841    }
3842
3843    /// Returns the backend-reported PCI bus address for the active adapter.
3844    ///
3845    /// Vulkan adapters expose this as `domain:bus:device.function` when the
3846    /// driver supports `VK_EXT_pci_bus_info`. An empty string means that the
3847    /// backend cannot identify a physical adapter instance; release evidence
3848    /// must not treat model identifiers alone as instance identity.
3849    pub fn adapter_pci_bus_id(&self) -> &str {
3850        &self.adapter_info.device_pci_bus_id
3851    }
3852
3853    /// Returns the texture format selected for the active presentation surface.
3854    pub fn surface_format(&self) -> wgpu::TextureFormat {
3855        self.config.format
3856    }
3857
3858    /// Returns the raster sample count selected for the active surface format.
3859    pub fn surface_sample_count(&self) -> u32 {
3860        self.sample_count
3861    }
3862
3863    /// Returns the driver name reported by the active graphics adapter.
3864    pub fn adapter_driver(&self) -> &str {
3865        &self.adapter_info.driver
3866    }
3867
3868    /// Returns the driver version or implementation detail reported by the adapter.
3869    pub fn adapter_driver_info(&self) -> &str {
3870        &self.adapter_info.driver_info
3871    }
3872
3873    /// Returns previous logical devices retained for safe native-driver teardown.
3874    pub fn quarantined_device_count(&self) -> usize {
3875        self.retired_devices.len()
3876    }
3877
3878    /// Returns the configured maximum previous-device quarantine size.
3879    pub fn max_quarantined_device_count(&self) -> usize {
3880        self.max_quarantined_devices
3881    }
3882
3883    /// Returns successful recoveries available before the bounded quarantine is full.
3884    pub fn remaining_device_recoveries(&self) -> usize {
3885        self.max_quarantined_devices
3886            .saturating_sub(self.retired_devices.len())
3887    }
3888
3889    /// Blocks until all previously submitted GPU work has completed.
3890    ///
3891    /// This is intended for diagnostic throughput measurements, readback, and
3892    /// controlled resource teardown. Calling it in an interactive frame loop
3893    /// defeats normal CPU/GPU pipelining.
3894    pub fn wait_for_gpu_idle(&self) -> Result<(), wgpu::PollError> {
3895        self.device
3896            .poll(wgpu::PollType::wait_indefinitely())
3897            .map(|_| ())
3898    }
3899
3900    /// Replaces display scale without changing physical surface dimensions.
3901    ///
3902    /// Invalid values return an error and leave the current scale unchanged.
3903    pub fn set_scale_factor(
3904        &mut self,
3905        scale_factor: f64,
3906    ) -> Result<(), RendererConfigurationError> {
3907        validate_scale_factor(scale_factor)?;
3908        self.scale_factor = scale_factor;
3909        Ok(())
3910    }
3911
3912    /// Reconfigures the surface after a host window resize.
3913    ///
3914    /// Zero width or height is ignored because minimized windows often report
3915    /// zero size and `wgpu` cannot configure a zero-sized surface.
3916    pub fn resize(&mut self, width: u32, height: u32) -> Result<(), RendererConfigurationError> {
3917        if width == 0 || height == 0 {
3918            return Ok(());
3919        }
3920        validate_surface_dimensions(width, height, self.device.limits().max_texture_dimension_2d)?;
3921
3922        self.config.width = width;
3923        self.config.height = height;
3924        self.surface.configure(&self.device, &self.config);
3925        self.multisample_target =
3926            create_multisample_target(&self.device, &self.config, self.sample_count);
3927        Ok(())
3928    }
3929
3930    /// Reconfigures physical surface size and logical-to-physical display scale.
3931    ///
3932    /// Invalid scale returns an error without changing either value. Zero
3933    /// physical dimensions update the scale but leave the minimized surface
3934    /// configuration unchanged.
3935    pub fn resize_with_scale_factor(
3936        &mut self,
3937        width: u32,
3938        height: u32,
3939        scale_factor: f64,
3940    ) -> Result<(), RendererConfigurationError> {
3941        validate_scale_factor(scale_factor)?;
3942        if width != 0 && height != 0 {
3943            validate_surface_dimensions(
3944                width,
3945                height,
3946                self.device.limits().max_texture_dimension_2d,
3947            )?;
3948        }
3949        self.resize(width, height)?;
3950        self.scale_factor = scale_factor;
3951        Ok(())
3952    }
3953
3954    /// Draws a scene using the supplied camera.
3955    ///
3956    /// Scene positions and sizes are in world units unless a style explicitly
3957    /// says logical screen pixels. The renderer converts world coordinates to
3958    /// logical screen coordinates through [`Camera2d`], then to normalized device
3959    /// coordinates for `wgpu`. Scissor rectangles are converted to physical
3960    /// surface pixels at the final backend boundary.
3961    pub fn render(
3962        &mut self,
3963        scene: &Scene,
3964        camera: &Camera2d,
3965    ) -> Result<RenderStatus, RendererFrameError> {
3966        self.render_with_metrics(scene, camera)
3967            .map(RenderReport::status)
3968    }
3969
3970    /// Draws fixed logical-screen geometry independently of any world camera.
3971    pub fn render_screen_scene(
3972        &mut self,
3973        scene: &ScreenScene,
3974    ) -> Result<RenderStatus, RendererFrameError> {
3975        self.render_screen_scene_with_metrics(scene)
3976            .map(RenderReport::status)
3977    }
3978
3979    /// Draws fixed logical-screen geometry and returns CPU-side stage timings.
3980    pub fn render_screen_scene_with_metrics(
3981        &mut self,
3982        scene: &ScreenScene,
3983    ) -> Result<RenderReport, RendererFrameError> {
3984        let viewport = LogicalViewport::new(self.logical_size().0, self.logical_size().1)
3985            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
3986        let camera =
3987            screen_camera(viewport).map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
3988        self.render_with_metrics(scene.as_scene(), &camera)
3989    }
3990
3991    /// Draws a scene and returns a CPU-side timing breakdown.
3992    ///
3993    /// Metrics separate tessellation, buffer upload, surface acquisition, and
3994    /// encode/submit/present dispatch. They do not measure GPU completion or the
3995    /// monitor scanout timestamp. Use this for diagnostics; [`WgpuRenderer::render`]
3996    /// is the simpler equivalent when stage timings are not needed.
3997    pub fn render_with_metrics(
3998        &mut self,
3999        scene: &Scene,
4000        camera: &Camera2d,
4001    ) -> Result<RenderReport, RendererFrameError> {
4002        self.render_with_metrics_in_region(scene, camera, None)
4003    }
4004
4005    /// Draws a world scene through a camera into one bounded logical viewport.
4006    ///
4007    /// Scene-local clips are interpreted relative to the viewport and are
4008    /// intersected with its physical bounds. The surface outside the viewport
4009    /// is cleared but receives no scene geometry.
4010    pub fn render_scene_in_viewport(
4011        &mut self,
4012        scene: &Scene,
4013        camera: &Camera2d,
4014        viewport: LogicalViewportRegion,
4015    ) -> Result<RenderStatus, RendererFrameError> {
4016        self.render_scene_in_viewport_with_metrics(scene, camera, viewport)
4017            .map(RenderReport::status)
4018    }
4019
4020    /// Draws one bounded scene viewport and returns CPU-side stage timings.
4021    pub fn render_scene_in_viewport_with_metrics(
4022        &mut self,
4023        scene: &Scene,
4024        camera: &Camera2d,
4025        viewport: LogicalViewportRegion,
4026    ) -> Result<RenderReport, RendererFrameError> {
4027        self.render_with_metrics_in_region(scene, camera, Some(viewport))
4028    }
4029
4030    /// Renders an ordinary world scene into an offscreen target.
4031    ///
4032    /// Target dimensions are physical texels. `pixel_scale` defines their
4033    /// logical viewport density independently of window DPI. Scene-local clips
4034    /// are relative to `viewport`, or to the complete logical target when no
4035    /// region is supplied. `load` explicitly controls preservation or clearing.
4036    #[allow(clippy::too_many_arguments)]
4037    pub fn render_scene_to_target(
4038        &mut self,
4039        target: &RenderTarget2d,
4040        scene: &Scene,
4041        camera: &Camera2d,
4042        pixel_scale: PhysicalPerLogical,
4043        viewport: Option<LogicalViewportRegion>,
4044        load: RenderTargetLoad,
4045    ) -> Result<RenderReport, RenderTargetError> {
4046        self.validate_render_target(target)?;
4047        if let RenderTargetLoad::Clear(color) = load
4048            && !color.is_normalized()
4049        {
4050            return Err(RenderTargetError::InvalidBackground);
4051        }
4052
4053        let frame_started_at = Instant::now();
4054        let scale = pixel_scale.get();
4055        let target_viewport = LogicalViewport::new(
4056            target.width() as f32 / scale,
4057            target.height() as f32 / scale,
4058        )
4059        .map_err(|_| RenderTargetError::Frame(RendererFrameError::InvalidViewport))?;
4060        let (local_viewport, origin) = match viewport {
4061            Some(region) => (region.viewport(), region.origin().to_vec2()),
4062            None => (target_viewport, Vec2::ZERO),
4063        };
4064        let max = origin + local_viewport.size();
4065        if !max.is_finite()
4066            || origin.x < 0.0
4067            || origin.y < 0.0
4068            || max.x > target_viewport.width()
4069            || max.y > target_viewport.height()
4070        {
4071            return Err(RenderTargetError::Frame(
4072                RendererFrameError::InvalidViewport,
4073            ));
4074        }
4075        let target_scissor = logical_viewport_scissor(
4076            origin,
4077            local_viewport,
4078            scale,
4079            target.width(),
4080            target.height(),
4081        )
4082        .ok_or(RenderTargetError::Frame(
4083            RendererFrameError::InvalidViewport,
4084        ))?;
4085        let camera_uniform =
4086            CameraUniform::new_in_region(*camera, local_viewport, origin, target_viewport).ok_or(
4087                RenderTargetError::Frame(RendererFrameError::InvalidGeometryTransform),
4088            )?;
4089
4090        let tessellation_started_at = Instant::now();
4091        if !scene_estimate_fits_streaming_device(scene, &self.device, 0, self.vertex_capacity) {
4092            return Err(RenderTargetError::Frame(
4093                RendererFrameError::GeometryCapacityTooLarge,
4094            ));
4095        }
4096        self.vertices.clear();
4097        self.draw_batches.clear();
4098        let tessellation_stats =
4099            tessellate_scene(scene, &mut self.vertices, &mut self.draw_batches)
4100                .map_err(RendererFrameError::from)
4101                .map_err(RenderTargetError::Frame)?;
4102        let tessellation = tessellation_started_at.elapsed();
4103
4104        let extents = GeometryExtents::from_vertices(&self.vertices);
4105        if !geometry_is_safe_for(
4106            extents,
4107            GeometryValidationSource::Tessellated(&self.vertices),
4108            camera_uniform,
4109        ) {
4110            return Err(RenderTargetError::Frame(
4111                RendererFrameError::InvalidGeometryTransform,
4112            ));
4113        }
4114        let upload_started_at = Instant::now();
4115        self.ensure_vertex_capacity(self.vertices.len())
4116            .map_err(RenderTargetError::Frame)?;
4117        if !self.vertices.is_empty() {
4118            self.queue
4119                .write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&self.vertices));
4120        }
4121        let upload = upload_started_at.elapsed();
4122        let uniform_started_at = Instant::now();
4123        self.queue.write_buffer(
4124            &self.camera_uniform_buffer,
4125            0,
4126            bytemuck::bytes_of(&camera_uniform),
4127        );
4128        let camera_uniform_upload = uniform_started_at.elapsed();
4129
4130        let encode_started_at = Instant::now();
4131        let mut encoder = self
4132            .device
4133            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
4134                label: Some("sim-engine scene target encoder"),
4135            });
4136        {
4137            let load = match load {
4138                RenderTargetLoad::Load => wgpu::LoadOp::Load,
4139                RenderTargetLoad::Clear(color) => {
4140                    wgpu::LoadOp::Clear(premultiplied_wgpu_color(color))
4141                }
4142            };
4143            let color_attachment = wgpu::RenderPassColorAttachment {
4144                view: &target.view,
4145                depth_slice: None,
4146                resolve_target: None,
4147                ops: wgpu::Operations {
4148                    load,
4149                    store: wgpu::StoreOp::Store,
4150                },
4151            };
4152            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
4153                label: Some("sim-engine scene target pass"),
4154                color_attachments: &[Some(color_attachment)],
4155                depth_stencil_attachment: None,
4156                timestamp_writes: None,
4157                occlusion_query_set: None,
4158                multiview_mask: None,
4159            });
4160            if !self.vertices.is_empty() {
4161                pass.set_pipeline(&self.target_pipeline);
4162                pass.set_bind_group(0, &self.camera_bind_group, &[]);
4163                pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
4164                for batch in &self.draw_batches {
4165                    let scissor = match batch.screen_clip {
4166                        Some(clip) => {
4167                            let Some(local) = screen_clip_to_scissor(clip, local_viewport, scale)
4168                            else {
4169                                continue;
4170                            };
4171                            let Some(scissor) = offset_scissor(local, target_scissor) else {
4172                                continue;
4173                            };
4174                            scissor
4175                        }
4176                        None => target_scissor,
4177                    };
4178                    pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
4179                    pass.draw(batch.vertex_range.clone(), 0..1);
4180                }
4181            }
4182        }
4183        self.queue.submit([encoder.finish()]);
4184        let encode = encode_started_at.elapsed();
4185
4186        Ok(render_report(
4187            RenderStatus::Drawn,
4188            tessellation,
4189            upload,
4190            camera_uniform_upload,
4191            Duration::ZERO,
4192            encode,
4193            frame_started_at.elapsed(),
4194            false,
4195            true,
4196            tessellation_stats,
4197        ))
4198    }
4199
4200    fn render_with_metrics_in_region(
4201        &mut self,
4202        scene: &Scene,
4203        camera: &Camera2d,
4204        viewport: Option<LogicalViewportRegion>,
4205    ) -> Result<RenderReport, RendererFrameError> {
4206        let frame_started_at = Instant::now();
4207        let (_, _, camera_uniform) = self.surface_geometry_context(*camera, viewport)?;
4208        let tessellation_started_at = Instant::now();
4209        if !scene_estimate_fits_streaming_device(scene, &self.device, 0, self.vertex_capacity) {
4210            return Err(RendererFrameError::GeometryCapacityTooLarge);
4211        }
4212        self.vertices.clear();
4213        self.draw_batches.clear();
4214        let tessellation_stats =
4215            tessellate_scene(scene, &mut self.vertices, &mut self.draw_batches)?;
4216        let tessellation = tessellation_started_at.elapsed();
4217
4218        let geometry_extents = GeometryExtents::from_vertices(&self.vertices);
4219        if !geometry_is_safe_for(
4220            geometry_extents,
4221            GeometryValidationSource::Tessellated(&self.vertices),
4222            camera_uniform,
4223        ) {
4224            return Err(RendererFrameError::InvalidGeometryTransform);
4225        }
4226
4227        let upload_started_at = Instant::now();
4228        self.ensure_vertex_capacity(self.vertices.len())?;
4229        let upload = upload_started_at.elapsed();
4230
4231        let vertex_buffer = Arc::clone(&self.vertex_buffer);
4232        let draw_batches = std::mem::take(&mut self.draw_batches);
4233        let vertices = std::mem::take(&mut self.vertices);
4234        let result = self.draw_geometry(
4235            scene.background(),
4236            &vertex_buffer,
4237            vertices.len(),
4238            geometry_extents,
4239            GeometryValidationSource::Tessellated(&vertices),
4240            None,
4241            &draw_batches,
4242            *camera,
4243            tessellation,
4244            upload,
4245            false,
4246            true,
4247            false,
4248            Some(&vertices),
4249            tessellation_stats,
4250            frame_started_at,
4251            viewport,
4252        );
4253        self.vertices = vertices;
4254        self.draw_batches = draw_batches;
4255        result
4256    }
4257
4258    /// Tessellates a scene once and uploads immutable geometry to a dedicated GPU buffer.
4259    ///
4260    /// Preparing is appropriate for geometry that will be drawn repeatedly while
4261    /// only the camera or target dimensions change. Any shape, style, gradient,
4262    /// ordering, or clipping change requires preparing a replacement scene.
4263    pub fn prepare_scene(&self, scene: &Scene) -> Result<PreparedScene, PreparedSceneError> {
4264        prepare_scene_resources(
4265            &self.device,
4266            &self.queue,
4267            Arc::clone(&self.renderer_identity),
4268            scene,
4269        )
4270    }
4271
4272    /// Tessellates fixed logical-screen geometry once for repeated composition.
4273    pub fn prepare_screen_scene(
4274        &self,
4275        scene: &ScreenScene,
4276    ) -> Result<PreparedScreenScene, PreparedSceneError> {
4277        self.prepare_scene(scene.as_scene())
4278            .map(|scene| PreparedScreenScene { scene })
4279    }
4280
4281    /// Restores prepared logical-screen geometry on a recreated renderer.
4282    pub fn restore_prepared_screen_scene(
4283        &self,
4284        source: &PreparedScreenScene,
4285    ) -> Result<PreparedScreenScene, PreparedSceneError> {
4286        self.restore_prepared_scene(&source.scene)
4287            .map(|scene| PreparedScreenScene { scene })
4288    }
4289
4290    /// Recreates prepared GPU resources on this renderer from a retained CPU snapshot.
4291    ///
4292    /// This supports renderer recreation after device loss without requiring the
4293    /// original high-level [`Scene`]. The returned snapshot belongs to this renderer.
4294    pub fn restore_prepared_scene(
4295        &self,
4296        source: &PreparedScene,
4297    ) -> Result<PreparedScene, PreparedSceneError> {
4298        restore_prepared_scene_resources(
4299            &self.device,
4300            &self.queue,
4301            Arc::clone(&self.renderer_identity),
4302            source,
4303        )
4304    }
4305
4306    /// Recreates a dynamic mesh on this renderer from its retained CPU vertices.
4307    ///
4308    /// Use this after recreating a renderer following device loss. The returned
4309    /// mesh belongs to this renderer and preserves the source mesh's capacity so
4310    /// subsequent updates retain the same allocation behavior.
4311    pub fn restore_dynamic_mesh(
4312        &self,
4313        source: &DynamicMesh2d,
4314    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4315        restore_dynamic_mesh_resources(
4316            &self.device,
4317            &self.queue,
4318            Arc::clone(&self.renderer_identity),
4319            source,
4320        )
4321    }
4322
4323    /// Creates mutable triangle-list geometry for a frequently changing visual.
4324    ///
4325    /// The vertex count must be divisible by three. The mesh is owned by this
4326    /// renderer and may only be updated or drawn through it.
4327    pub fn create_dynamic_mesh(
4328        &self,
4329        vertices: &[DynamicVertex2d],
4330    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4331        self.create_dynamic_mesh_inner(vertices, None)
4332    }
4333
4334    /// Creates bounded mutable colored triangles for composition in a frame.
4335    ///
4336    /// Validation and CPU reservation complete before any GPU allocation. The
4337    /// retained budget is also enforced by every later full or partial update.
4338    pub fn create_dynamic_mesh_with_budget(
4339        &self,
4340        vertices: &[DynamicVertex2d],
4341        budget: DynamicMeshBudget,
4342    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4343        self.create_dynamic_mesh_inner(vertices, Some(budget))
4344    }
4345
4346    fn create_dynamic_mesh_inner(
4347        &self,
4348        vertices: &[DynamicVertex2d],
4349        budget: Option<DynamicMeshBudget>,
4350    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4351        if let Some(budget) = budget {
4352            validate_dynamic_mesh_budget(budget, vertices.len())?;
4353        }
4354        let vertex_capacity = dynamic_vertex_capacity(vertices.len())
4355            .filter(|capacity| buffer_capacity_fits::<DynamicGpu>(&self.device, *capacity))
4356            .ok_or(DynamicMeshError::CapacityTooLarge)?;
4357        let vertices = dynamic_vertices_to_gpu(vertices)?;
4358        if let Some(budget) = budget {
4359            validate_dynamic_retained_capacity(budget, &vertices)?;
4360        }
4361        let vertex_buffer = Arc::new(create_dynamic_vertex_buffer(&self.device, vertex_capacity));
4362        if !vertices.is_empty() {
4363            self.queue
4364                .write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
4365            submit_pending_uploads(&self.queue);
4366        }
4367        Ok(DynamicMesh2d {
4368            renderer_identity: Arc::clone(&self.renderer_identity),
4369            geometry_extents: GeometryExtents::from_dynamic_vertices(&vertices),
4370            geometry_validation_cache: GeometryValidationCache::default(),
4371            vertex_buffer,
4372            vertices,
4373            vertex_capacity,
4374            budget,
4375        })
4376    }
4377
4378    /// Replaces all dynamic mesh vertices, growing GPU capacity only when needed.
4379    pub fn update_dynamic_mesh(
4380        &self,
4381        mesh: &mut DynamicMesh2d,
4382        vertices: &[DynamicVertex2d],
4383    ) -> Result<(), DynamicMeshError> {
4384        self.update_dynamic_mesh_with_metrics(mesh, vertices)
4385            .map(|_| ())
4386    }
4387
4388    /// Replaces all dynamic mesh vertices and returns CPU-side update metrics.
4389    pub fn update_dynamic_mesh_with_metrics(
4390        &self,
4391        mesh: &mut DynamicMesh2d,
4392        vertices: &[DynamicVertex2d],
4393    ) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
4394        self.validate_dynamic_mesh(mesh)?;
4395        replace_dynamic_mesh_resources(&self.device, &self.queue, mesh, vertices)
4396    }
4397
4398    /// Replaces a contiguous vertex range without reallocating the mesh buffer.
4399    ///
4400    /// The range must stay inside the current triangle list and its length must
4401    /// preserve triangle alignment, so callers cannot create partial triangles.
4402    pub fn update_dynamic_mesh_range(
4403        &self,
4404        mesh: &mut DynamicMesh2d,
4405        first_vertex: usize,
4406        vertices: &[DynamicVertex2d],
4407    ) -> Result<(), DynamicMeshError> {
4408        self.update_dynamic_mesh_range_with_metrics(mesh, first_vertex, vertices)
4409            .map(|_| ())
4410    }
4411
4412    /// Replaces a triangle-aligned range and returns CPU-side update metrics.
4413    pub fn update_dynamic_mesh_range_with_metrics(
4414        &self,
4415        mesh: &mut DynamicMesh2d,
4416        first_vertex: usize,
4417        vertices: &[DynamicVertex2d],
4418    ) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
4419        let update_started_at = Instant::now();
4420        self.validate_dynamic_mesh(mesh)?;
4421        let end = first_vertex
4422            .checked_add(vertices.len())
4423            .ok_or(DynamicMeshError::UpdateRangeOutOfBounds)?;
4424        if !first_vertex.is_multiple_of(3)
4425            || !vertices.len().is_multiple_of(3)
4426            || end > mesh.vertices.len()
4427        {
4428            return Err(DynamicMeshError::UpdateRangeOutOfBounds);
4429        }
4430        if let Some(budget) = mesh.budget {
4431            validate_dynamic_mesh_budget(budget, mesh.vertices.len())?;
4432            let upload_bytes = dynamic_mesh_bytes(vertices.len())?;
4433            if upload_bytes > budget.max_upload_bytes {
4434                return Err(DynamicMeshError::BudgetExceeded {
4435                    resource: DynamicMeshBudgetResource::UploadBytes,
4436                    limit: budget.max_upload_bytes,
4437                    actual: upload_bytes,
4438                });
4439            }
4440        }
4441        let vertices = dynamic_vertices_to_gpu(vertices)?;
4442        if !vertices.is_empty() {
4443            let offset = (first_vertex * std::mem::size_of::<DynamicGpu>()) as wgpu::BufferAddress;
4444            self.queue
4445                .write_buffer(&mesh.vertex_buffer, offset, bytemuck::cast_slice(&vertices));
4446            submit_pending_uploads(&self.queue);
4447            mesh.vertices[first_vertex..end].copy_from_slice(&vertices);
4448            mesh.geometry_extents = GeometryExtents::from_dynamic_vertices(&mesh.vertices);
4449            mesh.geometry_validation_cache.clear();
4450        }
4451        Ok(DynamicMeshUpdateReport {
4452            vertex_count: mesh.vertices.len(),
4453            upload: update_started_at.elapsed(),
4454            reallocated: false,
4455        })
4456    }
4457
4458    /// Draws dynamic triangle-list geometry with a normalized clear color.
4459    ///
4460    /// Every potentially visible triangle must remain fully inside the full
4461    /// surface clip volume and have a portable projected orientation. A
4462    /// hardware-clipped or ambiguous triangle returns
4463    /// `DynamicMeshRenderError::Frame(RendererFrameError::InvalidGeometryTransform)`.
4464    pub fn render_dynamic_mesh(
4465        &mut self,
4466        mesh: &DynamicMesh2d,
4467        background: Color,
4468        camera: &Camera2d,
4469    ) -> Result<RenderStatus, DynamicMeshRenderError> {
4470        self.render_dynamic_mesh_with_metrics(mesh, background, camera)
4471            .map(RenderReport::status)
4472    }
4473
4474    /// Draws dynamic triangle-list geometry and returns per-frame CPU metrics.
4475    ///
4476    /// Full-surface clip-volume crossing and association-dependent projected
4477    /// topology are rejected as
4478    /// `DynamicMeshRenderError::Frame(RendererFrameError::InvalidGeometryTransform)`.
4479    pub fn render_dynamic_mesh_with_metrics(
4480        &mut self,
4481        mesh: &DynamicMesh2d,
4482        background: Color,
4483        camera: &Camera2d,
4484    ) -> Result<RenderReport, DynamicMeshRenderError> {
4485        self.validate_dynamic_mesh(mesh)
4486            .map_err(|_| DynamicMeshRenderError::RendererMismatch)?;
4487        if !background.is_normalized() {
4488            return Err(DynamicMeshRenderError::InvalidBackground);
4489        }
4490        let draw_batches = (!mesh.vertices.is_empty()).then_some(PreparedDrawBatch {
4491            vertex_range: 0..mesh.vertices.len() as u32,
4492            screen_clip: None,
4493        });
4494        self.draw_geometry(
4495            background,
4496            &mesh.vertex_buffer,
4497            mesh.vertices.len(),
4498            mesh.geometry_extents,
4499            GeometryValidationSource::Dynamic(&mesh.vertices),
4500            Some(&mesh.geometry_validation_cache),
4501            draw_batches.as_slice(),
4502            *camera,
4503            Duration::ZERO,
4504            Duration::ZERO,
4505            false,
4506            true,
4507            true,
4508            None,
4509            TessellationStats::default(),
4510            Instant::now(),
4511            None,
4512        )
4513        .map_err(DynamicMeshRenderError::Frame)
4514    }
4515
4516    /// Creates an instanced particle field owned by this renderer.
4517    ///
4518    /// Each instance draws as one screen-space circle quad through a single GPU
4519    /// draw call. The retained CPU snapshot enables later restoration on a
4520    /// recreated renderer.
4521    pub fn create_particle_field(
4522        &self,
4523        instances: &[ParticleInstance2d],
4524    ) -> Result<ParticleField2d, ParticleFieldError> {
4525        self.create_particle_field_with_budget(instances, ParticleRenderBudget::UNBOUNDED)
4526    }
4527
4528    /// Creates an instanced particle field with hard retained-CPU, GPU-memory,
4529    /// upload, visible-instance, and visibility-work limits.
4530    pub fn create_particle_field_with_budget(
4531        &self,
4532        instances: &[ParticleInstance2d],
4533        budget: ParticleRenderBudget,
4534    ) -> Result<ParticleField2d, ParticleFieldError> {
4535        validate_particle_retained_count(instances.len(), budget)?;
4536        let instance_capacity = particle_budgeted_capacity(instances.len(), budget)
4537            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
4538            .ok_or(ParticleFieldError::CapacityTooLarge)?;
4539        let instances = particle_instances_to_gpu(instances)?;
4540        let visible_instances = allocate_particle_staging(instances.len(), budget)?;
4541        validate_particle_retained_capacities(
4542            instances.capacity(),
4543            visible_instances.capacity(),
4544            budget,
4545        )?;
4546        let instance_buffer = Arc::new(create_particle_instance_buffer(
4547            &self.device,
4548            instance_capacity,
4549        ));
4550        Ok(ParticleField2d {
4551            renderer_identity: Arc::clone(&self.renderer_identity),
4552            instance_buffer,
4553            statistics: particle_idle_statistics(instances.len()),
4554            instances,
4555            visible_instances,
4556            instance_capacity,
4557            budget,
4558        })
4559    }
4560
4561    /// Replaces a particle field's hard resource budget, shrinking memory when required.
4562    pub fn set_particle_field_budget(
4563        &self,
4564        field: &mut ParticleField2d,
4565        budget: ParticleRenderBudget,
4566    ) -> Result<(), ParticleFieldError> {
4567        self.validate_particle_field(field)?;
4568        validate_particle_retained_count(field.instances.len(), budget)?;
4569        let desired_capacity = particle_budgeted_capacity(field.instances.len(), budget)
4570            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
4571            .ok_or(ParticleFieldError::CapacityTooLarge)?;
4572        let visible_instances = allocate_particle_staging(field.instances.len(), budget)?;
4573        let replacement_instances = compact_particle_instances(
4574            &field.instances,
4575            field.instances.capacity(),
4576            visible_instances.capacity(),
4577            budget,
4578        )?;
4579        let replacement_buffer = (desired_capacity != field.instance_capacity).then(|| {
4580            Arc::new(create_particle_instance_buffer(
4581                &self.device,
4582                desired_capacity,
4583            ))
4584        });
4585        if let Some(instance_buffer) = replacement_buffer {
4586            field.instance_buffer = instance_buffer;
4587            field.instance_capacity = desired_capacity;
4588        }
4589        if let Some(instances) = replacement_instances {
4590            field.instances = instances;
4591        }
4592        field.budget = budget;
4593        field.visible_instances = visible_instances;
4594        field.statistics = particle_idle_statistics(field.instances.len());
4595        Ok(())
4596    }
4597
4598    /// Replaces all particle instances, reusing GPU capacity whenever possible.
4599    pub fn update_particle_field(
4600        &self,
4601        field: &mut ParticleField2d,
4602        instances: &[ParticleInstance2d],
4603    ) -> Result<ParticleStatistics, ParticleFieldError> {
4604        self.update_particle_field_with_metrics(field, instances)
4605            .map(|report| report.statistics())
4606    }
4607
4608    /// Replaces all particle instances and returns CPU-side preparation metrics.
4609    pub fn update_particle_field_with_metrics(
4610        &self,
4611        field: &mut ParticleField2d,
4612        instances: &[ParticleInstance2d],
4613    ) -> Result<ParticleFieldUpdateReport, ParticleFieldError> {
4614        let update_started_at = Instant::now();
4615        self.validate_particle_field(field)?;
4616        validate_particle_retained_count(instances.len(), field.budget)?;
4617        let desired_capacity = particle_budgeted_capacity(instances.len(), field.budget)
4618            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
4619            .ok_or(ParticleFieldError::CapacityTooLarge)?;
4620        let instances = particle_instances_to_gpu(instances)?;
4621        let visible_instances = allocate_particle_staging(instances.len(), field.budget)?;
4622        validate_particle_retained_capacities(
4623            instances.capacity(),
4624            visible_instances.capacity(),
4625            field.budget,
4626        )?;
4627        let reallocated = desired_capacity > field.instance_capacity;
4628        let replacement_buffer = reallocated.then(|| {
4629            Arc::new(create_particle_instance_buffer(
4630                &self.device,
4631                desired_capacity,
4632            ))
4633        });
4634        if let Some(instance_buffer) = replacement_buffer {
4635            field.instance_buffer = instance_buffer;
4636            field.instance_capacity = desired_capacity;
4637        }
4638        field.statistics = particle_idle_statistics(instances.len());
4639        field.instances = instances;
4640        field.visible_instances = visible_instances;
4641        Ok(ParticleFieldUpdateReport {
4642            statistics: field.statistics,
4643            preparation: update_started_at.elapsed(),
4644            reallocated,
4645        })
4646    }
4647
4648    /// Replaces a contiguous particle range without reallocating its GPU buffer.
4649    pub fn update_particle_field_range(
4650        &self,
4651        field: &mut ParticleField2d,
4652        first_instance: usize,
4653        instances: &[ParticleInstance2d],
4654    ) -> Result<ParticleStatistics, ParticleFieldError> {
4655        self.update_particle_field_range_with_metrics(field, first_instance, instances)
4656            .map(|report| report.statistics())
4657    }
4658
4659    /// Replaces a particle range and returns CPU-side preparation metrics.
4660    pub fn update_particle_field_range_with_metrics(
4661        &self,
4662        field: &mut ParticleField2d,
4663        first_instance: usize,
4664        instances: &[ParticleInstance2d],
4665    ) -> Result<ParticleFieldUpdateReport, ParticleFieldError> {
4666        let update_started_at = Instant::now();
4667        self.validate_particle_field(field)?;
4668        let range = particle_update_range(first_instance, instances.len(), field.instances.len())?;
4669        let instances = particle_instances_to_gpu(instances)?;
4670        if !instances.is_empty() {
4671            field.instances[range].copy_from_slice(&instances);
4672        }
4673        field.statistics = particle_idle_statistics(field.instances.len());
4674        Ok(ParticleFieldUpdateReport {
4675            statistics: field.statistics,
4676            preparation: update_started_at.elapsed(),
4677            reallocated: false,
4678        })
4679    }
4680
4681    /// Recreates a particle field on this renderer from retained CPU instances.
4682    pub fn restore_particle_field(
4683        &self,
4684        source: &ParticleField2d,
4685    ) -> Result<ParticleField2d, ParticleFieldError> {
4686        restore_particle_field_resources(
4687            &self.device,
4688            &self.queue,
4689            Arc::clone(&self.renderer_identity),
4690            source,
4691        )
4692    }
4693
4694    /// Creates a single-channel floating-point texture from a validated scalar grid.
4695    pub fn create_scalar_field_texture(
4696        &self,
4697        field: ScalarField,
4698    ) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
4699        create_scalar_field_texture_resources(
4700            &self.device,
4701            &self.queue,
4702            Arc::clone(&self.renderer_identity),
4703            field,
4704        )
4705    }
4706
4707    /// Creates an offscreen target with physical texture dimensions.
4708    pub fn create_render_target(
4709        &self,
4710        width: u32,
4711        height: u32,
4712    ) -> Result<RenderTarget2d, RenderTargetError> {
4713        if width == 0 || height == 0 {
4714            return Err(RenderTargetError::ZeroDimension);
4715        }
4716        if width > self.device.limits().max_texture_dimension_2d
4717            || height > self.device.limits().max_texture_dimension_2d
4718        {
4719            return Err(RenderTargetError::DimensionsTooLarge);
4720        }
4721        let allocation_bytes = render_target_allocation_bytes(self.config.format, width, height)
4722            .ok_or(RenderTargetError::DimensionsTooLarge)?;
4723        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
4724            label: Some("sim-engine render target"),
4725            size: wgpu::Extent3d {
4726                width,
4727                height,
4728                depth_or_array_layers: 1,
4729            },
4730            mip_level_count: 1,
4731            sample_count: 1,
4732            dimension: wgpu::TextureDimension::D2,
4733            format: self.config.format,
4734            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
4735                | wgpu::TextureUsages::TEXTURE_BINDING
4736                | wgpu::TextureUsages::COPY_SRC,
4737            view_formats: &[],
4738        });
4739        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4740        Ok(RenderTarget2d {
4741            renderer_identity: Arc::clone(&self.renderer_identity),
4742            resource_identity: Arc::new(()),
4743            _texture: texture,
4744            view,
4745            width,
4746            height,
4747            allocation_bytes,
4748        })
4749    }
4750
4751    /// Creates an empty ping-pong target pair for temporal accumulation.
4752    pub fn create_trail_buffer(
4753        &mut self,
4754        width: u32,
4755        height: u32,
4756    ) -> Result<TrailBuffer2d, RenderTargetError> {
4757        let front = self.create_render_target(width, height)?;
4758        let back = self.create_render_target(width, height)?;
4759        let trails = TrailBuffer2d {
4760            renderer_identity: Arc::clone(&self.renderer_identity),
4761            front,
4762            back,
4763        };
4764        self.draw_clear_trail_buffer(&trails, Color::rgba(0.0, 0.0, 0.0, 0.0), Instant::now());
4765        Ok(trails)
4766    }
4767
4768    /// Recreates an empty target with the source dimensions after device recovery.
4769    ///
4770    /// GPU pixels are deliberately not retained; callers redraw their source
4771    /// state into the restored target.
4772    pub fn restore_render_target(
4773        &self,
4774        source: &RenderTarget2d,
4775    ) -> Result<RenderTarget2d, RenderTargetError> {
4776        self.create_render_target(source.width(), source.height())
4777    }
4778
4779    /// Recreates an empty, deterministically cleared trail buffer after recovery.
4780    pub fn restore_trail_buffer(
4781        &mut self,
4782        source: &TrailBuffer2d,
4783    ) -> Result<TrailBuffer2d, RenderTargetError> {
4784        self.create_trail_buffer(source.width(), source.height())
4785    }
4786
4787    /// Retains one bounded frame of history and composites a fresh source target.
4788    ///
4789    /// `retention` and `source_opacity` must be finite values in `0.0..=1.0`.
4790    /// The source must be a distinct target; use [`WgpuRenderer::clear_trail_buffer`]
4791    /// to discard accumulated history deterministically.
4792    pub fn accumulate_trail_buffer(
4793        &mut self,
4794        trails: &mut TrailBuffer2d,
4795        source: &RenderTarget2d,
4796        retention: f32,
4797        source_opacity: f32,
4798        source_blend: BlendMode,
4799    ) -> Result<RenderReport, RenderTargetError> {
4800        self.validate_trail_buffer(trails)?;
4801        self.validate_render_target(source)?;
4802        if Arc::ptr_eq(&source.resource_identity, &trails.front.resource_identity)
4803            || Arc::ptr_eq(&source.resource_identity, &trails.back.resource_identity)
4804        {
4805            return Err(RenderTargetError::SourceAliasesDestination);
4806        }
4807        if !retention.is_finite()
4808            || !(0.0..=1.0).contains(&retention)
4809            || !source_opacity.is_finite()
4810            || !(0.0..=1.0).contains(&source_opacity)
4811        {
4812            return Err(RenderTargetError::InvalidOpacity);
4813        }
4814        Ok(self.draw_trail_accumulation(
4815            trails,
4816            source,
4817            retention,
4818            source_opacity,
4819            source_blend,
4820            Instant::now(),
4821        ))
4822    }
4823
4824    /// Clears both ping-pong targets, resetting all retained temporal history.
4825    pub fn clear_trail_buffer(
4826        &mut self,
4827        trails: &mut TrailBuffer2d,
4828        color: Color,
4829    ) -> Result<RenderReport, RenderTargetError> {
4830        self.validate_trail_buffer(trails)?;
4831        if !color.is_normalized() {
4832            return Err(RenderTargetError::InvalidBackground);
4833        }
4834        Ok(self.draw_clear_trail_buffer(trails, color, Instant::now()))
4835    }
4836
4837    /// Presents the most recently accumulated temporal target.
4838    pub fn compose_trail_buffer(
4839        &mut self,
4840        trails: &TrailBuffer2d,
4841        blend_mode: BlendMode,
4842        opacity: f32,
4843        background: Color,
4844    ) -> Result<RenderReport, RenderTargetError> {
4845        self.validate_trail_buffer(trails)?;
4846        self.compose_render_target(&trails.front, blend_mode, opacity, background)
4847    }
4848
4849    /// Replaces scalar data, recreating the texture only when dimensions change.
4850    pub fn update_scalar_field_texture(
4851        &self,
4852        texture: &mut ScalarFieldTexture,
4853        field: ScalarField,
4854    ) -> Result<ScalarFieldUploadReport, ScalarFieldTextureError> {
4855        let upload_started_at = Instant::now();
4856        self.validate_scalar_field_texture(texture)?;
4857        validate_scalar_field_device_extent(&self.device, &field)?;
4858        if !scalar_field_sources_are_portable(&field) {
4859            return Err(ScalarFieldTextureError::NonPortableValue);
4860        }
4861        let field = compact_scalar_field_for_retention(field)?;
4862        let (source_minimum, source_maximum) = field.value_range();
4863        let reallocated = texture.width() != field.width() || texture.height() != field.height();
4864        if reallocated {
4865            texture.texture = create_scalar_field_texture(&self.device, &field)?;
4866        }
4867        upload_scalar_field_texture(&self.queue, &texture.texture, &field)?;
4868        texture.field = field;
4869        texture.source_minimum = source_minimum;
4870        texture.source_maximum = source_maximum;
4871        Ok(ScalarFieldUploadReport {
4872            upload: upload_started_at.elapsed(),
4873            reallocated,
4874        })
4875    }
4876
4877    /// Updates a rectangular scalar texture region without recreating it.
4878    pub fn update_scalar_field_texture_region(
4879        &self,
4880        texture: &mut ScalarFieldTexture,
4881        x: usize,
4882        y: usize,
4883        width: usize,
4884        height: usize,
4885        values: &[f32],
4886    ) -> Result<ScalarFieldUploadReport, ScalarFieldTextureError> {
4887        let upload_started_at = Instant::now();
4888        self.validate_scalar_field_texture(texture)?;
4889        if values.iter().any(|value| !value.is_finite()) {
4890            return Err(ScalarFieldTextureError::NonFiniteUpdateValue);
4891        }
4892        if values
4893            .iter()
4894            .copied()
4895            .any(|value| !is_portable_shader_source(value))
4896        {
4897            return Err(ScalarFieldTextureError::NonPortableValue);
4898        }
4899        validate_scalar_field_texture_region(
4900            texture.width(),
4901            texture.height(),
4902            x,
4903            y,
4904            width,
4905            height,
4906            values.len(),
4907        )?;
4908        let update_minimum = values.iter().copied().fold(f32::INFINITY, f32::min);
4909        let update_maximum = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
4910        let overwrites_extremum = (y..y + height).any(|row| {
4911            let start = row * texture.width() + x;
4912            texture.field.values()[start..start + width]
4913                .iter()
4914                .any(|value| *value == texture.source_minimum || *value == texture.source_maximum)
4915        });
4916        let (source_minimum, source_maximum) = if overwrites_extremum {
4917            scalar_region_result_range(&texture.field, x, y, width, height, values)
4918        } else {
4919            (
4920                texture.source_minimum.min(update_minimum),
4921                texture.source_maximum.max(update_maximum),
4922            )
4923        };
4924        let source_extent = f64::from(source_maximum) - f64::from(source_minimum);
4925        if !source_extent.is_finite() || source_extent > f64::from(MAX_PORTABLE_SHADER_VALUE) {
4926            return Err(ScalarFieldTextureError::NonPortableValue);
4927        }
4928        texture
4929            .field
4930            .replace_region(x, y, width, height, values)
4931            .map_err(|error| match error {
4932                crate::ScalarFieldError::InvalidValueCount { .. } => {
4933                    ScalarFieldTextureError::InvalidUpdateValueCount
4934                }
4935                crate::ScalarFieldError::NonFiniteValue => {
4936                    ScalarFieldTextureError::NonFiniteUpdateValue
4937                }
4938                _ => ScalarFieldTextureError::UpdateRegionOutOfBounds,
4939            })?;
4940        upload_scalar_field_texture_region(
4941            &self.queue,
4942            &texture.texture,
4943            x,
4944            y,
4945            width,
4946            height,
4947            values,
4948        )?;
4949        texture.source_minimum = source_minimum;
4950        texture.source_maximum = source_maximum;
4951        Ok(ScalarFieldUploadReport {
4952            upload: upload_started_at.elapsed(),
4953            reallocated: false,
4954        })
4955    }
4956
4957    /// Recreates a scalar texture on this renderer from its retained CPU grid.
4958    pub fn restore_scalar_field_texture(
4959        &self,
4960        source: &ScalarFieldTexture,
4961    ) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
4962        validate_scalar_field_device_extent(&self.device, &source.field)?;
4963        let field = clone_scalar_field_for_restore(&source.field)?;
4964        self.create_scalar_field_texture(field)
4965    }
4966
4967    /// Draws a scalar texture across the logical viewport through a color map.
4968    ///
4969    /// `value_range` maps `minimum` to the first color-map entry and `maximum`
4970    /// to the last. Values outside the range clamp to those endpoints.
4971    pub fn render_scalar_field_texture(
4972        &mut self,
4973        texture: &ScalarFieldTexture,
4974        color_map: &ColorMap,
4975        value_range: (f32, f32),
4976        background: Color,
4977    ) -> Result<RenderStatus, ScalarFieldRenderError> {
4978        self.render_scalar_field_texture_with_metrics(texture, color_map, value_range, background)
4979            .map(RenderReport::status)
4980    }
4981
4982    /// Draws a scalar texture and returns normal CPU-side renderer metrics.
4983    pub fn render_scalar_field_texture_with_metrics(
4984        &mut self,
4985        texture: &ScalarFieldTexture,
4986        color_map: &ColorMap,
4987        (minimum, maximum): (f32, f32),
4988        background: Color,
4989    ) -> Result<RenderReport, ScalarFieldRenderError> {
4990        self.validate_scalar_field_texture(texture)
4991            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
4992        let value_extent = scalar_value_range_extent(minimum, maximum)
4993            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
4994        if !scalar_normalization_is_portable(texture, minimum, value_extent) {
4995            return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
4996        }
4997        if !background.is_normalized() {
4998            return Err(ScalarFieldRenderError::InvalidBackground);
4999        }
5000        self.draw_scalar_field_texture(
5001            texture,
5002            color_map,
5003            minimum,
5004            value_extent,
5005            ScalarFieldSampling::Nearest,
5006            background,
5007            Instant::now(),
5008        )
5009        .map_err(ScalarFieldRenderError::Frame)
5010    }
5011
5012    /// Draws a scalar texture with an explicit texel sampling mode.
5013    pub fn render_scalar_field_texture_with_sampling(
5014        &mut self,
5015        texture: &ScalarFieldTexture,
5016        color_map: &ColorMap,
5017        (minimum, maximum): (f32, f32),
5018        sampling: ScalarFieldSampling,
5019        background: Color,
5020    ) -> Result<RenderStatus, ScalarFieldRenderError> {
5021        self.validate_scalar_field_texture(texture)
5022            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
5023        let value_extent = scalar_value_range_extent(minimum, maximum)
5024            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
5025        if !scalar_normalization_is_portable(texture, minimum, value_extent) {
5026            return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
5027        }
5028        if !background.is_normalized() {
5029            return Err(ScalarFieldRenderError::InvalidBackground);
5030        }
5031        self.draw_scalar_field_texture(
5032            texture,
5033            color_map,
5034            minimum,
5035            value_extent,
5036            sampling,
5037            background,
5038            Instant::now(),
5039        )
5040        .map(RenderReport::status)
5041        .map_err(ScalarFieldRenderError::Frame)
5042    }
5043
5044    /// Renders a scalar heatmap into an offscreen target instead of presenting it.
5045    pub fn render_scalar_field_texture_to_target(
5046        &mut self,
5047        target: &RenderTarget2d,
5048        texture: &ScalarFieldTexture,
5049        color_map: &ColorMap,
5050        value_range: (f32, f32),
5051        background: Color,
5052    ) -> Result<RenderReport, ScalarFieldRenderError> {
5053        self.render_scalar_field_texture_to_target_with_sampling(
5054            target,
5055            texture,
5056            color_map,
5057            value_range,
5058            ScalarFieldSampling::Nearest,
5059            background,
5060        )
5061    }
5062
5063    /// Renders a scalar heatmap into a target with explicit source sampling.
5064    pub fn render_scalar_field_texture_to_target_with_sampling(
5065        &mut self,
5066        target: &RenderTarget2d,
5067        texture: &ScalarFieldTexture,
5068        color_map: &ColorMap,
5069        (minimum, maximum): (f32, f32),
5070        sampling: ScalarFieldSampling,
5071        background: Color,
5072    ) -> Result<RenderReport, ScalarFieldRenderError> {
5073        self.validate_render_target(target)
5074            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
5075        self.validate_scalar_field_texture(texture)
5076            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
5077        let value_extent = scalar_value_range_extent(minimum, maximum)
5078            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
5079        if !scalar_normalization_is_portable(texture, minimum, value_extent) {
5080            return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
5081        }
5082        if !background.is_normalized() {
5083            return Err(ScalarFieldRenderError::InvalidBackground);
5084        }
5085        Ok(self.draw_scalar_field_texture_to_target(
5086            target,
5087            texture,
5088            color_map,
5089            minimum,
5090            value_extent,
5091            sampling,
5092            background,
5093            Instant::now(),
5094        ))
5095    }
5096
5097    /// Composes a previously rendered target over the presentation surface.
5098    pub fn compose_render_target(
5099        &mut self,
5100        target: &RenderTarget2d,
5101        blend_mode: BlendMode,
5102        opacity: f32,
5103        background: Color,
5104    ) -> Result<RenderReport, RenderTargetError> {
5105        self.validate_render_target(target)?;
5106        if !opacity.is_finite() || !(0.0..=1.0).contains(&opacity) {
5107            return Err(RenderTargetError::InvalidOpacity);
5108        }
5109        if !background.is_normalized() {
5110            return Err(RenderTargetError::InvalidBackground);
5111        }
5112        self.draw_composed_render_target(target, blend_mode, opacity, background, Instant::now())
5113            .map_err(RenderTargetError::Frame)
5114    }
5115
5116    /// Draws a particle field with a normalized clear color.
5117    pub fn render_particle_field(
5118        &mut self,
5119        field: &mut ParticleField2d,
5120        background: Color,
5121        camera: &Camera2d,
5122    ) -> Result<RenderStatus, ParticleFieldRenderError> {
5123        self.render_particle_field_with_metrics(field, background, camera)
5124            .map(RenderReport::status)
5125    }
5126
5127    /// Draws a particle field and returns regular per-frame renderer metrics.
5128    pub fn render_particle_field_with_metrics(
5129        &mut self,
5130        field: &mut ParticleField2d,
5131        background: Color,
5132        camera: &Camera2d,
5133    ) -> Result<RenderReport, ParticleFieldRenderError> {
5134        self.validate_particle_field(field)
5135            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
5136        if !background.is_normalized() {
5137            return Err(ParticleFieldRenderError::InvalidBackground);
5138        }
5139        self.draw_particle_field(background, field, *camera, Instant::now())
5140            .map_err(|error| match error {
5141                RendererFrameError::InvalidGeometryTransform => {
5142                    ParticleFieldRenderError::InvalidGeometryTransform
5143                }
5144                other => ParticleFieldRenderError::Frame(other),
5145            })
5146    }
5147
5148    /// Draws a particle field into an offscreen target.
5149    ///
5150    /// Target dimensions may be lower than the presentation surface to bound
5151    /// raster cost. Camera coordinates and particle radii remain expressed in
5152    /// logical presentation pixels, so composing the target back to the surface
5153    /// preserves layout while trading only raster resolution.
5154    pub fn render_particle_field_to_target(
5155        &mut self,
5156        target: &RenderTarget2d,
5157        field: &mut ParticleField2d,
5158        camera: &Camera2d,
5159        load: RenderTargetLoad,
5160    ) -> Result<RenderReport, ParticleFieldRenderError> {
5161        self.validate_render_target(target)
5162            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
5163        self.validate_particle_field(field)
5164            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
5165        if matches!(load, RenderTargetLoad::Clear(color) if !color.is_normalized()) {
5166            return Err(ParticleFieldRenderError::InvalidBackground);
5167        }
5168        self.draw_particle_field_to_target(target, field, *camera, load, Instant::now())
5169            .map_err(|error| match error {
5170                RendererFrameError::InvalidGeometryTransform => {
5171                    ParticleFieldRenderError::InvalidGeometryTransform
5172                }
5173                other => ParticleFieldRenderError::Frame(other),
5174            })
5175    }
5176
5177    /// Draws geometry previously uploaded by [`WgpuRenderer::prepare_scene`].
5178    ///
5179    /// Camera and viewport changes are applied by the vertex shader and do not
5180    /// rebuild or re-upload the prepared geometry.
5181    pub fn render_prepared(
5182        &mut self,
5183        scene: &PreparedScene,
5184        camera: &Camera2d,
5185    ) -> Result<RenderStatus, PreparedSceneRenderError> {
5186        self.render_prepared_with_metrics(scene, camera)
5187            .map(RenderReport::status)
5188    }
5189
5190    /// Draws prepared logical-screen geometry independently of a world camera.
5191    ///
5192    /// The prepared resource must have been built from a [`ScreenScene`]. The
5193    /// renderer cannot infer the original coordinate space from raw prepared
5194    /// vertices, so passing world-space geometry is a caller contract error.
5195    pub fn render_prepared_screen_scene(
5196        &mut self,
5197        scene: &PreparedScreenScene,
5198    ) -> Result<RenderStatus, PreparedSceneRenderError> {
5199        let (width, height) = self.logical_size();
5200        let viewport = LogicalViewport::new(width, height).map_err(|_| {
5201            PreparedSceneRenderError::Frame(RendererFrameError::InvalidGeometryTransform)
5202        })?;
5203        let camera = screen_camera(viewport).map_err(|_| {
5204            PreparedSceneRenderError::Frame(RendererFrameError::InvalidGeometryTransform)
5205        })?;
5206        self.render_prepared(&scene.scene, &camera)
5207    }
5208
5209    /// Draws prepared geometry and reports per-frame CPU timing.
5210    ///
5211    /// Tessellation and geometry upload durations are zero because both happened
5212    /// in [`WgpuRenderer::prepare_scene`]. The camera uniform is still updated
5213    /// once per frame.
5214    pub fn render_prepared_with_metrics(
5215        &mut self,
5216        scene: &PreparedScene,
5217        camera: &Camera2d,
5218    ) -> Result<RenderReport, PreparedSceneRenderError> {
5219        if !prepared_scene_belongs_to(&self.renderer_identity, &scene.renderer_identity) {
5220            return Err(PreparedSceneRenderError::RendererMismatch);
5221        }
5222
5223        self.draw_geometry(
5224            scene.background,
5225            &scene.vertex_buffer,
5226            scene.vertex_count,
5227            scene.geometry_extents,
5228            GeometryValidationSource::Tessellated(&scene.vertices),
5229            Some(&scene.geometry_validation_cache),
5230            &scene.draw_batches,
5231            *camera,
5232            Duration::ZERO,
5233            Duration::ZERO,
5234            true,
5235            false,
5236            false,
5237            None,
5238            scene.tessellation,
5239            Instant::now(),
5240            None,
5241        )
5242        .map_err(PreparedSceneRenderError::Frame)
5243    }
5244
5245    fn surface_geometry_context(
5246        &self,
5247        camera: Camera2d,
5248        viewport_region: Option<LogicalViewportRegion>,
5249    ) -> Result<(LogicalViewport, ScissorRect, CameraUniform), RendererFrameError> {
5250        let (logical_width, logical_height) = self.logical_size();
5251        let target_viewport = LogicalViewport::new(logical_width, logical_height)
5252            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
5253        let (viewport, viewport_origin) = match viewport_region {
5254            Some(region) => (region.viewport(), region.origin().to_vec2()),
5255            None => (target_viewport, Vec2::ZERO),
5256        };
5257        let viewport_max = viewport_origin + viewport.size();
5258        if !viewport_origin.is_finite()
5259            || !viewport_max.is_finite()
5260            || viewport_origin.x < 0.0
5261            || viewport_origin.y < 0.0
5262            || viewport_max.x > target_viewport.width()
5263            || viewport_max.y > target_viewport.height()
5264        {
5265            return Err(RendererFrameError::InvalidViewport);
5266        }
5267        let viewport_scissor = logical_viewport_scissor(
5268            viewport_origin,
5269            viewport,
5270            self.scale_factor as f32,
5271            self.config.width,
5272            self.config.height,
5273        )
5274        .ok_or(RendererFrameError::InvalidViewport)?;
5275        let camera_uniform =
5276            CameraUniform::new_in_region(camera, viewport, viewport_origin, target_viewport)
5277                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
5278        Ok((viewport, viewport_scissor, camera_uniform))
5279    }
5280
5281    #[allow(clippy::too_many_arguments)]
5282    fn draw_geometry(
5283        &mut self,
5284        background: Color,
5285        vertex_buffer: &wgpu::Buffer,
5286        vertex_count: usize,
5287        geometry_extents: GeometryExtents,
5288        geometry_validation: GeometryValidationSource<'_>,
5289        geometry_validation_cache: Option<&GeometryValidationCache>,
5290        draw_batches: &[PreparedDrawBatch],
5291        camera: Camera2d,
5292        tessellation: Duration,
5293        mut upload: Duration,
5294        geometry_reused: bool,
5295        geometry_streamed: bool,
5296        uses_dynamic_pipeline: bool,
5297        pending_vertex_upload: Option<&[Vertex]>,
5298        tessellation_stats: TessellationStats,
5299        frame_started_at: Instant,
5300        viewport_region: Option<LogicalViewportRegion>,
5301    ) -> Result<RenderReport, RendererFrameError> {
5302        let (viewport, viewport_scissor, camera_uniform) =
5303            self.surface_geometry_context(camera, viewport_region)?;
5304        if !geometry_is_safe_for_cached(
5305            geometry_validation_cache,
5306            geometry_extents,
5307            geometry_validation,
5308            camera_uniform,
5309        ) {
5310            return Err(RendererFrameError::InvalidGeometryTransform);
5311        }
5312
5313        let surface_acquire_started_at = Instant::now();
5314        let surface_texture = match self.surface.get_current_texture() {
5315            wgpu::CurrentSurfaceTexture::Success(texture)
5316            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
5317            wgpu::CurrentSurfaceTexture::Timeout => {
5318                return Ok(render_report(
5319                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
5320                    tessellation,
5321                    upload,
5322                    Duration::ZERO,
5323                    surface_acquire_started_at.elapsed(),
5324                    Duration::ZERO,
5325                    frame_started_at.elapsed(),
5326                    geometry_reused,
5327                    geometry_streamed,
5328                    tessellation_stats,
5329                ));
5330            }
5331            wgpu::CurrentSurfaceTexture::Occluded => {
5332                return Ok(render_report(
5333                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
5334                    tessellation,
5335                    upload,
5336                    Duration::ZERO,
5337                    surface_acquire_started_at.elapsed(),
5338                    Duration::ZERO,
5339                    frame_started_at.elapsed(),
5340                    geometry_reused,
5341                    geometry_streamed,
5342                    tessellation_stats,
5343                ));
5344            }
5345            wgpu::CurrentSurfaceTexture::Outdated => {
5346                let _ = self.resize(self.config.width, self.config.height);
5347                return Ok(render_report(
5348                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
5349                    tessellation,
5350                    upload,
5351                    Duration::ZERO,
5352                    surface_acquire_started_at.elapsed(),
5353                    Duration::ZERO,
5354                    frame_started_at.elapsed(),
5355                    geometry_reused,
5356                    geometry_streamed,
5357                    tessellation_stats,
5358                ));
5359            }
5360            wgpu::CurrentSurfaceTexture::Lost => {
5361                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
5362            }
5363            wgpu::CurrentSurfaceTexture::Validation => {
5364                return Err(RendererFrameError::Surface(
5365                    RendererSurfaceStatus::Validation,
5366                ));
5367            }
5368        };
5369        let surface_acquire = surface_acquire_started_at.elapsed();
5370        let vertex_upload_started_at = Instant::now();
5371        if let Some(vertices) = pending_vertex_upload
5372            && !vertices.is_empty()
5373        {
5374            self.queue
5375                .write_buffer(vertex_buffer, 0, bytemuck::cast_slice(vertices));
5376        }
5377        upload = upload.saturating_add(vertex_upload_started_at.elapsed());
5378        let camera_uniform_upload_started_at = Instant::now();
5379        self.queue.write_buffer(
5380            &self.camera_uniform_buffer,
5381            0,
5382            bytemuck::bytes_of(&camera_uniform),
5383        );
5384        let camera_uniform_upload = camera_uniform_upload_started_at.elapsed();
5385
5386        let encode_submit_present_started_at = Instant::now();
5387        let surface_view = surface_texture
5388            .texture
5389            .create_view(&wgpu::TextureViewDescriptor::default());
5390        let (view, resolve_target) = match &self.multisample_target {
5391            Some(target) => (&target.view, Some(&surface_view)),
5392            None => (&surface_view, None),
5393        };
5394
5395        let mut encoder = self
5396            .device
5397            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5398                label: Some("sim-engine render encoder"),
5399            });
5400
5401        {
5402            let color_attachment = wgpu::RenderPassColorAttachment {
5403                view,
5404                depth_slice: None,
5405                resolve_target,
5406                ops: wgpu::Operations {
5407                    load: wgpu::LoadOp::Clear(background.to_wgpu()),
5408                    store: wgpu::StoreOp::Store,
5409                },
5410            };
5411            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5412                label: Some("sim-engine render pass"),
5413                color_attachments: &[Some(color_attachment)],
5414                depth_stencil_attachment: None,
5415                timestamp_writes: None,
5416                occlusion_query_set: None,
5417                multiview_mask: None,
5418            });
5419
5420            if vertex_count > 0 {
5421                let pipeline = if uses_dynamic_pipeline {
5422                    &self.dynamic_pipeline
5423                } else {
5424                    &self.pipeline
5425                };
5426                pass.set_pipeline(pipeline);
5427                pass.set_bind_group(0, &self.camera_bind_group, &[]);
5428                pass.set_vertex_buffer(0, vertex_buffer.slice(..));
5429                for batch in draw_batches {
5430                    let scissor = match batch.screen_clip {
5431                        Some(screen_clip) => {
5432                            let Some(local_scissor) = screen_clip_to_scissor(
5433                                screen_clip,
5434                                viewport,
5435                                self.scale_factor as f32,
5436                            ) else {
5437                                continue;
5438                            };
5439                            let Some(scissor) = offset_scissor(local_scissor, viewport_scissor)
5440                            else {
5441                                continue;
5442                            };
5443                            scissor
5444                        }
5445                        None => viewport_scissor,
5446                    };
5447                    pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
5448                    pass.draw(batch.vertex_range.clone(), 0..1);
5449                }
5450            }
5451        }
5452
5453        self.queue.submit([encoder.finish()]);
5454        self.notify_before_present();
5455        self.queue.present(surface_texture);
5456        let encode_submit_present = encode_submit_present_started_at.elapsed();
5457
5458        Ok(render_report(
5459            RenderStatus::Drawn,
5460            tessellation,
5461            upload,
5462            camera_uniform_upload,
5463            surface_acquire,
5464            encode_submit_present,
5465            frame_started_at.elapsed(),
5466            geometry_reused,
5467            geometry_streamed,
5468            tessellation_stats,
5469        ))
5470    }
5471
5472    #[allow(clippy::too_many_arguments)]
5473    fn draw_scalar_field_texture(
5474        &mut self,
5475        texture: &ScalarFieldTexture,
5476        color_map: &ColorMap,
5477        minimum: f32,
5478        value_extent: f32,
5479        sampling: ScalarFieldSampling,
5480        background: Color,
5481        frame_started_at: Instant,
5482    ) -> Result<RenderReport, RendererFrameError> {
5483        let uniform = HeatmapUniform::new(
5484            minimum,
5485            value_extent,
5486            texture.width(),
5487            texture.height(),
5488            sampling,
5489        );
5490        let acquire_started_at = Instant::now();
5491        let surface_texture = match self.surface.get_current_texture() {
5492            wgpu::CurrentSurfaceTexture::Success(texture)
5493            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
5494            wgpu::CurrentSurfaceTexture::Timeout => {
5495                return Ok(render_report(
5496                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
5497                    Duration::ZERO,
5498                    Duration::ZERO,
5499                    Duration::ZERO,
5500                    acquire_started_at.elapsed(),
5501                    Duration::ZERO,
5502                    frame_started_at.elapsed(),
5503                    false,
5504                    true,
5505                    TessellationStats::default(),
5506                ));
5507            }
5508            wgpu::CurrentSurfaceTexture::Occluded => {
5509                return Ok(render_report(
5510                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
5511                    Duration::ZERO,
5512                    Duration::ZERO,
5513                    Duration::ZERO,
5514                    acquire_started_at.elapsed(),
5515                    Duration::ZERO,
5516                    frame_started_at.elapsed(),
5517                    false,
5518                    true,
5519                    TessellationStats::default(),
5520                ));
5521            }
5522            wgpu::CurrentSurfaceTexture::Outdated => {
5523                let _ = self.resize(self.config.width, self.config.height);
5524                return Ok(render_report(
5525                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
5526                    Duration::ZERO,
5527                    Duration::ZERO,
5528                    Duration::ZERO,
5529                    acquire_started_at.elapsed(),
5530                    Duration::ZERO,
5531                    frame_started_at.elapsed(),
5532                    false,
5533                    true,
5534                    TessellationStats::default(),
5535                ));
5536            }
5537            wgpu::CurrentSurfaceTexture::Lost => {
5538                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
5539            }
5540            wgpu::CurrentSurfaceTexture::Validation => {
5541                return Err(RendererFrameError::Surface(
5542                    RendererSurfaceStatus::Validation,
5543                ));
5544            }
5545        };
5546        let surface_acquire = acquire_started_at.elapsed();
5547        let upload_started_at = Instant::now();
5548        let color_map_view = self.color_map_view(color_map);
5549        let scalar_view = texture
5550            .texture
5551            .create_view(&wgpu::TextureViewDescriptor::default());
5552        self.queue.write_buffer(
5553            &self.heatmap_uniform_buffer,
5554            0,
5555            bytemuck::bytes_of(&uniform),
5556        );
5557        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5558            label: Some("sim-engine heatmap bind group"),
5559            layout: &self.heatmap_bind_group_layout,
5560            entries: &[
5561                wgpu::BindGroupEntry {
5562                    binding: 0,
5563                    resource: wgpu::BindingResource::TextureView(&scalar_view),
5564                },
5565                wgpu::BindGroupEntry {
5566                    binding: 1,
5567                    resource: wgpu::BindingResource::TextureView(&color_map_view),
5568                },
5569                wgpu::BindGroupEntry {
5570                    binding: 2,
5571                    resource: self.heatmap_uniform_buffer.as_entire_binding(),
5572                },
5573            ],
5574        });
5575        let upload = upload_started_at.elapsed();
5576        let encode_started_at = Instant::now();
5577        let surface_view = surface_texture
5578            .texture
5579            .create_view(&wgpu::TextureViewDescriptor::default());
5580        let (view, resolve_target) = match &self.multisample_target {
5581            Some(target) => (&target.view, Some(&surface_view)),
5582            None => (&surface_view, None),
5583        };
5584        let mut encoder = self
5585            .device
5586            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5587                label: Some("sim-engine heatmap encoder"),
5588            });
5589        {
5590            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5591                label: Some("sim-engine heatmap pass"),
5592                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5593                    view,
5594                    depth_slice: None,
5595                    resolve_target,
5596                    ops: wgpu::Operations {
5597                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
5598                        store: wgpu::StoreOp::Store,
5599                    },
5600                })],
5601                depth_stencil_attachment: None,
5602                timestamp_writes: None,
5603                occlusion_query_set: None,
5604                multiview_mask: None,
5605            });
5606            pass.set_pipeline(&self.heatmap_pipeline);
5607            pass.set_bind_group(0, &bind_group, &[]);
5608            pass.draw(0..6, 0..1);
5609        }
5610        self.queue.submit([encoder.finish()]);
5611        self.notify_before_present();
5612        self.queue.present(surface_texture);
5613        Ok(render_report(
5614            RenderStatus::Drawn,
5615            Duration::ZERO,
5616            upload,
5617            Duration::ZERO,
5618            surface_acquire,
5619            encode_started_at.elapsed(),
5620            frame_started_at.elapsed(),
5621            false,
5622            true,
5623            TessellationStats::default(),
5624        ))
5625    }
5626
5627    #[allow(clippy::too_many_arguments)]
5628    fn draw_scalar_field_texture_to_target(
5629        &mut self,
5630        target: &RenderTarget2d,
5631        texture: &ScalarFieldTexture,
5632        color_map: &ColorMap,
5633        minimum: f32,
5634        value_extent: f32,
5635        sampling: ScalarFieldSampling,
5636        background: Color,
5637        frame_started_at: Instant,
5638    ) -> RenderReport {
5639        let upload_started_at = Instant::now();
5640        let color_map_view = self.color_map_view(color_map);
5641        let scalar_view = texture
5642            .texture
5643            .create_view(&wgpu::TextureViewDescriptor::default());
5644        self.queue.write_buffer(
5645            &self.heatmap_uniform_buffer,
5646            0,
5647            bytemuck::bytes_of(&HeatmapUniform::new(
5648                minimum,
5649                value_extent,
5650                texture.width(),
5651                texture.height(),
5652                sampling,
5653            )),
5654        );
5655        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5656            label: Some("sim-engine target heatmap bind group"),
5657            layout: &self.heatmap_bind_group_layout,
5658            entries: &[
5659                wgpu::BindGroupEntry {
5660                    binding: 0,
5661                    resource: wgpu::BindingResource::TextureView(&scalar_view),
5662                },
5663                wgpu::BindGroupEntry {
5664                    binding: 1,
5665                    resource: wgpu::BindingResource::TextureView(&color_map_view),
5666                },
5667                wgpu::BindGroupEntry {
5668                    binding: 2,
5669                    resource: self.heatmap_uniform_buffer.as_entire_binding(),
5670                },
5671            ],
5672        });
5673        let upload = upload_started_at.elapsed();
5674        let encode_started_at = Instant::now();
5675        let mut encoder = self
5676            .device
5677            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5678                label: Some("sim-engine render-target heatmap encoder"),
5679            });
5680        {
5681            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5682                label: Some("sim-engine render-target heatmap pass"),
5683                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5684                    view: &target.view,
5685                    depth_slice: None,
5686                    resolve_target: None,
5687                    ops: wgpu::Operations {
5688                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(background)),
5689                        store: wgpu::StoreOp::Store,
5690                    },
5691                })],
5692                depth_stencil_attachment: None,
5693                timestamp_writes: None,
5694                occlusion_query_set: None,
5695                multiview_mask: None,
5696            });
5697            pass.set_pipeline(&self.target_heatmap_pipeline);
5698            pass.set_bind_group(0, &bind_group, &[]);
5699            pass.draw(0..6, 0..1);
5700        }
5701        self.queue.submit([encoder.finish()]);
5702        render_report(
5703            RenderStatus::Drawn,
5704            Duration::ZERO,
5705            upload,
5706            Duration::ZERO,
5707            Duration::ZERO,
5708            encode_started_at.elapsed(),
5709            frame_started_at.elapsed(),
5710            false,
5711            true,
5712            TessellationStats::default(),
5713        )
5714    }
5715
5716    fn draw_composed_render_target(
5717        &mut self,
5718        target: &RenderTarget2d,
5719        blend_mode: BlendMode,
5720        opacity: f32,
5721        background: Color,
5722        frame_started_at: Instant,
5723    ) -> Result<RenderReport, RendererFrameError> {
5724        let acquire_started_at = Instant::now();
5725        let surface_texture = match self.surface.get_current_texture() {
5726            wgpu::CurrentSurfaceTexture::Success(texture)
5727            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
5728            wgpu::CurrentSurfaceTexture::Timeout => {
5729                return Ok(render_report(
5730                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
5731                    Duration::ZERO,
5732                    Duration::ZERO,
5733                    Duration::ZERO,
5734                    acquire_started_at.elapsed(),
5735                    Duration::ZERO,
5736                    frame_started_at.elapsed(),
5737                    false,
5738                    true,
5739                    TessellationStats::default(),
5740                ));
5741            }
5742            wgpu::CurrentSurfaceTexture::Occluded => {
5743                return Ok(render_report(
5744                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
5745                    Duration::ZERO,
5746                    Duration::ZERO,
5747                    Duration::ZERO,
5748                    acquire_started_at.elapsed(),
5749                    Duration::ZERO,
5750                    frame_started_at.elapsed(),
5751                    false,
5752                    true,
5753                    TessellationStats::default(),
5754                ));
5755            }
5756            wgpu::CurrentSurfaceTexture::Outdated => {
5757                let _ = self.resize(self.config.width, self.config.height);
5758                return Ok(render_report(
5759                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
5760                    Duration::ZERO,
5761                    Duration::ZERO,
5762                    Duration::ZERO,
5763                    acquire_started_at.elapsed(),
5764                    Duration::ZERO,
5765                    frame_started_at.elapsed(),
5766                    false,
5767                    true,
5768                    TessellationStats::default(),
5769                ));
5770            }
5771            wgpu::CurrentSurfaceTexture::Lost => {
5772                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
5773            }
5774            wgpu::CurrentSurfaceTexture::Validation => {
5775                return Err(RendererFrameError::Surface(
5776                    RendererSurfaceStatus::Validation,
5777                ));
5778            }
5779        };
5780        let surface_acquire = acquire_started_at.elapsed();
5781        let upload_started_at = Instant::now();
5782        self.queue.write_buffer(
5783            &self.composition_pipelines.uniform_buffer,
5784            0,
5785            bytemuck::bytes_of(&CompositeUniform::full_surface(opacity)),
5786        );
5787        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5788            label: Some("sim-engine composition bind group"),
5789            layout: &self.composition_pipelines.bind_group_layout,
5790            entries: &[
5791                wgpu::BindGroupEntry {
5792                    binding: 0,
5793                    resource: wgpu::BindingResource::TextureView(&target.view),
5794                },
5795                wgpu::BindGroupEntry {
5796                    binding: 1,
5797                    resource: self
5798                        .composition_pipelines
5799                        .uniform_buffer
5800                        .as_entire_binding(),
5801                },
5802            ],
5803        });
5804        let upload = upload_started_at.elapsed();
5805        let encode_started_at = Instant::now();
5806        let surface_view = surface_texture
5807            .texture
5808            .create_view(&wgpu::TextureViewDescriptor::default());
5809        let (view, resolve_target) = match &self.multisample_target {
5810            Some(multisample_target) => (&multisample_target.view, Some(&surface_view)),
5811            None => (&surface_view, None),
5812        };
5813        let mut encoder = self
5814            .device
5815            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5816                label: Some("sim-engine composition encoder"),
5817            });
5818        {
5819            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5820                label: Some("sim-engine composition pass"),
5821                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5822                    view,
5823                    depth_slice: None,
5824                    resolve_target,
5825                    ops: wgpu::Operations {
5826                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
5827                        store: wgpu::StoreOp::Store,
5828                    },
5829                })],
5830                depth_stencil_attachment: None,
5831                timestamp_writes: None,
5832                occlusion_query_set: None,
5833                multiview_mask: None,
5834            });
5835            pass.set_pipeline(self.composition_pipelines.pipeline(blend_mode));
5836            pass.set_bind_group(0, &bind_group, &[]);
5837            pass.draw(0..6, 0..1);
5838        }
5839        self.queue.submit([encoder.finish()]);
5840        self.notify_before_present();
5841        self.queue.present(surface_texture);
5842        Ok(render_report(
5843            RenderStatus::Drawn,
5844            Duration::ZERO,
5845            upload,
5846            Duration::ZERO,
5847            surface_acquire,
5848            encode_started_at.elapsed(),
5849            frame_started_at.elapsed(),
5850            false,
5851            true,
5852            TessellationStats::default(),
5853        ))
5854    }
5855
5856    #[allow(clippy::too_many_arguments)]
5857    fn draw_trail_accumulation(
5858        &mut self,
5859        trails: &mut TrailBuffer2d,
5860        source: &RenderTarget2d,
5861        retention: f32,
5862        source_opacity: f32,
5863        source_blend: BlendMode,
5864        frame_started_at: Instant,
5865    ) -> RenderReport {
5866        let upload_started_at = Instant::now();
5867        self.queue.write_buffer(
5868            &self.target_composition_pipelines.secondary_uniform_buffer,
5869            0,
5870            bytemuck::bytes_of(&CompositeUniform::full_surface(retention)),
5871        );
5872        self.queue.write_buffer(
5873            &self.target_composition_pipelines.uniform_buffer,
5874            0,
5875            bytemuck::bytes_of(&CompositeUniform::full_surface(source_opacity)),
5876        );
5877        let history_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5878            label: Some("sim-engine trail history bind group"),
5879            layout: &self.target_composition_pipelines.bind_group_layout,
5880            entries: &[
5881                wgpu::BindGroupEntry {
5882                    binding: 0,
5883                    resource: wgpu::BindingResource::TextureView(&trails.front.view),
5884                },
5885                wgpu::BindGroupEntry {
5886                    binding: 1,
5887                    resource: self
5888                        .target_composition_pipelines
5889                        .secondary_uniform_buffer
5890                        .as_entire_binding(),
5891                },
5892            ],
5893        });
5894        let source_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5895            label: Some("sim-engine trail source bind group"),
5896            layout: &self.target_composition_pipelines.bind_group_layout,
5897            entries: &[
5898                wgpu::BindGroupEntry {
5899                    binding: 0,
5900                    resource: wgpu::BindingResource::TextureView(&source.view),
5901                },
5902                wgpu::BindGroupEntry {
5903                    binding: 1,
5904                    resource: self
5905                        .target_composition_pipelines
5906                        .uniform_buffer
5907                        .as_entire_binding(),
5908                },
5909            ],
5910        });
5911        let upload = upload_started_at.elapsed();
5912        let encode_started_at = Instant::now();
5913        let mut encoder = self
5914            .device
5915            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5916                label: Some("sim-engine trail accumulation encoder"),
5917            });
5918        {
5919            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5920                label: Some("sim-engine trail history pass"),
5921                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5922                    view: &trails.back.view,
5923                    depth_slice: None,
5924                    resolve_target: None,
5925                    ops: wgpu::Operations {
5926                        load: wgpu::LoadOp::Clear(Color::rgba(0.0, 0.0, 0.0, 0.0).to_wgpu()),
5927                        store: wgpu::StoreOp::Store,
5928                    },
5929                })],
5930                depth_stencil_attachment: None,
5931                timestamp_writes: None,
5932                occlusion_query_set: None,
5933                multiview_mask: None,
5934            });
5935            pass.set_pipeline(&self.target_composition_pipelines.alpha);
5936            pass.set_bind_group(0, &history_bind_group, &[]);
5937            pass.draw(0..6, 0..1);
5938        }
5939        {
5940            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5941                label: Some("sim-engine trail source pass"),
5942                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5943                    view: &trails.back.view,
5944                    depth_slice: None,
5945                    resolve_target: None,
5946                    ops: wgpu::Operations {
5947                        load: wgpu::LoadOp::Load,
5948                        store: wgpu::StoreOp::Store,
5949                    },
5950                })],
5951                depth_stencil_attachment: None,
5952                timestamp_writes: None,
5953                occlusion_query_set: None,
5954                multiview_mask: None,
5955            });
5956            pass.set_pipeline(self.target_composition_pipelines.pipeline(source_blend));
5957            pass.set_bind_group(0, &source_bind_group, &[]);
5958            pass.draw(0..6, 0..1);
5959        }
5960        self.queue.submit([encoder.finish()]);
5961        std::mem::swap(&mut trails.front, &mut trails.back);
5962        render_report(
5963            RenderStatus::Drawn,
5964            Duration::ZERO,
5965            upload,
5966            Duration::ZERO,
5967            Duration::ZERO,
5968            encode_started_at.elapsed(),
5969            frame_started_at.elapsed(),
5970            false,
5971            true,
5972            TessellationStats::default(),
5973        )
5974    }
5975
5976    fn draw_clear_trail_buffer(
5977        &self,
5978        trails: &TrailBuffer2d,
5979        color: Color,
5980        frame_started_at: Instant,
5981    ) -> RenderReport {
5982        let encode_started_at = Instant::now();
5983        let mut encoder = self
5984            .device
5985            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5986                label: Some("sim-engine trail clear encoder"),
5987            });
5988        for view in [&trails.front.view, &trails.back.view] {
5989            let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5990                label: Some("sim-engine trail clear pass"),
5991                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5992                    view,
5993                    depth_slice: None,
5994                    resolve_target: None,
5995                    ops: wgpu::Operations {
5996                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(color)),
5997                        store: wgpu::StoreOp::Store,
5998                    },
5999                })],
6000                depth_stencil_attachment: None,
6001                timestamp_writes: None,
6002                occlusion_query_set: None,
6003                multiview_mask: None,
6004            });
6005        }
6006        self.queue.submit([encoder.finish()]);
6007        render_report(
6008            RenderStatus::Drawn,
6009            Duration::ZERO,
6010            Duration::ZERO,
6011            Duration::ZERO,
6012            Duration::ZERO,
6013            encode_started_at.elapsed(),
6014            frame_started_at.elapsed(),
6015            false,
6016            true,
6017            TessellationStats::default(),
6018        )
6019    }
6020
6021    fn prepare_particle_draw(
6022        &self,
6023        field: &mut ParticleField2d,
6024        camera: Camera2d,
6025    ) -> Result<ParticleDrawPreparation, RendererFrameError> {
6026        let (logical_width, logical_height) = self.logical_size();
6027        let viewport = LogicalViewport::new(logical_width, logical_height)
6028            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
6029        let Some(camera_uniform) = CameraUniform::new(camera, viewport) else {
6030            return Err(RendererFrameError::InvalidGeometryTransform);
6031        };
6032        let instance_count = field.instances.len();
6033        let visibility_checked = instance_count.min(field.budget.max_visibility_checks_per_frame);
6034        if visibility_checked < instance_count {
6035            field.visible_instances.clear();
6036            validate_particle_staging_capacity(&field.visible_instances, visibility_checked)?;
6037            for candidate_index in 0..visibility_checked {
6038                let source_index =
6039                    uniformly_sampled_index(candidate_index, instance_count, visibility_checked);
6040                let instance = field.instances[source_index];
6041                let Some(intersects) =
6042                    instance.validated_viewport_intersection(camera_uniform, viewport)
6043                else {
6044                    return Err(RendererFrameError::InvalidGeometryTransform);
6045                };
6046                if intersects {
6047                    field.visible_instances.push(instance);
6048                }
6049            }
6050            let visible_count = field.visible_instances.len();
6051            let selected_count = visible_count.min(field.budget.instance_limit());
6052            if selected_count < visible_count {
6053                let mut visible_index = 0;
6054                field.visible_instances.retain(|_| {
6055                    let selected = particle_visible_index_is_selected(
6056                        visible_index,
6057                        visible_count,
6058                        selected_count,
6059                    );
6060                    visible_index += 1;
6061                    selected
6062                });
6063            }
6064            let statistics = particle_statistics_with_budget(
6065                instance_count,
6066                visibility_checked,
6067                visible_count,
6068                selected_count,
6069                0,
6070            );
6071            return Ok(ParticleDrawPreparation {
6072                camera_uniform,
6073                visible_count: selected_count,
6074                statistics,
6075            });
6076        }
6077
6078        let visible_count = visible_particle_count(&field.instances, camera_uniform, viewport)?;
6079        let selected_count = visible_count.min(field.budget.instance_limit());
6080        let statistics = particle_statistics_with_budget(
6081            instance_count,
6082            instance_count,
6083            visible_count,
6084            selected_count,
6085            0,
6086        );
6087        if selected_count == field.instances.len() {
6088            field.visible_instances.clear();
6089        } else {
6090            field.visible_instances.clear();
6091            validate_particle_staging_capacity(&field.visible_instances, selected_count)?;
6092            let mut visible_index = 0;
6093            for instance in field.instances.iter().copied() {
6094                if !instance.intersects_viewport(camera_uniform, viewport) {
6095                    continue;
6096                }
6097                let selected_index = field.visible_instances.len();
6098                if selected_index < selected_count
6099                    && particle_visible_index_is_selected(
6100                        visible_index,
6101                        visible_count,
6102                        selected_count,
6103                    )
6104                {
6105                    field.visible_instances.push(instance);
6106                }
6107                visible_index += 1;
6108            }
6109        }
6110        Ok(ParticleDrawPreparation {
6111            camera_uniform,
6112            visible_count: selected_count,
6113            statistics,
6114        })
6115    }
6116
6117    fn upload_particle_draw(
6118        &self,
6119        field: &ParticleField2d,
6120        preparation: ParticleDrawPreparation,
6121    ) -> (Duration, Duration) {
6122        let visible_instances = if field.visible_instances.is_empty()
6123            && preparation.visible_count == field.instances.len()
6124        {
6125            field.instances.as_slice()
6126        } else {
6127            field.visible_instances.as_slice()
6128        };
6129        let upload_started_at = Instant::now();
6130        if !visible_instances.is_empty() {
6131            self.queue.write_buffer(
6132                &field.instance_buffer,
6133                0,
6134                bytemuck::cast_slice(visible_instances),
6135            );
6136        }
6137        let upload = upload_started_at.elapsed();
6138        let camera_uniform_upload_started_at = Instant::now();
6139        self.queue.write_buffer(
6140            &self.camera_uniform_buffer,
6141            0,
6142            bytemuck::bytes_of(&preparation.camera_uniform),
6143        );
6144        let camera_uniform_upload = camera_uniform_upload_started_at.elapsed();
6145        (upload, camera_uniform_upload)
6146    }
6147
6148    fn draw_particle_field(
6149        &mut self,
6150        background: Color,
6151        field: &mut ParticleField2d,
6152        camera: Camera2d,
6153        frame_started_at: Instant,
6154    ) -> Result<RenderReport, RendererFrameError> {
6155        let preparation_started_at = Instant::now();
6156        let preparation = self.prepare_particle_draw(field, camera)?;
6157        let preparation_duration = preparation_started_at.elapsed();
6158
6159        let surface_acquire_started_at = Instant::now();
6160        let surface_texture = match self.surface.get_current_texture() {
6161            wgpu::CurrentSurfaceTexture::Success(texture)
6162            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
6163            wgpu::CurrentSurfaceTexture::Timeout => {
6164                field.statistics = preparation.statistics;
6165                return Ok(render_report(
6166                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
6167                    preparation_duration,
6168                    Duration::ZERO,
6169                    Duration::ZERO,
6170                    surface_acquire_started_at.elapsed(),
6171                    Duration::ZERO,
6172                    frame_started_at.elapsed(),
6173                    false,
6174                    true,
6175                    TessellationStats::default(),
6176                ));
6177            }
6178            wgpu::CurrentSurfaceTexture::Occluded => {
6179                field.statistics = preparation.statistics;
6180                return Ok(render_report(
6181                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
6182                    preparation_duration,
6183                    Duration::ZERO,
6184                    Duration::ZERO,
6185                    surface_acquire_started_at.elapsed(),
6186                    Duration::ZERO,
6187                    frame_started_at.elapsed(),
6188                    false,
6189                    true,
6190                    TessellationStats::default(),
6191                ));
6192            }
6193            wgpu::CurrentSurfaceTexture::Outdated => {
6194                let _ = self.resize(self.config.width, self.config.height);
6195                field.statistics = preparation.statistics;
6196                return Ok(render_report(
6197                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
6198                    preparation_duration,
6199                    Duration::ZERO,
6200                    Duration::ZERO,
6201                    surface_acquire_started_at.elapsed(),
6202                    Duration::ZERO,
6203                    frame_started_at.elapsed(),
6204                    false,
6205                    true,
6206                    TessellationStats::default(),
6207                ));
6208            }
6209            wgpu::CurrentSurfaceTexture::Lost => {
6210                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
6211            }
6212            wgpu::CurrentSurfaceTexture::Validation => {
6213                return Err(RendererFrameError::Surface(
6214                    RendererSurfaceStatus::Validation,
6215                ));
6216            }
6217        };
6218        let surface_acquire = surface_acquire_started_at.elapsed();
6219        let (upload, camera_uniform_upload) = self.upload_particle_draw(field, preparation);
6220        let encode_submit_present_started_at = Instant::now();
6221        let surface_view = surface_texture
6222            .texture
6223            .create_view(&wgpu::TextureViewDescriptor::default());
6224        let (view, resolve_target) = match &self.multisample_target {
6225            Some(target) => (&target.view, Some(&surface_view)),
6226            None => (&surface_view, None),
6227        };
6228        let mut encoder = self
6229            .device
6230            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
6231                label: Some("sim-engine particle render encoder"),
6232            });
6233        {
6234            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
6235                label: Some("sim-engine particle render pass"),
6236                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
6237                    view,
6238                    depth_slice: None,
6239                    resolve_target,
6240                    ops: wgpu::Operations {
6241                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
6242                        store: wgpu::StoreOp::Store,
6243                    },
6244                })],
6245                depth_stencil_attachment: None,
6246                timestamp_writes: None,
6247                occlusion_query_set: None,
6248                multiview_mask: None,
6249            });
6250            if preparation.visible_count > 0 {
6251                pass.set_pipeline(&self.particle_pipeline);
6252                pass.set_bind_group(0, &self.camera_bind_group, &[]);
6253                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
6254                pass.set_vertex_buffer(1, field.instance_buffer.slice(..));
6255                pass.draw(0..6, 0..preparation.visible_count as u32);
6256            }
6257        }
6258        self.queue.submit([encoder.finish()]);
6259        self.notify_before_present();
6260        self.queue.present(surface_texture);
6261        field.statistics = ParticleStatistics {
6262            rendered: preparation.visible_count,
6263            ..preparation.statistics
6264        };
6265        Ok(render_report(
6266            RenderStatus::Drawn,
6267            preparation_duration,
6268            upload,
6269            camera_uniform_upload,
6270            surface_acquire,
6271            encode_submit_present_started_at.elapsed(),
6272            frame_started_at.elapsed(),
6273            false,
6274            true,
6275            TessellationStats::default(),
6276        ))
6277    }
6278
6279    fn draw_particle_field_to_target(
6280        &self,
6281        target: &RenderTarget2d,
6282        field: &mut ParticleField2d,
6283        camera: Camera2d,
6284        load: RenderTargetLoad,
6285        frame_started_at: Instant,
6286    ) -> Result<RenderReport, RendererFrameError> {
6287        let preparation_started_at = Instant::now();
6288        let preparation = self.prepare_particle_draw(field, camera)?;
6289        let preparation_duration = preparation_started_at.elapsed();
6290        let (upload, camera_uniform_upload) = self.upload_particle_draw(field, preparation);
6291        let encode_started_at = Instant::now();
6292        let mut encoder = self
6293            .device
6294            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
6295                label: Some("sim-engine target particle encoder"),
6296            });
6297        {
6298            let load = match load {
6299                RenderTargetLoad::Load => wgpu::LoadOp::Load,
6300                RenderTargetLoad::Clear(color) => {
6301                    wgpu::LoadOp::Clear(premultiplied_wgpu_color(color))
6302                }
6303            };
6304            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
6305                label: Some("sim-engine target particle pass"),
6306                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
6307                    view: &target.view,
6308                    depth_slice: None,
6309                    resolve_target: None,
6310                    ops: wgpu::Operations {
6311                        load,
6312                        store: wgpu::StoreOp::Store,
6313                    },
6314                })],
6315                depth_stencil_attachment: None,
6316                timestamp_writes: None,
6317                occlusion_query_set: None,
6318                multiview_mask: None,
6319            });
6320            if preparation.visible_count > 0 {
6321                pass.set_pipeline(&self.target_particle_pipeline);
6322                pass.set_bind_group(0, &self.camera_bind_group, &[]);
6323                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
6324                pass.set_vertex_buffer(1, field.instance_buffer.slice(..));
6325                pass.draw(0..6, 0..preparation.visible_count as u32);
6326            }
6327        }
6328        self.queue.submit([encoder.finish()]);
6329        field.statistics = ParticleStatistics {
6330            rendered: preparation.visible_count,
6331            ..preparation.statistics
6332        };
6333        Ok(render_report(
6334            RenderStatus::Drawn,
6335            preparation_duration,
6336            upload,
6337            camera_uniform_upload,
6338            Duration::ZERO,
6339            encode_started_at.elapsed(),
6340            frame_started_at.elapsed(),
6341            false,
6342            true,
6343            TessellationStats::default(),
6344        ))
6345    }
6346
6347    fn ensure_vertex_capacity(&mut self, vertex_count: usize) -> Result<(), RendererFrameError> {
6348        if vertex_count <= self.vertex_capacity {
6349            return Ok(());
6350        }
6351
6352        self.vertex_capacity = dynamic_vertex_capacity(vertex_count)
6353            .filter(|capacity| buffer_capacity_fits::<Vertex>(&self.device, *capacity))
6354            .ok_or(RendererFrameError::GeometryCapacityTooLarge)?;
6355        self.vertex_buffer = Arc::new(create_vertex_buffer(&self.device, self.vertex_capacity));
6356        Ok(())
6357    }
6358
6359    fn validate_dynamic_mesh(&self, mesh: &DynamicMesh2d) -> Result<(), DynamicMeshError> {
6360        prepared_scene_belongs_to(&self.renderer_identity, &mesh.renderer_identity)
6361            .then_some(())
6362            .ok_or(DynamicMeshError::RendererMismatch)
6363    }
6364
6365    fn validate_particle_field(&self, field: &ParticleField2d) -> Result<(), ParticleFieldError> {
6366        prepared_scene_belongs_to(&self.renderer_identity, &field.renderer_identity)
6367            .then_some(())
6368            .ok_or(ParticleFieldError::RendererMismatch)
6369    }
6370
6371    fn validate_scalar_field_texture(
6372        &self,
6373        texture: &ScalarFieldTexture,
6374    ) -> Result<(), ScalarFieldTextureError> {
6375        prepared_scene_belongs_to(&self.renderer_identity, &texture.renderer_identity)
6376            .then_some(())
6377            .ok_or(ScalarFieldTextureError::RendererMismatch)
6378    }
6379
6380    fn color_map_view(&mut self, color_map: &ColorMap) -> wgpu::TextureView {
6381        let lut = color_map_lut(color_map);
6382        if let Some(cached) = self
6383            .color_map_cache
6384            .as_ref()
6385            .filter(|cached| cached.lut == lut)
6386        {
6387            return cached.view.clone();
6388        }
6389        let cached = create_cached_color_map(&self.device, &self.queue, lut);
6390        let view = cached.view.clone();
6391        self.color_map_cache = Some(cached);
6392        view
6393    }
6394
6395    fn validate_render_target(&self, target: &RenderTarget2d) -> Result<(), RenderTargetError> {
6396        prepared_scene_belongs_to(&self.renderer_identity, &target.renderer_identity)
6397            .then_some(())
6398            .ok_or(RenderTargetError::RendererMismatch)
6399    }
6400
6401    fn validate_trail_buffer(&self, trails: &TrailBuffer2d) -> Result<(), RenderTargetError> {
6402        prepared_scene_belongs_to(&self.renderer_identity, &trails.renderer_identity)
6403            .then_some(())
6404            .ok_or(RenderTargetError::RendererMismatch)
6405    }
6406}
6407
6408fn invoke_pre_present_notify(
6409    present_mode: RendererSurfacePresentMode,
6410    notify: Option<&(dyn Fn() + Send + Sync)>,
6411) {
6412    if present_mode.is_refresh_synchronized()
6413        && let Some(notify) = notify
6414    {
6415        notify();
6416    }
6417}
6418
6419fn prepared_scene_belongs_to(renderer_identity: &Arc<()>, scene_identity: &Arc<()>) -> bool {
6420    Arc::ptr_eq(renderer_identity, scene_identity)
6421}
6422
6423fn render_target_allocation_bytes(
6424    format: wgpu::TextureFormat,
6425    width: u32,
6426    height: u32,
6427) -> Option<usize> {
6428    let bytes_per_texel = u64::from(format.block_copy_size(None)?);
6429    let byte_count = u64::from(width)
6430        .checked_mul(u64::from(height))?
6431        .checked_mul(bytes_per_texel)?;
6432    usize::try_from(byte_count).ok()
6433}
6434
6435fn dynamic_vertices_to_gpu(
6436    vertices: &[DynamicVertex2d],
6437) -> Result<Vec<DynamicGpu>, DynamicMeshError> {
6438    validate_dynamic_vertices(vertices)?;
6439    let requested_bytes = dynamic_mesh_bytes(vertices.len())?;
6440    let mut converted = Vec::new();
6441    converted
6442        .try_reserve_exact(vertices.len())
6443        .map_err(|_| DynamicMeshError::AllocationFailed { requested_bytes })?;
6444    converted.extend(vertices.iter().copied().map(dynamic_vertex_to_gpu));
6445    Ok(converted)
6446}
6447
6448fn replace_dynamic_mesh_resources(
6449    device: &wgpu::Device,
6450    queue: &wgpu::Queue,
6451    mesh: &mut DynamicMesh2d,
6452    vertices: &[DynamicVertex2d],
6453) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
6454    let update_started_at = Instant::now();
6455    validate_dynamic_vertices(vertices)?;
6456    if let Some(budget) = mesh.budget {
6457        validate_dynamic_mesh_budget(budget, vertices.len())?;
6458    }
6459    let reallocated = vertices.len() > mesh.vertex_capacity;
6460    let replacement_capacity = if reallocated {
6461        let capacity = dynamic_vertex_capacity(vertices.len())
6462            .filter(|capacity| buffer_capacity_fits::<DynamicGpu>(device, *capacity))
6463            .ok_or(DynamicMeshError::CapacityTooLarge)?;
6464        Some(capacity)
6465    } else {
6466        None
6467    };
6468    let replacement_vertices = dynamic_vertices_to_gpu(vertices)?;
6469    if let Some(budget) = mesh.budget {
6470        validate_dynamic_retained_capacity(budget, &replacement_vertices)?;
6471    }
6472    let replacement = if let Some(capacity) = replacement_capacity {
6473        let buffer = Arc::new(create_dynamic_vertex_buffer(device, capacity));
6474        Some((buffer, capacity))
6475    } else {
6476        None
6477    };
6478    let upload_buffer = replacement
6479        .as_ref()
6480        .map_or(mesh.vertex_buffer.as_ref(), |(buffer, _)| buffer.as_ref());
6481    if !replacement_vertices.is_empty() {
6482        queue.write_buffer(
6483            upload_buffer,
6484            0,
6485            bytemuck::cast_slice(&replacement_vertices),
6486        );
6487        submit_pending_uploads(queue);
6488    }
6489    if let Some((buffer, capacity)) = replacement {
6490        mesh.vertex_buffer = buffer;
6491        mesh.vertex_capacity = capacity;
6492    }
6493    mesh.geometry_extents = GeometryExtents::from_dynamic_vertices(&replacement_vertices);
6494    mesh.vertices = replacement_vertices;
6495    mesh.geometry_validation_cache.clear();
6496    Ok(DynamicMeshUpdateReport {
6497        vertex_count: mesh.vertices.len(),
6498        upload: update_started_at.elapsed(),
6499        reallocated,
6500    })
6501}
6502
6503fn dynamic_mesh_bytes(vertex_count: usize) -> Result<usize, DynamicMeshError> {
6504    vertex_count
6505        .checked_mul(std::mem::size_of::<DynamicGpu>())
6506        .ok_or(DynamicMeshError::CapacityTooLarge)
6507}
6508
6509fn validate_dynamic_mesh_budget(
6510    budget: DynamicMeshBudget,
6511    vertex_count: usize,
6512) -> Result<(), DynamicMeshError> {
6513    if u32::try_from(vertex_count).is_err() {
6514        return Err(DynamicMeshError::CapacityTooLarge);
6515    }
6516    if vertex_count > budget.max_vertices {
6517        return Err(DynamicMeshError::BudgetExceeded {
6518            resource: DynamicMeshBudgetResource::Vertices,
6519            limit: budget.max_vertices,
6520            actual: vertex_count,
6521        });
6522    }
6523    let bytes = dynamic_mesh_bytes(vertex_count)?;
6524    if bytes > budget.max_retained_bytes {
6525        return Err(DynamicMeshError::BudgetExceeded {
6526            resource: DynamicMeshBudgetResource::RetainedBytes,
6527            limit: budget.max_retained_bytes,
6528            actual: bytes,
6529        });
6530    }
6531    if bytes > budget.max_upload_bytes {
6532        return Err(DynamicMeshError::BudgetExceeded {
6533            resource: DynamicMeshBudgetResource::UploadBytes,
6534            limit: budget.max_upload_bytes,
6535            actual: bytes,
6536        });
6537    }
6538    Ok(())
6539}
6540
6541fn validate_dynamic_retained_capacity(
6542    budget: DynamicMeshBudget,
6543    vertices: &Vec<DynamicGpu>,
6544) -> Result<(), DynamicMeshError> {
6545    let actual = vertices
6546        .capacity()
6547        .checked_mul(std::mem::size_of::<DynamicGpu>())
6548        .ok_or(DynamicMeshError::CapacityTooLarge)?;
6549    if actual > budget.max_retained_bytes {
6550        return Err(DynamicMeshError::BudgetExceeded {
6551            resource: DynamicMeshBudgetResource::RetainedBytes,
6552            limit: budget.max_retained_bytes,
6553            actual,
6554        });
6555    }
6556    Ok(())
6557}
6558
6559fn validate_dynamic_vertices(vertices: &[DynamicVertex2d]) -> Result<(), DynamicMeshError> {
6560    if u32::try_from(vertices.len()).is_err() {
6561        return Err(DynamicMeshError::CapacityTooLarge);
6562    }
6563    if !vertices.len().is_multiple_of(3) {
6564        return Err(DynamicMeshError::InvalidVertexCount);
6565    }
6566    if vertices.iter().any(|vertex| {
6567        ![
6568            vertex.world_position.x,
6569            vertex.world_position.y,
6570            vertex.depth,
6571        ]
6572        .into_iter()
6573        .all(is_portable_shader_source)
6574    }) {
6575        return Err(DynamicMeshError::InvalidVertex);
6576    }
6577    // Private fields and the only public constructor make finiteness an
6578    // invariant of DynamicVertex2d. Keep the assertion in development without
6579    // rescanning an already-validated high-volume stream in release builds.
6580    debug_assert!(vertices.iter().all(|vertex| {
6581        vertex.world_position.is_finite()
6582            && vertex.depth.is_finite()
6583            && vertex.color.is_normalized()
6584    }));
6585    Ok(())
6586}
6587
6588fn dynamic_vertex_to_gpu(vertex: DynamicVertex2d) -> DynamicGpu {
6589    DynamicGpu {
6590        world_position: [vertex.world_position.x, vertex.world_position.y],
6591        depth: vertex.depth,
6592        color: vertex.color.to_array(),
6593    }
6594}
6595
6596fn dynamic_vertex_capacity(vertex_count: usize) -> Option<usize> {
6597    vertex_count.max(1).checked_next_power_of_two()
6598}
6599
6600fn particle_instances_to_gpu(
6601    instances: &[ParticleInstance2d],
6602) -> Result<Vec<ParticleGpu>, ParticleFieldError> {
6603    if u32::try_from(instances.len()).is_err() {
6604        return Err(ParticleFieldError::CapacityTooLarge);
6605    }
6606    let requested_bytes = instances
6607        .len()
6608        .checked_mul(std::mem::size_of::<ParticleGpu>())
6609        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6610    if instances.iter().copied().any(|instance| {
6611        let world_position = instance.world_position();
6612        let radius = instance.radius();
6613        let color = instance.color();
6614        let depth = instance.depth();
6615        ![world_position.x, world_position.y, radius, depth]
6616            .into_iter()
6617            .all(is_portable_shader_source)
6618            || radius <= 0.0
6619            || !color.is_normalized()
6620    }) {
6621        return Err(ParticleFieldError::InvalidInstance);
6622    }
6623    let mut output = Vec::new();
6624    output
6625        .try_reserve_exact(instances.len())
6626        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
6627    output.extend(instances.iter().copied().map(|instance| {
6628        let world_position = instance.world_position();
6629        ParticleGpu {
6630            world_position: [world_position.x, world_position.y],
6631            depth: instance.depth(),
6632            radius: instance.radius(),
6633            color: instance.color().to_array(),
6634        }
6635    }));
6636    Ok(output)
6637}
6638
6639fn particle_retained_bytes(instance_count: usize) -> Option<usize> {
6640    instance_count.checked_mul(std::mem::size_of::<ParticleGpu>())
6641}
6642
6643fn validate_particle_retained_count(
6644    instance_count: usize,
6645    budget: ParticleRenderBudget,
6646) -> Result<(), ParticleFieldError> {
6647    let staging_count = particle_staging_target(instance_count, budget);
6648    let retained_count = instance_count
6649        .checked_add(staging_count)
6650        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6651    let actual =
6652        particle_retained_bytes(retained_count).ok_or(ParticleFieldError::CapacityTooLarge)?;
6653    if actual > budget.max_retained_bytes {
6654        return Err(ParticleFieldError::RetainedBudgetExceeded {
6655            limit: budget.max_retained_bytes,
6656            actual,
6657        });
6658    }
6659    Ok(())
6660}
6661
6662fn validate_particle_retained_capacities(
6663    instance_capacity: usize,
6664    staging_capacity: usize,
6665    budget: ParticleRenderBudget,
6666) -> Result<(), ParticleFieldError> {
6667    let retained_capacity = instance_capacity
6668        .checked_add(staging_capacity)
6669        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6670    let actual =
6671        particle_retained_bytes(retained_capacity).ok_or(ParticleFieldError::CapacityTooLarge)?;
6672    if actual > budget.max_retained_bytes {
6673        return Err(ParticleFieldError::RetainedBudgetExceeded {
6674            limit: budget.max_retained_bytes,
6675            actual,
6676        });
6677    }
6678    Ok(())
6679}
6680
6681fn compact_particle_instances(
6682    source: &[ParticleGpu],
6683    current_capacity: usize,
6684    staging_capacity: usize,
6685    budget: ParticleRenderBudget,
6686) -> Result<Option<Vec<ParticleGpu>>, ParticleFieldError> {
6687    validate_particle_retained_count(source.len(), budget)?;
6688    if validate_particle_retained_capacities(current_capacity, staging_capacity, budget).is_ok() {
6689        return Ok(None);
6690    }
6691    let requested_bytes =
6692        particle_retained_bytes(source.len()).ok_or(ParticleFieldError::CapacityTooLarge)?;
6693    let mut compact = Vec::new();
6694    compact
6695        .try_reserve_exact(source.len())
6696        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
6697    compact.extend_from_slice(source);
6698    validate_particle_retained_capacities(compact.capacity(), staging_capacity, budget)?;
6699    Ok(Some(compact))
6700}
6701
6702fn particle_instance_capacity(instance_count: usize) -> Option<usize> {
6703    instance_count.max(1).checked_next_power_of_two()
6704}
6705
6706fn particle_budgeted_capacity(
6707    instance_count: usize,
6708    budget: ParticleRenderBudget,
6709) -> Option<usize> {
6710    let limit = budget.instance_limit();
6711    let required = instance_count.min(limit).max(1);
6712    particle_instance_capacity(required).map(|capacity| capacity.min(limit))
6713}
6714
6715fn allocate_particle_staging(
6716    instance_count: usize,
6717    budget: ParticleRenderBudget,
6718) -> Result<Vec<ParticleGpu>, ParticleFieldError> {
6719    let target = particle_staging_target(instance_count, budget);
6720    let requested_bytes = target
6721        .checked_mul(std::mem::size_of::<ParticleGpu>())
6722        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6723    let mut staging = Vec::new();
6724    staging
6725        .try_reserve_exact(target)
6726        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
6727    Ok(staging)
6728}
6729
6730fn particle_staging_target(instance_count: usize, budget: ParticleRenderBudget) -> usize {
6731    let visibility_checked = instance_count.min(budget.max_visibility_checks_per_frame);
6732    if visibility_checked < instance_count {
6733        visibility_checked
6734    } else {
6735        instance_count.min(budget.instance_limit())
6736    }
6737}
6738
6739fn buffer_allocation_bytes<T>(capacity: usize) -> Option<u64> {
6740    u64::try_from(capacity)
6741        .ok()?
6742        .checked_mul(std::mem::size_of::<T>() as u64)
6743}
6744
6745fn buffer_capacity_fits<T>(device: &wgpu::Device, capacity: usize) -> bool {
6746    buffer_allocation_bytes::<T>(capacity)
6747        .is_some_and(|bytes| bytes <= device.limits().max_buffer_size)
6748}
6749
6750fn scene_estimate_fits_prepared_device(scene: &Scene, device: &wgpu::Device) -> bool {
6751    buffer_capacity_fits::<Vertex>(
6752        device,
6753        scene.statistics().estimated_tessellated_vertices().max(1),
6754    )
6755}
6756
6757fn scene_estimate_fits_streaming_device(
6758    scene: &Scene,
6759    device: &wgpu::Device,
6760    prefix: usize,
6761    current_capacity: usize,
6762) -> bool {
6763    let Some(required) = prefix.checked_add(scene.statistics().estimated_tessellated_vertices())
6764    else {
6765        return false;
6766    };
6767    required <= current_capacity
6768        || dynamic_vertex_capacity(required)
6769            .is_some_and(|capacity| buffer_capacity_fits::<Vertex>(device, capacity))
6770}
6771
6772fn particle_update_range(
6773    first_instance: usize,
6774    replacement_count: usize,
6775    current_count: usize,
6776) -> Result<Range<usize>, ParticleFieldError> {
6777    let end = first_instance
6778        .checked_add(replacement_count)
6779        .ok_or(ParticleFieldError::UpdateRangeOutOfBounds)?;
6780    (end <= current_count)
6781        .then_some(first_instance..end)
6782        .ok_or(ParticleFieldError::UpdateRangeOutOfBounds)
6783}
6784
6785fn validate_particle_staging_capacity(
6786    instances: &Vec<ParticleGpu>,
6787    target_len: usize,
6788) -> Result<(), RendererFrameError> {
6789    let requested_bytes = target_len
6790        .checked_mul(std::mem::size_of::<ParticleGpu>())
6791        .ok_or(RendererFrameError::GeometryCapacityTooLarge)?;
6792    (instances.capacity() >= target_len)
6793        .then_some(())
6794        .ok_or(RendererFrameError::ParticleAllocationFailed { requested_bytes })
6795}
6796
6797#[cfg(test)]
6798fn visible_particle_instances(
6799    instances: &[ParticleGpu],
6800    camera: CameraUniform,
6801    viewport: LogicalViewport,
6802) -> Result<Vec<ParticleGpu>, RendererFrameError> {
6803    visible_particle_count(instances, camera, viewport)?;
6804    Ok(instances
6805        .iter()
6806        .copied()
6807        .filter(|instance| instance.intersects_viewport(camera, viewport))
6808        .collect())
6809}
6810
6811fn visible_particle_count(
6812    instances: &[ParticleGpu],
6813    camera: CameraUniform,
6814    viewport: LogicalViewport,
6815) -> Result<usize, RendererFrameError> {
6816    let mut visible = 0;
6817    for instance in instances.iter().copied() {
6818        let Some(intersects) = instance.validated_viewport_intersection(camera, viewport) else {
6819            return Err(RendererFrameError::InvalidGeometryTransform);
6820        };
6821        visible += usize::from(intersects);
6822    }
6823    Ok(visible)
6824}
6825
6826fn particle_visible_index_is_selected(
6827    visible_index: usize,
6828    visible_count: usize,
6829    selected_count: usize,
6830) -> bool {
6831    if visible_count == 0 || selected_count == 0 {
6832        return false;
6833    }
6834    let before = visible_index as u128 * selected_count as u128 / visible_count as u128;
6835    let after = (visible_index as u128 + 1) * selected_count as u128 / visible_count as u128;
6836    before < after
6837}
6838
6839fn uniformly_sampled_index(sample_index: usize, source_count: usize, sample_count: usize) -> usize {
6840    debug_assert!(sample_index < sample_count);
6841    debug_assert!(sample_count <= source_count);
6842    (((sample_index as u128 + 1) * source_count as u128 - 1) / sample_count as u128) as usize
6843}
6844
6845fn particle_idle_statistics(instance_count: usize) -> ParticleStatistics {
6846    ParticleStatistics {
6847        submitted: instance_count,
6848        visibility_checked: 0,
6849        visible: 0,
6850        culled: 0,
6851        budget_limited: 0,
6852        dropped: 0,
6853        rendered: 0,
6854    }
6855}
6856
6857#[cfg(test)]
6858fn particle_statistics(
6859    instance_count: usize,
6860    visible: usize,
6861    rendered: usize,
6862) -> ParticleStatistics {
6863    particle_statistics_with_budget(instance_count, instance_count, visible, visible, rendered)
6864}
6865
6866fn particle_statistics_with_budget(
6867    instance_count: usize,
6868    visibility_checked: usize,
6869    visible: usize,
6870    selected: usize,
6871    rendered: usize,
6872) -> ParticleStatistics {
6873    ParticleStatistics {
6874        submitted: instance_count,
6875        visibility_checked,
6876        visible,
6877        culled: visibility_checked.saturating_sub(visible),
6878        budget_limited: instance_count
6879            .saturating_sub(visibility_checked)
6880            .saturating_add(visible.saturating_sub(selected)),
6881        dropped: 0,
6882        rendered,
6883    }
6884}
6885
6886fn prepare_scene_resources(
6887    device: &wgpu::Device,
6888    queue: &wgpu::Queue,
6889    renderer_identity: Arc<()>,
6890    scene: &Scene,
6891) -> Result<PreparedScene, PreparedSceneError> {
6892    if !scene_command_sources_are_portable(scene) {
6893        return Err(PreparedSceneError::InvalidGeometrySources);
6894    }
6895    if !scene_estimate_fits_prepared_device(scene, device) {
6896        return Err(PreparedSceneError::CapacityTooLarge);
6897    }
6898    let mut vertices = Vec::new();
6899    let mut draw_batches = Vec::new();
6900    let tessellation = tessellate_scene(scene, &mut vertices, &mut draw_batches)?;
6901    let geometry_extents = GeometryExtents::from_vertices(&vertices);
6902    if !geometry_sources_are_portable(GeometryValidationSource::Tessellated(&vertices)) {
6903        return Err(PreparedSceneError::InvalidGeometrySources);
6904    }
6905    if !buffer_capacity_fits::<Vertex>(device, vertices.len().max(1)) {
6906        return Err(PreparedSceneError::CapacityTooLarge);
6907    }
6908    // Retain the tessellator allocation directly. Wrapping a Vec is O(1) and
6909    // avoids an infallible caller-scale Vec -> Arc<[T]> copy after GPU writes.
6910    let vertices = Arc::new(vertices);
6911    let vertex_buffer = Arc::new(create_vertex_buffer(device, vertices.len()));
6912    if !vertices.is_empty() {
6913        queue.write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
6914        submit_pending_uploads(queue);
6915    }
6916    let vertex_count = vertices.len();
6917
6918    Ok(PreparedScene {
6919        renderer_identity,
6920        background: scene.background(),
6921        vertex_buffer,
6922        vertices,
6923        command_count: scene.command_count(),
6924        vertex_count,
6925        geometry_extents,
6926        draw_batches,
6927        tessellation,
6928        geometry_validation_cache: GeometryValidationCache::default(),
6929    })
6930}
6931
6932fn scene_command_sources_are_portable(scene: &Scene) -> bool {
6933    scene.commands().iter().all(|command| {
6934        is_portable_shader_source(command.depth())
6935            && command.screen_clip().is_none_or(|clip| {
6936                portable_vec2(clip.min().to_vec2()) && portable_vec2(clip.max().to_vec2())
6937            })
6938            && match command.command() {
6939                DrawCommand::Circle(circle) => {
6940                    portable_vec2(circle.center())
6941                        && is_portable_shader_source(circle.radius())
6942                        && portable_shape_style(circle.style())
6943                }
6944                DrawCommand::Rect(rectangle) => {
6945                    portable_vec2(rectangle.rect().min())
6946                        && portable_vec2(rectangle.rect().max())
6947                        && is_portable_shader_source(rectangle.corner_radius())
6948                        && portable_shape_style(rectangle.style())
6949                }
6950                DrawCommand::Line(line) => {
6951                    portable_vec2(line.from())
6952                        && portable_vec2(line.to())
6953                        && portable_stroke_style(line.stroke_style())
6954                }
6955                DrawCommand::Polyline(polyline) => {
6956                    polyline.points().iter().copied().all(portable_vec2)
6957                        && portable_stroke_style(polyline.stroke_style())
6958                }
6959            }
6960    })
6961}
6962
6963fn portable_vec2(value: Vec2) -> bool {
6964    is_portable_shader_source(value.x) && is_portable_shader_source(value.y)
6965}
6966
6967fn portable_shape_style(style: ShapeStyle) -> bool {
6968    style
6969        .stroke()
6970        .is_none_or(|stroke| is_portable_shader_source(stroke.width()))
6971        && style.shadow().is_none_or(|shadow| {
6972            portable_vec2(shadow.offset().to_vec2()) && is_portable_shader_source(shadow.spread())
6973        })
6974}
6975
6976fn portable_stroke_style(style: crate::StrokeStyle2d) -> bool {
6977    let stroke = style.stroke();
6978    is_portable_shader_source(stroke.width())
6979        && is_portable_shader_source(style.miter_limit())
6980        && style.dash_pattern().is_none_or(|dash| {
6981            dash.lengths()
6982                .iter()
6983                .copied()
6984                .chain([dash.phase()])
6985                .all(is_portable_shader_source)
6986        })
6987        && style.start_marker().is_none_or(|marker| {
6988            is_portable_shader_source(marker.length().get())
6989                && is_portable_shader_source(marker.width().get())
6990        })
6991        && style.end_marker().is_none_or(|marker| {
6992            is_portable_shader_source(marker.length().get())
6993                && is_portable_shader_source(marker.width().get())
6994        })
6995}
6996
6997fn restore_prepared_scene_resources(
6998    device: &wgpu::Device,
6999    queue: &wgpu::Queue,
7000    renderer_identity: Arc<()>,
7001    source: &PreparedScene,
7002) -> Result<PreparedScene, PreparedSceneError> {
7003    if !buffer_capacity_fits::<Vertex>(device, source.vertices.len().max(1)) {
7004        return Err(PreparedSceneError::CapacityTooLarge);
7005    }
7006    if !geometry_sources_are_portable(GeometryValidationSource::Tessellated(&source.vertices)) {
7007        return Err(PreparedSceneError::InvalidGeometrySources);
7008    }
7009    let requested_bytes = source
7010        .draw_batches
7011        .len()
7012        .checked_mul(std::mem::size_of::<PreparedDrawBatch>())
7013        .ok_or(PreparedSceneError::CapacityTooLarge)?;
7014    let mut draw_batches = Vec::new();
7015    draw_batches
7016        .try_reserve_exact(source.draw_batches.len())
7017        .map_err(|_| PreparedSceneError::AllocationFailed { requested_bytes })?;
7018    draw_batches.extend_from_slice(&source.draw_batches);
7019    let vertex_buffer = Arc::new(create_vertex_buffer(device, source.vertices.len()));
7020    if !source.vertices.is_empty() {
7021        queue.write_buffer(
7022            &vertex_buffer,
7023            0,
7024            bytemuck::cast_slice(source.vertices.as_ref()),
7025        );
7026        submit_pending_uploads(queue);
7027    }
7028
7029    Ok(PreparedScene {
7030        renderer_identity,
7031        background: source.background,
7032        vertex_buffer,
7033        vertices: Arc::clone(&source.vertices),
7034        command_count: source.command_count,
7035        vertex_count: source.vertex_count,
7036        geometry_extents: source.geometry_extents,
7037        draw_batches,
7038        tessellation: source.tessellation,
7039        geometry_validation_cache: GeometryValidationCache::default(),
7040    })
7041}
7042
7043fn restore_dynamic_mesh_resources(
7044    device: &wgpu::Device,
7045    queue: &wgpu::Queue,
7046    renderer_identity: Arc<()>,
7047    source: &DynamicMesh2d,
7048) -> Result<DynamicMesh2d, DynamicMeshError> {
7049    if !buffer_capacity_fits::<DynamicGpu>(device, source.vertex_capacity) {
7050        return Err(DynamicMeshError::CapacityTooLarge);
7051    }
7052    if let Some(budget) = source.budget {
7053        validate_dynamic_mesh_budget(budget, source.vertices.len())?;
7054    }
7055    let requested_bytes = dynamic_mesh_bytes(source.vertices.len())?;
7056    let mut vertices = Vec::new();
7057    vertices
7058        .try_reserve_exact(source.vertices.len())
7059        .map_err(|_| DynamicMeshError::AllocationFailed { requested_bytes })?;
7060    vertices.extend_from_slice(&source.vertices);
7061    if let Some(budget) = source.budget {
7062        validate_dynamic_retained_capacity(budget, &vertices)?;
7063    }
7064    let vertex_buffer = Arc::new(create_dynamic_vertex_buffer(device, source.vertex_capacity));
7065    if !vertices.is_empty() {
7066        queue.write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(vertices.as_slice()));
7067        submit_pending_uploads(queue);
7068    }
7069    Ok(DynamicMesh2d {
7070        renderer_identity,
7071        vertex_buffer,
7072        vertices,
7073        vertex_capacity: source.vertex_capacity,
7074        geometry_extents: source.geometry_extents,
7075        geometry_validation_cache: GeometryValidationCache::default(),
7076        budget: source.budget,
7077    })
7078}
7079
7080fn restore_particle_field_resources(
7081    device: &wgpu::Device,
7082    _queue: &wgpu::Queue,
7083    renderer_identity: Arc<()>,
7084    source: &ParticleField2d,
7085) -> Result<ParticleField2d, ParticleFieldError> {
7086    validate_particle_retained_count(source.instances.len(), source.budget)?;
7087    if !buffer_capacity_fits::<ParticleGpu>(device, source.instance_capacity) {
7088        return Err(ParticleFieldError::CapacityTooLarge);
7089    }
7090    let requested_bytes = source
7091        .instances
7092        .len()
7093        .checked_mul(std::mem::size_of::<ParticleGpu>())
7094        .ok_or(ParticleFieldError::CapacityTooLarge)?;
7095    let mut instances = Vec::new();
7096    instances
7097        .try_reserve_exact(source.instances.len())
7098        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
7099    instances.extend_from_slice(&source.instances);
7100    let visible_instances = allocate_particle_staging(instances.len(), source.budget)?;
7101    validate_particle_retained_capacities(
7102        instances.capacity(),
7103        visible_instances.capacity(),
7104        source.budget,
7105    )?;
7106    let instance_buffer = Arc::new(create_particle_instance_buffer(
7107        device,
7108        source.instance_capacity,
7109    ));
7110    Ok(ParticleField2d {
7111        renderer_identity,
7112        instance_buffer,
7113        instances,
7114        visible_instances,
7115        instance_capacity: source.instance_capacity,
7116        budget: source.budget,
7117        statistics: particle_idle_statistics(source.instances.len()),
7118    })
7119}
7120
7121#[allow(clippy::too_many_arguments)]
7122fn render_report(
7123    status: RenderStatus,
7124    tessellation: Duration,
7125    upload: Duration,
7126    camera_uniform_upload: Duration,
7127    surface_acquire: Duration,
7128    encode_submit_present: Duration,
7129    total_cpu: Duration,
7130    geometry_reused: bool,
7131    geometry_streamed: bool,
7132    tessellation_stats: TessellationStats,
7133) -> RenderReport {
7134    RenderReport {
7135        status,
7136        metrics: RendererFrameMetrics {
7137            tessellation,
7138            upload,
7139            camera_uniform_upload,
7140            surface_acquire,
7141            encode_submit_present,
7142            total_cpu,
7143            geometry_reused,
7144            geometry_streamed,
7145            tessellation_stats,
7146        },
7147    }
7148}
7149
7150struct PipelineResources {
7151    pipeline: wgpu::RenderPipeline,
7152    target_pipeline: wgpu::RenderPipeline,
7153    dynamic_pipeline: wgpu::RenderPipeline,
7154    particle_pipeline: wgpu::RenderPipeline,
7155    target_particle_pipeline: wgpu::RenderPipeline,
7156    heatmap_pipeline: wgpu::RenderPipeline,
7157    target_heatmap_pipeline: wgpu::RenderPipeline,
7158    composition_pipelines: CompositionPipelines,
7159    target_composition_pipelines: CompositionPipelines,
7160    camera_uniform_buffer: wgpu::Buffer,
7161    camera_bind_group: wgpu::BindGroup,
7162    camera_bind_group_layout: wgpu::BindGroupLayout,
7163    heatmap_uniform_buffer: wgpu::Buffer,
7164    heatmap_bind_group_layout: wgpu::BindGroupLayout,
7165}
7166
7167fn create_pipeline(
7168    device: &wgpu::Device,
7169    format: wgpu::TextureFormat,
7170    sample_count: u32,
7171) -> PipelineResources {
7172    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
7173        label: Some("sim-engine flat color shader"),
7174        source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("primitive.wgsl"))),
7175    });
7176    let camera_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7177        label: Some("sim-engine camera uniform buffer"),
7178        size: std::mem::size_of::<CameraUniform>() as wgpu::BufferAddress,
7179        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7180        mapped_at_creation: false,
7181    });
7182    let camera_bind_group_layout =
7183        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7184            label: Some("sim-engine camera bind group layout"),
7185            entries: &[wgpu::BindGroupLayoutEntry {
7186                binding: 0,
7187                visibility: wgpu::ShaderStages::VERTEX,
7188                ty: wgpu::BindingType::Buffer {
7189                    ty: wgpu::BufferBindingType::Uniform,
7190                    has_dynamic_offset: false,
7191                    min_binding_size: None,
7192                },
7193                count: None,
7194            }],
7195        });
7196    let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
7197        label: Some("sim-engine camera bind group"),
7198        layout: &camera_bind_group_layout,
7199        entries: &[wgpu::BindGroupEntry {
7200            binding: 0,
7201            resource: camera_uniform_buffer.as_entire_binding(),
7202        }],
7203    });
7204    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7205        label: Some("sim-engine shape pipeline layout"),
7206        bind_group_layouts: &[Some(&camera_bind_group_layout)],
7207        immediate_size: 0,
7208    });
7209    let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7210        label: Some("sim-engine shape pipeline"),
7211        layout: Some(&pipeline_layout),
7212        vertex: wgpu::VertexState {
7213            module: &shader,
7214            entry_point: Some("vs_main"),
7215            compilation_options: wgpu::PipelineCompilationOptions::default(),
7216            buffers: &[Some(Vertex::LAYOUT)],
7217        },
7218        primitive: wgpu::PrimitiveState {
7219            topology: wgpu::PrimitiveTopology::TriangleList,
7220            ..Default::default()
7221        },
7222        depth_stencil: None,
7223        multisample: wgpu::MultisampleState {
7224            count: sample_count,
7225            ..Default::default()
7226        },
7227        fragment: Some(wgpu::FragmentState {
7228            module: &shader,
7229            entry_point: Some("fs_main"),
7230            compilation_options: wgpu::PipelineCompilationOptions::default(),
7231            targets: &[Some(wgpu::ColorTargetState {
7232                format,
7233                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7234                write_mask: wgpu::ColorWrites::ALL,
7235            })],
7236        }),
7237        multiview_mask: None,
7238        cache: None,
7239    });
7240
7241    let target_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7242        label: Some("sim-engine target shape pipeline"),
7243        layout: Some(&pipeline_layout),
7244        vertex: wgpu::VertexState {
7245            module: &shader,
7246            entry_point: Some("vs_main"),
7247            compilation_options: wgpu::PipelineCompilationOptions::default(),
7248            buffers: &[Some(Vertex::LAYOUT)],
7249        },
7250        primitive: wgpu::PrimitiveState {
7251            topology: wgpu::PrimitiveTopology::TriangleList,
7252            ..Default::default()
7253        },
7254        depth_stencil: None,
7255        multisample: wgpu::MultisampleState::default(),
7256        fragment: Some(wgpu::FragmentState {
7257            module: &shader,
7258            entry_point: Some("fs_main"),
7259            compilation_options: wgpu::PipelineCompilationOptions::default(),
7260            targets: &[Some(wgpu::ColorTargetState {
7261                format,
7262                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7263                write_mask: wgpu::ColorWrites::ALL,
7264            })],
7265        }),
7266        multiview_mask: None,
7267        cache: None,
7268    });
7269
7270    let dynamic_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7271        label: Some("sim-engine dynamic mesh pipeline"),
7272        layout: Some(&pipeline_layout),
7273        vertex: wgpu::VertexState {
7274            module: &shader,
7275            entry_point: Some("dynamic_vs_main"),
7276            compilation_options: wgpu::PipelineCompilationOptions::default(),
7277            buffers: &[Some(DynamicGpu::LAYOUT)],
7278        },
7279        primitive: wgpu::PrimitiveState {
7280            topology: wgpu::PrimitiveTopology::TriangleList,
7281            ..Default::default()
7282        },
7283        depth_stencil: None,
7284        multisample: wgpu::MultisampleState {
7285            count: sample_count,
7286            ..Default::default()
7287        },
7288        fragment: Some(wgpu::FragmentState {
7289            module: &shader,
7290            entry_point: Some("fs_main"),
7291            compilation_options: wgpu::PipelineCompilationOptions::default(),
7292            targets: &[Some(wgpu::ColorTargetState {
7293                format,
7294                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7295                write_mask: wgpu::ColorWrites::ALL,
7296            })],
7297        }),
7298        multiview_mask: None,
7299        cache: None,
7300    });
7301
7302    let particle_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7303        label: Some("sim-engine particle pipeline"),
7304        layout: Some(&pipeline_layout),
7305        vertex: wgpu::VertexState {
7306            module: &shader,
7307            entry_point: Some("particle_vs_main"),
7308            compilation_options: wgpu::PipelineCompilationOptions::default(),
7309            buffers: &[Some(ParticleUnitVertex::LAYOUT), Some(ParticleGpu::LAYOUT)],
7310        },
7311        primitive: wgpu::PrimitiveState {
7312            topology: wgpu::PrimitiveTopology::TriangleList,
7313            ..Default::default()
7314        },
7315        depth_stencil: None,
7316        multisample: wgpu::MultisampleState {
7317            count: sample_count,
7318            ..Default::default()
7319        },
7320        fragment: Some(wgpu::FragmentState {
7321            module: &shader,
7322            entry_point: Some("fs_main"),
7323            compilation_options: wgpu::PipelineCompilationOptions::default(),
7324            targets: &[Some(wgpu::ColorTargetState {
7325                format,
7326                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7327                write_mask: wgpu::ColorWrites::ALL,
7328            })],
7329        }),
7330        multiview_mask: None,
7331        cache: None,
7332    });
7333
7334    let target_particle_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7335        label: Some("sim-engine target particle pipeline"),
7336        layout: Some(&pipeline_layout),
7337        vertex: wgpu::VertexState {
7338            module: &shader,
7339            entry_point: Some("particle_vs_main"),
7340            compilation_options: wgpu::PipelineCompilationOptions::default(),
7341            buffers: &[Some(ParticleUnitVertex::LAYOUT), Some(ParticleGpu::LAYOUT)],
7342        },
7343        primitive: wgpu::PrimitiveState {
7344            topology: wgpu::PrimitiveTopology::TriangleList,
7345            ..Default::default()
7346        },
7347        depth_stencil: None,
7348        multisample: wgpu::MultisampleState {
7349            count: 1,
7350            ..Default::default()
7351        },
7352        fragment: Some(wgpu::FragmentState {
7353            module: &shader,
7354            entry_point: Some("fs_main"),
7355            compilation_options: wgpu::PipelineCompilationOptions::default(),
7356            targets: &[Some(wgpu::ColorTargetState {
7357                format,
7358                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7359                write_mask: wgpu::ColorWrites::ALL,
7360            })],
7361        }),
7362        multiview_mask: None,
7363        cache: None,
7364    });
7365
7366    let heatmap_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7367        label: Some("sim-engine heatmap uniform buffer"),
7368        size: std::mem::size_of::<HeatmapUniform>() as wgpu::BufferAddress,
7369        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7370        mapped_at_creation: false,
7371    });
7372    let heatmap_bind_group_layout =
7373        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7374            label: Some("sim-engine heatmap bind group layout"),
7375            entries: &[
7376                wgpu::BindGroupLayoutEntry {
7377                    binding: 0,
7378                    visibility: wgpu::ShaderStages::FRAGMENT,
7379                    ty: wgpu::BindingType::Texture {
7380                        multisampled: false,
7381                        view_dimension: wgpu::TextureViewDimension::D2,
7382                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7383                    },
7384                    count: None,
7385                },
7386                wgpu::BindGroupLayoutEntry {
7387                    binding: 1,
7388                    visibility: wgpu::ShaderStages::FRAGMENT,
7389                    ty: wgpu::BindingType::Texture {
7390                        multisampled: false,
7391                        view_dimension: wgpu::TextureViewDimension::D2,
7392                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7393                    },
7394                    count: None,
7395                },
7396                wgpu::BindGroupLayoutEntry {
7397                    binding: 2,
7398                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
7399                    ty: wgpu::BindingType::Buffer {
7400                        ty: wgpu::BufferBindingType::Uniform,
7401                        has_dynamic_offset: false,
7402                        min_binding_size: None,
7403                    },
7404                    count: None,
7405                },
7406            ],
7407        });
7408    let heatmap_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7409        label: Some("sim-engine heatmap pipeline layout"),
7410        bind_group_layouts: &[Some(&heatmap_bind_group_layout)],
7411        immediate_size: 0,
7412    });
7413    let heatmap_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7414        label: Some("sim-engine heatmap pipeline"),
7415        layout: Some(&heatmap_pipeline_layout),
7416        vertex: wgpu::VertexState {
7417            module: &shader,
7418            entry_point: Some("heatmap_vs_main"),
7419            compilation_options: wgpu::PipelineCompilationOptions::default(),
7420            buffers: &[],
7421        },
7422        primitive: wgpu::PrimitiveState {
7423            topology: wgpu::PrimitiveTopology::TriangleList,
7424            ..Default::default()
7425        },
7426        depth_stencil: None,
7427        multisample: wgpu::MultisampleState {
7428            count: sample_count,
7429            ..Default::default()
7430        },
7431        fragment: Some(wgpu::FragmentState {
7432            module: &shader,
7433            entry_point: Some("heatmap_fs_main"),
7434            compilation_options: wgpu::PipelineCompilationOptions::default(),
7435            targets: &[Some(wgpu::ColorTargetState {
7436                format,
7437                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7438                write_mask: wgpu::ColorWrites::ALL,
7439            })],
7440        }),
7441        multiview_mask: None,
7442        cache: None,
7443    });
7444
7445    let target_heatmap_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7446        label: Some("sim-engine render-target heatmap pipeline"),
7447        layout: Some(&heatmap_pipeline_layout),
7448        vertex: wgpu::VertexState {
7449            module: &shader,
7450            entry_point: Some("heatmap_vs_main"),
7451            compilation_options: wgpu::PipelineCompilationOptions::default(),
7452            buffers: &[],
7453        },
7454        primitive: wgpu::PrimitiveState {
7455            topology: wgpu::PrimitiveTopology::TriangleList,
7456            ..Default::default()
7457        },
7458        depth_stencil: None,
7459        multisample: wgpu::MultisampleState::default(),
7460        fragment: Some(wgpu::FragmentState {
7461            module: &shader,
7462            entry_point: Some("heatmap_fs_main"),
7463            compilation_options: wgpu::PipelineCompilationOptions::default(),
7464            targets: &[Some(wgpu::ColorTargetState {
7465                format,
7466                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7467                write_mask: wgpu::ColorWrites::ALL,
7468            })],
7469        }),
7470        multiview_mask: None,
7471        cache: None,
7472    });
7473
7474    let composition_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7475        label: Some("sim-engine composition uniform buffer"),
7476        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7477        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7478        mapped_at_creation: false,
7479    });
7480    let composition_secondary_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7481        label: Some("sim-engine composition secondary uniform buffer"),
7482        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7483        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7484        mapped_at_creation: false,
7485    });
7486    let composition_bind_group_layout =
7487        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7488            label: Some("sim-engine composition bind group layout"),
7489            entries: &[
7490                wgpu::BindGroupLayoutEntry {
7491                    binding: 0,
7492                    visibility: wgpu::ShaderStages::FRAGMENT,
7493                    ty: wgpu::BindingType::Texture {
7494                        multisampled: false,
7495                        view_dimension: wgpu::TextureViewDimension::D2,
7496                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7497                    },
7498                    count: None,
7499                },
7500                wgpu::BindGroupLayoutEntry {
7501                    binding: 1,
7502                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
7503                    ty: wgpu::BindingType::Buffer {
7504                        ty: wgpu::BufferBindingType::Uniform,
7505                        has_dynamic_offset: false,
7506                        min_binding_size: None,
7507                    },
7508                    count: None,
7509                },
7510            ],
7511        });
7512    let composition_pipeline_layout =
7513        device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7514            label: Some("sim-engine composition pipeline layout"),
7515            bind_group_layouts: &[Some(&composition_bind_group_layout)],
7516            immediate_size: 0,
7517        });
7518    let composition_pipelines = CompositionPipelines {
7519        alpha: create_composition_pipeline(
7520            device,
7521            &shader,
7522            &composition_pipeline_layout,
7523            format,
7524            sample_count,
7525            BlendMode::Alpha,
7526        ),
7527        additive: create_composition_pipeline(
7528            device,
7529            &shader,
7530            &composition_pipeline_layout,
7531            format,
7532            sample_count,
7533            BlendMode::Additive,
7534        ),
7535        replace: create_composition_pipeline(
7536            device,
7537            &shader,
7538            &composition_pipeline_layout,
7539            format,
7540            sample_count,
7541            BlendMode::Replace,
7542        ),
7543        uniform_buffer: composition_uniform_buffer,
7544        secondary_uniform_buffer: composition_secondary_uniform_buffer,
7545        bind_group_layout: composition_bind_group_layout,
7546    };
7547    let target_composition_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7548        label: Some("sim-engine target composition uniform buffer"),
7549        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7550        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7551        mapped_at_creation: false,
7552    });
7553    let target_composition_secondary_uniform_buffer =
7554        device.create_buffer(&wgpu::BufferDescriptor {
7555            label: Some("sim-engine target composition secondary uniform buffer"),
7556            size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7557            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7558            mapped_at_creation: false,
7559        });
7560    let target_composition_bind_group_layout =
7561        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7562            label: Some("sim-engine target composition bind group layout"),
7563            entries: &[
7564                wgpu::BindGroupLayoutEntry {
7565                    binding: 0,
7566                    visibility: wgpu::ShaderStages::FRAGMENT,
7567                    ty: wgpu::BindingType::Texture {
7568                        multisampled: false,
7569                        view_dimension: wgpu::TextureViewDimension::D2,
7570                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7571                    },
7572                    count: None,
7573                },
7574                wgpu::BindGroupLayoutEntry {
7575                    binding: 1,
7576                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
7577                    ty: wgpu::BindingType::Buffer {
7578                        ty: wgpu::BufferBindingType::Uniform,
7579                        has_dynamic_offset: false,
7580                        min_binding_size: None,
7581                    },
7582                    count: None,
7583                },
7584            ],
7585        });
7586    let target_composition_pipeline_layout =
7587        device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7588            label: Some("sim-engine target composition pipeline layout"),
7589            bind_group_layouts: &[Some(&target_composition_bind_group_layout)],
7590            immediate_size: 0,
7591        });
7592    let target_composition_pipelines = CompositionPipelines {
7593        alpha: create_composition_pipeline(
7594            device,
7595            &shader,
7596            &target_composition_pipeline_layout,
7597            format,
7598            1,
7599            BlendMode::Alpha,
7600        ),
7601        additive: create_composition_pipeline(
7602            device,
7603            &shader,
7604            &target_composition_pipeline_layout,
7605            format,
7606            1,
7607            BlendMode::Additive,
7608        ),
7609        replace: create_composition_pipeline(
7610            device,
7611            &shader,
7612            &target_composition_pipeline_layout,
7613            format,
7614            1,
7615            BlendMode::Replace,
7616        ),
7617        uniform_buffer: target_composition_uniform_buffer,
7618        secondary_uniform_buffer: target_composition_secondary_uniform_buffer,
7619        bind_group_layout: target_composition_bind_group_layout,
7620    };
7621
7622    PipelineResources {
7623        pipeline,
7624        target_pipeline,
7625        dynamic_pipeline,
7626        particle_pipeline,
7627        target_particle_pipeline,
7628        heatmap_pipeline,
7629        target_heatmap_pipeline,
7630        composition_pipelines,
7631        target_composition_pipelines,
7632        camera_uniform_buffer,
7633        camera_bind_group,
7634        camera_bind_group_layout,
7635        heatmap_uniform_buffer,
7636        heatmap_bind_group_layout,
7637    }
7638}
7639
7640fn preferred_sample_count(adapter: &wgpu::Adapter, format: wgpu::TextureFormat) -> u32 {
7641    let flags = adapter.get_texture_format_features(format).flags;
7642    if flags.contains(
7643        wgpu::TextureFormatFeatureFlags::MULTISAMPLE_X4
7644            | wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
7645    ) {
7646        PREFERRED_SAMPLE_COUNT
7647    } else {
7648        1
7649    }
7650}
7651
7652fn create_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
7653    device.create_buffer(&wgpu::BufferDescriptor {
7654        label: Some("sim-engine vertex buffer"),
7655        size: (capacity.max(1) * std::mem::size_of::<Vertex>()) as wgpu::BufferAddress,
7656        usage: wgpu::BufferUsages::VERTEX
7657            | wgpu::BufferUsages::COPY_DST
7658            | wgpu::BufferUsages::COPY_SRC,
7659        mapped_at_creation: false,
7660    })
7661}
7662
7663fn create_dynamic_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
7664    device.create_buffer(&wgpu::BufferDescriptor {
7665        label: Some("sim-engine dynamic vertex buffer"),
7666        size: (capacity.max(1) * std::mem::size_of::<DynamicGpu>()) as wgpu::BufferAddress,
7667        usage: wgpu::BufferUsages::VERTEX
7668            | wgpu::BufferUsages::COPY_DST
7669            | wgpu::BufferUsages::COPY_SRC,
7670        mapped_at_creation: false,
7671    })
7672}
7673
7674fn scalar_field_extent(field: &ScalarField) -> Result<wgpu::Extent3d, ScalarFieldTextureError> {
7675    let width =
7676        u32::try_from(field.width()).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7677    let height =
7678        u32::try_from(field.height()).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7679    let _bytes_per_row = width
7680        .checked_mul(std::mem::size_of::<f32>() as u32)
7681        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7682    Ok(wgpu::Extent3d {
7683        width,
7684        height,
7685        depth_or_array_layers: 1,
7686    })
7687}
7688
7689fn clone_scalar_field_for_restore(
7690    source: &ScalarField,
7691) -> Result<ScalarField, ScalarFieldTextureError> {
7692    let requested_bytes = source
7693        .values()
7694        .len()
7695        .checked_mul(std::mem::size_of::<f32>())
7696        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7697    let mut values = Vec::new();
7698    values
7699        .try_reserve_exact(source.values().len())
7700        .map_err(|_| ScalarFieldTextureError::AllocationFailed { requested_bytes })?;
7701    values.extend_from_slice(source.values());
7702    // The retained source already satisfies ScalarField's shape and finite
7703    // invariants. Keep the impossible defensive branch structured.
7704    ScalarField::new(source.width(), source.height(), values)
7705        .map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)
7706}
7707
7708fn scalar_value_range_extent(minimum: f32, maximum: f32) -> Option<f32> {
7709    if !is_portable_shader_source(minimum)
7710        || !is_portable_shader_source(maximum)
7711        || maximum <= minimum
7712    {
7713        return None;
7714    }
7715    let extent = maximum - minimum;
7716    (is_portable_shader_source(extent) && extent > 0.0).then_some(extent)
7717}
7718
7719fn scalar_field_sources_are_portable(field: &ScalarField) -> bool {
7720    if field
7721        .values()
7722        .iter()
7723        .copied()
7724        .any(|value| !is_portable_shader_source(value))
7725    {
7726        return false;
7727    }
7728    let (minimum, maximum) = field.value_range();
7729    let extent = f64::from(maximum) - f64::from(minimum);
7730    extent.is_finite() && extent <= f64::from(MAX_PORTABLE_SHADER_VALUE)
7731}
7732
7733fn scalar_normalization_is_portable(
7734    texture: &ScalarFieldTexture,
7735    minimum: f32,
7736    value_extent: f32,
7737) -> bool {
7738    if !is_portable_shader_source(minimum)
7739        || !is_portable_shader_source(value_extent)
7740        || value_extent <= 0.0
7741    {
7742        return false;
7743    }
7744    let Some(numerator) = shader_interval_sum_range([
7745        (
7746            f64::from(texture.source_minimum),
7747            f64::from(texture.source_maximum),
7748        ),
7749        (-f64::from(minimum), -f64::from(minimum)),
7750    ]) else {
7751        return false;
7752    };
7753    [numerator.0, numerator.1].into_iter().all(|value| {
7754        let normalized = value / f64::from(value_extent);
7755        normalized.is_finite() && normalized.abs() <= f64::from(MAX_PORTABLE_SHADER_VALUE)
7756    })
7757}
7758
7759fn compact_scalar_field_for_retention(
7760    field: ScalarField,
7761) -> Result<ScalarField, ScalarFieldTextureError> {
7762    let requested_bytes = field
7763        .values()
7764        .len()
7765        .checked_mul(std::mem::size_of::<f32>())
7766        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7767    if field.value_allocation_bytes() <= requested_bytes {
7768        return Ok(field);
7769    }
7770    clone_scalar_field_for_restore(&field)
7771}
7772
7773fn premultiplied_wgpu_color(color: Color) -> wgpu::Color {
7774    let [red, green, blue, alpha] = color.to_array();
7775    wgpu::Color {
7776        r: f64::from(red * alpha),
7777        g: f64::from(green * alpha),
7778        b: f64::from(blue * alpha),
7779        a: f64::from(alpha),
7780    }
7781}
7782
7783fn create_scalar_field_texture(
7784    device: &wgpu::Device,
7785    field: &ScalarField,
7786) -> Result<wgpu::Texture, ScalarFieldTextureError> {
7787    let extent = scalar_field_extent(field)?;
7788    let limits = device.limits();
7789    if extent.width > limits.max_texture_dimension_2d
7790        || extent.height > limits.max_texture_dimension_2d
7791    {
7792        return Err(ScalarFieldTextureError::DimensionsTooLarge);
7793    }
7794    Ok(device.create_texture(&wgpu::TextureDescriptor {
7795        label: Some("sim-engine scalar field texture"),
7796        size: extent,
7797        mip_level_count: 1,
7798        sample_count: 1,
7799        dimension: wgpu::TextureDimension::D2,
7800        format: wgpu::TextureFormat::R32Float,
7801        usage: wgpu::TextureUsages::TEXTURE_BINDING
7802            | wgpu::TextureUsages::COPY_DST
7803            | wgpu::TextureUsages::COPY_SRC,
7804        view_formats: &[],
7805    }))
7806}
7807
7808fn validate_scalar_field_device_extent(
7809    device: &wgpu::Device,
7810    field: &ScalarField,
7811) -> Result<wgpu::Extent3d, ScalarFieldTextureError> {
7812    let extent = scalar_field_extent(field)?;
7813    let limit = device.limits().max_texture_dimension_2d;
7814    if extent.width > limit || extent.height > limit {
7815        return Err(ScalarFieldTextureError::DimensionsTooLarge);
7816    }
7817    Ok(extent)
7818}
7819
7820fn upload_scalar_field_texture(
7821    queue: &wgpu::Queue,
7822    texture: &wgpu::Texture,
7823    field: &ScalarField,
7824) -> Result<(), ScalarFieldTextureError> {
7825    let extent = scalar_field_extent(field)?;
7826    queue.write_texture(
7827        wgpu::TexelCopyTextureInfo {
7828            texture,
7829            mip_level: 0,
7830            origin: wgpu::Origin3d::ZERO,
7831            aspect: wgpu::TextureAspect::All,
7832        },
7833        bytemuck::cast_slice(field.values()),
7834        wgpu::TexelCopyBufferLayout {
7835            offset: 0,
7836            bytes_per_row: Some(extent.width * std::mem::size_of::<f32>() as u32),
7837            rows_per_image: Some(extent.height),
7838        },
7839        extent,
7840    );
7841    submit_pending_uploads(queue);
7842    Ok(())
7843}
7844
7845fn upload_scalar_field_texture_region(
7846    queue: &wgpu::Queue,
7847    texture: &wgpu::Texture,
7848    x: usize,
7849    y: usize,
7850    width: usize,
7851    height: usize,
7852    values: &[f32],
7853) -> Result<(), ScalarFieldTextureError> {
7854    let width = u32::try_from(width).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7855    let height = u32::try_from(height).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7856    let x = u32::try_from(x).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7857    let y = u32::try_from(y).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7858    let bytes_per_row = width
7859        .checked_mul(std::mem::size_of::<f32>() as u32)
7860        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7861    queue.write_texture(
7862        wgpu::TexelCopyTextureInfo {
7863            texture,
7864            mip_level: 0,
7865            origin: wgpu::Origin3d { x, y, z: 0 },
7866            aspect: wgpu::TextureAspect::All,
7867        },
7868        bytemuck::cast_slice(values),
7869        wgpu::TexelCopyBufferLayout {
7870            offset: 0,
7871            bytes_per_row: Some(bytes_per_row),
7872            rows_per_image: Some(height),
7873        },
7874        wgpu::Extent3d {
7875            width,
7876            height,
7877            depth_or_array_layers: 1,
7878        },
7879    );
7880    submit_pending_uploads(queue);
7881    Ok(())
7882}
7883
7884/// Submits deferred `Queue::write_*` transfers without waiting for GPU completion.
7885///
7886/// Native `wgpu` retains staging allocations until a queue submission starts
7887/// their transfer. Standalone retained-resource mutations call this immediately;
7888/// render paths instead combine their writes with the draw submission.
7889pub(super) fn submit_pending_uploads(queue: &wgpu::Queue) {
7890    let _ = queue.submit([]);
7891}
7892
7893#[allow(clippy::too_many_arguments)]
7894fn validate_scalar_field_texture_region(
7895    texture_width: usize,
7896    texture_height: usize,
7897    x: usize,
7898    y: usize,
7899    width: usize,
7900    height: usize,
7901    value_count: usize,
7902) -> Result<(), ScalarFieldTextureError> {
7903    let expected = width
7904        .checked_mul(height)
7905        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7906    if value_count != expected {
7907        return Err(ScalarFieldTextureError::InvalidUpdateValueCount);
7908    }
7909    if width == 0
7910        || height == 0
7911        || x.checked_add(width).is_none_or(|end| end > texture_width)
7912        || y.checked_add(height).is_none_or(|end| end > texture_height)
7913    {
7914        return Err(ScalarFieldTextureError::UpdateRegionOutOfBounds);
7915    }
7916    for value in [x, y, width, height] {
7917        u32::try_from(value).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7918    }
7919    u32::try_from(width)
7920        .ok()
7921        .and_then(|width| width.checked_mul(std::mem::size_of::<f32>() as u32))
7922        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7923    Ok(())
7924}
7925
7926fn scalar_region_result_range(
7927    field: &ScalarField,
7928    x: usize,
7929    y: usize,
7930    width: usize,
7931    height: usize,
7932    values: &[f32],
7933) -> (f32, f32) {
7934    let mut minimum = f32::INFINITY;
7935    let mut maximum = f32::NEG_INFINITY;
7936    for row in 0..field.height() {
7937        for column in 0..field.width() {
7938            let value = if (x..x + width).contains(&column) && (y..y + height).contains(&row) {
7939                values[(row - y) * width + (column - x)]
7940            } else {
7941                field.values()[row * field.width() + column]
7942            };
7943            minimum = minimum.min(value);
7944            maximum = maximum.max(value);
7945        }
7946    }
7947    (minimum, maximum)
7948}
7949
7950fn create_scalar_field_texture_resources(
7951    device: &wgpu::Device,
7952    queue: &wgpu::Queue,
7953    renderer_identity: Arc<()>,
7954    field: ScalarField,
7955) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
7956    validate_scalar_field_device_extent(device, &field)?;
7957    if !scalar_field_sources_are_portable(&field) {
7958        return Err(ScalarFieldTextureError::NonPortableValue);
7959    }
7960    let field = compact_scalar_field_for_retention(field)?;
7961    let (source_minimum, source_maximum) = field.value_range();
7962    let texture = create_scalar_field_texture(device, &field)?;
7963    upload_scalar_field_texture(queue, &texture, &field)?;
7964    Ok(ScalarFieldTexture {
7965        renderer_identity,
7966        texture,
7967        field,
7968        source_minimum,
7969        source_maximum,
7970    })
7971}
7972
7973fn color_map_lut(color_map: &ColorMap) -> [u8; COLOR_MAP_LUT_SIZE as usize * 4] {
7974    let mut bytes = [0_u8; COLOR_MAP_LUT_SIZE as usize * 4];
7975    for index in 0..COLOR_MAP_LUT_SIZE {
7976        let color = color_map.sample_normalized(index as f32 / (COLOR_MAP_LUT_SIZE - 1) as f32);
7977        let offset = index as usize * 4;
7978        bytes[offset..offset + 4].copy_from_slice(
7979            &color
7980                .to_array()
7981                .map(|channel| (channel * 255.0).round() as u8),
7982        );
7983    }
7984    bytes
7985}
7986
7987fn create_cached_color_map(
7988    device: &wgpu::Device,
7989    queue: &wgpu::Queue,
7990    lut: [u8; COLOR_MAP_LUT_SIZE as usize * 4],
7991) -> CachedColorMap {
7992    let texture = device.create_texture(&wgpu::TextureDescriptor {
7993        label: Some("sim-engine color map texture"),
7994        size: wgpu::Extent3d {
7995            width: COLOR_MAP_LUT_SIZE,
7996            height: 1,
7997            depth_or_array_layers: 1,
7998        },
7999        mip_level_count: 1,
8000        sample_count: 1,
8001        dimension: wgpu::TextureDimension::D2,
8002        format: wgpu::TextureFormat::Rgba8Unorm,
8003        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
8004        view_formats: &[],
8005    });
8006    queue.write_texture(
8007        wgpu::TexelCopyTextureInfo {
8008            texture: &texture,
8009            mip_level: 0,
8010            origin: wgpu::Origin3d::ZERO,
8011            aspect: wgpu::TextureAspect::All,
8012        },
8013        &lut,
8014        wgpu::TexelCopyBufferLayout {
8015            offset: 0,
8016            bytes_per_row: Some(1024),
8017            rows_per_image: Some(1),
8018        },
8019        wgpu::Extent3d {
8020            width: COLOR_MAP_LUT_SIZE,
8021            height: 1,
8022            depth_or_array_layers: 1,
8023        },
8024    );
8025    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
8026    CachedColorMap {
8027        lut,
8028        _texture: texture,
8029        view,
8030    }
8031}
8032
8033fn create_submitted_particle_unit_buffer(
8034    device: &wgpu::Device,
8035    queue: &wgpu::Queue,
8036) -> wgpu::Buffer {
8037    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
8038        label: Some("sim-engine particle unit quad buffer"),
8039        size: (6 * std::mem::size_of::<ParticleUnitVertex>()) as wgpu::BufferAddress,
8040        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
8041        mapped_at_creation: false,
8042    });
8043    let unit_quad = [
8044        ParticleUnitVertex {
8045            direction: [-1.0, -1.0],
8046        },
8047        ParticleUnitVertex {
8048            direction: [1.0, -1.0],
8049        },
8050        ParticleUnitVertex {
8051            direction: [1.0, 1.0],
8052        },
8053        ParticleUnitVertex {
8054            direction: [-1.0, -1.0],
8055        },
8056        ParticleUnitVertex {
8057            direction: [1.0, 1.0],
8058        },
8059        ParticleUnitVertex {
8060            direction: [-1.0, 1.0],
8061        },
8062    ];
8063    queue.write_buffer(&buffer, 0, bytemuck::cast_slice(&unit_quad));
8064    submit_pending_uploads(queue);
8065    buffer
8066}
8067
8068fn create_particle_instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
8069    device.create_buffer(&wgpu::BufferDescriptor {
8070        label: Some("sim-engine particle instance buffer"),
8071        size: (capacity.max(1) * std::mem::size_of::<ParticleGpu>()) as wgpu::BufferAddress,
8072        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
8073        mapped_at_creation: false,
8074    })
8075}
8076
8077mod config;
8078mod exact_markers;
8079mod frame;
8080mod geometry;
8081mod glyph;
8082mod gpu_timing;
8083mod image;
8084mod mesh3d;
8085mod tessellation;
8086#[cfg(feature = "text")]
8087mod text;
8088#[cfg(feature = "text")]
8089pub use text::{
8090    PreparedTextError, TextAtlas2d, TextAtlasBudget, TextError, TextRun2d, TextUpdateReport,
8091};
8092mod visualization;
8093use config::{
8094    MultisampleTarget, create_multisample_target, logical_to_physical_screen,
8095    physical_to_logical_screen, validate_scale_factor, validate_surface_dimensions,
8096};
8097pub use config::{RendererPresentMode, RendererSurfacePresentMode, WgpuRendererOptions};
8098pub use frame::{
8099    FrameBudget, FrameBudgetResource, FrameCacheBudget, FrameCacheStatistics, FrameComposer,
8100    FrameComposerError, FramePassOptions, FrameReport, FrameSourceKind, FrameSourceStatistics,
8101    FrameStatistics,
8102};
8103pub use glyph::{
8104    GlyphAtlas2d, GlyphAtlasBudget, GlyphAtlasEntry, GlyphError, GlyphId, GlyphRun2d,
8105    GlyphRunBounds, GlyphRunBudget, GlyphRunStatistics, GlyphRunUploadReport, GlyphUploadReport,
8106    PositionedGlyph2d,
8107};
8108pub use gpu_timing::{
8109    GpuTimingBatch, GpuTimingId, GpuTimingSample, GpuTimingSource, GpuTimingStatistics,
8110    GpuTimingStatus,
8111};
8112pub use image::{
8113    Image2d, ImageBatch2d, ImageBatchBudget, ImageBatchPlacement, ImageBatchUploadReport,
8114    ImageBudget, ImageError, ImageSampling, ImageSprite2d, ImageTexelRect, ImageUploadReport,
8115};
8116use image::{ImageRenderer, ImageUniform};
8117use mesh3d::Mesh3dRenderer;
8118pub use mesh3d::{
8119    DynamicMesh3dBudget, DynamicMesh3dBudgetResource, DynamicMesh3dError,
8120    DynamicMesh3dUpdateReport, Mesh3dInstance, Mesh3dObjectError, Mesh3dPreflightReport,
8121    Mesh3dRenderBudget, Mesh3dRenderError, Mesh3dRenderReport, Mesh3dResourceError,
8122    Mesh3dSurfaceError, Mesh3dUploadBudget, Mesh3dUploadBudgetResource, Mesh3dUploadReport,
8123    Object3dId, RenderTarget3d, RetainedMesh3d, Scene3d, Scene3dBudget, Scene3dBudgetResource,
8124    Scene3dError, Scene3dMeshUpdateReport, Scene3dRestoreReport, Scene3dStatistics,
8125    SurfaceRasterization3d, Texture3d, Texture3dError, Texture3dOptions, Texture3dUpdateBudget,
8126    Texture3dUpdateBudgetResource, Texture3dUpdateError, Texture3dUpdateReport, TextureMaterial3d,
8127    TextureMipmaps3d,
8128};
8129use tessellation::{
8130    logical_viewport_scissor, offset_scissor, screen_clip_to_scissor, tessellate_scene,
8131};
8132use visualization::{CachedColorMap, CompositionPipelines, create_composition_pipeline};
8133pub use visualization::{
8134    LayeredVisualizationError, LayeredVisualizationOptions, LayeredVisualizationReport,
8135};
8136
8137#[cfg(test)]
8138use tessellation::world_vertex;
8139
8140#[cfg(test)]
8141mod tests;