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    camera_uniform_buffer: wgpu::Buffer,
3552    camera_bind_group: wgpu::BindGroup,
3553    camera_bind_group_layout: wgpu::BindGroupLayout,
3554    heatmap_uniform_buffer: wgpu::Buffer,
3555    heatmap_bind_group_layout: wgpu::BindGroupLayout,
3556    color_map_cache: Option<CachedColorMap>,
3557    frame_cache: frame::FrameCache,
3558    vertex_buffer: Arc<wgpu::Buffer>,
3559    particle_unit_buffer: wgpu::Buffer,
3560    vertex_capacity: usize,
3561    multisample_target: Option<MultisampleTarget>,
3562    sample_count: u32,
3563    vertices: Vec<Vertex>,
3564    draw_batches: Vec<PreparedDrawBatch>,
3565    retired_devices: Vec<RetiredDevice>,
3566    max_quarantined_devices: usize,
3567}
3568
3569struct RetiredDevice {
3570    _adapter: wgpu::Adapter,
3571    _device: wgpu::Device,
3572    _queue: wgpu::Queue,
3573}
3574
3575impl WgpuRenderer {
3576    /// Creates a renderer for a window or canvas surface target.
3577    ///
3578    /// `width` and `height` are physical surface pixels. Zero sizes are clamped
3579    /// to one pixel because `wgpu` surfaces cannot be configured at zero size.
3580    /// This convenience constructor assumes a display scale factor of `1.0`;
3581    /// HiDPI hosts should use [`WgpuRenderer::new_with_options`].
3582    pub async fn new(
3583        surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
3584        width: u32,
3585        height: u32,
3586    ) -> Result<Self, RendererInitError> {
3587        Self::new_with_options(
3588            surface_target,
3589            width,
3590            height,
3591            WgpuRendererOptions::default(),
3592        )
3593        .await
3594    }
3595
3596    /// Creates a renderer with explicit options.
3597    ///
3598    /// Use this when measuring renderer throughput or when the host application
3599    /// needs control over presentation behavior or display scale.
3600    pub async fn new_with_options(
3601        surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
3602        width: u32,
3603        height: u32,
3604        options: WgpuRendererOptions,
3605    ) -> Result<Self, RendererInitError> {
3606        let instance =
3607            wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
3608        let surface = instance
3609            .create_surface(surface_target)
3610            .map_err(RendererInitError::CreateSurface)?;
3611        let adapter = instance
3612            .request_adapter(&wgpu::RequestAdapterOptions {
3613                power_preference: wgpu::PowerPreference::HighPerformance,
3614                force_fallback_adapter: false,
3615                compatible_surface: Some(&surface),
3616                apply_limit_buckets: false,
3617            })
3618            .await
3619            .map_err(RendererInitError::RequestAdapter)?;
3620        let adapter_info = adapter.get_info();
3621
3622        let (device, queue) = adapter
3623            .request_device(&wgpu::DeviceDescriptor {
3624                label: Some("sim-engine device"),
3625                required_features: wgpu::Features::empty(),
3626                required_limits: wgpu::Limits::default(),
3627                experimental_features: wgpu::ExperimentalFeatures::disabled(),
3628                memory_hints: wgpu::MemoryHints::Performance,
3629                trace: wgpu::Trace::Off,
3630            })
3631            .await
3632            .map_err(RendererInitError::RequestDevice)?;
3633
3634        let width = width.max(1);
3635        let height = height.max(1);
3636        let dimension_limit = device.limits().max_texture_dimension_2d;
3637        if width > dimension_limit || height > dimension_limit {
3638            return Err(RendererInitError::SurfaceDimensionsTooLarge {
3639                width,
3640                height,
3641                limit: dimension_limit,
3642            });
3643        }
3644        let surface_capabilities = surface.get_capabilities(&adapter);
3645        let mut config = surface
3646            .get_default_config(&adapter, width, height)
3647            .ok_or(RendererInitError::NoSurfaceConfig)?;
3648        let surface_present_mode = select_surface_present_mode(
3649            options.present_mode(),
3650            &surface_capabilities.present_modes,
3651        );
3652        config.present_mode = surface_present_mode.to_wgpu();
3653        surface.configure(&device, &config);
3654
3655        let sample_count = preferred_sample_count(&adapter, config.format);
3656        let PipelineResources {
3657            pipeline,
3658            target_pipeline,
3659            dynamic_pipeline,
3660            particle_pipeline,
3661            target_particle_pipeline,
3662            heatmap_pipeline,
3663            target_heatmap_pipeline,
3664            composition_pipelines,
3665            target_composition_pipelines,
3666            camera_uniform_buffer,
3667            camera_bind_group,
3668            camera_bind_group_layout,
3669            heatmap_uniform_buffer,
3670            heatmap_bind_group_layout,
3671        } = create_pipeline(&device, config.format, sample_count);
3672        let vertex_buffer = Arc::new(create_vertex_buffer(&device, INITIAL_VERTEX_CAPACITY));
3673        let particle_unit_buffer = create_submitted_particle_unit_buffer(&device, &queue);
3674        let multisample_target = create_multisample_target(&device, &config, sample_count);
3675        let image_renderer = ImageRenderer::new(&device, config.format, sample_count);
3676        let mesh3d_renderer = Mesh3dRenderer::new(&device, config.format);
3677
3678        Ok(Self {
3679            renderer_identity: Arc::new(()),
3680            _instance: instance,
3681            surface,
3682            _adapter: adapter,
3683            adapter_info,
3684            device,
3685            queue,
3686            config,
3687            requested_present_mode: options.present_mode(),
3688            surface_present_mode,
3689            pre_present_notify: None,
3690            scale_factor: options.scale_factor(),
3691            pipeline,
3692            target_pipeline,
3693            dynamic_pipeline,
3694            particle_pipeline,
3695            target_particle_pipeline,
3696            heatmap_pipeline,
3697            target_heatmap_pipeline,
3698            composition_pipelines,
3699            target_composition_pipelines,
3700            image_renderer,
3701            mesh3d_renderer,
3702            camera_uniform_buffer,
3703            camera_bind_group,
3704            camera_bind_group_layout,
3705            heatmap_uniform_buffer,
3706            heatmap_bind_group_layout,
3707            color_map_cache: None,
3708            frame_cache: frame::FrameCache::default(),
3709            vertex_buffer,
3710            particle_unit_buffer,
3711            vertex_capacity: INITIAL_VERTEX_CAPACITY,
3712            multisample_target,
3713            sample_count,
3714            vertices: Vec::new(),
3715            draw_batches: Vec::new(),
3716            retired_devices: Vec::new(),
3717            max_quarantined_devices: options.max_quarantined_devices(),
3718        })
3719    }
3720
3721    /// Returns the configured surface size in physical pixels.
3722    pub fn size(&self) -> (u32, u32) {
3723        (self.config.width, self.config.height)
3724    }
3725
3726    /// Returns the render viewport size in logical screen pixels.
3727    ///
3728    /// Scene clipping, stroke widths, shadows, and camera zoom use this logical
3729    /// coordinate space so their visual size remains stable across display DPI.
3730    pub fn logical_size(&self) -> (f32, f32) {
3731        let scale_factor = self.scale_factor as f32;
3732        (
3733            self.config.width as f32 / scale_factor,
3734            self.config.height as f32 / scale_factor,
3735        )
3736    }
3737
3738    /// Returns the current camera viewport in logical screen pixels.
3739    pub fn logical_viewport(&self) -> Result<LogicalViewport, crate::LogicalViewportError> {
3740        let (width, height) = self.logical_size();
3741        LogicalViewport::new(width, height)
3742    }
3743
3744    /// Converts a physical surface position into logical screen pixels.
3745    pub fn physical_to_logical_screen(
3746        &self,
3747        position: PhysicalScreenPosition,
3748    ) -> Result<LogicalScreenPosition, RendererCoordinateError> {
3749        physical_to_logical_screen(position, self.scale_factor as f32)
3750    }
3751
3752    /// Converts a logical screen position into physical surface pixels.
3753    pub fn logical_to_physical_screen(
3754        &self,
3755        position: LogicalScreenPosition,
3756    ) -> Result<PhysicalScreenPosition, RendererCoordinateError> {
3757        logical_to_physical_screen(position, self.scale_factor as f32)
3758    }
3759
3760    /// Returns physical surface pixels per logical screen pixel.
3761    pub fn scale_factor(&self) -> f64 {
3762        self.scale_factor
3763    }
3764
3765    /// Returns the concrete presentation mode selected for the active surface.
3766    ///
3767    /// `RendererPresentMode::NoVsync` prefers Immediate, then Mailbox, then
3768    /// FIFO. This method reveals which supported fallback was configured. The
3769    /// desktop compositor may still pace host redraw callbacks independently.
3770    pub fn surface_present_mode(&self) -> RendererSurfacePresentMode {
3771        self.surface_present_mode
3772    }
3773
3774    /// Installs a host callback invoked immediately before synchronized
3775    /// surface presentation.
3776    ///
3777    /// A winit host should capture its `Arc<Window>` and call
3778    /// `Window::pre_present_notify` from this callback. The renderer invokes
3779    /// it after command submission and immediately before `Queue::present`,
3780    /// but only when the concrete surface mode is Mailbox, FIFO, or
3781    /// FIFO-relaxed. Immediate presentation deliberately remains uncapped.
3782    pub fn set_pre_present_notify(&mut self, notify: impl Fn() + Send + Sync + 'static) {
3783        self.pre_present_notify = Some(Arc::new(notify));
3784    }
3785
3786    /// Removes the synchronized-presentation callback, if one is installed.
3787    pub fn clear_pre_present_notify(&mut self) {
3788        self.pre_present_notify = None;
3789    }
3790
3791    fn notify_before_present(&self) {
3792        invoke_pre_present_notify(
3793            self.surface_present_mode,
3794            self.pre_present_notify.as_deref(),
3795        );
3796    }
3797
3798    /// Returns the active graphics adapter's human-readable name.
3799    pub fn adapter_name(&self) -> &str {
3800        &self.adapter_info.name
3801    }
3802
3803    /// Returns the active graphics API backend as a stable lowercase name.
3804    pub fn adapter_backend(&self) -> &'static str {
3805        self.adapter_info.backend.to_str()
3806    }
3807
3808    /// Returns the PCI vendor identifier reported for the active adapter.
3809    pub fn adapter_vendor_id(&self) -> u32 {
3810        self.adapter_info.vendor
3811    }
3812
3813    /// Returns the device identifier reported for the active adapter.
3814    pub fn adapter_device_id(&self) -> u32 {
3815        self.adapter_info.device
3816    }
3817
3818    /// Returns the backend-reported PCI bus address for the active adapter.
3819    ///
3820    /// Vulkan adapters expose this as `domain:bus:device.function` when the
3821    /// driver supports `VK_EXT_pci_bus_info`. An empty string means that the
3822    /// backend cannot identify a physical adapter instance; release evidence
3823    /// must not treat model identifiers alone as instance identity.
3824    pub fn adapter_pci_bus_id(&self) -> &str {
3825        &self.adapter_info.device_pci_bus_id
3826    }
3827
3828    /// Returns the texture format selected for the active presentation surface.
3829    pub fn surface_format(&self) -> wgpu::TextureFormat {
3830        self.config.format
3831    }
3832
3833    /// Returns the raster sample count selected for the active surface format.
3834    pub fn surface_sample_count(&self) -> u32 {
3835        self.sample_count
3836    }
3837
3838    /// Returns the driver name reported by the active graphics adapter.
3839    pub fn adapter_driver(&self) -> &str {
3840        &self.adapter_info.driver
3841    }
3842
3843    /// Returns the driver version or implementation detail reported by the adapter.
3844    pub fn adapter_driver_info(&self) -> &str {
3845        &self.adapter_info.driver_info
3846    }
3847
3848    /// Returns previous logical devices retained for safe native-driver teardown.
3849    pub fn quarantined_device_count(&self) -> usize {
3850        self.retired_devices.len()
3851    }
3852
3853    /// Returns the configured maximum previous-device quarantine size.
3854    pub fn max_quarantined_device_count(&self) -> usize {
3855        self.max_quarantined_devices
3856    }
3857
3858    /// Returns successful recoveries available before the bounded quarantine is full.
3859    pub fn remaining_device_recoveries(&self) -> usize {
3860        self.max_quarantined_devices
3861            .saturating_sub(self.retired_devices.len())
3862    }
3863
3864    /// Blocks until all previously submitted GPU work has completed.
3865    ///
3866    /// This is intended for diagnostic throughput measurements, readback, and
3867    /// controlled resource teardown. Calling it in an interactive frame loop
3868    /// defeats normal CPU/GPU pipelining.
3869    pub fn wait_for_gpu_idle(&self) -> Result<(), wgpu::PollError> {
3870        self.device
3871            .poll(wgpu::PollType::wait_indefinitely())
3872            .map(|_| ())
3873    }
3874
3875    /// Replaces display scale without changing physical surface dimensions.
3876    ///
3877    /// Invalid values return an error and leave the current scale unchanged.
3878    pub fn set_scale_factor(
3879        &mut self,
3880        scale_factor: f64,
3881    ) -> Result<(), RendererConfigurationError> {
3882        validate_scale_factor(scale_factor)?;
3883        self.scale_factor = scale_factor;
3884        Ok(())
3885    }
3886
3887    /// Reconfigures the surface after a host window resize.
3888    ///
3889    /// Zero width or height is ignored because minimized windows often report
3890    /// zero size and `wgpu` cannot configure a zero-sized surface.
3891    pub fn resize(&mut self, width: u32, height: u32) -> Result<(), RendererConfigurationError> {
3892        if width == 0 || height == 0 {
3893            return Ok(());
3894        }
3895        validate_surface_dimensions(width, height, self.device.limits().max_texture_dimension_2d)?;
3896
3897        self.config.width = width;
3898        self.config.height = height;
3899        self.surface.configure(&self.device, &self.config);
3900        self.multisample_target =
3901            create_multisample_target(&self.device, &self.config, self.sample_count);
3902        Ok(())
3903    }
3904
3905    /// Reconfigures physical surface size and logical-to-physical display scale.
3906    ///
3907    /// Invalid scale returns an error without changing either value. Zero
3908    /// physical dimensions update the scale but leave the minimized surface
3909    /// configuration unchanged.
3910    pub fn resize_with_scale_factor(
3911        &mut self,
3912        width: u32,
3913        height: u32,
3914        scale_factor: f64,
3915    ) -> Result<(), RendererConfigurationError> {
3916        validate_scale_factor(scale_factor)?;
3917        if width != 0 && height != 0 {
3918            validate_surface_dimensions(
3919                width,
3920                height,
3921                self.device.limits().max_texture_dimension_2d,
3922            )?;
3923        }
3924        self.resize(width, height)?;
3925        self.scale_factor = scale_factor;
3926        Ok(())
3927    }
3928
3929    /// Draws a scene using the supplied camera.
3930    ///
3931    /// Scene positions and sizes are in world units unless a style explicitly
3932    /// says logical screen pixels. The renderer converts world coordinates to
3933    /// logical screen coordinates through [`Camera2d`], then to normalized device
3934    /// coordinates for `wgpu`. Scissor rectangles are converted to physical
3935    /// surface pixels at the final backend boundary.
3936    pub fn render(
3937        &mut self,
3938        scene: &Scene,
3939        camera: &Camera2d,
3940    ) -> Result<RenderStatus, RendererFrameError> {
3941        self.render_with_metrics(scene, camera)
3942            .map(RenderReport::status)
3943    }
3944
3945    /// Draws fixed logical-screen geometry independently of any world camera.
3946    pub fn render_screen_scene(
3947        &mut self,
3948        scene: &ScreenScene,
3949    ) -> Result<RenderStatus, RendererFrameError> {
3950        self.render_screen_scene_with_metrics(scene)
3951            .map(RenderReport::status)
3952    }
3953
3954    /// Draws fixed logical-screen geometry and returns CPU-side stage timings.
3955    pub fn render_screen_scene_with_metrics(
3956        &mut self,
3957        scene: &ScreenScene,
3958    ) -> Result<RenderReport, RendererFrameError> {
3959        let viewport = LogicalViewport::new(self.logical_size().0, self.logical_size().1)
3960            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
3961        let camera =
3962            screen_camera(viewport).map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
3963        self.render_with_metrics(scene.as_scene(), &camera)
3964    }
3965
3966    /// Draws a scene and returns a CPU-side timing breakdown.
3967    ///
3968    /// Metrics separate tessellation, buffer upload, surface acquisition, and
3969    /// encode/submit/present dispatch. They do not measure GPU completion or the
3970    /// monitor scanout timestamp. Use this for diagnostics; [`WgpuRenderer::render`]
3971    /// is the simpler equivalent when stage timings are not needed.
3972    pub fn render_with_metrics(
3973        &mut self,
3974        scene: &Scene,
3975        camera: &Camera2d,
3976    ) -> Result<RenderReport, RendererFrameError> {
3977        self.render_with_metrics_in_region(scene, camera, None)
3978    }
3979
3980    /// Draws a world scene through a camera into one bounded logical viewport.
3981    ///
3982    /// Scene-local clips are interpreted relative to the viewport and are
3983    /// intersected with its physical bounds. The surface outside the viewport
3984    /// is cleared but receives no scene geometry.
3985    pub fn render_scene_in_viewport(
3986        &mut self,
3987        scene: &Scene,
3988        camera: &Camera2d,
3989        viewport: LogicalViewportRegion,
3990    ) -> Result<RenderStatus, RendererFrameError> {
3991        self.render_scene_in_viewport_with_metrics(scene, camera, viewport)
3992            .map(RenderReport::status)
3993    }
3994
3995    /// Draws one bounded scene viewport and returns CPU-side stage timings.
3996    pub fn render_scene_in_viewport_with_metrics(
3997        &mut self,
3998        scene: &Scene,
3999        camera: &Camera2d,
4000        viewport: LogicalViewportRegion,
4001    ) -> Result<RenderReport, RendererFrameError> {
4002        self.render_with_metrics_in_region(scene, camera, Some(viewport))
4003    }
4004
4005    /// Renders an ordinary world scene into an offscreen target.
4006    ///
4007    /// Target dimensions are physical texels. `pixel_scale` defines their
4008    /// logical viewport density independently of window DPI. Scene-local clips
4009    /// are relative to `viewport`, or to the complete logical target when no
4010    /// region is supplied. `load` explicitly controls preservation or clearing.
4011    #[allow(clippy::too_many_arguments)]
4012    pub fn render_scene_to_target(
4013        &mut self,
4014        target: &RenderTarget2d,
4015        scene: &Scene,
4016        camera: &Camera2d,
4017        pixel_scale: PhysicalPerLogical,
4018        viewport: Option<LogicalViewportRegion>,
4019        load: RenderTargetLoad,
4020    ) -> Result<RenderReport, RenderTargetError> {
4021        self.validate_render_target(target)?;
4022        if let RenderTargetLoad::Clear(color) = load
4023            && !color.is_normalized()
4024        {
4025            return Err(RenderTargetError::InvalidBackground);
4026        }
4027
4028        let frame_started_at = Instant::now();
4029        let scale = pixel_scale.get();
4030        let target_viewport = LogicalViewport::new(
4031            target.width() as f32 / scale,
4032            target.height() as f32 / scale,
4033        )
4034        .map_err(|_| RenderTargetError::Frame(RendererFrameError::InvalidViewport))?;
4035        let (local_viewport, origin) = match viewport {
4036            Some(region) => (region.viewport(), region.origin().to_vec2()),
4037            None => (target_viewport, Vec2::ZERO),
4038        };
4039        let max = origin + local_viewport.size();
4040        if !max.is_finite()
4041            || origin.x < 0.0
4042            || origin.y < 0.0
4043            || max.x > target_viewport.width()
4044            || max.y > target_viewport.height()
4045        {
4046            return Err(RenderTargetError::Frame(
4047                RendererFrameError::InvalidViewport,
4048            ));
4049        }
4050        let target_scissor = logical_viewport_scissor(
4051            origin,
4052            local_viewport,
4053            scale,
4054            target.width(),
4055            target.height(),
4056        )
4057        .ok_or(RenderTargetError::Frame(
4058            RendererFrameError::InvalidViewport,
4059        ))?;
4060        let camera_uniform =
4061            CameraUniform::new_in_region(*camera, local_viewport, origin, target_viewport).ok_or(
4062                RenderTargetError::Frame(RendererFrameError::InvalidGeometryTransform),
4063            )?;
4064
4065        let tessellation_started_at = Instant::now();
4066        if !scene_estimate_fits_streaming_device(scene, &self.device, 0, self.vertex_capacity) {
4067            return Err(RenderTargetError::Frame(
4068                RendererFrameError::GeometryCapacityTooLarge,
4069            ));
4070        }
4071        self.vertices.clear();
4072        self.draw_batches.clear();
4073        let tessellation_stats =
4074            tessellate_scene(scene, &mut self.vertices, &mut self.draw_batches)
4075                .map_err(RendererFrameError::from)
4076                .map_err(RenderTargetError::Frame)?;
4077        let tessellation = tessellation_started_at.elapsed();
4078
4079        let extents = GeometryExtents::from_vertices(&self.vertices);
4080        if !geometry_is_safe_for(
4081            extents,
4082            GeometryValidationSource::Tessellated(&self.vertices),
4083            camera_uniform,
4084        ) {
4085            return Err(RenderTargetError::Frame(
4086                RendererFrameError::InvalidGeometryTransform,
4087            ));
4088        }
4089        let upload_started_at = Instant::now();
4090        self.ensure_vertex_capacity(self.vertices.len())
4091            .map_err(RenderTargetError::Frame)?;
4092        if !self.vertices.is_empty() {
4093            self.queue
4094                .write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&self.vertices));
4095        }
4096        let upload = upload_started_at.elapsed();
4097        let uniform_started_at = Instant::now();
4098        self.queue.write_buffer(
4099            &self.camera_uniform_buffer,
4100            0,
4101            bytemuck::bytes_of(&camera_uniform),
4102        );
4103        let camera_uniform_upload = uniform_started_at.elapsed();
4104
4105        let encode_started_at = Instant::now();
4106        let mut encoder = self
4107            .device
4108            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
4109                label: Some("sim-engine scene target encoder"),
4110            });
4111        {
4112            let load = match load {
4113                RenderTargetLoad::Load => wgpu::LoadOp::Load,
4114                RenderTargetLoad::Clear(color) => {
4115                    wgpu::LoadOp::Clear(premultiplied_wgpu_color(color))
4116                }
4117            };
4118            let color_attachment = wgpu::RenderPassColorAttachment {
4119                view: &target.view,
4120                depth_slice: None,
4121                resolve_target: None,
4122                ops: wgpu::Operations {
4123                    load,
4124                    store: wgpu::StoreOp::Store,
4125                },
4126            };
4127            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
4128                label: Some("sim-engine scene target pass"),
4129                color_attachments: &[Some(color_attachment)],
4130                depth_stencil_attachment: None,
4131                timestamp_writes: None,
4132                occlusion_query_set: None,
4133                multiview_mask: None,
4134            });
4135            if !self.vertices.is_empty() {
4136                pass.set_pipeline(&self.target_pipeline);
4137                pass.set_bind_group(0, &self.camera_bind_group, &[]);
4138                pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
4139                for batch in &self.draw_batches {
4140                    let scissor = match batch.screen_clip {
4141                        Some(clip) => {
4142                            let Some(local) = screen_clip_to_scissor(clip, local_viewport, scale)
4143                            else {
4144                                continue;
4145                            };
4146                            let Some(scissor) = offset_scissor(local, target_scissor) else {
4147                                continue;
4148                            };
4149                            scissor
4150                        }
4151                        None => target_scissor,
4152                    };
4153                    pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
4154                    pass.draw(batch.vertex_range.clone(), 0..1);
4155                }
4156            }
4157        }
4158        self.queue.submit([encoder.finish()]);
4159        let encode = encode_started_at.elapsed();
4160
4161        Ok(render_report(
4162            RenderStatus::Drawn,
4163            tessellation,
4164            upload,
4165            camera_uniform_upload,
4166            Duration::ZERO,
4167            encode,
4168            frame_started_at.elapsed(),
4169            false,
4170            true,
4171            tessellation_stats,
4172        ))
4173    }
4174
4175    fn render_with_metrics_in_region(
4176        &mut self,
4177        scene: &Scene,
4178        camera: &Camera2d,
4179        viewport: Option<LogicalViewportRegion>,
4180    ) -> Result<RenderReport, RendererFrameError> {
4181        let frame_started_at = Instant::now();
4182        let (_, _, camera_uniform) = self.surface_geometry_context(*camera, viewport)?;
4183        let tessellation_started_at = Instant::now();
4184        if !scene_estimate_fits_streaming_device(scene, &self.device, 0, self.vertex_capacity) {
4185            return Err(RendererFrameError::GeometryCapacityTooLarge);
4186        }
4187        self.vertices.clear();
4188        self.draw_batches.clear();
4189        let tessellation_stats =
4190            tessellate_scene(scene, &mut self.vertices, &mut self.draw_batches)?;
4191        let tessellation = tessellation_started_at.elapsed();
4192
4193        let geometry_extents = GeometryExtents::from_vertices(&self.vertices);
4194        if !geometry_is_safe_for(
4195            geometry_extents,
4196            GeometryValidationSource::Tessellated(&self.vertices),
4197            camera_uniform,
4198        ) {
4199            return Err(RendererFrameError::InvalidGeometryTransform);
4200        }
4201
4202        let upload_started_at = Instant::now();
4203        self.ensure_vertex_capacity(self.vertices.len())?;
4204        let upload = upload_started_at.elapsed();
4205
4206        let vertex_buffer = Arc::clone(&self.vertex_buffer);
4207        let draw_batches = std::mem::take(&mut self.draw_batches);
4208        let vertices = std::mem::take(&mut self.vertices);
4209        let result = self.draw_geometry(
4210            scene.background(),
4211            &vertex_buffer,
4212            vertices.len(),
4213            geometry_extents,
4214            GeometryValidationSource::Tessellated(&vertices),
4215            None,
4216            &draw_batches,
4217            *camera,
4218            tessellation,
4219            upload,
4220            false,
4221            true,
4222            false,
4223            Some(&vertices),
4224            tessellation_stats,
4225            frame_started_at,
4226            viewport,
4227        );
4228        self.vertices = vertices;
4229        self.draw_batches = draw_batches;
4230        result
4231    }
4232
4233    /// Tessellates a scene once and uploads immutable geometry to a dedicated GPU buffer.
4234    ///
4235    /// Preparing is appropriate for geometry that will be drawn repeatedly while
4236    /// only the camera or target dimensions change. Any shape, style, gradient,
4237    /// ordering, or clipping change requires preparing a replacement scene.
4238    pub fn prepare_scene(&self, scene: &Scene) -> Result<PreparedScene, PreparedSceneError> {
4239        prepare_scene_resources(
4240            &self.device,
4241            &self.queue,
4242            Arc::clone(&self.renderer_identity),
4243            scene,
4244        )
4245    }
4246
4247    /// Tessellates fixed logical-screen geometry once for repeated composition.
4248    pub fn prepare_screen_scene(
4249        &self,
4250        scene: &ScreenScene,
4251    ) -> Result<PreparedScreenScene, PreparedSceneError> {
4252        self.prepare_scene(scene.as_scene())
4253            .map(|scene| PreparedScreenScene { scene })
4254    }
4255
4256    /// Restores prepared logical-screen geometry on a recreated renderer.
4257    pub fn restore_prepared_screen_scene(
4258        &self,
4259        source: &PreparedScreenScene,
4260    ) -> Result<PreparedScreenScene, PreparedSceneError> {
4261        self.restore_prepared_scene(&source.scene)
4262            .map(|scene| PreparedScreenScene { scene })
4263    }
4264
4265    /// Recreates prepared GPU resources on this renderer from a retained CPU snapshot.
4266    ///
4267    /// This supports renderer recreation after device loss without requiring the
4268    /// original high-level [`Scene`]. The returned snapshot belongs to this renderer.
4269    pub fn restore_prepared_scene(
4270        &self,
4271        source: &PreparedScene,
4272    ) -> Result<PreparedScene, PreparedSceneError> {
4273        restore_prepared_scene_resources(
4274            &self.device,
4275            &self.queue,
4276            Arc::clone(&self.renderer_identity),
4277            source,
4278        )
4279    }
4280
4281    /// Recreates a dynamic mesh on this renderer from its retained CPU vertices.
4282    ///
4283    /// Use this after recreating a renderer following device loss. The returned
4284    /// mesh belongs to this renderer and preserves the source mesh's capacity so
4285    /// subsequent updates retain the same allocation behavior.
4286    pub fn restore_dynamic_mesh(
4287        &self,
4288        source: &DynamicMesh2d,
4289    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4290        restore_dynamic_mesh_resources(
4291            &self.device,
4292            &self.queue,
4293            Arc::clone(&self.renderer_identity),
4294            source,
4295        )
4296    }
4297
4298    /// Creates mutable triangle-list geometry for a frequently changing visual.
4299    ///
4300    /// The vertex count must be divisible by three. The mesh is owned by this
4301    /// renderer and may only be updated or drawn through it.
4302    pub fn create_dynamic_mesh(
4303        &self,
4304        vertices: &[DynamicVertex2d],
4305    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4306        self.create_dynamic_mesh_inner(vertices, None)
4307    }
4308
4309    /// Creates bounded mutable colored triangles for composition in a frame.
4310    ///
4311    /// Validation and CPU reservation complete before any GPU allocation. The
4312    /// retained budget is also enforced by every later full or partial update.
4313    pub fn create_dynamic_mesh_with_budget(
4314        &self,
4315        vertices: &[DynamicVertex2d],
4316        budget: DynamicMeshBudget,
4317    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4318        self.create_dynamic_mesh_inner(vertices, Some(budget))
4319    }
4320
4321    fn create_dynamic_mesh_inner(
4322        &self,
4323        vertices: &[DynamicVertex2d],
4324        budget: Option<DynamicMeshBudget>,
4325    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4326        if let Some(budget) = budget {
4327            validate_dynamic_mesh_budget(budget, vertices.len())?;
4328        }
4329        let vertex_capacity = dynamic_vertex_capacity(vertices.len())
4330            .filter(|capacity| buffer_capacity_fits::<DynamicGpu>(&self.device, *capacity))
4331            .ok_or(DynamicMeshError::CapacityTooLarge)?;
4332        let vertices = dynamic_vertices_to_gpu(vertices)?;
4333        if let Some(budget) = budget {
4334            validate_dynamic_retained_capacity(budget, &vertices)?;
4335        }
4336        let vertex_buffer = Arc::new(create_dynamic_vertex_buffer(&self.device, vertex_capacity));
4337        if !vertices.is_empty() {
4338            self.queue
4339                .write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
4340            submit_pending_uploads(&self.queue);
4341        }
4342        Ok(DynamicMesh2d {
4343            renderer_identity: Arc::clone(&self.renderer_identity),
4344            geometry_extents: GeometryExtents::from_dynamic_vertices(&vertices),
4345            geometry_validation_cache: GeometryValidationCache::default(),
4346            vertex_buffer,
4347            vertices,
4348            vertex_capacity,
4349            budget,
4350        })
4351    }
4352
4353    /// Replaces all dynamic mesh vertices, growing GPU capacity only when needed.
4354    pub fn update_dynamic_mesh(
4355        &self,
4356        mesh: &mut DynamicMesh2d,
4357        vertices: &[DynamicVertex2d],
4358    ) -> Result<(), DynamicMeshError> {
4359        self.update_dynamic_mesh_with_metrics(mesh, vertices)
4360            .map(|_| ())
4361    }
4362
4363    /// Replaces all dynamic mesh vertices and returns CPU-side update metrics.
4364    pub fn update_dynamic_mesh_with_metrics(
4365        &self,
4366        mesh: &mut DynamicMesh2d,
4367        vertices: &[DynamicVertex2d],
4368    ) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
4369        self.validate_dynamic_mesh(mesh)?;
4370        replace_dynamic_mesh_resources(&self.device, &self.queue, mesh, vertices)
4371    }
4372
4373    /// Replaces a contiguous vertex range without reallocating the mesh buffer.
4374    ///
4375    /// The range must stay inside the current triangle list and its length must
4376    /// preserve triangle alignment, so callers cannot create partial triangles.
4377    pub fn update_dynamic_mesh_range(
4378        &self,
4379        mesh: &mut DynamicMesh2d,
4380        first_vertex: usize,
4381        vertices: &[DynamicVertex2d],
4382    ) -> Result<(), DynamicMeshError> {
4383        self.update_dynamic_mesh_range_with_metrics(mesh, first_vertex, vertices)
4384            .map(|_| ())
4385    }
4386
4387    /// Replaces a triangle-aligned range and returns CPU-side update metrics.
4388    pub fn update_dynamic_mesh_range_with_metrics(
4389        &self,
4390        mesh: &mut DynamicMesh2d,
4391        first_vertex: usize,
4392        vertices: &[DynamicVertex2d],
4393    ) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
4394        let update_started_at = Instant::now();
4395        self.validate_dynamic_mesh(mesh)?;
4396        let end = first_vertex
4397            .checked_add(vertices.len())
4398            .ok_or(DynamicMeshError::UpdateRangeOutOfBounds)?;
4399        if !first_vertex.is_multiple_of(3)
4400            || !vertices.len().is_multiple_of(3)
4401            || end > mesh.vertices.len()
4402        {
4403            return Err(DynamicMeshError::UpdateRangeOutOfBounds);
4404        }
4405        if let Some(budget) = mesh.budget {
4406            validate_dynamic_mesh_budget(budget, mesh.vertices.len())?;
4407            let upload_bytes = dynamic_mesh_bytes(vertices.len())?;
4408            if upload_bytes > budget.max_upload_bytes {
4409                return Err(DynamicMeshError::BudgetExceeded {
4410                    resource: DynamicMeshBudgetResource::UploadBytes,
4411                    limit: budget.max_upload_bytes,
4412                    actual: upload_bytes,
4413                });
4414            }
4415        }
4416        let vertices = dynamic_vertices_to_gpu(vertices)?;
4417        if !vertices.is_empty() {
4418            let offset = (first_vertex * std::mem::size_of::<DynamicGpu>()) as wgpu::BufferAddress;
4419            self.queue
4420                .write_buffer(&mesh.vertex_buffer, offset, bytemuck::cast_slice(&vertices));
4421            submit_pending_uploads(&self.queue);
4422            mesh.vertices[first_vertex..end].copy_from_slice(&vertices);
4423            mesh.geometry_extents = GeometryExtents::from_dynamic_vertices(&mesh.vertices);
4424            mesh.geometry_validation_cache.clear();
4425        }
4426        Ok(DynamicMeshUpdateReport {
4427            vertex_count: mesh.vertices.len(),
4428            upload: update_started_at.elapsed(),
4429            reallocated: false,
4430        })
4431    }
4432
4433    /// Draws dynamic triangle-list geometry with a normalized clear color.
4434    ///
4435    /// Every potentially visible triangle must remain fully inside the full
4436    /// surface clip volume and have a portable projected orientation. A
4437    /// hardware-clipped or ambiguous triangle returns
4438    /// `DynamicMeshRenderError::Frame(RendererFrameError::InvalidGeometryTransform)`.
4439    pub fn render_dynamic_mesh(
4440        &mut self,
4441        mesh: &DynamicMesh2d,
4442        background: Color,
4443        camera: &Camera2d,
4444    ) -> Result<RenderStatus, DynamicMeshRenderError> {
4445        self.render_dynamic_mesh_with_metrics(mesh, background, camera)
4446            .map(RenderReport::status)
4447    }
4448
4449    /// Draws dynamic triangle-list geometry and returns per-frame CPU metrics.
4450    ///
4451    /// Full-surface clip-volume crossing and association-dependent projected
4452    /// topology are rejected as
4453    /// `DynamicMeshRenderError::Frame(RendererFrameError::InvalidGeometryTransform)`.
4454    pub fn render_dynamic_mesh_with_metrics(
4455        &mut self,
4456        mesh: &DynamicMesh2d,
4457        background: Color,
4458        camera: &Camera2d,
4459    ) -> Result<RenderReport, DynamicMeshRenderError> {
4460        self.validate_dynamic_mesh(mesh)
4461            .map_err(|_| DynamicMeshRenderError::RendererMismatch)?;
4462        if !background.is_normalized() {
4463            return Err(DynamicMeshRenderError::InvalidBackground);
4464        }
4465        let draw_batches = (!mesh.vertices.is_empty()).then_some(PreparedDrawBatch {
4466            vertex_range: 0..mesh.vertices.len() as u32,
4467            screen_clip: None,
4468        });
4469        self.draw_geometry(
4470            background,
4471            &mesh.vertex_buffer,
4472            mesh.vertices.len(),
4473            mesh.geometry_extents,
4474            GeometryValidationSource::Dynamic(&mesh.vertices),
4475            Some(&mesh.geometry_validation_cache),
4476            draw_batches.as_slice(),
4477            *camera,
4478            Duration::ZERO,
4479            Duration::ZERO,
4480            false,
4481            true,
4482            true,
4483            None,
4484            TessellationStats::default(),
4485            Instant::now(),
4486            None,
4487        )
4488        .map_err(DynamicMeshRenderError::Frame)
4489    }
4490
4491    /// Creates an instanced particle field owned by this renderer.
4492    ///
4493    /// Each instance draws as one screen-space circle quad through a single GPU
4494    /// draw call. The retained CPU snapshot enables later restoration on a
4495    /// recreated renderer.
4496    pub fn create_particle_field(
4497        &self,
4498        instances: &[ParticleInstance2d],
4499    ) -> Result<ParticleField2d, ParticleFieldError> {
4500        self.create_particle_field_with_budget(instances, ParticleRenderBudget::UNBOUNDED)
4501    }
4502
4503    /// Creates an instanced particle field with hard retained-CPU, GPU-memory,
4504    /// upload, visible-instance, and visibility-work limits.
4505    pub fn create_particle_field_with_budget(
4506        &self,
4507        instances: &[ParticleInstance2d],
4508        budget: ParticleRenderBudget,
4509    ) -> Result<ParticleField2d, ParticleFieldError> {
4510        validate_particle_retained_count(instances.len(), budget)?;
4511        let instance_capacity = particle_budgeted_capacity(instances.len(), budget)
4512            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
4513            .ok_or(ParticleFieldError::CapacityTooLarge)?;
4514        let instances = particle_instances_to_gpu(instances)?;
4515        let visible_instances = allocate_particle_staging(instances.len(), budget)?;
4516        validate_particle_retained_capacities(
4517            instances.capacity(),
4518            visible_instances.capacity(),
4519            budget,
4520        )?;
4521        let instance_buffer = Arc::new(create_particle_instance_buffer(
4522            &self.device,
4523            instance_capacity,
4524        ));
4525        Ok(ParticleField2d {
4526            renderer_identity: Arc::clone(&self.renderer_identity),
4527            instance_buffer,
4528            statistics: particle_idle_statistics(instances.len()),
4529            instances,
4530            visible_instances,
4531            instance_capacity,
4532            budget,
4533        })
4534    }
4535
4536    /// Replaces a particle field's hard resource budget, shrinking memory when required.
4537    pub fn set_particle_field_budget(
4538        &self,
4539        field: &mut ParticleField2d,
4540        budget: ParticleRenderBudget,
4541    ) -> Result<(), ParticleFieldError> {
4542        self.validate_particle_field(field)?;
4543        validate_particle_retained_count(field.instances.len(), budget)?;
4544        let desired_capacity = particle_budgeted_capacity(field.instances.len(), budget)
4545            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
4546            .ok_or(ParticleFieldError::CapacityTooLarge)?;
4547        let visible_instances = allocate_particle_staging(field.instances.len(), budget)?;
4548        let replacement_instances = compact_particle_instances(
4549            &field.instances,
4550            field.instances.capacity(),
4551            visible_instances.capacity(),
4552            budget,
4553        )?;
4554        let replacement_buffer = (desired_capacity != field.instance_capacity).then(|| {
4555            Arc::new(create_particle_instance_buffer(
4556                &self.device,
4557                desired_capacity,
4558            ))
4559        });
4560        if let Some(instance_buffer) = replacement_buffer {
4561            field.instance_buffer = instance_buffer;
4562            field.instance_capacity = desired_capacity;
4563        }
4564        if let Some(instances) = replacement_instances {
4565            field.instances = instances;
4566        }
4567        field.budget = budget;
4568        field.visible_instances = visible_instances;
4569        field.statistics = particle_idle_statistics(field.instances.len());
4570        Ok(())
4571    }
4572
4573    /// Replaces all particle instances, reusing GPU capacity whenever possible.
4574    pub fn update_particle_field(
4575        &self,
4576        field: &mut ParticleField2d,
4577        instances: &[ParticleInstance2d],
4578    ) -> Result<ParticleStatistics, ParticleFieldError> {
4579        self.update_particle_field_with_metrics(field, instances)
4580            .map(|report| report.statistics())
4581    }
4582
4583    /// Replaces all particle instances and returns CPU-side preparation metrics.
4584    pub fn update_particle_field_with_metrics(
4585        &self,
4586        field: &mut ParticleField2d,
4587        instances: &[ParticleInstance2d],
4588    ) -> Result<ParticleFieldUpdateReport, ParticleFieldError> {
4589        let update_started_at = Instant::now();
4590        self.validate_particle_field(field)?;
4591        validate_particle_retained_count(instances.len(), field.budget)?;
4592        let desired_capacity = particle_budgeted_capacity(instances.len(), field.budget)
4593            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
4594            .ok_or(ParticleFieldError::CapacityTooLarge)?;
4595        let instances = particle_instances_to_gpu(instances)?;
4596        let visible_instances = allocate_particle_staging(instances.len(), field.budget)?;
4597        validate_particle_retained_capacities(
4598            instances.capacity(),
4599            visible_instances.capacity(),
4600            field.budget,
4601        )?;
4602        let reallocated = desired_capacity > field.instance_capacity;
4603        let replacement_buffer = reallocated.then(|| {
4604            Arc::new(create_particle_instance_buffer(
4605                &self.device,
4606                desired_capacity,
4607            ))
4608        });
4609        if let Some(instance_buffer) = replacement_buffer {
4610            field.instance_buffer = instance_buffer;
4611            field.instance_capacity = desired_capacity;
4612        }
4613        field.statistics = particle_idle_statistics(instances.len());
4614        field.instances = instances;
4615        field.visible_instances = visible_instances;
4616        Ok(ParticleFieldUpdateReport {
4617            statistics: field.statistics,
4618            preparation: update_started_at.elapsed(),
4619            reallocated,
4620        })
4621    }
4622
4623    /// Replaces a contiguous particle range without reallocating its GPU buffer.
4624    pub fn update_particle_field_range(
4625        &self,
4626        field: &mut ParticleField2d,
4627        first_instance: usize,
4628        instances: &[ParticleInstance2d],
4629    ) -> Result<ParticleStatistics, ParticleFieldError> {
4630        self.update_particle_field_range_with_metrics(field, first_instance, instances)
4631            .map(|report| report.statistics())
4632    }
4633
4634    /// Replaces a particle range and returns CPU-side preparation metrics.
4635    pub fn update_particle_field_range_with_metrics(
4636        &self,
4637        field: &mut ParticleField2d,
4638        first_instance: usize,
4639        instances: &[ParticleInstance2d],
4640    ) -> Result<ParticleFieldUpdateReport, ParticleFieldError> {
4641        let update_started_at = Instant::now();
4642        self.validate_particle_field(field)?;
4643        let range = particle_update_range(first_instance, instances.len(), field.instances.len())?;
4644        let instances = particle_instances_to_gpu(instances)?;
4645        if !instances.is_empty() {
4646            field.instances[range].copy_from_slice(&instances);
4647        }
4648        field.statistics = particle_idle_statistics(field.instances.len());
4649        Ok(ParticleFieldUpdateReport {
4650            statistics: field.statistics,
4651            preparation: update_started_at.elapsed(),
4652            reallocated: false,
4653        })
4654    }
4655
4656    /// Recreates a particle field on this renderer from retained CPU instances.
4657    pub fn restore_particle_field(
4658        &self,
4659        source: &ParticleField2d,
4660    ) -> Result<ParticleField2d, ParticleFieldError> {
4661        restore_particle_field_resources(
4662            &self.device,
4663            &self.queue,
4664            Arc::clone(&self.renderer_identity),
4665            source,
4666        )
4667    }
4668
4669    /// Creates a single-channel floating-point texture from a validated scalar grid.
4670    pub fn create_scalar_field_texture(
4671        &self,
4672        field: ScalarField,
4673    ) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
4674        create_scalar_field_texture_resources(
4675            &self.device,
4676            &self.queue,
4677            Arc::clone(&self.renderer_identity),
4678            field,
4679        )
4680    }
4681
4682    /// Creates an offscreen target with physical texture dimensions.
4683    pub fn create_render_target(
4684        &self,
4685        width: u32,
4686        height: u32,
4687    ) -> Result<RenderTarget2d, RenderTargetError> {
4688        if width == 0 || height == 0 {
4689            return Err(RenderTargetError::ZeroDimension);
4690        }
4691        if width > self.device.limits().max_texture_dimension_2d
4692            || height > self.device.limits().max_texture_dimension_2d
4693        {
4694            return Err(RenderTargetError::DimensionsTooLarge);
4695        }
4696        let allocation_bytes = render_target_allocation_bytes(self.config.format, width, height)
4697            .ok_or(RenderTargetError::DimensionsTooLarge)?;
4698        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
4699            label: Some("sim-engine render target"),
4700            size: wgpu::Extent3d {
4701                width,
4702                height,
4703                depth_or_array_layers: 1,
4704            },
4705            mip_level_count: 1,
4706            sample_count: 1,
4707            dimension: wgpu::TextureDimension::D2,
4708            format: self.config.format,
4709            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
4710                | wgpu::TextureUsages::TEXTURE_BINDING
4711                | wgpu::TextureUsages::COPY_SRC,
4712            view_formats: &[],
4713        });
4714        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4715        Ok(RenderTarget2d {
4716            renderer_identity: Arc::clone(&self.renderer_identity),
4717            resource_identity: Arc::new(()),
4718            _texture: texture,
4719            view,
4720            width,
4721            height,
4722            allocation_bytes,
4723        })
4724    }
4725
4726    /// Creates an empty ping-pong target pair for temporal accumulation.
4727    pub fn create_trail_buffer(
4728        &mut self,
4729        width: u32,
4730        height: u32,
4731    ) -> Result<TrailBuffer2d, RenderTargetError> {
4732        let front = self.create_render_target(width, height)?;
4733        let back = self.create_render_target(width, height)?;
4734        let trails = TrailBuffer2d {
4735            renderer_identity: Arc::clone(&self.renderer_identity),
4736            front,
4737            back,
4738        };
4739        self.draw_clear_trail_buffer(&trails, Color::rgba(0.0, 0.0, 0.0, 0.0), Instant::now());
4740        Ok(trails)
4741    }
4742
4743    /// Recreates an empty target with the source dimensions after device recovery.
4744    ///
4745    /// GPU pixels are deliberately not retained; callers redraw their source
4746    /// state into the restored target.
4747    pub fn restore_render_target(
4748        &self,
4749        source: &RenderTarget2d,
4750    ) -> Result<RenderTarget2d, RenderTargetError> {
4751        self.create_render_target(source.width(), source.height())
4752    }
4753
4754    /// Recreates an empty, deterministically cleared trail buffer after recovery.
4755    pub fn restore_trail_buffer(
4756        &mut self,
4757        source: &TrailBuffer2d,
4758    ) -> Result<TrailBuffer2d, RenderTargetError> {
4759        self.create_trail_buffer(source.width(), source.height())
4760    }
4761
4762    /// Retains one bounded frame of history and composites a fresh source target.
4763    ///
4764    /// `retention` and `source_opacity` must be finite values in `0.0..=1.0`.
4765    /// The source must be a distinct target; use [`WgpuRenderer::clear_trail_buffer`]
4766    /// to discard accumulated history deterministically.
4767    pub fn accumulate_trail_buffer(
4768        &mut self,
4769        trails: &mut TrailBuffer2d,
4770        source: &RenderTarget2d,
4771        retention: f32,
4772        source_opacity: f32,
4773        source_blend: BlendMode,
4774    ) -> Result<RenderReport, RenderTargetError> {
4775        self.validate_trail_buffer(trails)?;
4776        self.validate_render_target(source)?;
4777        if Arc::ptr_eq(&source.resource_identity, &trails.front.resource_identity)
4778            || Arc::ptr_eq(&source.resource_identity, &trails.back.resource_identity)
4779        {
4780            return Err(RenderTargetError::SourceAliasesDestination);
4781        }
4782        if !retention.is_finite()
4783            || !(0.0..=1.0).contains(&retention)
4784            || !source_opacity.is_finite()
4785            || !(0.0..=1.0).contains(&source_opacity)
4786        {
4787            return Err(RenderTargetError::InvalidOpacity);
4788        }
4789        Ok(self.draw_trail_accumulation(
4790            trails,
4791            source,
4792            retention,
4793            source_opacity,
4794            source_blend,
4795            Instant::now(),
4796        ))
4797    }
4798
4799    /// Clears both ping-pong targets, resetting all retained temporal history.
4800    pub fn clear_trail_buffer(
4801        &mut self,
4802        trails: &mut TrailBuffer2d,
4803        color: Color,
4804    ) -> Result<RenderReport, RenderTargetError> {
4805        self.validate_trail_buffer(trails)?;
4806        if !color.is_normalized() {
4807            return Err(RenderTargetError::InvalidBackground);
4808        }
4809        Ok(self.draw_clear_trail_buffer(trails, color, Instant::now()))
4810    }
4811
4812    /// Presents the most recently accumulated temporal target.
4813    pub fn compose_trail_buffer(
4814        &mut self,
4815        trails: &TrailBuffer2d,
4816        blend_mode: BlendMode,
4817        opacity: f32,
4818        background: Color,
4819    ) -> Result<RenderReport, RenderTargetError> {
4820        self.validate_trail_buffer(trails)?;
4821        self.compose_render_target(&trails.front, blend_mode, opacity, background)
4822    }
4823
4824    /// Replaces scalar data, recreating the texture only when dimensions change.
4825    pub fn update_scalar_field_texture(
4826        &self,
4827        texture: &mut ScalarFieldTexture,
4828        field: ScalarField,
4829    ) -> Result<ScalarFieldUploadReport, ScalarFieldTextureError> {
4830        let upload_started_at = Instant::now();
4831        self.validate_scalar_field_texture(texture)?;
4832        validate_scalar_field_device_extent(&self.device, &field)?;
4833        if !scalar_field_sources_are_portable(&field) {
4834            return Err(ScalarFieldTextureError::NonPortableValue);
4835        }
4836        let field = compact_scalar_field_for_retention(field)?;
4837        let (source_minimum, source_maximum) = field.value_range();
4838        let reallocated = texture.width() != field.width() || texture.height() != field.height();
4839        if reallocated {
4840            texture.texture = create_scalar_field_texture(&self.device, &field)?;
4841        }
4842        upload_scalar_field_texture(&self.queue, &texture.texture, &field)?;
4843        texture.field = field;
4844        texture.source_minimum = source_minimum;
4845        texture.source_maximum = source_maximum;
4846        Ok(ScalarFieldUploadReport {
4847            upload: upload_started_at.elapsed(),
4848            reallocated,
4849        })
4850    }
4851
4852    /// Updates a rectangular scalar texture region without recreating it.
4853    pub fn update_scalar_field_texture_region(
4854        &self,
4855        texture: &mut ScalarFieldTexture,
4856        x: usize,
4857        y: usize,
4858        width: usize,
4859        height: usize,
4860        values: &[f32],
4861    ) -> Result<ScalarFieldUploadReport, ScalarFieldTextureError> {
4862        let upload_started_at = Instant::now();
4863        self.validate_scalar_field_texture(texture)?;
4864        if values.iter().any(|value| !value.is_finite()) {
4865            return Err(ScalarFieldTextureError::NonFiniteUpdateValue);
4866        }
4867        if values
4868            .iter()
4869            .copied()
4870            .any(|value| !is_portable_shader_source(value))
4871        {
4872            return Err(ScalarFieldTextureError::NonPortableValue);
4873        }
4874        validate_scalar_field_texture_region(
4875            texture.width(),
4876            texture.height(),
4877            x,
4878            y,
4879            width,
4880            height,
4881            values.len(),
4882        )?;
4883        let update_minimum = values.iter().copied().fold(f32::INFINITY, f32::min);
4884        let update_maximum = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
4885        let overwrites_extremum = (y..y + height).any(|row| {
4886            let start = row * texture.width() + x;
4887            texture.field.values()[start..start + width]
4888                .iter()
4889                .any(|value| *value == texture.source_minimum || *value == texture.source_maximum)
4890        });
4891        let (source_minimum, source_maximum) = if overwrites_extremum {
4892            scalar_region_result_range(&texture.field, x, y, width, height, values)
4893        } else {
4894            (
4895                texture.source_minimum.min(update_minimum),
4896                texture.source_maximum.max(update_maximum),
4897            )
4898        };
4899        let source_extent = f64::from(source_maximum) - f64::from(source_minimum);
4900        if !source_extent.is_finite() || source_extent > f64::from(MAX_PORTABLE_SHADER_VALUE) {
4901            return Err(ScalarFieldTextureError::NonPortableValue);
4902        }
4903        texture
4904            .field
4905            .replace_region(x, y, width, height, values)
4906            .map_err(|error| match error {
4907                crate::ScalarFieldError::InvalidValueCount { .. } => {
4908                    ScalarFieldTextureError::InvalidUpdateValueCount
4909                }
4910                crate::ScalarFieldError::NonFiniteValue => {
4911                    ScalarFieldTextureError::NonFiniteUpdateValue
4912                }
4913                _ => ScalarFieldTextureError::UpdateRegionOutOfBounds,
4914            })?;
4915        upload_scalar_field_texture_region(
4916            &self.queue,
4917            &texture.texture,
4918            x,
4919            y,
4920            width,
4921            height,
4922            values,
4923        )?;
4924        texture.source_minimum = source_minimum;
4925        texture.source_maximum = source_maximum;
4926        Ok(ScalarFieldUploadReport {
4927            upload: upload_started_at.elapsed(),
4928            reallocated: false,
4929        })
4930    }
4931
4932    /// Recreates a scalar texture on this renderer from its retained CPU grid.
4933    pub fn restore_scalar_field_texture(
4934        &self,
4935        source: &ScalarFieldTexture,
4936    ) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
4937        validate_scalar_field_device_extent(&self.device, &source.field)?;
4938        let field = clone_scalar_field_for_restore(&source.field)?;
4939        self.create_scalar_field_texture(field)
4940    }
4941
4942    /// Draws a scalar texture across the logical viewport through a color map.
4943    ///
4944    /// `value_range` maps `minimum` to the first color-map entry and `maximum`
4945    /// to the last. Values outside the range clamp to those endpoints.
4946    pub fn render_scalar_field_texture(
4947        &mut self,
4948        texture: &ScalarFieldTexture,
4949        color_map: &ColorMap,
4950        value_range: (f32, f32),
4951        background: Color,
4952    ) -> Result<RenderStatus, ScalarFieldRenderError> {
4953        self.render_scalar_field_texture_with_metrics(texture, color_map, value_range, background)
4954            .map(RenderReport::status)
4955    }
4956
4957    /// Draws a scalar texture and returns normal CPU-side renderer metrics.
4958    pub fn render_scalar_field_texture_with_metrics(
4959        &mut self,
4960        texture: &ScalarFieldTexture,
4961        color_map: &ColorMap,
4962        (minimum, maximum): (f32, f32),
4963        background: Color,
4964    ) -> Result<RenderReport, ScalarFieldRenderError> {
4965        self.validate_scalar_field_texture(texture)
4966            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
4967        let value_extent = scalar_value_range_extent(minimum, maximum)
4968            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
4969        if !scalar_normalization_is_portable(texture, minimum, value_extent) {
4970            return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
4971        }
4972        if !background.is_normalized() {
4973            return Err(ScalarFieldRenderError::InvalidBackground);
4974        }
4975        self.draw_scalar_field_texture(
4976            texture,
4977            color_map,
4978            minimum,
4979            value_extent,
4980            ScalarFieldSampling::Nearest,
4981            background,
4982            Instant::now(),
4983        )
4984        .map_err(ScalarFieldRenderError::Frame)
4985    }
4986
4987    /// Draws a scalar texture with an explicit texel sampling mode.
4988    pub fn render_scalar_field_texture_with_sampling(
4989        &mut self,
4990        texture: &ScalarFieldTexture,
4991        color_map: &ColorMap,
4992        (minimum, maximum): (f32, f32),
4993        sampling: ScalarFieldSampling,
4994        background: Color,
4995    ) -> Result<RenderStatus, ScalarFieldRenderError> {
4996        self.validate_scalar_field_texture(texture)
4997            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
4998        let value_extent = scalar_value_range_extent(minimum, maximum)
4999            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
5000        if !scalar_normalization_is_portable(texture, minimum, value_extent) {
5001            return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
5002        }
5003        if !background.is_normalized() {
5004            return Err(ScalarFieldRenderError::InvalidBackground);
5005        }
5006        self.draw_scalar_field_texture(
5007            texture,
5008            color_map,
5009            minimum,
5010            value_extent,
5011            sampling,
5012            background,
5013            Instant::now(),
5014        )
5015        .map(RenderReport::status)
5016        .map_err(ScalarFieldRenderError::Frame)
5017    }
5018
5019    /// Renders a scalar heatmap into an offscreen target instead of presenting it.
5020    pub fn render_scalar_field_texture_to_target(
5021        &mut self,
5022        target: &RenderTarget2d,
5023        texture: &ScalarFieldTexture,
5024        color_map: &ColorMap,
5025        value_range: (f32, f32),
5026        background: Color,
5027    ) -> Result<RenderReport, ScalarFieldRenderError> {
5028        self.render_scalar_field_texture_to_target_with_sampling(
5029            target,
5030            texture,
5031            color_map,
5032            value_range,
5033            ScalarFieldSampling::Nearest,
5034            background,
5035        )
5036    }
5037
5038    /// Renders a scalar heatmap into a target with explicit source sampling.
5039    pub fn render_scalar_field_texture_to_target_with_sampling(
5040        &mut self,
5041        target: &RenderTarget2d,
5042        texture: &ScalarFieldTexture,
5043        color_map: &ColorMap,
5044        (minimum, maximum): (f32, f32),
5045        sampling: ScalarFieldSampling,
5046        background: Color,
5047    ) -> Result<RenderReport, ScalarFieldRenderError> {
5048        self.validate_render_target(target)
5049            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
5050        self.validate_scalar_field_texture(texture)
5051            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
5052        let value_extent = scalar_value_range_extent(minimum, maximum)
5053            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
5054        if !scalar_normalization_is_portable(texture, minimum, value_extent) {
5055            return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
5056        }
5057        if !background.is_normalized() {
5058            return Err(ScalarFieldRenderError::InvalidBackground);
5059        }
5060        Ok(self.draw_scalar_field_texture_to_target(
5061            target,
5062            texture,
5063            color_map,
5064            minimum,
5065            value_extent,
5066            sampling,
5067            background,
5068            Instant::now(),
5069        ))
5070    }
5071
5072    /// Composes a previously rendered target over the presentation surface.
5073    pub fn compose_render_target(
5074        &mut self,
5075        target: &RenderTarget2d,
5076        blend_mode: BlendMode,
5077        opacity: f32,
5078        background: Color,
5079    ) -> Result<RenderReport, RenderTargetError> {
5080        self.validate_render_target(target)?;
5081        if !opacity.is_finite() || !(0.0..=1.0).contains(&opacity) {
5082            return Err(RenderTargetError::InvalidOpacity);
5083        }
5084        if !background.is_normalized() {
5085            return Err(RenderTargetError::InvalidBackground);
5086        }
5087        self.draw_composed_render_target(target, blend_mode, opacity, background, Instant::now())
5088            .map_err(RenderTargetError::Frame)
5089    }
5090
5091    /// Draws a particle field with a normalized clear color.
5092    pub fn render_particle_field(
5093        &mut self,
5094        field: &mut ParticleField2d,
5095        background: Color,
5096        camera: &Camera2d,
5097    ) -> Result<RenderStatus, ParticleFieldRenderError> {
5098        self.render_particle_field_with_metrics(field, background, camera)
5099            .map(RenderReport::status)
5100    }
5101
5102    /// Draws a particle field and returns regular per-frame renderer metrics.
5103    pub fn render_particle_field_with_metrics(
5104        &mut self,
5105        field: &mut ParticleField2d,
5106        background: Color,
5107        camera: &Camera2d,
5108    ) -> Result<RenderReport, ParticleFieldRenderError> {
5109        self.validate_particle_field(field)
5110            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
5111        if !background.is_normalized() {
5112            return Err(ParticleFieldRenderError::InvalidBackground);
5113        }
5114        self.draw_particle_field(background, field, *camera, Instant::now())
5115            .map_err(|error| match error {
5116                RendererFrameError::InvalidGeometryTransform => {
5117                    ParticleFieldRenderError::InvalidGeometryTransform
5118                }
5119                other => ParticleFieldRenderError::Frame(other),
5120            })
5121    }
5122
5123    /// Draws a particle field into an offscreen target.
5124    ///
5125    /// Target dimensions may be lower than the presentation surface to bound
5126    /// raster cost. Camera coordinates and particle radii remain expressed in
5127    /// logical presentation pixels, so composing the target back to the surface
5128    /// preserves layout while trading only raster resolution.
5129    pub fn render_particle_field_to_target(
5130        &mut self,
5131        target: &RenderTarget2d,
5132        field: &mut ParticleField2d,
5133        camera: &Camera2d,
5134        load: RenderTargetLoad,
5135    ) -> Result<RenderReport, ParticleFieldRenderError> {
5136        self.validate_render_target(target)
5137            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
5138        self.validate_particle_field(field)
5139            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
5140        if matches!(load, RenderTargetLoad::Clear(color) if !color.is_normalized()) {
5141            return Err(ParticleFieldRenderError::InvalidBackground);
5142        }
5143        self.draw_particle_field_to_target(target, field, *camera, load, Instant::now())
5144            .map_err(|error| match error {
5145                RendererFrameError::InvalidGeometryTransform => {
5146                    ParticleFieldRenderError::InvalidGeometryTransform
5147                }
5148                other => ParticleFieldRenderError::Frame(other),
5149            })
5150    }
5151
5152    /// Draws geometry previously uploaded by [`WgpuRenderer::prepare_scene`].
5153    ///
5154    /// Camera and viewport changes are applied by the vertex shader and do not
5155    /// rebuild or re-upload the prepared geometry.
5156    pub fn render_prepared(
5157        &mut self,
5158        scene: &PreparedScene,
5159        camera: &Camera2d,
5160    ) -> Result<RenderStatus, PreparedSceneRenderError> {
5161        self.render_prepared_with_metrics(scene, camera)
5162            .map(RenderReport::status)
5163    }
5164
5165    /// Draws prepared logical-screen geometry independently of a world camera.
5166    ///
5167    /// The prepared resource must have been built from a [`ScreenScene`]. The
5168    /// renderer cannot infer the original coordinate space from raw prepared
5169    /// vertices, so passing world-space geometry is a caller contract error.
5170    pub fn render_prepared_screen_scene(
5171        &mut self,
5172        scene: &PreparedScreenScene,
5173    ) -> Result<RenderStatus, PreparedSceneRenderError> {
5174        let (width, height) = self.logical_size();
5175        let viewport = LogicalViewport::new(width, height).map_err(|_| {
5176            PreparedSceneRenderError::Frame(RendererFrameError::InvalidGeometryTransform)
5177        })?;
5178        let camera = screen_camera(viewport).map_err(|_| {
5179            PreparedSceneRenderError::Frame(RendererFrameError::InvalidGeometryTransform)
5180        })?;
5181        self.render_prepared(&scene.scene, &camera)
5182    }
5183
5184    /// Draws prepared geometry and reports per-frame CPU timing.
5185    ///
5186    /// Tessellation and geometry upload durations are zero because both happened
5187    /// in [`WgpuRenderer::prepare_scene`]. The camera uniform is still updated
5188    /// once per frame.
5189    pub fn render_prepared_with_metrics(
5190        &mut self,
5191        scene: &PreparedScene,
5192        camera: &Camera2d,
5193    ) -> Result<RenderReport, PreparedSceneRenderError> {
5194        if !prepared_scene_belongs_to(&self.renderer_identity, &scene.renderer_identity) {
5195            return Err(PreparedSceneRenderError::RendererMismatch);
5196        }
5197
5198        self.draw_geometry(
5199            scene.background,
5200            &scene.vertex_buffer,
5201            scene.vertex_count,
5202            scene.geometry_extents,
5203            GeometryValidationSource::Tessellated(&scene.vertices),
5204            Some(&scene.geometry_validation_cache),
5205            &scene.draw_batches,
5206            *camera,
5207            Duration::ZERO,
5208            Duration::ZERO,
5209            true,
5210            false,
5211            false,
5212            None,
5213            scene.tessellation,
5214            Instant::now(),
5215            None,
5216        )
5217        .map_err(PreparedSceneRenderError::Frame)
5218    }
5219
5220    fn surface_geometry_context(
5221        &self,
5222        camera: Camera2d,
5223        viewport_region: Option<LogicalViewportRegion>,
5224    ) -> Result<(LogicalViewport, ScissorRect, CameraUniform), RendererFrameError> {
5225        let (logical_width, logical_height) = self.logical_size();
5226        let target_viewport = LogicalViewport::new(logical_width, logical_height)
5227            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
5228        let (viewport, viewport_origin) = match viewport_region {
5229            Some(region) => (region.viewport(), region.origin().to_vec2()),
5230            None => (target_viewport, Vec2::ZERO),
5231        };
5232        let viewport_max = viewport_origin + viewport.size();
5233        if !viewport_origin.is_finite()
5234            || !viewport_max.is_finite()
5235            || viewport_origin.x < 0.0
5236            || viewport_origin.y < 0.0
5237            || viewport_max.x > target_viewport.width()
5238            || viewport_max.y > target_viewport.height()
5239        {
5240            return Err(RendererFrameError::InvalidViewport);
5241        }
5242        let viewport_scissor = logical_viewport_scissor(
5243            viewport_origin,
5244            viewport,
5245            self.scale_factor as f32,
5246            self.config.width,
5247            self.config.height,
5248        )
5249        .ok_or(RendererFrameError::InvalidViewport)?;
5250        let camera_uniform =
5251            CameraUniform::new_in_region(camera, viewport, viewport_origin, target_viewport)
5252                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
5253        Ok((viewport, viewport_scissor, camera_uniform))
5254    }
5255
5256    #[allow(clippy::too_many_arguments)]
5257    fn draw_geometry(
5258        &mut self,
5259        background: Color,
5260        vertex_buffer: &wgpu::Buffer,
5261        vertex_count: usize,
5262        geometry_extents: GeometryExtents,
5263        geometry_validation: GeometryValidationSource<'_>,
5264        geometry_validation_cache: Option<&GeometryValidationCache>,
5265        draw_batches: &[PreparedDrawBatch],
5266        camera: Camera2d,
5267        tessellation: Duration,
5268        mut upload: Duration,
5269        geometry_reused: bool,
5270        geometry_streamed: bool,
5271        uses_dynamic_pipeline: bool,
5272        pending_vertex_upload: Option<&[Vertex]>,
5273        tessellation_stats: TessellationStats,
5274        frame_started_at: Instant,
5275        viewport_region: Option<LogicalViewportRegion>,
5276    ) -> Result<RenderReport, RendererFrameError> {
5277        let (viewport, viewport_scissor, camera_uniform) =
5278            self.surface_geometry_context(camera, viewport_region)?;
5279        if !geometry_is_safe_for_cached(
5280            geometry_validation_cache,
5281            geometry_extents,
5282            geometry_validation,
5283            camera_uniform,
5284        ) {
5285            return Err(RendererFrameError::InvalidGeometryTransform);
5286        }
5287
5288        let surface_acquire_started_at = Instant::now();
5289        let surface_texture = match self.surface.get_current_texture() {
5290            wgpu::CurrentSurfaceTexture::Success(texture)
5291            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
5292            wgpu::CurrentSurfaceTexture::Timeout => {
5293                return Ok(render_report(
5294                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
5295                    tessellation,
5296                    upload,
5297                    Duration::ZERO,
5298                    surface_acquire_started_at.elapsed(),
5299                    Duration::ZERO,
5300                    frame_started_at.elapsed(),
5301                    geometry_reused,
5302                    geometry_streamed,
5303                    tessellation_stats,
5304                ));
5305            }
5306            wgpu::CurrentSurfaceTexture::Occluded => {
5307                return Ok(render_report(
5308                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
5309                    tessellation,
5310                    upload,
5311                    Duration::ZERO,
5312                    surface_acquire_started_at.elapsed(),
5313                    Duration::ZERO,
5314                    frame_started_at.elapsed(),
5315                    geometry_reused,
5316                    geometry_streamed,
5317                    tessellation_stats,
5318                ));
5319            }
5320            wgpu::CurrentSurfaceTexture::Outdated => {
5321                let _ = self.resize(self.config.width, self.config.height);
5322                return Ok(render_report(
5323                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
5324                    tessellation,
5325                    upload,
5326                    Duration::ZERO,
5327                    surface_acquire_started_at.elapsed(),
5328                    Duration::ZERO,
5329                    frame_started_at.elapsed(),
5330                    geometry_reused,
5331                    geometry_streamed,
5332                    tessellation_stats,
5333                ));
5334            }
5335            wgpu::CurrentSurfaceTexture::Lost => {
5336                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
5337            }
5338            wgpu::CurrentSurfaceTexture::Validation => {
5339                return Err(RendererFrameError::Surface(
5340                    RendererSurfaceStatus::Validation,
5341                ));
5342            }
5343        };
5344        let surface_acquire = surface_acquire_started_at.elapsed();
5345        let vertex_upload_started_at = Instant::now();
5346        if let Some(vertices) = pending_vertex_upload
5347            && !vertices.is_empty()
5348        {
5349            self.queue
5350                .write_buffer(vertex_buffer, 0, bytemuck::cast_slice(vertices));
5351        }
5352        upload = upload.saturating_add(vertex_upload_started_at.elapsed());
5353        let camera_uniform_upload_started_at = Instant::now();
5354        self.queue.write_buffer(
5355            &self.camera_uniform_buffer,
5356            0,
5357            bytemuck::bytes_of(&camera_uniform),
5358        );
5359        let camera_uniform_upload = camera_uniform_upload_started_at.elapsed();
5360
5361        let encode_submit_present_started_at = Instant::now();
5362        let surface_view = surface_texture
5363            .texture
5364            .create_view(&wgpu::TextureViewDescriptor::default());
5365        let (view, resolve_target) = match &self.multisample_target {
5366            Some(target) => (&target.view, Some(&surface_view)),
5367            None => (&surface_view, None),
5368        };
5369
5370        let mut encoder = self
5371            .device
5372            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5373                label: Some("sim-engine render encoder"),
5374            });
5375
5376        {
5377            let color_attachment = wgpu::RenderPassColorAttachment {
5378                view,
5379                depth_slice: None,
5380                resolve_target,
5381                ops: wgpu::Operations {
5382                    load: wgpu::LoadOp::Clear(background.to_wgpu()),
5383                    store: wgpu::StoreOp::Store,
5384                },
5385            };
5386            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5387                label: Some("sim-engine render pass"),
5388                color_attachments: &[Some(color_attachment)],
5389                depth_stencil_attachment: None,
5390                timestamp_writes: None,
5391                occlusion_query_set: None,
5392                multiview_mask: None,
5393            });
5394
5395            if vertex_count > 0 {
5396                let pipeline = if uses_dynamic_pipeline {
5397                    &self.dynamic_pipeline
5398                } else {
5399                    &self.pipeline
5400                };
5401                pass.set_pipeline(pipeline);
5402                pass.set_bind_group(0, &self.camera_bind_group, &[]);
5403                pass.set_vertex_buffer(0, vertex_buffer.slice(..));
5404                for batch in draw_batches {
5405                    let scissor = match batch.screen_clip {
5406                        Some(screen_clip) => {
5407                            let Some(local_scissor) = screen_clip_to_scissor(
5408                                screen_clip,
5409                                viewport,
5410                                self.scale_factor as f32,
5411                            ) else {
5412                                continue;
5413                            };
5414                            let Some(scissor) = offset_scissor(local_scissor, viewport_scissor)
5415                            else {
5416                                continue;
5417                            };
5418                            scissor
5419                        }
5420                        None => viewport_scissor,
5421                    };
5422                    pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
5423                    pass.draw(batch.vertex_range.clone(), 0..1);
5424                }
5425            }
5426        }
5427
5428        self.queue.submit([encoder.finish()]);
5429        self.notify_before_present();
5430        self.queue.present(surface_texture);
5431        let encode_submit_present = encode_submit_present_started_at.elapsed();
5432
5433        Ok(render_report(
5434            RenderStatus::Drawn,
5435            tessellation,
5436            upload,
5437            camera_uniform_upload,
5438            surface_acquire,
5439            encode_submit_present,
5440            frame_started_at.elapsed(),
5441            geometry_reused,
5442            geometry_streamed,
5443            tessellation_stats,
5444        ))
5445    }
5446
5447    #[allow(clippy::too_many_arguments)]
5448    fn draw_scalar_field_texture(
5449        &mut self,
5450        texture: &ScalarFieldTexture,
5451        color_map: &ColorMap,
5452        minimum: f32,
5453        value_extent: f32,
5454        sampling: ScalarFieldSampling,
5455        background: Color,
5456        frame_started_at: Instant,
5457    ) -> Result<RenderReport, RendererFrameError> {
5458        let uniform = HeatmapUniform::new(
5459            minimum,
5460            value_extent,
5461            texture.width(),
5462            texture.height(),
5463            sampling,
5464        );
5465        let acquire_started_at = Instant::now();
5466        let surface_texture = match self.surface.get_current_texture() {
5467            wgpu::CurrentSurfaceTexture::Success(texture)
5468            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
5469            wgpu::CurrentSurfaceTexture::Timeout => {
5470                return Ok(render_report(
5471                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
5472                    Duration::ZERO,
5473                    Duration::ZERO,
5474                    Duration::ZERO,
5475                    acquire_started_at.elapsed(),
5476                    Duration::ZERO,
5477                    frame_started_at.elapsed(),
5478                    false,
5479                    true,
5480                    TessellationStats::default(),
5481                ));
5482            }
5483            wgpu::CurrentSurfaceTexture::Occluded => {
5484                return Ok(render_report(
5485                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
5486                    Duration::ZERO,
5487                    Duration::ZERO,
5488                    Duration::ZERO,
5489                    acquire_started_at.elapsed(),
5490                    Duration::ZERO,
5491                    frame_started_at.elapsed(),
5492                    false,
5493                    true,
5494                    TessellationStats::default(),
5495                ));
5496            }
5497            wgpu::CurrentSurfaceTexture::Outdated => {
5498                let _ = self.resize(self.config.width, self.config.height);
5499                return Ok(render_report(
5500                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
5501                    Duration::ZERO,
5502                    Duration::ZERO,
5503                    Duration::ZERO,
5504                    acquire_started_at.elapsed(),
5505                    Duration::ZERO,
5506                    frame_started_at.elapsed(),
5507                    false,
5508                    true,
5509                    TessellationStats::default(),
5510                ));
5511            }
5512            wgpu::CurrentSurfaceTexture::Lost => {
5513                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
5514            }
5515            wgpu::CurrentSurfaceTexture::Validation => {
5516                return Err(RendererFrameError::Surface(
5517                    RendererSurfaceStatus::Validation,
5518                ));
5519            }
5520        };
5521        let surface_acquire = acquire_started_at.elapsed();
5522        let upload_started_at = Instant::now();
5523        let color_map_view = self.color_map_view(color_map);
5524        let scalar_view = texture
5525            .texture
5526            .create_view(&wgpu::TextureViewDescriptor::default());
5527        self.queue.write_buffer(
5528            &self.heatmap_uniform_buffer,
5529            0,
5530            bytemuck::bytes_of(&uniform),
5531        );
5532        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5533            label: Some("sim-engine heatmap bind group"),
5534            layout: &self.heatmap_bind_group_layout,
5535            entries: &[
5536                wgpu::BindGroupEntry {
5537                    binding: 0,
5538                    resource: wgpu::BindingResource::TextureView(&scalar_view),
5539                },
5540                wgpu::BindGroupEntry {
5541                    binding: 1,
5542                    resource: wgpu::BindingResource::TextureView(&color_map_view),
5543                },
5544                wgpu::BindGroupEntry {
5545                    binding: 2,
5546                    resource: self.heatmap_uniform_buffer.as_entire_binding(),
5547                },
5548            ],
5549        });
5550        let upload = upload_started_at.elapsed();
5551        let encode_started_at = Instant::now();
5552        let surface_view = surface_texture
5553            .texture
5554            .create_view(&wgpu::TextureViewDescriptor::default());
5555        let (view, resolve_target) = match &self.multisample_target {
5556            Some(target) => (&target.view, Some(&surface_view)),
5557            None => (&surface_view, None),
5558        };
5559        let mut encoder = self
5560            .device
5561            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5562                label: Some("sim-engine heatmap encoder"),
5563            });
5564        {
5565            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5566                label: Some("sim-engine heatmap pass"),
5567                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5568                    view,
5569                    depth_slice: None,
5570                    resolve_target,
5571                    ops: wgpu::Operations {
5572                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
5573                        store: wgpu::StoreOp::Store,
5574                    },
5575                })],
5576                depth_stencil_attachment: None,
5577                timestamp_writes: None,
5578                occlusion_query_set: None,
5579                multiview_mask: None,
5580            });
5581            pass.set_pipeline(&self.heatmap_pipeline);
5582            pass.set_bind_group(0, &bind_group, &[]);
5583            pass.draw(0..6, 0..1);
5584        }
5585        self.queue.submit([encoder.finish()]);
5586        self.notify_before_present();
5587        self.queue.present(surface_texture);
5588        Ok(render_report(
5589            RenderStatus::Drawn,
5590            Duration::ZERO,
5591            upload,
5592            Duration::ZERO,
5593            surface_acquire,
5594            encode_started_at.elapsed(),
5595            frame_started_at.elapsed(),
5596            false,
5597            true,
5598            TessellationStats::default(),
5599        ))
5600    }
5601
5602    #[allow(clippy::too_many_arguments)]
5603    fn draw_scalar_field_texture_to_target(
5604        &mut self,
5605        target: &RenderTarget2d,
5606        texture: &ScalarFieldTexture,
5607        color_map: &ColorMap,
5608        minimum: f32,
5609        value_extent: f32,
5610        sampling: ScalarFieldSampling,
5611        background: Color,
5612        frame_started_at: Instant,
5613    ) -> RenderReport {
5614        let upload_started_at = Instant::now();
5615        let color_map_view = self.color_map_view(color_map);
5616        let scalar_view = texture
5617            .texture
5618            .create_view(&wgpu::TextureViewDescriptor::default());
5619        self.queue.write_buffer(
5620            &self.heatmap_uniform_buffer,
5621            0,
5622            bytemuck::bytes_of(&HeatmapUniform::new(
5623                minimum,
5624                value_extent,
5625                texture.width(),
5626                texture.height(),
5627                sampling,
5628            )),
5629        );
5630        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5631            label: Some("sim-engine target heatmap bind group"),
5632            layout: &self.heatmap_bind_group_layout,
5633            entries: &[
5634                wgpu::BindGroupEntry {
5635                    binding: 0,
5636                    resource: wgpu::BindingResource::TextureView(&scalar_view),
5637                },
5638                wgpu::BindGroupEntry {
5639                    binding: 1,
5640                    resource: wgpu::BindingResource::TextureView(&color_map_view),
5641                },
5642                wgpu::BindGroupEntry {
5643                    binding: 2,
5644                    resource: self.heatmap_uniform_buffer.as_entire_binding(),
5645                },
5646            ],
5647        });
5648        let upload = upload_started_at.elapsed();
5649        let encode_started_at = Instant::now();
5650        let mut encoder = self
5651            .device
5652            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5653                label: Some("sim-engine render-target heatmap encoder"),
5654            });
5655        {
5656            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5657                label: Some("sim-engine render-target heatmap pass"),
5658                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5659                    view: &target.view,
5660                    depth_slice: None,
5661                    resolve_target: None,
5662                    ops: wgpu::Operations {
5663                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(background)),
5664                        store: wgpu::StoreOp::Store,
5665                    },
5666                })],
5667                depth_stencil_attachment: None,
5668                timestamp_writes: None,
5669                occlusion_query_set: None,
5670                multiview_mask: None,
5671            });
5672            pass.set_pipeline(&self.target_heatmap_pipeline);
5673            pass.set_bind_group(0, &bind_group, &[]);
5674            pass.draw(0..6, 0..1);
5675        }
5676        self.queue.submit([encoder.finish()]);
5677        render_report(
5678            RenderStatus::Drawn,
5679            Duration::ZERO,
5680            upload,
5681            Duration::ZERO,
5682            Duration::ZERO,
5683            encode_started_at.elapsed(),
5684            frame_started_at.elapsed(),
5685            false,
5686            true,
5687            TessellationStats::default(),
5688        )
5689    }
5690
5691    fn draw_composed_render_target(
5692        &mut self,
5693        target: &RenderTarget2d,
5694        blend_mode: BlendMode,
5695        opacity: f32,
5696        background: Color,
5697        frame_started_at: Instant,
5698    ) -> Result<RenderReport, RendererFrameError> {
5699        let acquire_started_at = Instant::now();
5700        let surface_texture = match self.surface.get_current_texture() {
5701            wgpu::CurrentSurfaceTexture::Success(texture)
5702            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
5703            wgpu::CurrentSurfaceTexture::Timeout => {
5704                return Ok(render_report(
5705                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
5706                    Duration::ZERO,
5707                    Duration::ZERO,
5708                    Duration::ZERO,
5709                    acquire_started_at.elapsed(),
5710                    Duration::ZERO,
5711                    frame_started_at.elapsed(),
5712                    false,
5713                    true,
5714                    TessellationStats::default(),
5715                ));
5716            }
5717            wgpu::CurrentSurfaceTexture::Occluded => {
5718                return Ok(render_report(
5719                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
5720                    Duration::ZERO,
5721                    Duration::ZERO,
5722                    Duration::ZERO,
5723                    acquire_started_at.elapsed(),
5724                    Duration::ZERO,
5725                    frame_started_at.elapsed(),
5726                    false,
5727                    true,
5728                    TessellationStats::default(),
5729                ));
5730            }
5731            wgpu::CurrentSurfaceTexture::Outdated => {
5732                let _ = self.resize(self.config.width, self.config.height);
5733                return Ok(render_report(
5734                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
5735                    Duration::ZERO,
5736                    Duration::ZERO,
5737                    Duration::ZERO,
5738                    acquire_started_at.elapsed(),
5739                    Duration::ZERO,
5740                    frame_started_at.elapsed(),
5741                    false,
5742                    true,
5743                    TessellationStats::default(),
5744                ));
5745            }
5746            wgpu::CurrentSurfaceTexture::Lost => {
5747                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
5748            }
5749            wgpu::CurrentSurfaceTexture::Validation => {
5750                return Err(RendererFrameError::Surface(
5751                    RendererSurfaceStatus::Validation,
5752                ));
5753            }
5754        };
5755        let surface_acquire = acquire_started_at.elapsed();
5756        let upload_started_at = Instant::now();
5757        self.queue.write_buffer(
5758            &self.composition_pipelines.uniform_buffer,
5759            0,
5760            bytemuck::bytes_of(&CompositeUniform::full_surface(opacity)),
5761        );
5762        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5763            label: Some("sim-engine composition bind group"),
5764            layout: &self.composition_pipelines.bind_group_layout,
5765            entries: &[
5766                wgpu::BindGroupEntry {
5767                    binding: 0,
5768                    resource: wgpu::BindingResource::TextureView(&target.view),
5769                },
5770                wgpu::BindGroupEntry {
5771                    binding: 1,
5772                    resource: self
5773                        .composition_pipelines
5774                        .uniform_buffer
5775                        .as_entire_binding(),
5776                },
5777            ],
5778        });
5779        let upload = upload_started_at.elapsed();
5780        let encode_started_at = Instant::now();
5781        let surface_view = surface_texture
5782            .texture
5783            .create_view(&wgpu::TextureViewDescriptor::default());
5784        let (view, resolve_target) = match &self.multisample_target {
5785            Some(multisample_target) => (&multisample_target.view, Some(&surface_view)),
5786            None => (&surface_view, None),
5787        };
5788        let mut encoder = self
5789            .device
5790            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5791                label: Some("sim-engine composition encoder"),
5792            });
5793        {
5794            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5795                label: Some("sim-engine composition pass"),
5796                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5797                    view,
5798                    depth_slice: None,
5799                    resolve_target,
5800                    ops: wgpu::Operations {
5801                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
5802                        store: wgpu::StoreOp::Store,
5803                    },
5804                })],
5805                depth_stencil_attachment: None,
5806                timestamp_writes: None,
5807                occlusion_query_set: None,
5808                multiview_mask: None,
5809            });
5810            pass.set_pipeline(self.composition_pipelines.pipeline(blend_mode));
5811            pass.set_bind_group(0, &bind_group, &[]);
5812            pass.draw(0..6, 0..1);
5813        }
5814        self.queue.submit([encoder.finish()]);
5815        self.notify_before_present();
5816        self.queue.present(surface_texture);
5817        Ok(render_report(
5818            RenderStatus::Drawn,
5819            Duration::ZERO,
5820            upload,
5821            Duration::ZERO,
5822            surface_acquire,
5823            encode_started_at.elapsed(),
5824            frame_started_at.elapsed(),
5825            false,
5826            true,
5827            TessellationStats::default(),
5828        ))
5829    }
5830
5831    #[allow(clippy::too_many_arguments)]
5832    fn draw_trail_accumulation(
5833        &mut self,
5834        trails: &mut TrailBuffer2d,
5835        source: &RenderTarget2d,
5836        retention: f32,
5837        source_opacity: f32,
5838        source_blend: BlendMode,
5839        frame_started_at: Instant,
5840    ) -> RenderReport {
5841        let upload_started_at = Instant::now();
5842        self.queue.write_buffer(
5843            &self.target_composition_pipelines.secondary_uniform_buffer,
5844            0,
5845            bytemuck::bytes_of(&CompositeUniform::full_surface(retention)),
5846        );
5847        self.queue.write_buffer(
5848            &self.target_composition_pipelines.uniform_buffer,
5849            0,
5850            bytemuck::bytes_of(&CompositeUniform::full_surface(source_opacity)),
5851        );
5852        let history_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5853            label: Some("sim-engine trail history bind group"),
5854            layout: &self.target_composition_pipelines.bind_group_layout,
5855            entries: &[
5856                wgpu::BindGroupEntry {
5857                    binding: 0,
5858                    resource: wgpu::BindingResource::TextureView(&trails.front.view),
5859                },
5860                wgpu::BindGroupEntry {
5861                    binding: 1,
5862                    resource: self
5863                        .target_composition_pipelines
5864                        .secondary_uniform_buffer
5865                        .as_entire_binding(),
5866                },
5867            ],
5868        });
5869        let source_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5870            label: Some("sim-engine trail source bind group"),
5871            layout: &self.target_composition_pipelines.bind_group_layout,
5872            entries: &[
5873                wgpu::BindGroupEntry {
5874                    binding: 0,
5875                    resource: wgpu::BindingResource::TextureView(&source.view),
5876                },
5877                wgpu::BindGroupEntry {
5878                    binding: 1,
5879                    resource: self
5880                        .target_composition_pipelines
5881                        .uniform_buffer
5882                        .as_entire_binding(),
5883                },
5884            ],
5885        });
5886        let upload = upload_started_at.elapsed();
5887        let encode_started_at = Instant::now();
5888        let mut encoder = self
5889            .device
5890            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5891                label: Some("sim-engine trail accumulation encoder"),
5892            });
5893        {
5894            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5895                label: Some("sim-engine trail history pass"),
5896                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5897                    view: &trails.back.view,
5898                    depth_slice: None,
5899                    resolve_target: None,
5900                    ops: wgpu::Operations {
5901                        load: wgpu::LoadOp::Clear(Color::rgba(0.0, 0.0, 0.0, 0.0).to_wgpu()),
5902                        store: wgpu::StoreOp::Store,
5903                    },
5904                })],
5905                depth_stencil_attachment: None,
5906                timestamp_writes: None,
5907                occlusion_query_set: None,
5908                multiview_mask: None,
5909            });
5910            pass.set_pipeline(&self.target_composition_pipelines.alpha);
5911            pass.set_bind_group(0, &history_bind_group, &[]);
5912            pass.draw(0..6, 0..1);
5913        }
5914        {
5915            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5916                label: Some("sim-engine trail source pass"),
5917                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5918                    view: &trails.back.view,
5919                    depth_slice: None,
5920                    resolve_target: None,
5921                    ops: wgpu::Operations {
5922                        load: wgpu::LoadOp::Load,
5923                        store: wgpu::StoreOp::Store,
5924                    },
5925                })],
5926                depth_stencil_attachment: None,
5927                timestamp_writes: None,
5928                occlusion_query_set: None,
5929                multiview_mask: None,
5930            });
5931            pass.set_pipeline(self.target_composition_pipelines.pipeline(source_blend));
5932            pass.set_bind_group(0, &source_bind_group, &[]);
5933            pass.draw(0..6, 0..1);
5934        }
5935        self.queue.submit([encoder.finish()]);
5936        std::mem::swap(&mut trails.front, &mut trails.back);
5937        render_report(
5938            RenderStatus::Drawn,
5939            Duration::ZERO,
5940            upload,
5941            Duration::ZERO,
5942            Duration::ZERO,
5943            encode_started_at.elapsed(),
5944            frame_started_at.elapsed(),
5945            false,
5946            true,
5947            TessellationStats::default(),
5948        )
5949    }
5950
5951    fn draw_clear_trail_buffer(
5952        &self,
5953        trails: &TrailBuffer2d,
5954        color: Color,
5955        frame_started_at: Instant,
5956    ) -> RenderReport {
5957        let encode_started_at = Instant::now();
5958        let mut encoder = self
5959            .device
5960            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5961                label: Some("sim-engine trail clear encoder"),
5962            });
5963        for view in [&trails.front.view, &trails.back.view] {
5964            let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5965                label: Some("sim-engine trail clear pass"),
5966                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5967                    view,
5968                    depth_slice: None,
5969                    resolve_target: None,
5970                    ops: wgpu::Operations {
5971                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(color)),
5972                        store: wgpu::StoreOp::Store,
5973                    },
5974                })],
5975                depth_stencil_attachment: None,
5976                timestamp_writes: None,
5977                occlusion_query_set: None,
5978                multiview_mask: None,
5979            });
5980        }
5981        self.queue.submit([encoder.finish()]);
5982        render_report(
5983            RenderStatus::Drawn,
5984            Duration::ZERO,
5985            Duration::ZERO,
5986            Duration::ZERO,
5987            Duration::ZERO,
5988            encode_started_at.elapsed(),
5989            frame_started_at.elapsed(),
5990            false,
5991            true,
5992            TessellationStats::default(),
5993        )
5994    }
5995
5996    fn prepare_particle_draw(
5997        &self,
5998        field: &mut ParticleField2d,
5999        camera: Camera2d,
6000    ) -> Result<ParticleDrawPreparation, RendererFrameError> {
6001        let (logical_width, logical_height) = self.logical_size();
6002        let viewport = LogicalViewport::new(logical_width, logical_height)
6003            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
6004        let Some(camera_uniform) = CameraUniform::new(camera, viewport) else {
6005            return Err(RendererFrameError::InvalidGeometryTransform);
6006        };
6007        let instance_count = field.instances.len();
6008        let visibility_checked = instance_count.min(field.budget.max_visibility_checks_per_frame);
6009        if visibility_checked < instance_count {
6010            field.visible_instances.clear();
6011            validate_particle_staging_capacity(&field.visible_instances, visibility_checked)?;
6012            for candidate_index in 0..visibility_checked {
6013                let source_index =
6014                    uniformly_sampled_index(candidate_index, instance_count, visibility_checked);
6015                let instance = field.instances[source_index];
6016                let Some(intersects) =
6017                    instance.validated_viewport_intersection(camera_uniform, viewport)
6018                else {
6019                    return Err(RendererFrameError::InvalidGeometryTransform);
6020                };
6021                if intersects {
6022                    field.visible_instances.push(instance);
6023                }
6024            }
6025            let visible_count = field.visible_instances.len();
6026            let selected_count = visible_count.min(field.budget.instance_limit());
6027            if selected_count < visible_count {
6028                let mut visible_index = 0;
6029                field.visible_instances.retain(|_| {
6030                    let selected = particle_visible_index_is_selected(
6031                        visible_index,
6032                        visible_count,
6033                        selected_count,
6034                    );
6035                    visible_index += 1;
6036                    selected
6037                });
6038            }
6039            let statistics = particle_statistics_with_budget(
6040                instance_count,
6041                visibility_checked,
6042                visible_count,
6043                selected_count,
6044                0,
6045            );
6046            return Ok(ParticleDrawPreparation {
6047                camera_uniform,
6048                visible_count: selected_count,
6049                statistics,
6050            });
6051        }
6052
6053        let visible_count = visible_particle_count(&field.instances, camera_uniform, viewport)?;
6054        let selected_count = visible_count.min(field.budget.instance_limit());
6055        let statistics = particle_statistics_with_budget(
6056            instance_count,
6057            instance_count,
6058            visible_count,
6059            selected_count,
6060            0,
6061        );
6062        if selected_count == field.instances.len() {
6063            field.visible_instances.clear();
6064        } else {
6065            field.visible_instances.clear();
6066            validate_particle_staging_capacity(&field.visible_instances, selected_count)?;
6067            let mut visible_index = 0;
6068            for instance in field.instances.iter().copied() {
6069                if !instance.intersects_viewport(camera_uniform, viewport) {
6070                    continue;
6071                }
6072                let selected_index = field.visible_instances.len();
6073                if selected_index < selected_count
6074                    && particle_visible_index_is_selected(
6075                        visible_index,
6076                        visible_count,
6077                        selected_count,
6078                    )
6079                {
6080                    field.visible_instances.push(instance);
6081                }
6082                visible_index += 1;
6083            }
6084        }
6085        Ok(ParticleDrawPreparation {
6086            camera_uniform,
6087            visible_count: selected_count,
6088            statistics,
6089        })
6090    }
6091
6092    fn upload_particle_draw(
6093        &self,
6094        field: &ParticleField2d,
6095        preparation: ParticleDrawPreparation,
6096    ) -> (Duration, Duration) {
6097        let visible_instances = if field.visible_instances.is_empty()
6098            && preparation.visible_count == field.instances.len()
6099        {
6100            field.instances.as_slice()
6101        } else {
6102            field.visible_instances.as_slice()
6103        };
6104        let upload_started_at = Instant::now();
6105        if !visible_instances.is_empty() {
6106            self.queue.write_buffer(
6107                &field.instance_buffer,
6108                0,
6109                bytemuck::cast_slice(visible_instances),
6110            );
6111        }
6112        let upload = upload_started_at.elapsed();
6113        let camera_uniform_upload_started_at = Instant::now();
6114        self.queue.write_buffer(
6115            &self.camera_uniform_buffer,
6116            0,
6117            bytemuck::bytes_of(&preparation.camera_uniform),
6118        );
6119        let camera_uniform_upload = camera_uniform_upload_started_at.elapsed();
6120        (upload, camera_uniform_upload)
6121    }
6122
6123    fn draw_particle_field(
6124        &mut self,
6125        background: Color,
6126        field: &mut ParticleField2d,
6127        camera: Camera2d,
6128        frame_started_at: Instant,
6129    ) -> Result<RenderReport, RendererFrameError> {
6130        let preparation_started_at = Instant::now();
6131        let preparation = self.prepare_particle_draw(field, camera)?;
6132        let preparation_duration = preparation_started_at.elapsed();
6133
6134        let surface_acquire_started_at = Instant::now();
6135        let surface_texture = match self.surface.get_current_texture() {
6136            wgpu::CurrentSurfaceTexture::Success(texture)
6137            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
6138            wgpu::CurrentSurfaceTexture::Timeout => {
6139                field.statistics = preparation.statistics;
6140                return Ok(render_report(
6141                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
6142                    preparation_duration,
6143                    Duration::ZERO,
6144                    Duration::ZERO,
6145                    surface_acquire_started_at.elapsed(),
6146                    Duration::ZERO,
6147                    frame_started_at.elapsed(),
6148                    false,
6149                    true,
6150                    TessellationStats::default(),
6151                ));
6152            }
6153            wgpu::CurrentSurfaceTexture::Occluded => {
6154                field.statistics = preparation.statistics;
6155                return Ok(render_report(
6156                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
6157                    preparation_duration,
6158                    Duration::ZERO,
6159                    Duration::ZERO,
6160                    surface_acquire_started_at.elapsed(),
6161                    Duration::ZERO,
6162                    frame_started_at.elapsed(),
6163                    false,
6164                    true,
6165                    TessellationStats::default(),
6166                ));
6167            }
6168            wgpu::CurrentSurfaceTexture::Outdated => {
6169                let _ = self.resize(self.config.width, self.config.height);
6170                field.statistics = preparation.statistics;
6171                return Ok(render_report(
6172                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
6173                    preparation_duration,
6174                    Duration::ZERO,
6175                    Duration::ZERO,
6176                    surface_acquire_started_at.elapsed(),
6177                    Duration::ZERO,
6178                    frame_started_at.elapsed(),
6179                    false,
6180                    true,
6181                    TessellationStats::default(),
6182                ));
6183            }
6184            wgpu::CurrentSurfaceTexture::Lost => {
6185                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
6186            }
6187            wgpu::CurrentSurfaceTexture::Validation => {
6188                return Err(RendererFrameError::Surface(
6189                    RendererSurfaceStatus::Validation,
6190                ));
6191            }
6192        };
6193        let surface_acquire = surface_acquire_started_at.elapsed();
6194        let (upload, camera_uniform_upload) = self.upload_particle_draw(field, preparation);
6195        let encode_submit_present_started_at = Instant::now();
6196        let surface_view = surface_texture
6197            .texture
6198            .create_view(&wgpu::TextureViewDescriptor::default());
6199        let (view, resolve_target) = match &self.multisample_target {
6200            Some(target) => (&target.view, Some(&surface_view)),
6201            None => (&surface_view, None),
6202        };
6203        let mut encoder = self
6204            .device
6205            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
6206                label: Some("sim-engine particle render encoder"),
6207            });
6208        {
6209            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
6210                label: Some("sim-engine particle render pass"),
6211                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
6212                    view,
6213                    depth_slice: None,
6214                    resolve_target,
6215                    ops: wgpu::Operations {
6216                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
6217                        store: wgpu::StoreOp::Store,
6218                    },
6219                })],
6220                depth_stencil_attachment: None,
6221                timestamp_writes: None,
6222                occlusion_query_set: None,
6223                multiview_mask: None,
6224            });
6225            if preparation.visible_count > 0 {
6226                pass.set_pipeline(&self.particle_pipeline);
6227                pass.set_bind_group(0, &self.camera_bind_group, &[]);
6228                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
6229                pass.set_vertex_buffer(1, field.instance_buffer.slice(..));
6230                pass.draw(0..6, 0..preparation.visible_count as u32);
6231            }
6232        }
6233        self.queue.submit([encoder.finish()]);
6234        self.notify_before_present();
6235        self.queue.present(surface_texture);
6236        field.statistics = ParticleStatistics {
6237            rendered: preparation.visible_count,
6238            ..preparation.statistics
6239        };
6240        Ok(render_report(
6241            RenderStatus::Drawn,
6242            preparation_duration,
6243            upload,
6244            camera_uniform_upload,
6245            surface_acquire,
6246            encode_submit_present_started_at.elapsed(),
6247            frame_started_at.elapsed(),
6248            false,
6249            true,
6250            TessellationStats::default(),
6251        ))
6252    }
6253
6254    fn draw_particle_field_to_target(
6255        &self,
6256        target: &RenderTarget2d,
6257        field: &mut ParticleField2d,
6258        camera: Camera2d,
6259        load: RenderTargetLoad,
6260        frame_started_at: Instant,
6261    ) -> Result<RenderReport, RendererFrameError> {
6262        let preparation_started_at = Instant::now();
6263        let preparation = self.prepare_particle_draw(field, camera)?;
6264        let preparation_duration = preparation_started_at.elapsed();
6265        let (upload, camera_uniform_upload) = self.upload_particle_draw(field, preparation);
6266        let encode_started_at = Instant::now();
6267        let mut encoder = self
6268            .device
6269            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
6270                label: Some("sim-engine target particle encoder"),
6271            });
6272        {
6273            let load = match load {
6274                RenderTargetLoad::Load => wgpu::LoadOp::Load,
6275                RenderTargetLoad::Clear(color) => {
6276                    wgpu::LoadOp::Clear(premultiplied_wgpu_color(color))
6277                }
6278            };
6279            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
6280                label: Some("sim-engine target particle pass"),
6281                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
6282                    view: &target.view,
6283                    depth_slice: None,
6284                    resolve_target: None,
6285                    ops: wgpu::Operations {
6286                        load,
6287                        store: wgpu::StoreOp::Store,
6288                    },
6289                })],
6290                depth_stencil_attachment: None,
6291                timestamp_writes: None,
6292                occlusion_query_set: None,
6293                multiview_mask: None,
6294            });
6295            if preparation.visible_count > 0 {
6296                pass.set_pipeline(&self.target_particle_pipeline);
6297                pass.set_bind_group(0, &self.camera_bind_group, &[]);
6298                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
6299                pass.set_vertex_buffer(1, field.instance_buffer.slice(..));
6300                pass.draw(0..6, 0..preparation.visible_count as u32);
6301            }
6302        }
6303        self.queue.submit([encoder.finish()]);
6304        field.statistics = ParticleStatistics {
6305            rendered: preparation.visible_count,
6306            ..preparation.statistics
6307        };
6308        Ok(render_report(
6309            RenderStatus::Drawn,
6310            preparation_duration,
6311            upload,
6312            camera_uniform_upload,
6313            Duration::ZERO,
6314            encode_started_at.elapsed(),
6315            frame_started_at.elapsed(),
6316            false,
6317            true,
6318            TessellationStats::default(),
6319        ))
6320    }
6321
6322    fn ensure_vertex_capacity(&mut self, vertex_count: usize) -> Result<(), RendererFrameError> {
6323        if vertex_count <= self.vertex_capacity {
6324            return Ok(());
6325        }
6326
6327        self.vertex_capacity = dynamic_vertex_capacity(vertex_count)
6328            .filter(|capacity| buffer_capacity_fits::<Vertex>(&self.device, *capacity))
6329            .ok_or(RendererFrameError::GeometryCapacityTooLarge)?;
6330        self.vertex_buffer = Arc::new(create_vertex_buffer(&self.device, self.vertex_capacity));
6331        Ok(())
6332    }
6333
6334    fn validate_dynamic_mesh(&self, mesh: &DynamicMesh2d) -> Result<(), DynamicMeshError> {
6335        prepared_scene_belongs_to(&self.renderer_identity, &mesh.renderer_identity)
6336            .then_some(())
6337            .ok_or(DynamicMeshError::RendererMismatch)
6338    }
6339
6340    fn validate_particle_field(&self, field: &ParticleField2d) -> Result<(), ParticleFieldError> {
6341        prepared_scene_belongs_to(&self.renderer_identity, &field.renderer_identity)
6342            .then_some(())
6343            .ok_or(ParticleFieldError::RendererMismatch)
6344    }
6345
6346    fn validate_scalar_field_texture(
6347        &self,
6348        texture: &ScalarFieldTexture,
6349    ) -> Result<(), ScalarFieldTextureError> {
6350        prepared_scene_belongs_to(&self.renderer_identity, &texture.renderer_identity)
6351            .then_some(())
6352            .ok_or(ScalarFieldTextureError::RendererMismatch)
6353    }
6354
6355    fn color_map_view(&mut self, color_map: &ColorMap) -> wgpu::TextureView {
6356        let lut = color_map_lut(color_map);
6357        if let Some(cached) = self
6358            .color_map_cache
6359            .as_ref()
6360            .filter(|cached| cached.lut == lut)
6361        {
6362            return cached.view.clone();
6363        }
6364        let cached = create_cached_color_map(&self.device, &self.queue, lut);
6365        let view = cached.view.clone();
6366        self.color_map_cache = Some(cached);
6367        view
6368    }
6369
6370    fn validate_render_target(&self, target: &RenderTarget2d) -> Result<(), RenderTargetError> {
6371        prepared_scene_belongs_to(&self.renderer_identity, &target.renderer_identity)
6372            .then_some(())
6373            .ok_or(RenderTargetError::RendererMismatch)
6374    }
6375
6376    fn validate_trail_buffer(&self, trails: &TrailBuffer2d) -> Result<(), RenderTargetError> {
6377        prepared_scene_belongs_to(&self.renderer_identity, &trails.renderer_identity)
6378            .then_some(())
6379            .ok_or(RenderTargetError::RendererMismatch)
6380    }
6381}
6382
6383fn invoke_pre_present_notify(
6384    present_mode: RendererSurfacePresentMode,
6385    notify: Option<&(dyn Fn() + Send + Sync)>,
6386) {
6387    if present_mode.is_refresh_synchronized()
6388        && let Some(notify) = notify
6389    {
6390        notify();
6391    }
6392}
6393
6394fn prepared_scene_belongs_to(renderer_identity: &Arc<()>, scene_identity: &Arc<()>) -> bool {
6395    Arc::ptr_eq(renderer_identity, scene_identity)
6396}
6397
6398fn render_target_allocation_bytes(
6399    format: wgpu::TextureFormat,
6400    width: u32,
6401    height: u32,
6402) -> Option<usize> {
6403    let bytes_per_texel = u64::from(format.block_copy_size(None)?);
6404    let byte_count = u64::from(width)
6405        .checked_mul(u64::from(height))?
6406        .checked_mul(bytes_per_texel)?;
6407    usize::try_from(byte_count).ok()
6408}
6409
6410fn dynamic_vertices_to_gpu(
6411    vertices: &[DynamicVertex2d],
6412) -> Result<Vec<DynamicGpu>, DynamicMeshError> {
6413    validate_dynamic_vertices(vertices)?;
6414    let requested_bytes = dynamic_mesh_bytes(vertices.len())?;
6415    let mut converted = Vec::new();
6416    converted
6417        .try_reserve_exact(vertices.len())
6418        .map_err(|_| DynamicMeshError::AllocationFailed { requested_bytes })?;
6419    converted.extend(vertices.iter().copied().map(dynamic_vertex_to_gpu));
6420    Ok(converted)
6421}
6422
6423fn replace_dynamic_mesh_resources(
6424    device: &wgpu::Device,
6425    queue: &wgpu::Queue,
6426    mesh: &mut DynamicMesh2d,
6427    vertices: &[DynamicVertex2d],
6428) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
6429    let update_started_at = Instant::now();
6430    validate_dynamic_vertices(vertices)?;
6431    if let Some(budget) = mesh.budget {
6432        validate_dynamic_mesh_budget(budget, vertices.len())?;
6433    }
6434    let reallocated = vertices.len() > mesh.vertex_capacity;
6435    let replacement_capacity = if reallocated {
6436        let capacity = dynamic_vertex_capacity(vertices.len())
6437            .filter(|capacity| buffer_capacity_fits::<DynamicGpu>(device, *capacity))
6438            .ok_or(DynamicMeshError::CapacityTooLarge)?;
6439        Some(capacity)
6440    } else {
6441        None
6442    };
6443    let replacement_vertices = dynamic_vertices_to_gpu(vertices)?;
6444    if let Some(budget) = mesh.budget {
6445        validate_dynamic_retained_capacity(budget, &replacement_vertices)?;
6446    }
6447    let replacement = if let Some(capacity) = replacement_capacity {
6448        let buffer = Arc::new(create_dynamic_vertex_buffer(device, capacity));
6449        Some((buffer, capacity))
6450    } else {
6451        None
6452    };
6453    let upload_buffer = replacement
6454        .as_ref()
6455        .map_or(mesh.vertex_buffer.as_ref(), |(buffer, _)| buffer.as_ref());
6456    if !replacement_vertices.is_empty() {
6457        queue.write_buffer(
6458            upload_buffer,
6459            0,
6460            bytemuck::cast_slice(&replacement_vertices),
6461        );
6462        submit_pending_uploads(queue);
6463    }
6464    if let Some((buffer, capacity)) = replacement {
6465        mesh.vertex_buffer = buffer;
6466        mesh.vertex_capacity = capacity;
6467    }
6468    mesh.geometry_extents = GeometryExtents::from_dynamic_vertices(&replacement_vertices);
6469    mesh.vertices = replacement_vertices;
6470    mesh.geometry_validation_cache.clear();
6471    Ok(DynamicMeshUpdateReport {
6472        vertex_count: mesh.vertices.len(),
6473        upload: update_started_at.elapsed(),
6474        reallocated,
6475    })
6476}
6477
6478fn dynamic_mesh_bytes(vertex_count: usize) -> Result<usize, DynamicMeshError> {
6479    vertex_count
6480        .checked_mul(std::mem::size_of::<DynamicGpu>())
6481        .ok_or(DynamicMeshError::CapacityTooLarge)
6482}
6483
6484fn validate_dynamic_mesh_budget(
6485    budget: DynamicMeshBudget,
6486    vertex_count: usize,
6487) -> Result<(), DynamicMeshError> {
6488    if u32::try_from(vertex_count).is_err() {
6489        return Err(DynamicMeshError::CapacityTooLarge);
6490    }
6491    if vertex_count > budget.max_vertices {
6492        return Err(DynamicMeshError::BudgetExceeded {
6493            resource: DynamicMeshBudgetResource::Vertices,
6494            limit: budget.max_vertices,
6495            actual: vertex_count,
6496        });
6497    }
6498    let bytes = dynamic_mesh_bytes(vertex_count)?;
6499    if bytes > budget.max_retained_bytes {
6500        return Err(DynamicMeshError::BudgetExceeded {
6501            resource: DynamicMeshBudgetResource::RetainedBytes,
6502            limit: budget.max_retained_bytes,
6503            actual: bytes,
6504        });
6505    }
6506    if bytes > budget.max_upload_bytes {
6507        return Err(DynamicMeshError::BudgetExceeded {
6508            resource: DynamicMeshBudgetResource::UploadBytes,
6509            limit: budget.max_upload_bytes,
6510            actual: bytes,
6511        });
6512    }
6513    Ok(())
6514}
6515
6516fn validate_dynamic_retained_capacity(
6517    budget: DynamicMeshBudget,
6518    vertices: &Vec<DynamicGpu>,
6519) -> Result<(), DynamicMeshError> {
6520    let actual = vertices
6521        .capacity()
6522        .checked_mul(std::mem::size_of::<DynamicGpu>())
6523        .ok_or(DynamicMeshError::CapacityTooLarge)?;
6524    if actual > budget.max_retained_bytes {
6525        return Err(DynamicMeshError::BudgetExceeded {
6526            resource: DynamicMeshBudgetResource::RetainedBytes,
6527            limit: budget.max_retained_bytes,
6528            actual,
6529        });
6530    }
6531    Ok(())
6532}
6533
6534fn validate_dynamic_vertices(vertices: &[DynamicVertex2d]) -> Result<(), DynamicMeshError> {
6535    if u32::try_from(vertices.len()).is_err() {
6536        return Err(DynamicMeshError::CapacityTooLarge);
6537    }
6538    if !vertices.len().is_multiple_of(3) {
6539        return Err(DynamicMeshError::InvalidVertexCount);
6540    }
6541    if vertices.iter().any(|vertex| {
6542        ![
6543            vertex.world_position.x,
6544            vertex.world_position.y,
6545            vertex.depth,
6546        ]
6547        .into_iter()
6548        .all(is_portable_shader_source)
6549    }) {
6550        return Err(DynamicMeshError::InvalidVertex);
6551    }
6552    // Private fields and the only public constructor make finiteness an
6553    // invariant of DynamicVertex2d. Keep the assertion in development without
6554    // rescanning an already-validated high-volume stream in release builds.
6555    debug_assert!(vertices.iter().all(|vertex| {
6556        vertex.world_position.is_finite()
6557            && vertex.depth.is_finite()
6558            && vertex.color.is_normalized()
6559    }));
6560    Ok(())
6561}
6562
6563fn dynamic_vertex_to_gpu(vertex: DynamicVertex2d) -> DynamicGpu {
6564    DynamicGpu {
6565        world_position: [vertex.world_position.x, vertex.world_position.y],
6566        depth: vertex.depth,
6567        color: vertex.color.to_array(),
6568    }
6569}
6570
6571fn dynamic_vertex_capacity(vertex_count: usize) -> Option<usize> {
6572    vertex_count.max(1).checked_next_power_of_two()
6573}
6574
6575fn particle_instances_to_gpu(
6576    instances: &[ParticleInstance2d],
6577) -> Result<Vec<ParticleGpu>, ParticleFieldError> {
6578    if u32::try_from(instances.len()).is_err() {
6579        return Err(ParticleFieldError::CapacityTooLarge);
6580    }
6581    let requested_bytes = instances
6582        .len()
6583        .checked_mul(std::mem::size_of::<ParticleGpu>())
6584        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6585    if instances.iter().copied().any(|instance| {
6586        let world_position = instance.world_position();
6587        let radius = instance.radius();
6588        let color = instance.color();
6589        let depth = instance.depth();
6590        ![world_position.x, world_position.y, radius, depth]
6591            .into_iter()
6592            .all(is_portable_shader_source)
6593            || radius <= 0.0
6594            || !color.is_normalized()
6595    }) {
6596        return Err(ParticleFieldError::InvalidInstance);
6597    }
6598    let mut output = Vec::new();
6599    output
6600        .try_reserve_exact(instances.len())
6601        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
6602    output.extend(instances.iter().copied().map(|instance| {
6603        let world_position = instance.world_position();
6604        ParticleGpu {
6605            world_position: [world_position.x, world_position.y],
6606            depth: instance.depth(),
6607            radius: instance.radius(),
6608            color: instance.color().to_array(),
6609        }
6610    }));
6611    Ok(output)
6612}
6613
6614fn particle_retained_bytes(instance_count: usize) -> Option<usize> {
6615    instance_count.checked_mul(std::mem::size_of::<ParticleGpu>())
6616}
6617
6618fn validate_particle_retained_count(
6619    instance_count: usize,
6620    budget: ParticleRenderBudget,
6621) -> Result<(), ParticleFieldError> {
6622    let staging_count = particle_staging_target(instance_count, budget);
6623    let retained_count = instance_count
6624        .checked_add(staging_count)
6625        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6626    let actual =
6627        particle_retained_bytes(retained_count).ok_or(ParticleFieldError::CapacityTooLarge)?;
6628    if actual > budget.max_retained_bytes {
6629        return Err(ParticleFieldError::RetainedBudgetExceeded {
6630            limit: budget.max_retained_bytes,
6631            actual,
6632        });
6633    }
6634    Ok(())
6635}
6636
6637fn validate_particle_retained_capacities(
6638    instance_capacity: usize,
6639    staging_capacity: usize,
6640    budget: ParticleRenderBudget,
6641) -> Result<(), ParticleFieldError> {
6642    let retained_capacity = instance_capacity
6643        .checked_add(staging_capacity)
6644        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6645    let actual =
6646        particle_retained_bytes(retained_capacity).ok_or(ParticleFieldError::CapacityTooLarge)?;
6647    if actual > budget.max_retained_bytes {
6648        return Err(ParticleFieldError::RetainedBudgetExceeded {
6649            limit: budget.max_retained_bytes,
6650            actual,
6651        });
6652    }
6653    Ok(())
6654}
6655
6656fn compact_particle_instances(
6657    source: &[ParticleGpu],
6658    current_capacity: usize,
6659    staging_capacity: usize,
6660    budget: ParticleRenderBudget,
6661) -> Result<Option<Vec<ParticleGpu>>, ParticleFieldError> {
6662    validate_particle_retained_count(source.len(), budget)?;
6663    if validate_particle_retained_capacities(current_capacity, staging_capacity, budget).is_ok() {
6664        return Ok(None);
6665    }
6666    let requested_bytes =
6667        particle_retained_bytes(source.len()).ok_or(ParticleFieldError::CapacityTooLarge)?;
6668    let mut compact = Vec::new();
6669    compact
6670        .try_reserve_exact(source.len())
6671        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
6672    compact.extend_from_slice(source);
6673    validate_particle_retained_capacities(compact.capacity(), staging_capacity, budget)?;
6674    Ok(Some(compact))
6675}
6676
6677fn particle_instance_capacity(instance_count: usize) -> Option<usize> {
6678    instance_count.max(1).checked_next_power_of_two()
6679}
6680
6681fn particle_budgeted_capacity(
6682    instance_count: usize,
6683    budget: ParticleRenderBudget,
6684) -> Option<usize> {
6685    let limit = budget.instance_limit();
6686    let required = instance_count.min(limit).max(1);
6687    particle_instance_capacity(required).map(|capacity| capacity.min(limit))
6688}
6689
6690fn allocate_particle_staging(
6691    instance_count: usize,
6692    budget: ParticleRenderBudget,
6693) -> Result<Vec<ParticleGpu>, ParticleFieldError> {
6694    let target = particle_staging_target(instance_count, budget);
6695    let requested_bytes = target
6696        .checked_mul(std::mem::size_of::<ParticleGpu>())
6697        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6698    let mut staging = Vec::new();
6699    staging
6700        .try_reserve_exact(target)
6701        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
6702    Ok(staging)
6703}
6704
6705fn particle_staging_target(instance_count: usize, budget: ParticleRenderBudget) -> usize {
6706    let visibility_checked = instance_count.min(budget.max_visibility_checks_per_frame);
6707    if visibility_checked < instance_count {
6708        visibility_checked
6709    } else {
6710        instance_count.min(budget.instance_limit())
6711    }
6712}
6713
6714fn buffer_allocation_bytes<T>(capacity: usize) -> Option<u64> {
6715    u64::try_from(capacity)
6716        .ok()?
6717        .checked_mul(std::mem::size_of::<T>() as u64)
6718}
6719
6720fn buffer_capacity_fits<T>(device: &wgpu::Device, capacity: usize) -> bool {
6721    buffer_allocation_bytes::<T>(capacity)
6722        .is_some_and(|bytes| bytes <= device.limits().max_buffer_size)
6723}
6724
6725fn scene_estimate_fits_prepared_device(scene: &Scene, device: &wgpu::Device) -> bool {
6726    buffer_capacity_fits::<Vertex>(
6727        device,
6728        scene.statistics().estimated_tessellated_vertices().max(1),
6729    )
6730}
6731
6732fn scene_estimate_fits_streaming_device(
6733    scene: &Scene,
6734    device: &wgpu::Device,
6735    prefix: usize,
6736    current_capacity: usize,
6737) -> bool {
6738    let Some(required) = prefix.checked_add(scene.statistics().estimated_tessellated_vertices())
6739    else {
6740        return false;
6741    };
6742    required <= current_capacity
6743        || dynamic_vertex_capacity(required)
6744            .is_some_and(|capacity| buffer_capacity_fits::<Vertex>(device, capacity))
6745}
6746
6747fn particle_update_range(
6748    first_instance: usize,
6749    replacement_count: usize,
6750    current_count: usize,
6751) -> Result<Range<usize>, ParticleFieldError> {
6752    let end = first_instance
6753        .checked_add(replacement_count)
6754        .ok_or(ParticleFieldError::UpdateRangeOutOfBounds)?;
6755    (end <= current_count)
6756        .then_some(first_instance..end)
6757        .ok_or(ParticleFieldError::UpdateRangeOutOfBounds)
6758}
6759
6760fn validate_particle_staging_capacity(
6761    instances: &Vec<ParticleGpu>,
6762    target_len: usize,
6763) -> Result<(), RendererFrameError> {
6764    let requested_bytes = target_len
6765        .checked_mul(std::mem::size_of::<ParticleGpu>())
6766        .ok_or(RendererFrameError::GeometryCapacityTooLarge)?;
6767    (instances.capacity() >= target_len)
6768        .then_some(())
6769        .ok_or(RendererFrameError::ParticleAllocationFailed { requested_bytes })
6770}
6771
6772#[cfg(test)]
6773fn visible_particle_instances(
6774    instances: &[ParticleGpu],
6775    camera: CameraUniform,
6776    viewport: LogicalViewport,
6777) -> Result<Vec<ParticleGpu>, RendererFrameError> {
6778    visible_particle_count(instances, camera, viewport)?;
6779    Ok(instances
6780        .iter()
6781        .copied()
6782        .filter(|instance| instance.intersects_viewport(camera, viewport))
6783        .collect())
6784}
6785
6786fn visible_particle_count(
6787    instances: &[ParticleGpu],
6788    camera: CameraUniform,
6789    viewport: LogicalViewport,
6790) -> Result<usize, RendererFrameError> {
6791    let mut visible = 0;
6792    for instance in instances.iter().copied() {
6793        let Some(intersects) = instance.validated_viewport_intersection(camera, viewport) else {
6794            return Err(RendererFrameError::InvalidGeometryTransform);
6795        };
6796        visible += usize::from(intersects);
6797    }
6798    Ok(visible)
6799}
6800
6801fn particle_visible_index_is_selected(
6802    visible_index: usize,
6803    visible_count: usize,
6804    selected_count: usize,
6805) -> bool {
6806    if visible_count == 0 || selected_count == 0 {
6807        return false;
6808    }
6809    let before = visible_index as u128 * selected_count as u128 / visible_count as u128;
6810    let after = (visible_index as u128 + 1) * selected_count as u128 / visible_count as u128;
6811    before < after
6812}
6813
6814fn uniformly_sampled_index(sample_index: usize, source_count: usize, sample_count: usize) -> usize {
6815    debug_assert!(sample_index < sample_count);
6816    debug_assert!(sample_count <= source_count);
6817    (((sample_index as u128 + 1) * source_count as u128 - 1) / sample_count as u128) as usize
6818}
6819
6820fn particle_idle_statistics(instance_count: usize) -> ParticleStatistics {
6821    ParticleStatistics {
6822        submitted: instance_count,
6823        visibility_checked: 0,
6824        visible: 0,
6825        culled: 0,
6826        budget_limited: 0,
6827        dropped: 0,
6828        rendered: 0,
6829    }
6830}
6831
6832#[cfg(test)]
6833fn particle_statistics(
6834    instance_count: usize,
6835    visible: usize,
6836    rendered: usize,
6837) -> ParticleStatistics {
6838    particle_statistics_with_budget(instance_count, instance_count, visible, visible, rendered)
6839}
6840
6841fn particle_statistics_with_budget(
6842    instance_count: usize,
6843    visibility_checked: usize,
6844    visible: usize,
6845    selected: usize,
6846    rendered: usize,
6847) -> ParticleStatistics {
6848    ParticleStatistics {
6849        submitted: instance_count,
6850        visibility_checked,
6851        visible,
6852        culled: visibility_checked.saturating_sub(visible),
6853        budget_limited: instance_count
6854            .saturating_sub(visibility_checked)
6855            .saturating_add(visible.saturating_sub(selected)),
6856        dropped: 0,
6857        rendered,
6858    }
6859}
6860
6861fn prepare_scene_resources(
6862    device: &wgpu::Device,
6863    queue: &wgpu::Queue,
6864    renderer_identity: Arc<()>,
6865    scene: &Scene,
6866) -> Result<PreparedScene, PreparedSceneError> {
6867    if !scene_command_sources_are_portable(scene) {
6868        return Err(PreparedSceneError::InvalidGeometrySources);
6869    }
6870    if !scene_estimate_fits_prepared_device(scene, device) {
6871        return Err(PreparedSceneError::CapacityTooLarge);
6872    }
6873    let mut vertices = Vec::new();
6874    let mut draw_batches = Vec::new();
6875    let tessellation = tessellate_scene(scene, &mut vertices, &mut draw_batches)?;
6876    let geometry_extents = GeometryExtents::from_vertices(&vertices);
6877    if !geometry_sources_are_portable(GeometryValidationSource::Tessellated(&vertices)) {
6878        return Err(PreparedSceneError::InvalidGeometrySources);
6879    }
6880    if !buffer_capacity_fits::<Vertex>(device, vertices.len().max(1)) {
6881        return Err(PreparedSceneError::CapacityTooLarge);
6882    }
6883    // Retain the tessellator allocation directly. Wrapping a Vec is O(1) and
6884    // avoids an infallible caller-scale Vec -> Arc<[T]> copy after GPU writes.
6885    let vertices = Arc::new(vertices);
6886    let vertex_buffer = Arc::new(create_vertex_buffer(device, vertices.len()));
6887    if !vertices.is_empty() {
6888        queue.write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
6889        submit_pending_uploads(queue);
6890    }
6891    let vertex_count = vertices.len();
6892
6893    Ok(PreparedScene {
6894        renderer_identity,
6895        background: scene.background(),
6896        vertex_buffer,
6897        vertices,
6898        command_count: scene.command_count(),
6899        vertex_count,
6900        geometry_extents,
6901        draw_batches,
6902        tessellation,
6903        geometry_validation_cache: GeometryValidationCache::default(),
6904    })
6905}
6906
6907fn scene_command_sources_are_portable(scene: &Scene) -> bool {
6908    scene.commands().iter().all(|command| {
6909        is_portable_shader_source(command.depth())
6910            && command.screen_clip().is_none_or(|clip| {
6911                portable_vec2(clip.min().to_vec2()) && portable_vec2(clip.max().to_vec2())
6912            })
6913            && match command.command() {
6914                DrawCommand::Circle(circle) => {
6915                    portable_vec2(circle.center())
6916                        && is_portable_shader_source(circle.radius())
6917                        && portable_shape_style(circle.style())
6918                }
6919                DrawCommand::Rect(rectangle) => {
6920                    portable_vec2(rectangle.rect().min())
6921                        && portable_vec2(rectangle.rect().max())
6922                        && is_portable_shader_source(rectangle.corner_radius())
6923                        && portable_shape_style(rectangle.style())
6924                }
6925                DrawCommand::Line(line) => {
6926                    portable_vec2(line.from())
6927                        && portable_vec2(line.to())
6928                        && portable_stroke_style(line.stroke_style())
6929                }
6930                DrawCommand::Polyline(polyline) => {
6931                    polyline.points().iter().copied().all(portable_vec2)
6932                        && portable_stroke_style(polyline.stroke_style())
6933                }
6934            }
6935    })
6936}
6937
6938fn portable_vec2(value: Vec2) -> bool {
6939    is_portable_shader_source(value.x) && is_portable_shader_source(value.y)
6940}
6941
6942fn portable_shape_style(style: ShapeStyle) -> bool {
6943    style
6944        .stroke()
6945        .is_none_or(|stroke| is_portable_shader_source(stroke.width()))
6946        && style.shadow().is_none_or(|shadow| {
6947            portable_vec2(shadow.offset().to_vec2()) && is_portable_shader_source(shadow.spread())
6948        })
6949}
6950
6951fn portable_stroke_style(style: crate::StrokeStyle2d) -> bool {
6952    let stroke = style.stroke();
6953    is_portable_shader_source(stroke.width())
6954        && is_portable_shader_source(style.miter_limit())
6955        && style.dash_pattern().is_none_or(|dash| {
6956            dash.lengths()
6957                .iter()
6958                .copied()
6959                .chain([dash.phase()])
6960                .all(is_portable_shader_source)
6961        })
6962        && style.start_marker().is_none_or(|marker| {
6963            is_portable_shader_source(marker.length().get())
6964                && is_portable_shader_source(marker.width().get())
6965        })
6966        && style.end_marker().is_none_or(|marker| {
6967            is_portable_shader_source(marker.length().get())
6968                && is_portable_shader_source(marker.width().get())
6969        })
6970}
6971
6972fn restore_prepared_scene_resources(
6973    device: &wgpu::Device,
6974    queue: &wgpu::Queue,
6975    renderer_identity: Arc<()>,
6976    source: &PreparedScene,
6977) -> Result<PreparedScene, PreparedSceneError> {
6978    if !buffer_capacity_fits::<Vertex>(device, source.vertices.len().max(1)) {
6979        return Err(PreparedSceneError::CapacityTooLarge);
6980    }
6981    if !geometry_sources_are_portable(GeometryValidationSource::Tessellated(&source.vertices)) {
6982        return Err(PreparedSceneError::InvalidGeometrySources);
6983    }
6984    let requested_bytes = source
6985        .draw_batches
6986        .len()
6987        .checked_mul(std::mem::size_of::<PreparedDrawBatch>())
6988        .ok_or(PreparedSceneError::CapacityTooLarge)?;
6989    let mut draw_batches = Vec::new();
6990    draw_batches
6991        .try_reserve_exact(source.draw_batches.len())
6992        .map_err(|_| PreparedSceneError::AllocationFailed { requested_bytes })?;
6993    draw_batches.extend_from_slice(&source.draw_batches);
6994    let vertex_buffer = Arc::new(create_vertex_buffer(device, source.vertices.len()));
6995    if !source.vertices.is_empty() {
6996        queue.write_buffer(
6997            &vertex_buffer,
6998            0,
6999            bytemuck::cast_slice(source.vertices.as_ref()),
7000        );
7001        submit_pending_uploads(queue);
7002    }
7003
7004    Ok(PreparedScene {
7005        renderer_identity,
7006        background: source.background,
7007        vertex_buffer,
7008        vertices: Arc::clone(&source.vertices),
7009        command_count: source.command_count,
7010        vertex_count: source.vertex_count,
7011        geometry_extents: source.geometry_extents,
7012        draw_batches,
7013        tessellation: source.tessellation,
7014        geometry_validation_cache: GeometryValidationCache::default(),
7015    })
7016}
7017
7018fn restore_dynamic_mesh_resources(
7019    device: &wgpu::Device,
7020    queue: &wgpu::Queue,
7021    renderer_identity: Arc<()>,
7022    source: &DynamicMesh2d,
7023) -> Result<DynamicMesh2d, DynamicMeshError> {
7024    if !buffer_capacity_fits::<DynamicGpu>(device, source.vertex_capacity) {
7025        return Err(DynamicMeshError::CapacityTooLarge);
7026    }
7027    if let Some(budget) = source.budget {
7028        validate_dynamic_mesh_budget(budget, source.vertices.len())?;
7029    }
7030    let requested_bytes = dynamic_mesh_bytes(source.vertices.len())?;
7031    let mut vertices = Vec::new();
7032    vertices
7033        .try_reserve_exact(source.vertices.len())
7034        .map_err(|_| DynamicMeshError::AllocationFailed { requested_bytes })?;
7035    vertices.extend_from_slice(&source.vertices);
7036    if let Some(budget) = source.budget {
7037        validate_dynamic_retained_capacity(budget, &vertices)?;
7038    }
7039    let vertex_buffer = Arc::new(create_dynamic_vertex_buffer(device, source.vertex_capacity));
7040    if !vertices.is_empty() {
7041        queue.write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(vertices.as_slice()));
7042        submit_pending_uploads(queue);
7043    }
7044    Ok(DynamicMesh2d {
7045        renderer_identity,
7046        vertex_buffer,
7047        vertices,
7048        vertex_capacity: source.vertex_capacity,
7049        geometry_extents: source.geometry_extents,
7050        geometry_validation_cache: GeometryValidationCache::default(),
7051        budget: source.budget,
7052    })
7053}
7054
7055fn restore_particle_field_resources(
7056    device: &wgpu::Device,
7057    _queue: &wgpu::Queue,
7058    renderer_identity: Arc<()>,
7059    source: &ParticleField2d,
7060) -> Result<ParticleField2d, ParticleFieldError> {
7061    validate_particle_retained_count(source.instances.len(), source.budget)?;
7062    if !buffer_capacity_fits::<ParticleGpu>(device, source.instance_capacity) {
7063        return Err(ParticleFieldError::CapacityTooLarge);
7064    }
7065    let requested_bytes = source
7066        .instances
7067        .len()
7068        .checked_mul(std::mem::size_of::<ParticleGpu>())
7069        .ok_or(ParticleFieldError::CapacityTooLarge)?;
7070    let mut instances = Vec::new();
7071    instances
7072        .try_reserve_exact(source.instances.len())
7073        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
7074    instances.extend_from_slice(&source.instances);
7075    let visible_instances = allocate_particle_staging(instances.len(), source.budget)?;
7076    validate_particle_retained_capacities(
7077        instances.capacity(),
7078        visible_instances.capacity(),
7079        source.budget,
7080    )?;
7081    let instance_buffer = Arc::new(create_particle_instance_buffer(
7082        device,
7083        source.instance_capacity,
7084    ));
7085    Ok(ParticleField2d {
7086        renderer_identity,
7087        instance_buffer,
7088        instances,
7089        visible_instances,
7090        instance_capacity: source.instance_capacity,
7091        budget: source.budget,
7092        statistics: particle_idle_statistics(source.instances.len()),
7093    })
7094}
7095
7096#[allow(clippy::too_many_arguments)]
7097fn render_report(
7098    status: RenderStatus,
7099    tessellation: Duration,
7100    upload: Duration,
7101    camera_uniform_upload: Duration,
7102    surface_acquire: Duration,
7103    encode_submit_present: Duration,
7104    total_cpu: Duration,
7105    geometry_reused: bool,
7106    geometry_streamed: bool,
7107    tessellation_stats: TessellationStats,
7108) -> RenderReport {
7109    RenderReport {
7110        status,
7111        metrics: RendererFrameMetrics {
7112            tessellation,
7113            upload,
7114            camera_uniform_upload,
7115            surface_acquire,
7116            encode_submit_present,
7117            total_cpu,
7118            geometry_reused,
7119            geometry_streamed,
7120            tessellation_stats,
7121        },
7122    }
7123}
7124
7125struct PipelineResources {
7126    pipeline: wgpu::RenderPipeline,
7127    target_pipeline: wgpu::RenderPipeline,
7128    dynamic_pipeline: wgpu::RenderPipeline,
7129    particle_pipeline: wgpu::RenderPipeline,
7130    target_particle_pipeline: wgpu::RenderPipeline,
7131    heatmap_pipeline: wgpu::RenderPipeline,
7132    target_heatmap_pipeline: wgpu::RenderPipeline,
7133    composition_pipelines: CompositionPipelines,
7134    target_composition_pipelines: CompositionPipelines,
7135    camera_uniform_buffer: wgpu::Buffer,
7136    camera_bind_group: wgpu::BindGroup,
7137    camera_bind_group_layout: wgpu::BindGroupLayout,
7138    heatmap_uniform_buffer: wgpu::Buffer,
7139    heatmap_bind_group_layout: wgpu::BindGroupLayout,
7140}
7141
7142fn create_pipeline(
7143    device: &wgpu::Device,
7144    format: wgpu::TextureFormat,
7145    sample_count: u32,
7146) -> PipelineResources {
7147    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
7148        label: Some("sim-engine flat color shader"),
7149        source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("primitive.wgsl"))),
7150    });
7151    let camera_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7152        label: Some("sim-engine camera uniform buffer"),
7153        size: std::mem::size_of::<CameraUniform>() as wgpu::BufferAddress,
7154        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7155        mapped_at_creation: false,
7156    });
7157    let camera_bind_group_layout =
7158        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7159            label: Some("sim-engine camera bind group layout"),
7160            entries: &[wgpu::BindGroupLayoutEntry {
7161                binding: 0,
7162                visibility: wgpu::ShaderStages::VERTEX,
7163                ty: wgpu::BindingType::Buffer {
7164                    ty: wgpu::BufferBindingType::Uniform,
7165                    has_dynamic_offset: false,
7166                    min_binding_size: None,
7167                },
7168                count: None,
7169            }],
7170        });
7171    let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
7172        label: Some("sim-engine camera bind group"),
7173        layout: &camera_bind_group_layout,
7174        entries: &[wgpu::BindGroupEntry {
7175            binding: 0,
7176            resource: camera_uniform_buffer.as_entire_binding(),
7177        }],
7178    });
7179    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7180        label: Some("sim-engine shape pipeline layout"),
7181        bind_group_layouts: &[Some(&camera_bind_group_layout)],
7182        immediate_size: 0,
7183    });
7184    let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7185        label: Some("sim-engine shape pipeline"),
7186        layout: Some(&pipeline_layout),
7187        vertex: wgpu::VertexState {
7188            module: &shader,
7189            entry_point: Some("vs_main"),
7190            compilation_options: wgpu::PipelineCompilationOptions::default(),
7191            buffers: &[Some(Vertex::LAYOUT)],
7192        },
7193        primitive: wgpu::PrimitiveState {
7194            topology: wgpu::PrimitiveTopology::TriangleList,
7195            ..Default::default()
7196        },
7197        depth_stencil: None,
7198        multisample: wgpu::MultisampleState {
7199            count: sample_count,
7200            ..Default::default()
7201        },
7202        fragment: Some(wgpu::FragmentState {
7203            module: &shader,
7204            entry_point: Some("fs_main"),
7205            compilation_options: wgpu::PipelineCompilationOptions::default(),
7206            targets: &[Some(wgpu::ColorTargetState {
7207                format,
7208                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7209                write_mask: wgpu::ColorWrites::ALL,
7210            })],
7211        }),
7212        multiview_mask: None,
7213        cache: None,
7214    });
7215
7216    let target_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7217        label: Some("sim-engine target shape pipeline"),
7218        layout: Some(&pipeline_layout),
7219        vertex: wgpu::VertexState {
7220            module: &shader,
7221            entry_point: Some("vs_main"),
7222            compilation_options: wgpu::PipelineCompilationOptions::default(),
7223            buffers: &[Some(Vertex::LAYOUT)],
7224        },
7225        primitive: wgpu::PrimitiveState {
7226            topology: wgpu::PrimitiveTopology::TriangleList,
7227            ..Default::default()
7228        },
7229        depth_stencil: None,
7230        multisample: wgpu::MultisampleState::default(),
7231        fragment: Some(wgpu::FragmentState {
7232            module: &shader,
7233            entry_point: Some("fs_main"),
7234            compilation_options: wgpu::PipelineCompilationOptions::default(),
7235            targets: &[Some(wgpu::ColorTargetState {
7236                format,
7237                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7238                write_mask: wgpu::ColorWrites::ALL,
7239            })],
7240        }),
7241        multiview_mask: None,
7242        cache: None,
7243    });
7244
7245    let dynamic_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7246        label: Some("sim-engine dynamic mesh pipeline"),
7247        layout: Some(&pipeline_layout),
7248        vertex: wgpu::VertexState {
7249            module: &shader,
7250            entry_point: Some("dynamic_vs_main"),
7251            compilation_options: wgpu::PipelineCompilationOptions::default(),
7252            buffers: &[Some(DynamicGpu::LAYOUT)],
7253        },
7254        primitive: wgpu::PrimitiveState {
7255            topology: wgpu::PrimitiveTopology::TriangleList,
7256            ..Default::default()
7257        },
7258        depth_stencil: None,
7259        multisample: wgpu::MultisampleState {
7260            count: sample_count,
7261            ..Default::default()
7262        },
7263        fragment: Some(wgpu::FragmentState {
7264            module: &shader,
7265            entry_point: Some("fs_main"),
7266            compilation_options: wgpu::PipelineCompilationOptions::default(),
7267            targets: &[Some(wgpu::ColorTargetState {
7268                format,
7269                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7270                write_mask: wgpu::ColorWrites::ALL,
7271            })],
7272        }),
7273        multiview_mask: None,
7274        cache: None,
7275    });
7276
7277    let particle_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7278        label: Some("sim-engine particle pipeline"),
7279        layout: Some(&pipeline_layout),
7280        vertex: wgpu::VertexState {
7281            module: &shader,
7282            entry_point: Some("particle_vs_main"),
7283            compilation_options: wgpu::PipelineCompilationOptions::default(),
7284            buffers: &[Some(ParticleUnitVertex::LAYOUT), Some(ParticleGpu::LAYOUT)],
7285        },
7286        primitive: wgpu::PrimitiveState {
7287            topology: wgpu::PrimitiveTopology::TriangleList,
7288            ..Default::default()
7289        },
7290        depth_stencil: None,
7291        multisample: wgpu::MultisampleState {
7292            count: sample_count,
7293            ..Default::default()
7294        },
7295        fragment: Some(wgpu::FragmentState {
7296            module: &shader,
7297            entry_point: Some("fs_main"),
7298            compilation_options: wgpu::PipelineCompilationOptions::default(),
7299            targets: &[Some(wgpu::ColorTargetState {
7300                format,
7301                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7302                write_mask: wgpu::ColorWrites::ALL,
7303            })],
7304        }),
7305        multiview_mask: None,
7306        cache: None,
7307    });
7308
7309    let target_particle_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7310        label: Some("sim-engine target particle pipeline"),
7311        layout: Some(&pipeline_layout),
7312        vertex: wgpu::VertexState {
7313            module: &shader,
7314            entry_point: Some("particle_vs_main"),
7315            compilation_options: wgpu::PipelineCompilationOptions::default(),
7316            buffers: &[Some(ParticleUnitVertex::LAYOUT), Some(ParticleGpu::LAYOUT)],
7317        },
7318        primitive: wgpu::PrimitiveState {
7319            topology: wgpu::PrimitiveTopology::TriangleList,
7320            ..Default::default()
7321        },
7322        depth_stencil: None,
7323        multisample: wgpu::MultisampleState {
7324            count: 1,
7325            ..Default::default()
7326        },
7327        fragment: Some(wgpu::FragmentState {
7328            module: &shader,
7329            entry_point: Some("fs_main"),
7330            compilation_options: wgpu::PipelineCompilationOptions::default(),
7331            targets: &[Some(wgpu::ColorTargetState {
7332                format,
7333                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7334                write_mask: wgpu::ColorWrites::ALL,
7335            })],
7336        }),
7337        multiview_mask: None,
7338        cache: None,
7339    });
7340
7341    let heatmap_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7342        label: Some("sim-engine heatmap uniform buffer"),
7343        size: std::mem::size_of::<HeatmapUniform>() as wgpu::BufferAddress,
7344        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7345        mapped_at_creation: false,
7346    });
7347    let heatmap_bind_group_layout =
7348        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7349            label: Some("sim-engine heatmap bind group layout"),
7350            entries: &[
7351                wgpu::BindGroupLayoutEntry {
7352                    binding: 0,
7353                    visibility: wgpu::ShaderStages::FRAGMENT,
7354                    ty: wgpu::BindingType::Texture {
7355                        multisampled: false,
7356                        view_dimension: wgpu::TextureViewDimension::D2,
7357                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7358                    },
7359                    count: None,
7360                },
7361                wgpu::BindGroupLayoutEntry {
7362                    binding: 1,
7363                    visibility: wgpu::ShaderStages::FRAGMENT,
7364                    ty: wgpu::BindingType::Texture {
7365                        multisampled: false,
7366                        view_dimension: wgpu::TextureViewDimension::D2,
7367                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7368                    },
7369                    count: None,
7370                },
7371                wgpu::BindGroupLayoutEntry {
7372                    binding: 2,
7373                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
7374                    ty: wgpu::BindingType::Buffer {
7375                        ty: wgpu::BufferBindingType::Uniform,
7376                        has_dynamic_offset: false,
7377                        min_binding_size: None,
7378                    },
7379                    count: None,
7380                },
7381            ],
7382        });
7383    let heatmap_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7384        label: Some("sim-engine heatmap pipeline layout"),
7385        bind_group_layouts: &[Some(&heatmap_bind_group_layout)],
7386        immediate_size: 0,
7387    });
7388    let heatmap_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7389        label: Some("sim-engine heatmap pipeline"),
7390        layout: Some(&heatmap_pipeline_layout),
7391        vertex: wgpu::VertexState {
7392            module: &shader,
7393            entry_point: Some("heatmap_vs_main"),
7394            compilation_options: wgpu::PipelineCompilationOptions::default(),
7395            buffers: &[],
7396        },
7397        primitive: wgpu::PrimitiveState {
7398            topology: wgpu::PrimitiveTopology::TriangleList,
7399            ..Default::default()
7400        },
7401        depth_stencil: None,
7402        multisample: wgpu::MultisampleState {
7403            count: sample_count,
7404            ..Default::default()
7405        },
7406        fragment: Some(wgpu::FragmentState {
7407            module: &shader,
7408            entry_point: Some("heatmap_fs_main"),
7409            compilation_options: wgpu::PipelineCompilationOptions::default(),
7410            targets: &[Some(wgpu::ColorTargetState {
7411                format,
7412                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7413                write_mask: wgpu::ColorWrites::ALL,
7414            })],
7415        }),
7416        multiview_mask: None,
7417        cache: None,
7418    });
7419
7420    let target_heatmap_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7421        label: Some("sim-engine render-target heatmap pipeline"),
7422        layout: Some(&heatmap_pipeline_layout),
7423        vertex: wgpu::VertexState {
7424            module: &shader,
7425            entry_point: Some("heatmap_vs_main"),
7426            compilation_options: wgpu::PipelineCompilationOptions::default(),
7427            buffers: &[],
7428        },
7429        primitive: wgpu::PrimitiveState {
7430            topology: wgpu::PrimitiveTopology::TriangleList,
7431            ..Default::default()
7432        },
7433        depth_stencil: None,
7434        multisample: wgpu::MultisampleState::default(),
7435        fragment: Some(wgpu::FragmentState {
7436            module: &shader,
7437            entry_point: Some("heatmap_fs_main"),
7438            compilation_options: wgpu::PipelineCompilationOptions::default(),
7439            targets: &[Some(wgpu::ColorTargetState {
7440                format,
7441                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7442                write_mask: wgpu::ColorWrites::ALL,
7443            })],
7444        }),
7445        multiview_mask: None,
7446        cache: None,
7447    });
7448
7449    let composition_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7450        label: Some("sim-engine composition uniform buffer"),
7451        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7452        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7453        mapped_at_creation: false,
7454    });
7455    let composition_secondary_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7456        label: Some("sim-engine composition secondary uniform buffer"),
7457        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7458        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7459        mapped_at_creation: false,
7460    });
7461    let composition_bind_group_layout =
7462        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7463            label: Some("sim-engine composition bind group layout"),
7464            entries: &[
7465                wgpu::BindGroupLayoutEntry {
7466                    binding: 0,
7467                    visibility: wgpu::ShaderStages::FRAGMENT,
7468                    ty: wgpu::BindingType::Texture {
7469                        multisampled: false,
7470                        view_dimension: wgpu::TextureViewDimension::D2,
7471                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7472                    },
7473                    count: None,
7474                },
7475                wgpu::BindGroupLayoutEntry {
7476                    binding: 1,
7477                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
7478                    ty: wgpu::BindingType::Buffer {
7479                        ty: wgpu::BufferBindingType::Uniform,
7480                        has_dynamic_offset: false,
7481                        min_binding_size: None,
7482                    },
7483                    count: None,
7484                },
7485            ],
7486        });
7487    let composition_pipeline_layout =
7488        device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7489            label: Some("sim-engine composition pipeline layout"),
7490            bind_group_layouts: &[Some(&composition_bind_group_layout)],
7491            immediate_size: 0,
7492        });
7493    let composition_pipelines = CompositionPipelines {
7494        alpha: create_composition_pipeline(
7495            device,
7496            &shader,
7497            &composition_pipeline_layout,
7498            format,
7499            sample_count,
7500            BlendMode::Alpha,
7501        ),
7502        additive: create_composition_pipeline(
7503            device,
7504            &shader,
7505            &composition_pipeline_layout,
7506            format,
7507            sample_count,
7508            BlendMode::Additive,
7509        ),
7510        replace: create_composition_pipeline(
7511            device,
7512            &shader,
7513            &composition_pipeline_layout,
7514            format,
7515            sample_count,
7516            BlendMode::Replace,
7517        ),
7518        uniform_buffer: composition_uniform_buffer,
7519        secondary_uniform_buffer: composition_secondary_uniform_buffer,
7520        bind_group_layout: composition_bind_group_layout,
7521    };
7522    let target_composition_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7523        label: Some("sim-engine target composition uniform buffer"),
7524        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7525        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7526        mapped_at_creation: false,
7527    });
7528    let target_composition_secondary_uniform_buffer =
7529        device.create_buffer(&wgpu::BufferDescriptor {
7530            label: Some("sim-engine target composition secondary uniform buffer"),
7531            size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7532            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7533            mapped_at_creation: false,
7534        });
7535    let target_composition_bind_group_layout =
7536        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7537            label: Some("sim-engine target composition bind group layout"),
7538            entries: &[
7539                wgpu::BindGroupLayoutEntry {
7540                    binding: 0,
7541                    visibility: wgpu::ShaderStages::FRAGMENT,
7542                    ty: wgpu::BindingType::Texture {
7543                        multisampled: false,
7544                        view_dimension: wgpu::TextureViewDimension::D2,
7545                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7546                    },
7547                    count: None,
7548                },
7549                wgpu::BindGroupLayoutEntry {
7550                    binding: 1,
7551                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
7552                    ty: wgpu::BindingType::Buffer {
7553                        ty: wgpu::BufferBindingType::Uniform,
7554                        has_dynamic_offset: false,
7555                        min_binding_size: None,
7556                    },
7557                    count: None,
7558                },
7559            ],
7560        });
7561    let target_composition_pipeline_layout =
7562        device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7563            label: Some("sim-engine target composition pipeline layout"),
7564            bind_group_layouts: &[Some(&target_composition_bind_group_layout)],
7565            immediate_size: 0,
7566        });
7567    let target_composition_pipelines = CompositionPipelines {
7568        alpha: create_composition_pipeline(
7569            device,
7570            &shader,
7571            &target_composition_pipeline_layout,
7572            format,
7573            1,
7574            BlendMode::Alpha,
7575        ),
7576        additive: create_composition_pipeline(
7577            device,
7578            &shader,
7579            &target_composition_pipeline_layout,
7580            format,
7581            1,
7582            BlendMode::Additive,
7583        ),
7584        replace: create_composition_pipeline(
7585            device,
7586            &shader,
7587            &target_composition_pipeline_layout,
7588            format,
7589            1,
7590            BlendMode::Replace,
7591        ),
7592        uniform_buffer: target_composition_uniform_buffer,
7593        secondary_uniform_buffer: target_composition_secondary_uniform_buffer,
7594        bind_group_layout: target_composition_bind_group_layout,
7595    };
7596
7597    PipelineResources {
7598        pipeline,
7599        target_pipeline,
7600        dynamic_pipeline,
7601        particle_pipeline,
7602        target_particle_pipeline,
7603        heatmap_pipeline,
7604        target_heatmap_pipeline,
7605        composition_pipelines,
7606        target_composition_pipelines,
7607        camera_uniform_buffer,
7608        camera_bind_group,
7609        camera_bind_group_layout,
7610        heatmap_uniform_buffer,
7611        heatmap_bind_group_layout,
7612    }
7613}
7614
7615fn preferred_sample_count(adapter: &wgpu::Adapter, format: wgpu::TextureFormat) -> u32 {
7616    let flags = adapter.get_texture_format_features(format).flags;
7617    if flags.contains(
7618        wgpu::TextureFormatFeatureFlags::MULTISAMPLE_X4
7619            | wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
7620    ) {
7621        PREFERRED_SAMPLE_COUNT
7622    } else {
7623        1
7624    }
7625}
7626
7627fn create_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
7628    device.create_buffer(&wgpu::BufferDescriptor {
7629        label: Some("sim-engine vertex buffer"),
7630        size: (capacity.max(1) * std::mem::size_of::<Vertex>()) as wgpu::BufferAddress,
7631        usage: wgpu::BufferUsages::VERTEX
7632            | wgpu::BufferUsages::COPY_DST
7633            | wgpu::BufferUsages::COPY_SRC,
7634        mapped_at_creation: false,
7635    })
7636}
7637
7638fn create_dynamic_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
7639    device.create_buffer(&wgpu::BufferDescriptor {
7640        label: Some("sim-engine dynamic vertex buffer"),
7641        size: (capacity.max(1) * std::mem::size_of::<DynamicGpu>()) as wgpu::BufferAddress,
7642        usage: wgpu::BufferUsages::VERTEX
7643            | wgpu::BufferUsages::COPY_DST
7644            | wgpu::BufferUsages::COPY_SRC,
7645        mapped_at_creation: false,
7646    })
7647}
7648
7649fn scalar_field_extent(field: &ScalarField) -> Result<wgpu::Extent3d, ScalarFieldTextureError> {
7650    let width =
7651        u32::try_from(field.width()).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7652    let height =
7653        u32::try_from(field.height()).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7654    let _bytes_per_row = width
7655        .checked_mul(std::mem::size_of::<f32>() as u32)
7656        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7657    Ok(wgpu::Extent3d {
7658        width,
7659        height,
7660        depth_or_array_layers: 1,
7661    })
7662}
7663
7664fn clone_scalar_field_for_restore(
7665    source: &ScalarField,
7666) -> Result<ScalarField, ScalarFieldTextureError> {
7667    let requested_bytes = source
7668        .values()
7669        .len()
7670        .checked_mul(std::mem::size_of::<f32>())
7671        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7672    let mut values = Vec::new();
7673    values
7674        .try_reserve_exact(source.values().len())
7675        .map_err(|_| ScalarFieldTextureError::AllocationFailed { requested_bytes })?;
7676    values.extend_from_slice(source.values());
7677    // The retained source already satisfies ScalarField's shape and finite
7678    // invariants. Keep the impossible defensive branch structured.
7679    ScalarField::new(source.width(), source.height(), values)
7680        .map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)
7681}
7682
7683fn scalar_value_range_extent(minimum: f32, maximum: f32) -> Option<f32> {
7684    if !is_portable_shader_source(minimum)
7685        || !is_portable_shader_source(maximum)
7686        || maximum <= minimum
7687    {
7688        return None;
7689    }
7690    let extent = maximum - minimum;
7691    (is_portable_shader_source(extent) && extent > 0.0).then_some(extent)
7692}
7693
7694fn scalar_field_sources_are_portable(field: &ScalarField) -> bool {
7695    if field
7696        .values()
7697        .iter()
7698        .copied()
7699        .any(|value| !is_portable_shader_source(value))
7700    {
7701        return false;
7702    }
7703    let (minimum, maximum) = field.value_range();
7704    let extent = f64::from(maximum) - f64::from(minimum);
7705    extent.is_finite() && extent <= f64::from(MAX_PORTABLE_SHADER_VALUE)
7706}
7707
7708fn scalar_normalization_is_portable(
7709    texture: &ScalarFieldTexture,
7710    minimum: f32,
7711    value_extent: f32,
7712) -> bool {
7713    if !is_portable_shader_source(minimum)
7714        || !is_portable_shader_source(value_extent)
7715        || value_extent <= 0.0
7716    {
7717        return false;
7718    }
7719    let Some(numerator) = shader_interval_sum_range([
7720        (
7721            f64::from(texture.source_minimum),
7722            f64::from(texture.source_maximum),
7723        ),
7724        (-f64::from(minimum), -f64::from(minimum)),
7725    ]) else {
7726        return false;
7727    };
7728    [numerator.0, numerator.1].into_iter().all(|value| {
7729        let normalized = value / f64::from(value_extent);
7730        normalized.is_finite() && normalized.abs() <= f64::from(MAX_PORTABLE_SHADER_VALUE)
7731    })
7732}
7733
7734fn compact_scalar_field_for_retention(
7735    field: ScalarField,
7736) -> Result<ScalarField, ScalarFieldTextureError> {
7737    let requested_bytes = field
7738        .values()
7739        .len()
7740        .checked_mul(std::mem::size_of::<f32>())
7741        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7742    if field.value_allocation_bytes() <= requested_bytes {
7743        return Ok(field);
7744    }
7745    clone_scalar_field_for_restore(&field)
7746}
7747
7748fn premultiplied_wgpu_color(color: Color) -> wgpu::Color {
7749    let [red, green, blue, alpha] = color.to_array();
7750    wgpu::Color {
7751        r: f64::from(red * alpha),
7752        g: f64::from(green * alpha),
7753        b: f64::from(blue * alpha),
7754        a: f64::from(alpha),
7755    }
7756}
7757
7758fn create_scalar_field_texture(
7759    device: &wgpu::Device,
7760    field: &ScalarField,
7761) -> Result<wgpu::Texture, ScalarFieldTextureError> {
7762    let extent = scalar_field_extent(field)?;
7763    let limits = device.limits();
7764    if extent.width > limits.max_texture_dimension_2d
7765        || extent.height > limits.max_texture_dimension_2d
7766    {
7767        return Err(ScalarFieldTextureError::DimensionsTooLarge);
7768    }
7769    Ok(device.create_texture(&wgpu::TextureDescriptor {
7770        label: Some("sim-engine scalar field texture"),
7771        size: extent,
7772        mip_level_count: 1,
7773        sample_count: 1,
7774        dimension: wgpu::TextureDimension::D2,
7775        format: wgpu::TextureFormat::R32Float,
7776        usage: wgpu::TextureUsages::TEXTURE_BINDING
7777            | wgpu::TextureUsages::COPY_DST
7778            | wgpu::TextureUsages::COPY_SRC,
7779        view_formats: &[],
7780    }))
7781}
7782
7783fn validate_scalar_field_device_extent(
7784    device: &wgpu::Device,
7785    field: &ScalarField,
7786) -> Result<wgpu::Extent3d, ScalarFieldTextureError> {
7787    let extent = scalar_field_extent(field)?;
7788    let limit = device.limits().max_texture_dimension_2d;
7789    if extent.width > limit || extent.height > limit {
7790        return Err(ScalarFieldTextureError::DimensionsTooLarge);
7791    }
7792    Ok(extent)
7793}
7794
7795fn upload_scalar_field_texture(
7796    queue: &wgpu::Queue,
7797    texture: &wgpu::Texture,
7798    field: &ScalarField,
7799) -> Result<(), ScalarFieldTextureError> {
7800    let extent = scalar_field_extent(field)?;
7801    queue.write_texture(
7802        wgpu::TexelCopyTextureInfo {
7803            texture,
7804            mip_level: 0,
7805            origin: wgpu::Origin3d::ZERO,
7806            aspect: wgpu::TextureAspect::All,
7807        },
7808        bytemuck::cast_slice(field.values()),
7809        wgpu::TexelCopyBufferLayout {
7810            offset: 0,
7811            bytes_per_row: Some(extent.width * std::mem::size_of::<f32>() as u32),
7812            rows_per_image: Some(extent.height),
7813        },
7814        extent,
7815    );
7816    submit_pending_uploads(queue);
7817    Ok(())
7818}
7819
7820fn upload_scalar_field_texture_region(
7821    queue: &wgpu::Queue,
7822    texture: &wgpu::Texture,
7823    x: usize,
7824    y: usize,
7825    width: usize,
7826    height: usize,
7827    values: &[f32],
7828) -> Result<(), ScalarFieldTextureError> {
7829    let width = u32::try_from(width).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7830    let height = u32::try_from(height).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7831    let x = u32::try_from(x).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7832    let y = u32::try_from(y).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7833    let bytes_per_row = width
7834        .checked_mul(std::mem::size_of::<f32>() as u32)
7835        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7836    queue.write_texture(
7837        wgpu::TexelCopyTextureInfo {
7838            texture,
7839            mip_level: 0,
7840            origin: wgpu::Origin3d { x, y, z: 0 },
7841            aspect: wgpu::TextureAspect::All,
7842        },
7843        bytemuck::cast_slice(values),
7844        wgpu::TexelCopyBufferLayout {
7845            offset: 0,
7846            bytes_per_row: Some(bytes_per_row),
7847            rows_per_image: Some(height),
7848        },
7849        wgpu::Extent3d {
7850            width,
7851            height,
7852            depth_or_array_layers: 1,
7853        },
7854    );
7855    submit_pending_uploads(queue);
7856    Ok(())
7857}
7858
7859/// Submits deferred `Queue::write_*` transfers without waiting for GPU completion.
7860///
7861/// Native `wgpu` retains staging allocations until a queue submission starts
7862/// their transfer. Standalone retained-resource mutations call this immediately;
7863/// render paths instead combine their writes with the draw submission.
7864pub(super) fn submit_pending_uploads(queue: &wgpu::Queue) {
7865    let _ = queue.submit([]);
7866}
7867
7868#[allow(clippy::too_many_arguments)]
7869fn validate_scalar_field_texture_region(
7870    texture_width: usize,
7871    texture_height: usize,
7872    x: usize,
7873    y: usize,
7874    width: usize,
7875    height: usize,
7876    value_count: usize,
7877) -> Result<(), ScalarFieldTextureError> {
7878    let expected = width
7879        .checked_mul(height)
7880        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7881    if value_count != expected {
7882        return Err(ScalarFieldTextureError::InvalidUpdateValueCount);
7883    }
7884    if width == 0
7885        || height == 0
7886        || x.checked_add(width).is_none_or(|end| end > texture_width)
7887        || y.checked_add(height).is_none_or(|end| end > texture_height)
7888    {
7889        return Err(ScalarFieldTextureError::UpdateRegionOutOfBounds);
7890    }
7891    for value in [x, y, width, height] {
7892        u32::try_from(value).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7893    }
7894    u32::try_from(width)
7895        .ok()
7896        .and_then(|width| width.checked_mul(std::mem::size_of::<f32>() as u32))
7897        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7898    Ok(())
7899}
7900
7901fn scalar_region_result_range(
7902    field: &ScalarField,
7903    x: usize,
7904    y: usize,
7905    width: usize,
7906    height: usize,
7907    values: &[f32],
7908) -> (f32, f32) {
7909    let mut minimum = f32::INFINITY;
7910    let mut maximum = f32::NEG_INFINITY;
7911    for row in 0..field.height() {
7912        for column in 0..field.width() {
7913            let value = if (x..x + width).contains(&column) && (y..y + height).contains(&row) {
7914                values[(row - y) * width + (column - x)]
7915            } else {
7916                field.values()[row * field.width() + column]
7917            };
7918            minimum = minimum.min(value);
7919            maximum = maximum.max(value);
7920        }
7921    }
7922    (minimum, maximum)
7923}
7924
7925fn create_scalar_field_texture_resources(
7926    device: &wgpu::Device,
7927    queue: &wgpu::Queue,
7928    renderer_identity: Arc<()>,
7929    field: ScalarField,
7930) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
7931    validate_scalar_field_device_extent(device, &field)?;
7932    if !scalar_field_sources_are_portable(&field) {
7933        return Err(ScalarFieldTextureError::NonPortableValue);
7934    }
7935    let field = compact_scalar_field_for_retention(field)?;
7936    let (source_minimum, source_maximum) = field.value_range();
7937    let texture = create_scalar_field_texture(device, &field)?;
7938    upload_scalar_field_texture(queue, &texture, &field)?;
7939    Ok(ScalarFieldTexture {
7940        renderer_identity,
7941        texture,
7942        field,
7943        source_minimum,
7944        source_maximum,
7945    })
7946}
7947
7948fn color_map_lut(color_map: &ColorMap) -> [u8; COLOR_MAP_LUT_SIZE as usize * 4] {
7949    let mut bytes = [0_u8; COLOR_MAP_LUT_SIZE as usize * 4];
7950    for index in 0..COLOR_MAP_LUT_SIZE {
7951        let color = color_map.sample_normalized(index as f32 / (COLOR_MAP_LUT_SIZE - 1) as f32);
7952        let offset = index as usize * 4;
7953        bytes[offset..offset + 4].copy_from_slice(
7954            &color
7955                .to_array()
7956                .map(|channel| (channel * 255.0).round() as u8),
7957        );
7958    }
7959    bytes
7960}
7961
7962fn create_cached_color_map(
7963    device: &wgpu::Device,
7964    queue: &wgpu::Queue,
7965    lut: [u8; COLOR_MAP_LUT_SIZE as usize * 4],
7966) -> CachedColorMap {
7967    let texture = device.create_texture(&wgpu::TextureDescriptor {
7968        label: Some("sim-engine color map texture"),
7969        size: wgpu::Extent3d {
7970            width: COLOR_MAP_LUT_SIZE,
7971            height: 1,
7972            depth_or_array_layers: 1,
7973        },
7974        mip_level_count: 1,
7975        sample_count: 1,
7976        dimension: wgpu::TextureDimension::D2,
7977        format: wgpu::TextureFormat::Rgba8Unorm,
7978        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
7979        view_formats: &[],
7980    });
7981    queue.write_texture(
7982        wgpu::TexelCopyTextureInfo {
7983            texture: &texture,
7984            mip_level: 0,
7985            origin: wgpu::Origin3d::ZERO,
7986            aspect: wgpu::TextureAspect::All,
7987        },
7988        &lut,
7989        wgpu::TexelCopyBufferLayout {
7990            offset: 0,
7991            bytes_per_row: Some(1024),
7992            rows_per_image: Some(1),
7993        },
7994        wgpu::Extent3d {
7995            width: COLOR_MAP_LUT_SIZE,
7996            height: 1,
7997            depth_or_array_layers: 1,
7998        },
7999    );
8000    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
8001    CachedColorMap {
8002        lut,
8003        _texture: texture,
8004        view,
8005    }
8006}
8007
8008fn create_submitted_particle_unit_buffer(
8009    device: &wgpu::Device,
8010    queue: &wgpu::Queue,
8011) -> wgpu::Buffer {
8012    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
8013        label: Some("sim-engine particle unit quad buffer"),
8014        size: (6 * std::mem::size_of::<ParticleUnitVertex>()) as wgpu::BufferAddress,
8015        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
8016        mapped_at_creation: false,
8017    });
8018    let unit_quad = [
8019        ParticleUnitVertex {
8020            direction: [-1.0, -1.0],
8021        },
8022        ParticleUnitVertex {
8023            direction: [1.0, -1.0],
8024        },
8025        ParticleUnitVertex {
8026            direction: [1.0, 1.0],
8027        },
8028        ParticleUnitVertex {
8029            direction: [-1.0, -1.0],
8030        },
8031        ParticleUnitVertex {
8032            direction: [1.0, 1.0],
8033        },
8034        ParticleUnitVertex {
8035            direction: [-1.0, 1.0],
8036        },
8037    ];
8038    queue.write_buffer(&buffer, 0, bytemuck::cast_slice(&unit_quad));
8039    submit_pending_uploads(queue);
8040    buffer
8041}
8042
8043fn create_particle_instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
8044    device.create_buffer(&wgpu::BufferDescriptor {
8045        label: Some("sim-engine particle instance buffer"),
8046        size: (capacity.max(1) * std::mem::size_of::<ParticleGpu>()) as wgpu::BufferAddress,
8047        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
8048        mapped_at_creation: false,
8049    })
8050}
8051
8052mod config;
8053mod exact_markers;
8054mod frame;
8055mod geometry;
8056mod glyph;
8057mod image;
8058mod mesh3d;
8059mod tessellation;
8060#[cfg(feature = "text")]
8061mod text;
8062#[cfg(feature = "text")]
8063pub use text::{TextAtlas2d, TextAtlasBudget, TextError, TextRun2d, TextUpdateReport};
8064mod visualization;
8065use config::{
8066    MultisampleTarget, create_multisample_target, logical_to_physical_screen,
8067    physical_to_logical_screen, validate_scale_factor, validate_surface_dimensions,
8068};
8069pub use config::{RendererPresentMode, RendererSurfacePresentMode, WgpuRendererOptions};
8070pub use frame::{
8071    FrameBudget, FrameBudgetResource, FrameCacheBudget, FrameCacheStatistics, FrameComposer,
8072    FrameComposerError, FramePassOptions, FrameReport, FrameSourceKind, FrameSourceStatistics,
8073    FrameStatistics,
8074};
8075pub use glyph::{
8076    GlyphAtlas2d, GlyphAtlasBudget, GlyphAtlasEntry, GlyphError, GlyphId, GlyphRun2d,
8077    GlyphRunBounds, GlyphRunBudget, GlyphRunStatistics, GlyphRunUploadReport, GlyphUploadReport,
8078    PositionedGlyph2d,
8079};
8080pub use image::{
8081    Image2d, ImageBatch2d, ImageBatchBudget, ImageBatchPlacement, ImageBatchUploadReport,
8082    ImageBudget, ImageError, ImageSampling, ImageSprite2d, ImageTexelRect, ImageUploadReport,
8083};
8084use image::{ImageRenderer, ImageUniform};
8085use mesh3d::Mesh3dRenderer;
8086pub use mesh3d::{
8087    Mesh3dInstance, Mesh3dObjectError, Mesh3dPreflightReport, Mesh3dRenderBudget,
8088    Mesh3dRenderError, Mesh3dRenderReport, Mesh3dResourceError, Mesh3dUploadBudget,
8089    Mesh3dUploadBudgetResource, Mesh3dUploadReport, Object3dId, RenderTarget3d, RetainedMesh3d,
8090    Scene3d, Scene3dBudget, Scene3dBudgetResource, Scene3dError, Scene3dMeshUpdateReport,
8091    Scene3dRestoreReport, Scene3dStatistics, Texture3d, Texture3dError, TextureMaterial3d,
8092};
8093use tessellation::{
8094    logical_viewport_scissor, offset_scissor, screen_clip_to_scissor, tessellate_scene,
8095};
8096use visualization::{CachedColorMap, CompositionPipelines, create_composition_pipeline};
8097pub use visualization::{
8098    LayeredVisualizationError, LayeredVisualizationOptions, LayeredVisualizationReport,
8099};
8100
8101#[cfg(test)]
8102use tessellation::world_vertex;
8103
8104#[cfg(test)]
8105mod tests;