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
555mod validation2d;
556#[cfg(test)]
557use validation2d::{
558    GEOMETRY_VALIDATION_CACHE_CAPACITY, dynamic_triangle_topology_is_portable,
559    geometry_vertex_centers_are_portable, logical_stroke_branches_are_stable,
560    logical_stroke_vertex_screen_ranges, shader_interval_sum_is_safe, shader_stroke_screen_bounds,
561    tessellated_triangle_topology_is_portable, tessellated_vertex_clip_ranges,
562};
563use validation2d::{
564    GeometryValidationCache, GeometryValidationSource, center_axis,
565    clip_triangle_has_stable_signed_area, clip_triangle_is_wholly_outside, geometry_is_safe_for,
566    geometry_is_safe_for_cached, geometry_sources_are_portable, interval_products_f64,
567    is_nonzero_subnormal, range_abs, range_dot, range_negate, range_vector_add, range_vector_scale,
568    rounded_f32_add_range, rounded_f32_product_range, screen_ranges_to_clip,
569    shader_clip_interval_is_safe, shader_direction_dot_range, shader_interval_sum_range,
570    shader_relative_component_bounds, shader_world_dot_range, stroke_safe_unit_range,
571    tessellated_vertex_base_screen_ranges, triangle_position_sources_equal,
572};
573
574mod primitive_targets;
575mod screen_primitives;
576pub use screen_primitives::{
577    ScreenPrimitive2d, ScreenPrimitiveBatch2d, ScreenPrimitiveBudget, ScreenPrimitiveError,
578    ScreenPrimitiveUploadReport,
579};
580
581mod outcomes;
582pub use outcomes::{
583    PreparedSceneError, PreparedSceneRenderError, RenderReport, RenderStatus,
584    RendererConfigurationError, RendererCoordinateError, RendererFrameError, RendererFrameMetrics,
585    RendererInitError, RendererPreparationMetrics, RendererSurfaceStatus,
586};
587
588/// Immutable scene geometry tessellated and uploaded once for repeated drawing.
589///
590/// Camera movement, zoom, rotation, projection tilt, viewport resizing, and DPI
591/// changes do not invalidate prepared geometry. Shape, style, gradient, layer,
592/// or clip changes require preparing a replacement. A prepared scene can only be
593/// rendered by the [`WgpuRenderer`] that created it. Use
594/// [`WgpuRenderer::restore_prepared_scene`] to recreate its GPU buffer for a
595/// replacement renderer after device loss. Portable shader arithmetic is proved
596/// once per exact camera/viewport uniform and retained in a bounded cache.
597pub struct PreparedScene {
598    renderer_identity: Arc<()>,
599    background: Color,
600    vertex_buffer: Arc<wgpu::Buffer>,
601    vertices: Arc<Vec<Vertex>>,
602    command_count: usize,
603    vertex_count: usize,
604    geometry_extents: GeometryExtents,
605    draw_batches: Vec<PreparedDrawBatch>,
606    tessellation: TessellationStats,
607    geometry_validation_cache: GeometryValidationCache,
608}
609
610/// Immutable prepared geometry whose positions are logical screen pixels.
611///
612/// This distinct wrapper prevents a world camera from being supplied to fixed
613/// UI geometry. It is created by [`WgpuRenderer::prepare_screen_scene`].
614pub struct PreparedScreenScene {
615    scene: PreparedScene,
616}
617
618impl PreparedScene {
619    /// Returns the number of accepted source scene commands.
620    pub fn command_count(&self) -> usize {
621        self.command_count
622    }
623
624    /// Returns the number of triangle-list vertices stored in the GPU buffer.
625    pub fn vertex_count(&self) -> usize {
626        self.vertex_count
627    }
628
629    /// Returns the number of clip-compatible draw batches.
630    pub fn draw_batch_count(&self) -> usize {
631        self.draw_batches.len()
632    }
633
634    /// Returns currently allocated CPU recovery bytes for vertices and draw batches.
635    pub fn recovery_memory_bytes(&self) -> usize {
636        self.vertices
637            .capacity()
638            .saturating_mul(std::mem::size_of::<Vertex>())
639            .saturating_add(
640                self.draw_batches
641                    .capacity()
642                    .saturating_mul(std::mem::size_of::<PreparedDrawBatch>()),
643            )
644    }
645
646    /// Returns command-level tessellation results captured during preparation.
647    pub fn tessellation_stats(&self) -> TessellationStats {
648        self.tessellation
649    }
650}
651
652impl PreparedScreenScene {
653    /// Returns the number of accepted source screen commands.
654    pub fn command_count(&self) -> usize {
655        self.scene.command_count()
656    }
657
658    /// Returns the retained triangle-list vertex count.
659    pub fn vertex_count(&self) -> usize {
660        self.scene.vertex_count()
661    }
662
663    /// Returns the number of clip-compatible draw batches.
664    pub fn draw_batch_count(&self) -> usize {
665        self.scene.draw_batch_count()
666    }
667
668    /// Returns retained CPU bytes available for device-loss recovery.
669    pub fn recovery_memory_bytes(&self) -> usize {
670        self.scene.recovery_memory_bytes()
671    }
672
673    /// Returns preparation-time tessellation statistics.
674    pub fn tessellation_stats(&self) -> TessellationStats {
675        self.scene.tessellation_stats()
676    }
677}
678
679/// `wgpu` backend that renders [`Scene`] commands into a presentation surface.
680///
681/// The renderer owns the GPU device, queue, surface, pipeline, and transient
682/// vertex buffer. Window creation stays outside the library so each application
683/// can choose its own windowing framework.
684pub struct WgpuRenderer {
685    renderer_identity: Arc<()>,
686    _instance: wgpu::Instance,
687    surface: wgpu::Surface<'static>,
688    _adapter: wgpu::Adapter,
689    adapter_info: wgpu::AdapterInfo,
690    device: wgpu::Device,
691    queue: wgpu::Queue,
692    config: wgpu::SurfaceConfiguration,
693    requested_present_mode: RendererPresentMode,
694    surface_present_mode: RendererSurfacePresentMode,
695    pre_present_notify: Option<Arc<dyn Fn() + Send + Sync>>,
696    scale_factor: f64,
697    pipeline: wgpu::RenderPipeline,
698    target_pipeline: wgpu::RenderPipeline,
699    screen_primitive_pipeline: wgpu::RenderPipeline,
700    target_screen_primitive_pipeline: wgpu::RenderPipeline,
701    dynamic_pipeline: wgpu::RenderPipeline,
702    particle_pipeline: wgpu::RenderPipeline,
703    target_particle_pipeline: wgpu::RenderPipeline,
704    heatmap_pipeline: wgpu::RenderPipeline,
705    target_heatmap_pipeline: wgpu::RenderPipeline,
706    composition_pipelines: CompositionPipelines,
707    target_composition_pipelines: CompositionPipelines,
708    image_renderer: ImageRenderer,
709    mesh3d_renderer: Mesh3dRenderer,
710    gpu_timing: gpu_timing::GpuTimingCollector,
711    gpu_timing_requested: bool,
712    camera_uniform_buffer: wgpu::Buffer,
713    camera_bind_group: wgpu::BindGroup,
714    camera_bind_group_layout: wgpu::BindGroupLayout,
715    heatmap_uniform_buffer: wgpu::Buffer,
716    heatmap_bind_group_layout: wgpu::BindGroupLayout,
717    color_map_cache: Option<CachedColorMap>,
718    frame_cache: frame::FrameCache,
719    vertex_buffer: Arc<wgpu::Buffer>,
720    particle_unit_buffer: wgpu::Buffer,
721    vertex_capacity: usize,
722    multisample_target: Option<MultisampleTarget>,
723    sample_count: u32,
724    vertices: Vec<Vertex>,
725    draw_batches: Vec<PreparedDrawBatch>,
726    retired_devices: Vec<RetiredDevice>,
727    max_quarantined_devices: usize,
728}
729
730struct RetiredDevice {
731    _adapter: wgpu::Adapter,
732    _device: wgpu::Device,
733    _queue: wgpu::Queue,
734}
735
736fn invoke_pre_present_notify(
737    present_mode: RendererSurfacePresentMode,
738    notify: Option<&(dyn Fn() + Send + Sync)>,
739) {
740    if present_mode.is_refresh_synchronized()
741        && let Some(notify) = notify
742    {
743        notify();
744    }
745}
746
747fn prepared_scene_belongs_to(renderer_identity: &Arc<()>, scene_identity: &Arc<()>) -> bool {
748    Arc::ptr_eq(renderer_identity, scene_identity)
749}
750
751fn render_target_allocation_bytes(
752    format: wgpu::TextureFormat,
753    width: u32,
754    height: u32,
755) -> Option<usize> {
756    let bytes_per_texel = u64::from(format.block_copy_size(None)?);
757    let byte_count = u64::from(width)
758        .checked_mul(u64::from(height))?
759        .checked_mul(bytes_per_texel)?;
760    usize::try_from(byte_count).ok()
761}
762
763fn dynamic_vertices_to_gpu(
764    vertices: &[DynamicVertex2d],
765) -> Result<Vec<DynamicGpu>, DynamicMeshError> {
766    validate_dynamic_vertices(vertices)?;
767    let requested_bytes = dynamic_mesh_bytes(vertices.len())?;
768    let mut converted = Vec::new();
769    converted
770        .try_reserve_exact(vertices.len())
771        .map_err(|_| DynamicMeshError::AllocationFailed { requested_bytes })?;
772    converted.extend(vertices.iter().copied().map(dynamic_vertex_to_gpu));
773    Ok(converted)
774}
775
776fn replace_dynamic_mesh_resources(
777    device: &wgpu::Device,
778    queue: &wgpu::Queue,
779    mesh: &mut DynamicMesh2d,
780    vertices: &[DynamicVertex2d],
781) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
782    let update_started_at = Instant::now();
783    validate_dynamic_vertices(vertices)?;
784    if let Some(budget) = mesh.budget {
785        validate_dynamic_mesh_budget(budget, vertices.len())?;
786    }
787    let reallocated = vertices.len() > mesh.vertex_capacity;
788    let replacement_capacity = if reallocated {
789        let capacity = dynamic_vertex_capacity(vertices.len())
790            .filter(|capacity| buffer_capacity_fits::<DynamicGpu>(device, *capacity))
791            .ok_or(DynamicMeshError::CapacityTooLarge)?;
792        Some(capacity)
793    } else {
794        None
795    };
796    let replacement_vertices = dynamic_vertices_to_gpu(vertices)?;
797    if let Some(budget) = mesh.budget {
798        validate_dynamic_retained_capacity(budget, &replacement_vertices)?;
799    }
800    let replacement = if let Some(capacity) = replacement_capacity {
801        let buffer = Arc::new(create_dynamic_vertex_buffer(device, capacity));
802        Some((buffer, capacity))
803    } else {
804        None
805    };
806    let upload_buffer = replacement
807        .as_ref()
808        .map_or(mesh.vertex_buffer.as_ref(), |(buffer, _)| buffer.as_ref());
809    if !replacement_vertices.is_empty() {
810        queue.write_buffer(
811            upload_buffer,
812            0,
813            bytemuck::cast_slice(&replacement_vertices),
814        );
815        submit_pending_uploads(queue);
816    }
817    if let Some((buffer, capacity)) = replacement {
818        mesh.vertex_buffer = buffer;
819        mesh.vertex_capacity = capacity;
820    }
821    mesh.geometry_extents = GeometryExtents::from_dynamic_vertices(&replacement_vertices);
822    mesh.vertices = replacement_vertices;
823    mesh.geometry_validation_cache.clear();
824    Ok(DynamicMeshUpdateReport {
825        vertex_count: mesh.vertices.len(),
826        upload: update_started_at.elapsed(),
827        reallocated,
828    })
829}
830
831fn dynamic_mesh_bytes(vertex_count: usize) -> Result<usize, DynamicMeshError> {
832    vertex_count
833        .checked_mul(std::mem::size_of::<DynamicGpu>())
834        .ok_or(DynamicMeshError::CapacityTooLarge)
835}
836
837fn validate_dynamic_mesh_budget(
838    budget: DynamicMeshBudget,
839    vertex_count: usize,
840) -> Result<(), DynamicMeshError> {
841    if u32::try_from(vertex_count).is_err() {
842        return Err(DynamicMeshError::CapacityTooLarge);
843    }
844    if vertex_count > budget.max_vertices {
845        return Err(DynamicMeshError::BudgetExceeded {
846            resource: DynamicMeshBudgetResource::Vertices,
847            limit: budget.max_vertices,
848            actual: vertex_count,
849        });
850    }
851    let bytes = dynamic_mesh_bytes(vertex_count)?;
852    if bytes > budget.max_retained_bytes {
853        return Err(DynamicMeshError::BudgetExceeded {
854            resource: DynamicMeshBudgetResource::RetainedBytes,
855            limit: budget.max_retained_bytes,
856            actual: bytes,
857        });
858    }
859    if bytes > budget.max_upload_bytes {
860        return Err(DynamicMeshError::BudgetExceeded {
861            resource: DynamicMeshBudgetResource::UploadBytes,
862            limit: budget.max_upload_bytes,
863            actual: bytes,
864        });
865    }
866    Ok(())
867}
868
869fn validate_dynamic_retained_capacity(
870    budget: DynamicMeshBudget,
871    vertices: &Vec<DynamicGpu>,
872) -> Result<(), DynamicMeshError> {
873    let actual = vertices
874        .capacity()
875        .checked_mul(std::mem::size_of::<DynamicGpu>())
876        .ok_or(DynamicMeshError::CapacityTooLarge)?;
877    if actual > budget.max_retained_bytes {
878        return Err(DynamicMeshError::BudgetExceeded {
879            resource: DynamicMeshBudgetResource::RetainedBytes,
880            limit: budget.max_retained_bytes,
881            actual,
882        });
883    }
884    Ok(())
885}
886
887fn validate_dynamic_vertices(vertices: &[DynamicVertex2d]) -> Result<(), DynamicMeshError> {
888    if u32::try_from(vertices.len()).is_err() {
889        return Err(DynamicMeshError::CapacityTooLarge);
890    }
891    if !vertices.len().is_multiple_of(3) {
892        return Err(DynamicMeshError::InvalidVertexCount);
893    }
894    if vertices.iter().any(|vertex| {
895        ![
896            vertex.world_position.x,
897            vertex.world_position.y,
898            vertex.depth,
899        ]
900        .into_iter()
901        .all(is_portable_shader_source)
902    }) {
903        return Err(DynamicMeshError::InvalidVertex);
904    }
905    // Private fields and the only public constructor make finiteness an
906    // invariant of DynamicVertex2d. Keep the assertion in development without
907    // rescanning an already-validated high-volume stream in release builds.
908    debug_assert!(vertices.iter().all(|vertex| {
909        vertex.world_position.is_finite()
910            && vertex.depth.is_finite()
911            && vertex.color.is_normalized()
912    }));
913    Ok(())
914}
915
916fn dynamic_vertex_to_gpu(vertex: DynamicVertex2d) -> DynamicGpu {
917    DynamicGpu {
918        world_position: [vertex.world_position.x, vertex.world_position.y],
919        depth: vertex.depth,
920        color: vertex.color.to_array(),
921    }
922}
923
924fn dynamic_vertex_capacity(vertex_count: usize) -> Option<usize> {
925    vertex_count.max(1).checked_next_power_of_two()
926}
927
928fn particle_instances_to_gpu(
929    instances: &[ParticleInstance2d],
930) -> Result<Vec<ParticleGpu>, ParticleFieldError> {
931    if u32::try_from(instances.len()).is_err() {
932        return Err(ParticleFieldError::CapacityTooLarge);
933    }
934    let requested_bytes = instances
935        .len()
936        .checked_mul(std::mem::size_of::<ParticleGpu>())
937        .ok_or(ParticleFieldError::CapacityTooLarge)?;
938    if instances.iter().copied().any(|instance| {
939        let world_position = instance.world_position();
940        let radius = instance.radius();
941        let color = instance.color();
942        let depth = instance.depth();
943        ![world_position.x, world_position.y, radius, depth]
944            .into_iter()
945            .all(is_portable_shader_source)
946            || radius <= 0.0
947            || !color.is_normalized()
948    }) {
949        return Err(ParticleFieldError::InvalidInstance);
950    }
951    let mut output = Vec::new();
952    output
953        .try_reserve_exact(instances.len())
954        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
955    output.extend(instances.iter().copied().map(|instance| {
956        let world_position = instance.world_position();
957        ParticleGpu {
958            world_position: [world_position.x, world_position.y],
959            depth: instance.depth(),
960            radius: instance.radius(),
961            color: instance.color().to_array(),
962        }
963    }));
964    Ok(output)
965}
966
967fn particle_retained_bytes(instance_count: usize) -> Option<usize> {
968    instance_count.checked_mul(std::mem::size_of::<ParticleGpu>())
969}
970
971fn validate_particle_retained_count(
972    instance_count: usize,
973    budget: ParticleRenderBudget,
974) -> Result<(), ParticleFieldError> {
975    let staging_count = particle_staging_target(instance_count, budget);
976    let retained_count = instance_count
977        .checked_add(staging_count)
978        .ok_or(ParticleFieldError::CapacityTooLarge)?;
979    let actual =
980        particle_retained_bytes(retained_count).ok_or(ParticleFieldError::CapacityTooLarge)?;
981    if actual > budget.max_retained_bytes {
982        return Err(ParticleFieldError::RetainedBudgetExceeded {
983            limit: budget.max_retained_bytes,
984            actual,
985        });
986    }
987    Ok(())
988}
989
990fn validate_particle_retained_capacities(
991    instance_capacity: usize,
992    staging_capacity: usize,
993    budget: ParticleRenderBudget,
994) -> Result<(), ParticleFieldError> {
995    let retained_capacity = instance_capacity
996        .checked_add(staging_capacity)
997        .ok_or(ParticleFieldError::CapacityTooLarge)?;
998    let actual =
999        particle_retained_bytes(retained_capacity).ok_or(ParticleFieldError::CapacityTooLarge)?;
1000    if actual > budget.max_retained_bytes {
1001        return Err(ParticleFieldError::RetainedBudgetExceeded {
1002            limit: budget.max_retained_bytes,
1003            actual,
1004        });
1005    }
1006    Ok(())
1007}
1008
1009fn compact_particle_instances(
1010    source: &[ParticleGpu],
1011    current_capacity: usize,
1012    staging_capacity: usize,
1013    budget: ParticleRenderBudget,
1014) -> Result<Option<Vec<ParticleGpu>>, ParticleFieldError> {
1015    validate_particle_retained_count(source.len(), budget)?;
1016    if validate_particle_retained_capacities(current_capacity, staging_capacity, budget).is_ok() {
1017        return Ok(None);
1018    }
1019    let requested_bytes =
1020        particle_retained_bytes(source.len()).ok_or(ParticleFieldError::CapacityTooLarge)?;
1021    let mut compact = Vec::new();
1022    compact
1023        .try_reserve_exact(source.len())
1024        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
1025    compact.extend_from_slice(source);
1026    validate_particle_retained_capacities(compact.capacity(), staging_capacity, budget)?;
1027    Ok(Some(compact))
1028}
1029
1030fn particle_instance_capacity(instance_count: usize) -> Option<usize> {
1031    instance_count.max(1).checked_next_power_of_two()
1032}
1033
1034fn particle_budgeted_capacity(
1035    instance_count: usize,
1036    budget: ParticleRenderBudget,
1037) -> Option<usize> {
1038    let limit = budget.instance_limit();
1039    let required = instance_count.min(limit).max(1);
1040    particle_instance_capacity(required).map(|capacity| capacity.min(limit))
1041}
1042
1043fn allocate_particle_staging(
1044    instance_count: usize,
1045    budget: ParticleRenderBudget,
1046) -> Result<Vec<ParticleGpu>, ParticleFieldError> {
1047    let target = particle_staging_target(instance_count, budget);
1048    let requested_bytes = target
1049        .checked_mul(std::mem::size_of::<ParticleGpu>())
1050        .ok_or(ParticleFieldError::CapacityTooLarge)?;
1051    let mut staging = Vec::new();
1052    staging
1053        .try_reserve_exact(target)
1054        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
1055    Ok(staging)
1056}
1057
1058fn particle_staging_target(instance_count: usize, budget: ParticleRenderBudget) -> usize {
1059    let visibility_checked = instance_count.min(budget.max_visibility_checks_per_frame);
1060    if visibility_checked < instance_count {
1061        visibility_checked
1062    } else {
1063        instance_count.min(budget.instance_limit())
1064    }
1065}
1066
1067fn buffer_allocation_bytes<T>(capacity: usize) -> Option<u64> {
1068    u64::try_from(capacity)
1069        .ok()?
1070        .checked_mul(std::mem::size_of::<T>() as u64)
1071}
1072
1073fn buffer_capacity_fits<T>(device: &wgpu::Device, capacity: usize) -> bool {
1074    buffer_allocation_bytes::<T>(capacity)
1075        .is_some_and(|bytes| bytes <= device.limits().max_buffer_size)
1076}
1077
1078fn scene_estimate_fits_prepared_device(scene: &Scene, device: &wgpu::Device) -> bool {
1079    buffer_capacity_fits::<Vertex>(
1080        device,
1081        scene.statistics().estimated_tessellated_vertices().max(1),
1082    )
1083}
1084
1085fn scene_estimate_fits_streaming_device(
1086    scene: &Scene,
1087    device: &wgpu::Device,
1088    prefix: usize,
1089    current_capacity: usize,
1090) -> bool {
1091    let Some(required) = prefix.checked_add(scene.statistics().estimated_tessellated_vertices())
1092    else {
1093        return false;
1094    };
1095    required <= current_capacity
1096        || dynamic_vertex_capacity(required)
1097            .is_some_and(|capacity| buffer_capacity_fits::<Vertex>(device, capacity))
1098}
1099
1100fn particle_update_range(
1101    first_instance: usize,
1102    replacement_count: usize,
1103    current_count: usize,
1104) -> Result<Range<usize>, ParticleFieldError> {
1105    let end = first_instance
1106        .checked_add(replacement_count)
1107        .ok_or(ParticleFieldError::UpdateRangeOutOfBounds)?;
1108    (end <= current_count)
1109        .then_some(first_instance..end)
1110        .ok_or(ParticleFieldError::UpdateRangeOutOfBounds)
1111}
1112
1113fn validate_particle_staging_capacity(
1114    instances: &Vec<ParticleGpu>,
1115    target_len: usize,
1116) -> Result<(), RendererFrameError> {
1117    let requested_bytes = target_len
1118        .checked_mul(std::mem::size_of::<ParticleGpu>())
1119        .ok_or(RendererFrameError::GeometryCapacityTooLarge)?;
1120    (instances.capacity() >= target_len)
1121        .then_some(())
1122        .ok_or(RendererFrameError::ParticleAllocationFailed { requested_bytes })
1123}
1124
1125#[cfg(test)]
1126fn visible_particle_instances(
1127    instances: &[ParticleGpu],
1128    camera: CameraUniform,
1129    viewport: LogicalViewport,
1130) -> Result<Vec<ParticleGpu>, RendererFrameError> {
1131    visible_particle_count(instances, camera, viewport)?;
1132    Ok(instances
1133        .iter()
1134        .copied()
1135        .filter(|instance| instance.intersects_viewport(camera, viewport))
1136        .collect())
1137}
1138
1139fn visible_particle_count(
1140    instances: &[ParticleGpu],
1141    camera: CameraUniform,
1142    viewport: LogicalViewport,
1143) -> Result<usize, RendererFrameError> {
1144    let mut visible = 0;
1145    for instance in instances.iter().copied() {
1146        let Some(intersects) = instance.validated_viewport_intersection(camera, viewport) else {
1147            return Err(RendererFrameError::InvalidGeometryTransform);
1148        };
1149        visible += usize::from(intersects);
1150    }
1151    Ok(visible)
1152}
1153
1154fn particle_visible_index_is_selected(
1155    visible_index: usize,
1156    visible_count: usize,
1157    selected_count: usize,
1158) -> bool {
1159    if visible_count == 0 || selected_count == 0 {
1160        return false;
1161    }
1162    let before = visible_index as u128 * selected_count as u128 / visible_count as u128;
1163    let after = (visible_index as u128 + 1) * selected_count as u128 / visible_count as u128;
1164    before < after
1165}
1166
1167fn uniformly_sampled_index(sample_index: usize, source_count: usize, sample_count: usize) -> usize {
1168    debug_assert!(sample_index < sample_count);
1169    debug_assert!(sample_count <= source_count);
1170    (((sample_index as u128 + 1) * source_count as u128 - 1) / sample_count as u128) as usize
1171}
1172
1173fn particle_idle_statistics(instance_count: usize) -> ParticleStatistics {
1174    ParticleStatistics {
1175        submitted: instance_count,
1176        visibility_checked: 0,
1177        visible: 0,
1178        culled: 0,
1179        budget_limited: 0,
1180        dropped: 0,
1181        rendered: 0,
1182    }
1183}
1184
1185#[cfg(test)]
1186fn particle_statistics(
1187    instance_count: usize,
1188    visible: usize,
1189    rendered: usize,
1190) -> ParticleStatistics {
1191    particle_statistics_with_budget(instance_count, instance_count, visible, visible, rendered)
1192}
1193
1194fn particle_statistics_with_budget(
1195    instance_count: usize,
1196    visibility_checked: usize,
1197    visible: usize,
1198    selected: usize,
1199    rendered: usize,
1200) -> ParticleStatistics {
1201    ParticleStatistics {
1202        submitted: instance_count,
1203        visibility_checked,
1204        visible,
1205        culled: visibility_checked.saturating_sub(visible),
1206        budget_limited: instance_count
1207            .saturating_sub(visibility_checked)
1208            .saturating_add(visible.saturating_sub(selected)),
1209        dropped: 0,
1210        rendered,
1211    }
1212}
1213
1214fn prepare_scene_resources(
1215    device: &wgpu::Device,
1216    queue: &wgpu::Queue,
1217    renderer_identity: Arc<()>,
1218    scene: &Scene,
1219) -> Result<PreparedScene, PreparedSceneError> {
1220    if !scene_command_sources_are_portable(scene) {
1221        return Err(PreparedSceneError::InvalidGeometrySources);
1222    }
1223    if !scene_estimate_fits_prepared_device(scene, device) {
1224        return Err(PreparedSceneError::CapacityTooLarge);
1225    }
1226    let mut vertices = Vec::new();
1227    let mut draw_batches = Vec::new();
1228    let tessellation = tessellate_scene(scene, &mut vertices, &mut draw_batches)?;
1229    let geometry_extents = GeometryExtents::from_vertices(&vertices);
1230    if !geometry_sources_are_portable(GeometryValidationSource::Tessellated(&vertices)) {
1231        return Err(PreparedSceneError::InvalidGeometrySources);
1232    }
1233    if !buffer_capacity_fits::<Vertex>(device, vertices.len().max(1)) {
1234        return Err(PreparedSceneError::CapacityTooLarge);
1235    }
1236    // Retain the tessellator allocation directly. Wrapping a Vec is O(1) and
1237    // avoids an infallible caller-scale Vec -> Arc<[T]> copy after GPU writes.
1238    let vertices = Arc::new(vertices);
1239    let vertex_buffer = Arc::new(create_vertex_buffer(device, vertices.len()));
1240    if !vertices.is_empty() {
1241        queue.write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
1242        submit_pending_uploads(queue);
1243    }
1244    let vertex_count = vertices.len();
1245
1246    Ok(PreparedScene {
1247        renderer_identity,
1248        background: scene.background(),
1249        vertex_buffer,
1250        vertices,
1251        command_count: scene.command_count(),
1252        vertex_count,
1253        geometry_extents,
1254        draw_batches,
1255        tessellation,
1256        geometry_validation_cache: GeometryValidationCache::default(),
1257    })
1258}
1259
1260fn scene_command_sources_are_portable(scene: &Scene) -> bool {
1261    scene.commands().iter().all(|command| {
1262        is_portable_shader_source(command.depth())
1263            && command.screen_clip().is_none_or(|clip| {
1264                portable_vec2(clip.min().to_vec2()) && portable_vec2(clip.max().to_vec2())
1265            })
1266            && match command.command() {
1267                DrawCommand::Circle(circle) => {
1268                    portable_vec2(circle.center())
1269                        && is_portable_shader_source(circle.radius())
1270                        && portable_shape_style(circle.style())
1271                }
1272                DrawCommand::Rect(rectangle) => {
1273                    portable_vec2(rectangle.rect().min())
1274                        && portable_vec2(rectangle.rect().max())
1275                        && is_portable_shader_source(rectangle.corner_radius())
1276                        && portable_shape_style(rectangle.style())
1277                }
1278                DrawCommand::Line(line) => {
1279                    portable_vec2(line.from())
1280                        && portable_vec2(line.to())
1281                        && portable_stroke_style(line.stroke_style())
1282                }
1283                DrawCommand::Polyline(polyline) => {
1284                    polyline.points().iter().copied().all(portable_vec2)
1285                        && portable_stroke_style(polyline.stroke_style())
1286                }
1287            }
1288    })
1289}
1290
1291fn portable_vec2(value: Vec2) -> bool {
1292    is_portable_shader_source(value.x) && is_portable_shader_source(value.y)
1293}
1294
1295fn portable_shape_style(style: ShapeStyle) -> bool {
1296    style
1297        .stroke()
1298        .is_none_or(|stroke| is_portable_shader_source(stroke.width()))
1299        && style.shadow().is_none_or(|shadow| {
1300            portable_vec2(shadow.offset().to_vec2()) && is_portable_shader_source(shadow.spread())
1301        })
1302}
1303
1304fn portable_stroke_style(style: crate::StrokeStyle2d) -> bool {
1305    let stroke = style.stroke();
1306    is_portable_shader_source(stroke.width())
1307        && is_portable_shader_source(style.miter_limit())
1308        && style.dash_pattern().is_none_or(|dash| {
1309            dash.lengths()
1310                .iter()
1311                .copied()
1312                .chain([dash.phase()])
1313                .all(is_portable_shader_source)
1314        })
1315        && style.start_marker().is_none_or(|marker| {
1316            is_portable_shader_source(marker.length().get())
1317                && is_portable_shader_source(marker.width().get())
1318        })
1319        && style.end_marker().is_none_or(|marker| {
1320            is_portable_shader_source(marker.length().get())
1321                && is_portable_shader_source(marker.width().get())
1322        })
1323}
1324
1325fn restore_prepared_scene_resources(
1326    device: &wgpu::Device,
1327    queue: &wgpu::Queue,
1328    renderer_identity: Arc<()>,
1329    source: &PreparedScene,
1330) -> Result<PreparedScene, PreparedSceneError> {
1331    if !buffer_capacity_fits::<Vertex>(device, source.vertices.len().max(1)) {
1332        return Err(PreparedSceneError::CapacityTooLarge);
1333    }
1334    if !geometry_sources_are_portable(GeometryValidationSource::Tessellated(&source.vertices)) {
1335        return Err(PreparedSceneError::InvalidGeometrySources);
1336    }
1337    let requested_bytes = source
1338        .draw_batches
1339        .len()
1340        .checked_mul(std::mem::size_of::<PreparedDrawBatch>())
1341        .ok_or(PreparedSceneError::CapacityTooLarge)?;
1342    let mut draw_batches = Vec::new();
1343    draw_batches
1344        .try_reserve_exact(source.draw_batches.len())
1345        .map_err(|_| PreparedSceneError::AllocationFailed { requested_bytes })?;
1346    draw_batches.extend_from_slice(&source.draw_batches);
1347    let vertex_buffer = Arc::new(create_vertex_buffer(device, source.vertices.len()));
1348    if !source.vertices.is_empty() {
1349        queue.write_buffer(
1350            &vertex_buffer,
1351            0,
1352            bytemuck::cast_slice(source.vertices.as_ref()),
1353        );
1354        submit_pending_uploads(queue);
1355    }
1356
1357    Ok(PreparedScene {
1358        renderer_identity,
1359        background: source.background,
1360        vertex_buffer,
1361        vertices: Arc::clone(&source.vertices),
1362        command_count: source.command_count,
1363        vertex_count: source.vertex_count,
1364        geometry_extents: source.geometry_extents,
1365        draw_batches,
1366        tessellation: source.tessellation,
1367        geometry_validation_cache: GeometryValidationCache::default(),
1368    })
1369}
1370
1371fn restore_dynamic_mesh_resources(
1372    device: &wgpu::Device,
1373    queue: &wgpu::Queue,
1374    renderer_identity: Arc<()>,
1375    source: &DynamicMesh2d,
1376) -> Result<DynamicMesh2d, DynamicMeshError> {
1377    if !buffer_capacity_fits::<DynamicGpu>(device, source.vertex_capacity) {
1378        return Err(DynamicMeshError::CapacityTooLarge);
1379    }
1380    if let Some(budget) = source.budget {
1381        validate_dynamic_mesh_budget(budget, source.vertices.len())?;
1382    }
1383    let requested_bytes = dynamic_mesh_bytes(source.vertices.len())?;
1384    let mut vertices = Vec::new();
1385    vertices
1386        .try_reserve_exact(source.vertices.len())
1387        .map_err(|_| DynamicMeshError::AllocationFailed { requested_bytes })?;
1388    vertices.extend_from_slice(&source.vertices);
1389    if let Some(budget) = source.budget {
1390        validate_dynamic_retained_capacity(budget, &vertices)?;
1391    }
1392    let vertex_buffer = Arc::new(create_dynamic_vertex_buffer(device, source.vertex_capacity));
1393    if !vertices.is_empty() {
1394        queue.write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(vertices.as_slice()));
1395        submit_pending_uploads(queue);
1396    }
1397    Ok(DynamicMesh2d {
1398        renderer_identity,
1399        vertex_buffer,
1400        vertices,
1401        vertex_capacity: source.vertex_capacity,
1402        geometry_extents: source.geometry_extents,
1403        geometry_validation_cache: GeometryValidationCache::default(),
1404        budget: source.budget,
1405    })
1406}
1407
1408fn restore_particle_field_resources(
1409    device: &wgpu::Device,
1410    _queue: &wgpu::Queue,
1411    renderer_identity: Arc<()>,
1412    source: &ParticleField2d,
1413) -> Result<ParticleField2d, ParticleFieldError> {
1414    validate_particle_retained_count(source.instances.len(), source.budget)?;
1415    if !buffer_capacity_fits::<ParticleGpu>(device, source.instance_capacity) {
1416        return Err(ParticleFieldError::CapacityTooLarge);
1417    }
1418    let requested_bytes = source
1419        .instances
1420        .len()
1421        .checked_mul(std::mem::size_of::<ParticleGpu>())
1422        .ok_or(ParticleFieldError::CapacityTooLarge)?;
1423    let mut instances = Vec::new();
1424    instances
1425        .try_reserve_exact(source.instances.len())
1426        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
1427    instances.extend_from_slice(&source.instances);
1428    let visible_instances = allocate_particle_staging(instances.len(), source.budget)?;
1429    validate_particle_retained_capacities(
1430        instances.capacity(),
1431        visible_instances.capacity(),
1432        source.budget,
1433    )?;
1434    let instance_buffer = Arc::new(create_particle_instance_buffer(
1435        device,
1436        source.instance_capacity,
1437    ));
1438    Ok(ParticleField2d {
1439        renderer_identity,
1440        instance_buffer,
1441        instances,
1442        visible_instances,
1443        instance_capacity: source.instance_capacity,
1444        budget: source.budget,
1445        statistics: particle_idle_statistics(source.instances.len()),
1446    })
1447}
1448
1449#[allow(clippy::too_many_arguments)]
1450fn render_report(
1451    status: RenderStatus,
1452    tessellation: Duration,
1453    upload: Duration,
1454    camera_uniform_upload: Duration,
1455    surface_acquire: Duration,
1456    encode_submit_present: Duration,
1457    total_cpu: Duration,
1458    geometry_reused: bool,
1459    geometry_streamed: bool,
1460    tessellation_stats: TessellationStats,
1461) -> RenderReport {
1462    RenderReport {
1463        status,
1464        metrics: RendererFrameMetrics {
1465            tessellation,
1466            upload,
1467            camera_uniform_upload,
1468            surface_acquire,
1469            encode_submit_present,
1470            total_cpu,
1471            geometry_reused,
1472            geometry_streamed,
1473            tessellation_stats,
1474            preparation: None,
1475        },
1476    }
1477}
1478
1479fn preferred_sample_count(adapter: &wgpu::Adapter, format: wgpu::TextureFormat) -> u32 {
1480    let flags = adapter.get_texture_format_features(format).flags;
1481    if flags.contains(
1482        wgpu::TextureFormatFeatureFlags::MULTISAMPLE_X4
1483            | wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
1484    ) {
1485        PREFERRED_SAMPLE_COUNT
1486    } else {
1487        1
1488    }
1489}
1490
1491fn create_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
1492    device.create_buffer(&wgpu::BufferDescriptor {
1493        label: Some("sim-engine vertex buffer"),
1494        size: (capacity.max(1) * std::mem::size_of::<Vertex>()) as wgpu::BufferAddress,
1495        usage: wgpu::BufferUsages::VERTEX
1496            | wgpu::BufferUsages::COPY_DST
1497            | wgpu::BufferUsages::COPY_SRC,
1498        mapped_at_creation: false,
1499    })
1500}
1501
1502fn create_dynamic_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
1503    device.create_buffer(&wgpu::BufferDescriptor {
1504        label: Some("sim-engine dynamic vertex buffer"),
1505        size: (capacity.max(1) * std::mem::size_of::<DynamicGpu>()) as wgpu::BufferAddress,
1506        usage: wgpu::BufferUsages::VERTEX
1507            | wgpu::BufferUsages::COPY_DST
1508            | wgpu::BufferUsages::COPY_SRC,
1509        mapped_at_creation: false,
1510    })
1511}
1512
1513fn scalar_field_extent(field: &ScalarField) -> Result<wgpu::Extent3d, ScalarFieldTextureError> {
1514    let width =
1515        u32::try_from(field.width()).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
1516    let height =
1517        u32::try_from(field.height()).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
1518    let _bytes_per_row = width
1519        .checked_mul(std::mem::size_of::<f32>() as u32)
1520        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
1521    Ok(wgpu::Extent3d {
1522        width,
1523        height,
1524        depth_or_array_layers: 1,
1525    })
1526}
1527
1528fn clone_scalar_field_for_restore(
1529    source: &ScalarField,
1530) -> Result<ScalarField, ScalarFieldTextureError> {
1531    let requested_bytes = source
1532        .values()
1533        .len()
1534        .checked_mul(std::mem::size_of::<f32>())
1535        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
1536    let mut values = Vec::new();
1537    values
1538        .try_reserve_exact(source.values().len())
1539        .map_err(|_| ScalarFieldTextureError::AllocationFailed { requested_bytes })?;
1540    values.extend_from_slice(source.values());
1541    // The retained source already satisfies ScalarField's shape and finite
1542    // invariants. Keep the impossible defensive branch structured.
1543    ScalarField::new(source.width(), source.height(), values)
1544        .map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)
1545}
1546
1547fn scalar_value_range_extent(minimum: f32, maximum: f32) -> Option<f32> {
1548    if !is_portable_shader_source(minimum)
1549        || !is_portable_shader_source(maximum)
1550        || maximum <= minimum
1551    {
1552        return None;
1553    }
1554    let extent = maximum - minimum;
1555    (is_portable_shader_source(extent) && extent > 0.0).then_some(extent)
1556}
1557
1558fn scalar_field_sources_are_portable(field: &ScalarField) -> bool {
1559    if field
1560        .values()
1561        .iter()
1562        .copied()
1563        .any(|value| !is_portable_shader_source(value))
1564    {
1565        return false;
1566    }
1567    let (minimum, maximum) = field.value_range();
1568    let extent = f64::from(maximum) - f64::from(minimum);
1569    extent.is_finite() && extent <= f64::from(MAX_PORTABLE_SHADER_VALUE)
1570}
1571
1572fn scalar_normalization_is_portable(
1573    texture: &ScalarFieldTexture,
1574    minimum: f32,
1575    value_extent: f32,
1576) -> bool {
1577    if !is_portable_shader_source(minimum)
1578        || !is_portable_shader_source(value_extent)
1579        || value_extent <= 0.0
1580    {
1581        return false;
1582    }
1583    let Some(numerator) = shader_interval_sum_range([
1584        (
1585            f64::from(texture.source_minimum),
1586            f64::from(texture.source_maximum),
1587        ),
1588        (-f64::from(minimum), -f64::from(minimum)),
1589    ]) else {
1590        return false;
1591    };
1592    [numerator.0, numerator.1].into_iter().all(|value| {
1593        let normalized = value / f64::from(value_extent);
1594        normalized.is_finite() && normalized.abs() <= f64::from(MAX_PORTABLE_SHADER_VALUE)
1595    })
1596}
1597
1598fn compact_scalar_field_for_retention(
1599    field: ScalarField,
1600) -> Result<ScalarField, ScalarFieldTextureError> {
1601    let requested_bytes = field
1602        .values()
1603        .len()
1604        .checked_mul(std::mem::size_of::<f32>())
1605        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
1606    if field.value_allocation_bytes() <= requested_bytes {
1607        return Ok(field);
1608    }
1609    clone_scalar_field_for_restore(&field)
1610}
1611
1612fn premultiplied_wgpu_color(color: Color) -> wgpu::Color {
1613    let [red, green, blue, alpha] = color.to_array();
1614    wgpu::Color {
1615        r: f64::from(red * alpha),
1616        g: f64::from(green * alpha),
1617        b: f64::from(blue * alpha),
1618        a: f64::from(alpha),
1619    }
1620}
1621
1622fn create_scalar_field_texture(
1623    device: &wgpu::Device,
1624    field: &ScalarField,
1625) -> Result<wgpu::Texture, ScalarFieldTextureError> {
1626    let extent = scalar_field_extent(field)?;
1627    let limits = device.limits();
1628    if extent.width > limits.max_texture_dimension_2d
1629        || extent.height > limits.max_texture_dimension_2d
1630    {
1631        return Err(ScalarFieldTextureError::DimensionsTooLarge);
1632    }
1633    Ok(device.create_texture(&wgpu::TextureDescriptor {
1634        label: Some("sim-engine scalar field texture"),
1635        size: extent,
1636        mip_level_count: 1,
1637        sample_count: 1,
1638        dimension: wgpu::TextureDimension::D2,
1639        format: wgpu::TextureFormat::R32Float,
1640        usage: wgpu::TextureUsages::TEXTURE_BINDING
1641            | wgpu::TextureUsages::COPY_DST
1642            | wgpu::TextureUsages::COPY_SRC,
1643        view_formats: &[],
1644    }))
1645}
1646
1647fn validate_scalar_field_device_extent(
1648    device: &wgpu::Device,
1649    field: &ScalarField,
1650) -> Result<wgpu::Extent3d, ScalarFieldTextureError> {
1651    let extent = scalar_field_extent(field)?;
1652    let limit = device.limits().max_texture_dimension_2d;
1653    if extent.width > limit || extent.height > limit {
1654        return Err(ScalarFieldTextureError::DimensionsTooLarge);
1655    }
1656    Ok(extent)
1657}
1658
1659fn upload_scalar_field_texture(
1660    queue: &wgpu::Queue,
1661    texture: &wgpu::Texture,
1662    field: &ScalarField,
1663) -> Result<(), ScalarFieldTextureError> {
1664    let extent = scalar_field_extent(field)?;
1665    queue.write_texture(
1666        wgpu::TexelCopyTextureInfo {
1667            texture,
1668            mip_level: 0,
1669            origin: wgpu::Origin3d::ZERO,
1670            aspect: wgpu::TextureAspect::All,
1671        },
1672        bytemuck::cast_slice(field.values()),
1673        wgpu::TexelCopyBufferLayout {
1674            offset: 0,
1675            bytes_per_row: Some(extent.width * std::mem::size_of::<f32>() as u32),
1676            rows_per_image: Some(extent.height),
1677        },
1678        extent,
1679    );
1680    submit_pending_uploads(queue);
1681    Ok(())
1682}
1683
1684fn upload_scalar_field_texture_region(
1685    queue: &wgpu::Queue,
1686    texture: &wgpu::Texture,
1687    x: usize,
1688    y: usize,
1689    width: usize,
1690    height: usize,
1691    values: &[f32],
1692) -> Result<(), ScalarFieldTextureError> {
1693    let width = u32::try_from(width).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
1694    let height = u32::try_from(height).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
1695    let x = u32::try_from(x).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
1696    let y = u32::try_from(y).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
1697    let bytes_per_row = width
1698        .checked_mul(std::mem::size_of::<f32>() as u32)
1699        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
1700    queue.write_texture(
1701        wgpu::TexelCopyTextureInfo {
1702            texture,
1703            mip_level: 0,
1704            origin: wgpu::Origin3d { x, y, z: 0 },
1705            aspect: wgpu::TextureAspect::All,
1706        },
1707        bytemuck::cast_slice(values),
1708        wgpu::TexelCopyBufferLayout {
1709            offset: 0,
1710            bytes_per_row: Some(bytes_per_row),
1711            rows_per_image: Some(height),
1712        },
1713        wgpu::Extent3d {
1714            width,
1715            height,
1716            depth_or_array_layers: 1,
1717        },
1718    );
1719    submit_pending_uploads(queue);
1720    Ok(())
1721}
1722
1723/// Submits deferred `Queue::write_*` transfers without waiting for GPU completion.
1724///
1725/// Native `wgpu` retains staging allocations until a queue submission starts
1726/// their transfer. Standalone retained-resource mutations call this immediately;
1727/// render paths instead combine their writes with the draw submission.
1728pub(super) fn submit_pending_uploads(queue: &wgpu::Queue) {
1729    let _ = queue.submit([]);
1730}
1731
1732#[allow(clippy::too_many_arguments)]
1733fn validate_scalar_field_texture_region(
1734    texture_width: usize,
1735    texture_height: usize,
1736    x: usize,
1737    y: usize,
1738    width: usize,
1739    height: usize,
1740    value_count: usize,
1741) -> Result<(), ScalarFieldTextureError> {
1742    let expected = width
1743        .checked_mul(height)
1744        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
1745    if value_count != expected {
1746        return Err(ScalarFieldTextureError::InvalidUpdateValueCount);
1747    }
1748    if width == 0
1749        || height == 0
1750        || x.checked_add(width).is_none_or(|end| end > texture_width)
1751        || y.checked_add(height).is_none_or(|end| end > texture_height)
1752    {
1753        return Err(ScalarFieldTextureError::UpdateRegionOutOfBounds);
1754    }
1755    for value in [x, y, width, height] {
1756        u32::try_from(value).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
1757    }
1758    u32::try_from(width)
1759        .ok()
1760        .and_then(|width| width.checked_mul(std::mem::size_of::<f32>() as u32))
1761        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
1762    Ok(())
1763}
1764
1765fn scalar_region_result_range(
1766    field: &ScalarField,
1767    x: usize,
1768    y: usize,
1769    width: usize,
1770    height: usize,
1771    values: &[f32],
1772) -> (f32, f32) {
1773    let mut minimum = f32::INFINITY;
1774    let mut maximum = f32::NEG_INFINITY;
1775    for row in 0..field.height() {
1776        for column in 0..field.width() {
1777            let value = if (x..x + width).contains(&column) && (y..y + height).contains(&row) {
1778                values[(row - y) * width + (column - x)]
1779            } else {
1780                field.values()[row * field.width() + column]
1781            };
1782            minimum = minimum.min(value);
1783            maximum = maximum.max(value);
1784        }
1785    }
1786    (minimum, maximum)
1787}
1788
1789fn create_scalar_field_texture_resources(
1790    device: &wgpu::Device,
1791    queue: &wgpu::Queue,
1792    renderer_identity: Arc<()>,
1793    field: ScalarField,
1794) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
1795    validate_scalar_field_device_extent(device, &field)?;
1796    if !scalar_field_sources_are_portable(&field) {
1797        return Err(ScalarFieldTextureError::NonPortableValue);
1798    }
1799    let field = compact_scalar_field_for_retention(field)?;
1800    let (source_minimum, source_maximum) = field.value_range();
1801    let texture = create_scalar_field_texture(device, &field)?;
1802    upload_scalar_field_texture(queue, &texture, &field)?;
1803    Ok(ScalarFieldTexture {
1804        renderer_identity,
1805        texture,
1806        field,
1807        source_minimum,
1808        source_maximum,
1809    })
1810}
1811
1812fn color_map_lut(color_map: &ColorMap) -> [u8; COLOR_MAP_LUT_SIZE as usize * 4] {
1813    let mut bytes = [0_u8; COLOR_MAP_LUT_SIZE as usize * 4];
1814    for index in 0..COLOR_MAP_LUT_SIZE {
1815        let color = color_map.sample_normalized(index as f32 / (COLOR_MAP_LUT_SIZE - 1) as f32);
1816        let offset = index as usize * 4;
1817        bytes[offset..offset + 4].copy_from_slice(
1818            &color
1819                .to_array()
1820                .map(|channel| (channel * 255.0).round() as u8),
1821        );
1822    }
1823    bytes
1824}
1825
1826fn create_cached_color_map(
1827    device: &wgpu::Device,
1828    queue: &wgpu::Queue,
1829    lut: [u8; COLOR_MAP_LUT_SIZE as usize * 4],
1830) -> CachedColorMap {
1831    let texture = device.create_texture(&wgpu::TextureDescriptor {
1832        label: Some("sim-engine color map texture"),
1833        size: wgpu::Extent3d {
1834            width: COLOR_MAP_LUT_SIZE,
1835            height: 1,
1836            depth_or_array_layers: 1,
1837        },
1838        mip_level_count: 1,
1839        sample_count: 1,
1840        dimension: wgpu::TextureDimension::D2,
1841        format: wgpu::TextureFormat::Rgba8Unorm,
1842        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1843        view_formats: &[],
1844    });
1845    queue.write_texture(
1846        wgpu::TexelCopyTextureInfo {
1847            texture: &texture,
1848            mip_level: 0,
1849            origin: wgpu::Origin3d::ZERO,
1850            aspect: wgpu::TextureAspect::All,
1851        },
1852        &lut,
1853        wgpu::TexelCopyBufferLayout {
1854            offset: 0,
1855            bytes_per_row: Some(1024),
1856            rows_per_image: Some(1),
1857        },
1858        wgpu::Extent3d {
1859            width: COLOR_MAP_LUT_SIZE,
1860            height: 1,
1861            depth_or_array_layers: 1,
1862        },
1863    );
1864    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
1865    CachedColorMap {
1866        lut,
1867        _texture: texture,
1868        view,
1869    }
1870}
1871
1872fn create_submitted_particle_unit_buffer(
1873    device: &wgpu::Device,
1874    queue: &wgpu::Queue,
1875) -> wgpu::Buffer {
1876    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
1877        label: Some("sim-engine particle unit quad buffer"),
1878        size: (6 * std::mem::size_of::<ParticleUnitVertex>()) as wgpu::BufferAddress,
1879        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1880        mapped_at_creation: false,
1881    });
1882    let unit_quad = [
1883        ParticleUnitVertex {
1884            direction: [-1.0, -1.0],
1885        },
1886        ParticleUnitVertex {
1887            direction: [1.0, -1.0],
1888        },
1889        ParticleUnitVertex {
1890            direction: [1.0, 1.0],
1891        },
1892        ParticleUnitVertex {
1893            direction: [-1.0, -1.0],
1894        },
1895        ParticleUnitVertex {
1896            direction: [1.0, 1.0],
1897        },
1898        ParticleUnitVertex {
1899            direction: [-1.0, 1.0],
1900        },
1901    ];
1902    queue.write_buffer(&buffer, 0, bytemuck::cast_slice(&unit_quad));
1903    submit_pending_uploads(queue);
1904    buffer
1905}
1906
1907fn create_particle_instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
1908    device.create_buffer(&wgpu::BufferDescriptor {
1909        label: Some("sim-engine particle instance buffer"),
1910        size: (capacity.max(1) * std::mem::size_of::<ParticleGpu>()) as wgpu::BufferAddress,
1911        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1912        mapped_at_creation: false,
1913    })
1914}
1915
1916mod config;
1917mod diagnostics;
1918mod dynamic_mesh;
1919mod exact_markers;
1920mod frame;
1921mod geometry;
1922mod glyph;
1923mod glyph_batch;
1924mod gpu_timing;
1925mod image;
1926mod initialization;
1927mod mesh3d;
1928mod particles;
1929mod pipelines;
1930mod scalar_fields;
1931mod scenes;
1932mod targets;
1933mod tessellation;
1934#[cfg(feature = "text")]
1935mod text;
1936#[cfg(feature = "text")]
1937pub use text::{
1938    PreparedTextError, TextAtlas2d, TextAtlasBudget, TextError, TextRun2d, TextUpdateReport,
1939};
1940mod visualization;
1941use config::{
1942    MultisampleTarget, create_multisample_target, logical_to_physical_screen,
1943    physical_to_logical_screen, validate_scale_factor, validate_surface_dimensions,
1944};
1945pub use config::{RendererPresentMode, RendererSurfacePresentMode, WgpuRendererOptions};
1946pub use diagnostics::RendererDiagnostics;
1947pub use dynamic_mesh::{
1948    DynamicMesh2d, DynamicMeshBudget, DynamicMeshBudgetResource, DynamicMeshError,
1949    DynamicMeshRenderError, DynamicMeshUpdateReport, DynamicVertex2d,
1950};
1951pub use frame::{
1952    FrameBudget, FrameBudgetResource, FrameCacheBudget, FrameCacheStatistics, FrameComposer,
1953    FrameComposerError, FramePassOptions, FrameReport, FrameSourceKind, FrameSourceStatistics,
1954    FrameStatistics,
1955};
1956pub use glyph::{
1957    GlyphAtlas2d, GlyphAtlasBudget, GlyphAtlasEntry, GlyphError, GlyphId, GlyphRun2d,
1958    GlyphRunBounds, GlyphRunBudget, GlyphRunStatistics, GlyphRunUploadReport, GlyphUploadReport,
1959    PositionedGlyph2d,
1960};
1961pub use glyph_batch::{
1962    GlyphBatch2d, GlyphBatchBudget, GlyphBatchUploadReport, GlyphRunPlacement2d,
1963};
1964pub use gpu_timing::{
1965    GpuTimingBatch, GpuTimingId, GpuTimingSample, GpuTimingSource, GpuTimingStatistics,
1966    GpuTimingStatus,
1967};
1968pub use image::{
1969    Image2d, ImageBatch2d, ImageBatchBudget, ImageBatchPlacement, ImageBatchUploadReport,
1970    ImageBudget, ImageError, ImageSampling, ImageSprite2d, ImageTexelRect, ImageUploadReport,
1971};
1972use image::{ImageRenderer, ImageUniform};
1973use mesh3d::Mesh3dRenderer;
1974pub use mesh3d::{
1975    DynamicMesh3dBudget, DynamicMesh3dBudgetResource, DynamicMesh3dError,
1976    DynamicMesh3dUpdateReport, Mesh3dInstance, Mesh3dObjectError, Mesh3dPreflightReport,
1977    Mesh3dRenderBudget, Mesh3dRenderError, Mesh3dRenderReport, Mesh3dResourceError,
1978    Mesh3dSurfaceError, Mesh3dUploadBudget, Mesh3dUploadBudgetResource, Mesh3dUploadReport,
1979    Object3dId, RenderTarget3d, RetainedMesh3d, Scene3d, Scene3dBudget, Scene3dBudgetResource,
1980    Scene3dError, Scene3dMeshUpdateReport, Scene3dRestoreReport, Scene3dStatistics,
1981    SurfaceRasterization3d, Texture3d, Texture3dError, Texture3dOptions, Texture3dUpdateBudget,
1982    Texture3dUpdateBudgetResource, Texture3dUpdateError, Texture3dUpdateReport, TextureMaterial3d,
1983    TextureMipmaps3d,
1984};
1985pub use particles::{
1986    ParticleBudgetError, ParticleField2d, ParticleFieldError, ParticleFieldRenderError,
1987    ParticleFieldUpdateReport, ParticleRenderBudget, ParticleStatistics,
1988};
1989use pipelines::{PipelineResources, create_pipeline};
1990pub use scalar_fields::{
1991    ScalarFieldRenderError, ScalarFieldTexture, ScalarFieldTextureError, ScalarFieldUploadReport,
1992};
1993pub use targets::{RenderTarget2d, RenderTargetError, TrailBuffer2d};
1994use tessellation::{
1995    logical_viewport_scissor, offset_scissor, screen_clip_to_scissor, tessellate_scene,
1996};
1997use visualization::{CachedColorMap, CompositionPipelines};
1998pub use visualization::{
1999    LayeredVisualizationError, LayeredVisualizationOptions, LayeredVisualizationReport,
2000};
2001
2002#[cfg(test)]
2003use tessellation::world_vertex;
2004
2005#[cfg(test)]
2006mod tests;
2007
2008#[cfg(test)]
2009mod test_support;