Skip to main content

rust_glass/gpu/
mod.rs

1//! wgpu renderer.
2//!
3//! A frame is split into passes. Before each pass that contains glass, the
4//! region behind that glass is copied from the scene and blurred into a mip
5//! chain, which the glass samples. Glass can therefore refract everything below
6//! it, including other glass. Commands that do not overlap are free to move to
7//! an earlier pass, so a window full of controls needs only a few.
8
9use std::collections::HashMap;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicU8, Ordering};
12
13use bytemuck::{Pod, Zeroable};
14
15use crate::paint::{Cmd, DrawData, GShapeInst, GlassInst, ImageId, MaskInst, ShapeInst};
16use crate::text::{ATLAS_SIZE, AtlasUpload, SPRITE_ATLAS_SIZE};
17
18const SCENE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgb10a2Unorm;
19const MIPS: u32 = 6;
20const PAD: u32 = 32;
21const MAX_PROBES: u64 = 512;
22const INFO_STRIDE: u64 = 256;
23const MAX_PASSES: u64 = 64;
24
25/// Device and queue, shared by all windows.
26pub struct Gpu {
27    // Kept for as long as the device and its surfaces live.
28    #[allow(dead_code)]
29    pub instance: wgpu::Instance,
30    pub adapter: wgpu::Adapter,
31    pub device: wgpu::Device,
32    pub queue: wgpu::Queue,
33}
34
35impl Gpu {
36    pub fn instance() -> wgpu::Instance {
37        let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
38        desc.backends = wgpu::Backends::PRIMARY;
39        if cfg!(not(debug_assertions)) {
40            desc.flags = wgpu::InstanceFlags::empty();
41        }
42        wgpu::Instance::new(desc.with_env())
43    }
44
45    pub fn new(
46        instance: wgpu::Instance,
47        surface: Option<&wgpu::Surface<'_>>,
48        low_power: bool,
49    ) -> Result<Self, String> {
50        let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
51            power_preference: if low_power {
52                wgpu::PowerPreference::LowPower
53            } else {
54                wgpu::PowerPreference::HighPerformance
55            },
56            compatible_surface: surface,
57            ..Default::default()
58        }))
59        .map_err(|e| format!("no graphics adapter: {e}"))?;
60        let features = adapter.features() & wgpu::Features::TIMESTAMP_QUERY;
61        let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
62            label: Some("rust-glass"),
63            required_features: features,
64            required_limits: wgpu::Limits::default().using_resolution(adapter.limits()),
65            memory_hints: wgpu::MemoryHints::MemoryUsage,
66            ..Default::default()
67        }))
68        .map_err(|e| format!("no graphics device: {e}"))?;
69        Ok(Self { instance, adapter, device, queue })
70    }
71
72    pub fn describe(&self) -> String {
73        let i = self.adapter.get_info();
74        format!("{} ({:?})", i.name, i.backend)
75    }
76}
77
78#[repr(C)]
79#[derive(Clone, Copy, Pod, Zeroable)]
80struct Globals {
81    size: [f32; 2],
82    tex_size: [f32; 2],
83    light: [f32; 2],
84    time: f32,
85    ppp: f32,
86}
87
88#[repr(C)]
89#[derive(Clone, Copy, Pod, Zeroable)]
90struct StatInfo {
91    tex_size: [f32; 2],
92    size: [f32; 2],
93    first: u32,
94    pad: [u32; 3],
95}
96
97#[derive(Clone, Copy, Debug)]
98struct Px {
99    x0: f32,
100    y0: f32,
101    x1: f32,
102    y1: f32,
103}
104
105impl Px {
106    const NONE: Px = Px { x0: 1e9, y0: 1e9, x1: -1e9, y1: -1e9 };
107    fn new(a: [f32; 4]) -> Self {
108        Self { x0: a[0], y0: a[1], x1: a[2], y1: a[3] }
109    }
110    fn union(&self, o: &Px) -> Px {
111        Px { x0: self.x0.min(o.x0), y0: self.y0.min(o.y0), x1: self.x1.max(o.x1), y1: self.y1.max(o.y1) }
112    }
113    fn intersect(&self, o: &Px) -> Px {
114        Px { x0: self.x0.max(o.x0), y0: self.y0.max(o.y0), x1: self.x1.min(o.x1), y1: self.y1.min(o.y1) }
115    }
116    fn grow(&self, v: f32) -> Px {
117        Px { x0: self.x0 - v, y0: self.y0 - v, x1: self.x1 + v, y1: self.y1 + v }
118    }
119    fn empty(&self) -> bool {
120        self.x1 <= self.x0 || self.y1 <= self.y0
121    }
122}
123
124#[derive(Clone, Copy, Debug)]
125enum Item {
126    Shapes { start: u32, end: u32, image: ImageId },
127    Glass(u32),
128}
129
130#[derive(Default)]
131struct Pass {
132    items: Vec<Item>,
133    capture: Option<Px>,
134    max_lod: u32,
135    probes: std::ops::Range<u32>,
136}
137
138/// A pass while it is being collected.
139#[derive(Default)]
140struct Work {
141    pass: Pass,
142    shapes: Vec<ShapeInst>,
143    probes: Vec<u32>,
144}
145
146#[derive(Default)]
147struct Plan {
148    passes: Vec<Pass>,
149    /// Shapes reordered by pass.
150    shapes: Vec<ShapeInst>,
151    /// Indices into the probe list, reordered by pass.
152    probes: Vec<u32>,
153}
154
155const TILE: f32 = 8.0;
156
157/// Highest pass that has drawn into each tile (plus one), and the pass whose
158/// shadow covers it.
159#[derive(Default)]
160struct Grid {
161    w: usize,
162    h: usize,
163    cells: Vec<[u8; 2]>,
164}
165
166impl Grid {
167    fn reset(&mut self, screen: Px) {
168        self.w = (screen.x1 / TILE).ceil() as usize;
169        self.h = (screen.y1 / TILE).ceil() as usize;
170        self.cells.clear();
171        self.cells.resize(self.w * self.h, [0; 2]);
172    }
173    fn span(&self, r: &Px) -> (usize, usize, usize, usize) {
174        let f = |v: f32, n: usize| ((v / TILE).max(0.0) as usize).min(n);
175        let c = |v: f32, n: usize| ((v / TILE).ceil().max(0.0) as usize).min(n);
176        (f(r.x0, self.w), f(r.y0, self.h), c(r.x1, self.w), c(r.y1, self.h))
177    }
178    fn query(&self, r: &Px) -> (u8, u8) {
179        let (x0, y0, x1, y1) = self.span(r);
180        let mut m = (0, 0);
181        for y in y0..y1 {
182            for c in &self.cells[y * self.w + x0..y * self.w + x1] {
183                m = (m.0.max(c[0]), m.1.max(c[1]));
184            }
185        }
186        m
187    }
188    fn mark(&mut self, r: &Px, v: u8) {
189        self.each(r, |c| c[0] = c[0].max(v));
190    }
191    fn shade(&mut self, r: &Px, v: u8) {
192        if !r.empty() {
193            self.each(r, |c| c[1] = c[1].max(v));
194        }
195    }
196    fn each(&mut self, r: &Px, f: impl Fn(&mut [u8; 2])) {
197        let (x0, y0, x1, y1) = self.span(r);
198        for y in y0..y1 {
199            for c in &mut self.cells[y * self.w + x0..y * self.w + x1] {
200                f(c);
201            }
202        }
203    }
204}
205
206/// What the renderer did in the last frame.
207#[derive(Clone, Copy, Debug, Default)]
208pub struct FrameStats {
209    /// Render passes. Glass needs a pass to read what is below it.
210    pub passes: u32,
211    /// Pixels copied for glass to read, in total.
212    pub captured_px: u64,
213    /// Shapes, glyphs and images drawn.
214    pub shapes: u32,
215    /// Glass elements drawn.
216    pub glasses: u32,
217    /// GPU time in milliseconds, smoothed. `None` where the GPU cannot
218    /// measure time, such as some virtual machines.
219    pub gpu_ms: Option<f32>,
220}
221
222struct Readback {
223    buffer: wgpu::Buffer,
224    keys: Vec<u64>,
225    /// 0 free, 1 pending, 2 ready, 3 failed
226    state: Arc<AtomicU8>,
227}
228
229struct Timing {
230    set: wgpu::QuerySet,
231    resolve: wgpu::Buffer,
232    read: wgpu::Buffer,
233    state: Arc<AtomicU8>,
234    period: f32,
235}
236
237struct Targets {
238    size: (u32, u32),
239    tex: (u32, u32),
240    scene: wgpu::Texture,
241    scene_view: wgpu::TextureView,
242    backdrop: wgpu::Texture,
243    mip_views: Vec<wgpu::TextureView>,
244    mip_groups: Vec<wgpu::BindGroup>,
245    present_group: wgpu::BindGroup,
246    glass_group: wgpu::BindGroup,
247    stats_group: wgpu::BindGroup,
248}
249
250struct Growable {
251    buffer: wgpu::Buffer,
252    label: &'static str,
253}
254
255impl Growable {
256    fn new(device: &wgpu::Device, label: &'static str, size: u64) -> Self {
257        Self { buffer: Self::make(device, label, size), label }
258    }
259    fn make(device: &wgpu::Device, label: &str, size: u64) -> wgpu::Buffer {
260        device.create_buffer(&wgpu::BufferDescriptor {
261            label: Some(label),
262            size,
263            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
264            mapped_at_creation: false,
265        })
266    }
267    /// Returns true when the buffer was reallocated.
268    fn write<T: Pod>(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, data: &[T]) -> bool {
269        if data.is_empty() {
270            return false;
271        }
272        let bytes: &[u8] = bytemuck::cast_slice(data);
273        let grown = bytes.len() as u64 > self.buffer.size();
274        if grown {
275            self.buffer = Self::make(device, self.label, (bytes.len() as u64).next_power_of_two());
276        }
277        queue.write_buffer(&self.buffer, 0, bytes);
278        grown
279    }
280}
281
282pub struct Renderer {
283    device: wgpu::Device,
284    queue: wgpu::Queue,
285    shape_pipe: wgpu::RenderPipeline,
286    glass_pipe: wgpu::RenderPipeline,
287    blur_pipe: wgpu::RenderPipeline,
288    present_pipe: wgpu::RenderPipeline,
289    stats_pipe: wgpu::ComputePipeline,
290    shape_layout: wgpu::BindGroupLayout,
291    glass_layout: wgpu::BindGroupLayout,
292    backdrop_layout: wgpu::BindGroupLayout,
293    blur_layout: wgpu::BindGroupLayout,
294    image_layout: wgpu::BindGroupLayout,
295    stats_layout: wgpu::BindGroupLayout,
296    sampler: wgpu::Sampler,
297    globals: wgpu::Buffer,
298    shapes: Growable,
299    glasses: Growable,
300    gshapes: Growable,
301    masks: Growable,
302    shape_group: wgpu::BindGroup,
303    glass_group: wgpu::BindGroup,
304    atlas: wgpu::Texture,
305    sprites: wgpu::Texture,
306    atlas_group: wgpu::BindGroup,
307    images: HashMap<u32, (wgpu::Texture, wgpu::BindGroup)>,
308    next_image: u32,
309    targets: Option<Targets>,
310    probes: wgpu::Buffer,
311    stats: wgpu::Buffer,
312    infos: wgpu::Buffer,
313    readbacks: Vec<Readback>,
314    timing: Option<Timing>,
315    grid: Grid,
316    pub frame_stats: FrameStats,
317}
318
319impl Renderer {
320    pub fn new(gpu: &Gpu, output: wgpu::TextureFormat) -> Self {
321        let device = gpu.device.clone();
322        let queue = gpu.queue.clone();
323
324        let common = include_str!("common.wgsl");
325        let module = |label: &str, src: String| {
326            device.create_shader_module(wgpu::ShaderModuleDescriptor {
327                label: Some(label),
328                source: wgpu::ShaderSource::Wgsl(src.into()),
329            })
330        };
331        let shape_mod = module("shape", format!("{common}\n{}", include_str!("shape.wgsl")));
332        let glass_mod = module("glass", format!("{common}\n{}", include_str!("glass.wgsl")));
333        let blur_mod = module("blur", include_str!("blur.wgsl").into());
334        let stats_mod = module("stats", include_str!("stats.wgsl").into());
335
336        let vf = wgpu::ShaderStages::VERTEX_FRAGMENT;
337        let fr = wgpu::ShaderStages::FRAGMENT;
338        let cs = wgpu::ShaderStages::COMPUTE;
339        let uniform = |binding, vis, dynamic| wgpu::BindGroupLayoutEntry {
340            binding,
341            visibility: vis,
342            ty: wgpu::BindingType::Buffer {
343                ty: wgpu::BufferBindingType::Uniform,
344                has_dynamic_offset: dynamic,
345                min_binding_size: None,
346            },
347            count: None,
348        };
349        let storage = |binding, vis, read_only| wgpu::BindGroupLayoutEntry {
350            binding,
351            visibility: vis,
352            ty: wgpu::BindingType::Buffer {
353                ty: wgpu::BufferBindingType::Storage { read_only },
354                has_dynamic_offset: false,
355                min_binding_size: None,
356            },
357            count: None,
358        };
359        let texture = |binding, vis| wgpu::BindGroupLayoutEntry {
360            binding,
361            visibility: vis,
362            ty: wgpu::BindingType::Texture {
363                sample_type: wgpu::TextureSampleType::Float { filterable: true },
364                view_dimension: wgpu::TextureViewDimension::D2,
365                multisampled: false,
366            },
367            count: None,
368        };
369        let sampler_entry = |binding, vis| wgpu::BindGroupLayoutEntry {
370            binding,
371            visibility: vis,
372            ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
373            count: None,
374        };
375        let layout = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| {
376            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries })
377        };
378        let shape_layout = layout(
379            "shape",
380            &[uniform(0, vf, false), storage(1, vf, true), sampler_entry(2, fr), storage(3, vf, true)],
381        );
382        let glass_layout = layout(
383            "glass",
384            &[
385                uniform(0, vf, false),
386                storage(1, vf, true),
387                sampler_entry(2, fr),
388                storage(3, vf, true),
389                storage(4, vf, true),
390            ],
391        );
392        let atlas_layout = layout("atlas", &[texture(0, fr), texture(1, fr)]);
393        let image_layout = layout("image", &[texture(0, fr)]);
394        let backdrop_layout = layout("backdrop", &[texture(0, fr)]);
395        let blur_layout = layout("blur", &[texture(0, fr), sampler_entry(1, fr)]);
396        let stats_layout = layout(
397            "stats",
398            &[
399                storage(0, cs, true),
400                storage(1, cs, false),
401                texture(2, cs),
402                sampler_entry(3, cs),
403                uniform(4, cs, true),
404            ],
405        );
406
407        let pipe_layout = |groups: &[Option<&wgpu::BindGroupLayout>]| {
408            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
409                label: None,
410                bind_group_layouts: groups,
411                immediate_size: 0,
412            })
413        };
414        let premultiplied = wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING;
415        let pipe = |label: &str,
416                    layout: &wgpu::PipelineLayout,
417                    m: &wgpu::ShaderModule,
418                    fs: &str,
419                    topo,
420                    format,
421                    blend| {
422            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
423                label: Some(label),
424                layout: Some(layout),
425                vertex: wgpu::VertexState {
426                    module: m,
427                    entry_point: Some("vs"),
428                    compilation_options: Default::default(),
429                    buffers: &[],
430                },
431                primitive: wgpu::PrimitiveState { topology: topo, ..Default::default() },
432                depth_stencil: None,
433                multisample: Default::default(),
434                fragment: Some(wgpu::FragmentState {
435                    module: m,
436                    entry_point: Some(fs),
437                    compilation_options: Default::default(),
438                    targets: &[Some(wgpu::ColorTargetState {
439                        format,
440                        blend,
441                        write_mask: wgpu::ColorWrites::COLOR,
442                    })],
443                }),
444                multiview_mask: None,
445                cache: None,
446            })
447        };
448        use wgpu::PrimitiveTopology::{TriangleList, TriangleStrip};
449        let shape_pipe = pipe(
450            "shape",
451            &pipe_layout(&[Some(&shape_layout), Some(&atlas_layout), Some(&image_layout)]),
452            &shape_mod,
453            "fs",
454            TriangleStrip,
455            SCENE_FORMAT,
456            Some(premultiplied),
457        );
458        let glass_pipe = pipe(
459            "glass",
460            &pipe_layout(&[Some(&glass_layout), Some(&backdrop_layout)]),
461            &glass_mod,
462            "fs",
463            TriangleStrip,
464            SCENE_FORMAT,
465            Some(premultiplied),
466        );
467        let blur_pl = pipe_layout(&[Some(&blur_layout)]);
468        let blur_pipe = pipe("blur", &blur_pl, &blur_mod, "fs", TriangleList, SCENE_FORMAT, None);
469        let present_pipe = pipe("present", &blur_pl, &blur_mod, "present", TriangleList, output, None);
470        let stats_pipe = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
471            label: Some("stats"),
472            layout: Some(&pipe_layout(&[Some(&stats_layout)])),
473            module: &stats_mod,
474            entry_point: Some("main"),
475            compilation_options: Default::default(),
476            cache: None,
477        });
478
479        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
480            label: Some("linear"),
481            mag_filter: wgpu::FilterMode::Linear,
482            min_filter: wgpu::FilterMode::Linear,
483            mipmap_filter: wgpu::MipmapFilterMode::Linear,
484            ..Default::default()
485        });
486
487        let buffer = |label, size, usage| {
488            device.create_buffer(&wgpu::BufferDescriptor {
489                label: Some(label),
490                size,
491                usage,
492                mapped_at_creation: false,
493            })
494        };
495        use wgpu::BufferUsages as U;
496        let globals = buffer("globals", std::mem::size_of::<Globals>() as u64, U::UNIFORM | U::COPY_DST);
497        let shapes = Growable::new(&device, "shapes", 2048 * std::mem::size_of::<ShapeInst>() as u64);
498        let glasses = Growable::new(&device, "glasses", 128 * std::mem::size_of::<GlassInst>() as u64);
499        let gshapes = Growable::new(&device, "gshapes", 256 * std::mem::size_of::<GShapeInst>() as u64);
500        let masks = Growable::new(&device, "masks", 64 * std::mem::size_of::<MaskInst>() as u64);
501        let probes = buffer("probes", MAX_PROBES * 16, U::STORAGE | U::COPY_DST);
502        let stats = buffer("stats", MAX_PROBES * 8, U::STORAGE | U::COPY_SRC);
503        let infos = buffer("infos", MAX_PASSES * INFO_STRIDE, U::UNIFORM | U::COPY_DST);
504
505        let tex2d = |label: &str, size: u32, format| {
506            device.create_texture(&wgpu::TextureDescriptor {
507                label: Some(label),
508                size: wgpu::Extent3d { width: size, height: size, depth_or_array_layers: 1 },
509                mip_level_count: 1,
510                sample_count: 1,
511                dimension: wgpu::TextureDimension::D2,
512                format,
513                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
514                view_formats: &[],
515            })
516        };
517        let atlas = tex2d("glyphs", ATLAS_SIZE, wgpu::TextureFormat::R8Unorm);
518        let sprites = tex2d("sprites", SPRITE_ATLAS_SIZE, wgpu::TextureFormat::Rgba8Unorm);
519        let atlas_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
520            label: Some("atlas"),
521            layout: &atlas_layout,
522            entries: &[
523                wgpu::BindGroupEntry {
524                    binding: 0,
525                    resource: wgpu::BindingResource::TextureView(&atlas.create_view(&Default::default())),
526                },
527                wgpu::BindGroupEntry {
528                    binding: 1,
529                    resource: wgpu::BindingResource::TextureView(&sprites.create_view(&Default::default())),
530                },
531            ],
532        });
533
534        let shape_group = Self::group4(&device, &shape_layout, &globals, &masks, &sampler, &[&shapes]);
535        let glass_group =
536            Self::group4(&device, &glass_layout, &globals, &masks, &sampler, &[&glasses, &gshapes]);
537
538        let readbacks = (0..3)
539            .map(|_| Readback {
540                buffer: buffer("stats readback", MAX_PROBES * 8, U::COPY_DST | U::MAP_READ),
541                keys: Vec::new(),
542                state: Arc::new(AtomicU8::new(0)),
543            })
544            .collect();
545
546        let timing = device.features().contains(wgpu::Features::TIMESTAMP_QUERY).then(|| Timing {
547            set: device.create_query_set(&wgpu::QuerySetDescriptor {
548                label: Some("timing"),
549                ty: wgpu::QueryType::Timestamp,
550                count: 2,
551            }),
552            resolve: buffer("timing", 16, U::QUERY_RESOLVE | U::COPY_SRC),
553            read: buffer("timing read", 16, U::COPY_DST | U::MAP_READ),
554            state: Arc::new(AtomicU8::new(0)),
555            period: queue.get_timestamp_period(),
556        });
557
558        let mut r = Self {
559            device,
560            queue,
561            shape_pipe,
562            glass_pipe,
563            blur_pipe,
564            present_pipe,
565            stats_pipe,
566            shape_layout,
567            glass_layout,
568            backdrop_layout,
569            blur_layout,
570            image_layout,
571            stats_layout,
572            sampler,
573            globals,
574            shapes,
575            glasses,
576            gshapes,
577            masks,
578            shape_group,
579            glass_group,
580            atlas,
581            sprites,
582            atlas_group,
583            images: HashMap::new(),
584            next_image: 0,
585            targets: None,
586            probes,
587            stats,
588            infos,
589            readbacks,
590            timing,
591            grid: Grid::default(),
592            frame_stats: FrameStats::default(),
593        };
594        r.add_image(1, 1, &[255; 4]);
595        r
596    }
597
598    fn group4(
599        device: &wgpu::Device,
600        layout: &wgpu::BindGroupLayout,
601        globals: &wgpu::Buffer,
602        masks: &Growable,
603        sampler: &wgpu::Sampler,
604        rest: &[&Growable],
605    ) -> wgpu::BindGroup {
606        let mut entries = vec![
607            wgpu::BindGroupEntry { binding: 0, resource: globals.as_entire_binding() },
608            wgpu::BindGroupEntry { binding: 1, resource: masks.buffer.as_entire_binding() },
609            wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(sampler) },
610        ];
611        for (i, b) in rest.iter().enumerate() {
612            entries
613                .push(wgpu::BindGroupEntry { binding: 3 + i as u32, resource: b.buffer.as_entire_binding() });
614        }
615        device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout, entries: &entries })
616    }
617
618    /// Upload an RGBA8 image (not premultiplied).
619    pub fn add_image(&mut self, w: u32, h: u32, rgba: &[u8]) -> ImageId {
620        assert_eq!(rgba.len(), (w * h * 4) as usize, "image data does not match its size");
621        let levels = 32 - w.max(h).max(1).leading_zeros();
622        let t = self.device.create_texture(&wgpu::TextureDescriptor {
623            label: Some("image"),
624            size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
625            mip_level_count: levels,
626            sample_count: 1,
627            dimension: wgpu::TextureDimension::D2,
628            format: wgpu::TextureFormat::Rgba8Unorm,
629            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
630            view_formats: &[],
631        });
632        self.write_texture(&t, 0, 0, 0, w, h, 4, rgba);
633        // Smaller versions, so scaled down images stay smooth.
634        let (mut lw, mut lh) = (w, h);
635        let mut level: Vec<u8> = Vec::new();
636        for m in 1..levels {
637            let src: &[u8] = if m == 1 { rgba } else { &level };
638            let (nw, nh, next) = halve(src, lw, lh);
639            self.write_texture(&t, m, 0, 0, nw, nh, 4, &next);
640            (lw, lh, level) = (nw, nh, next);
641        }
642        let group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
643            label: Some("image"),
644            layout: &self.image_layout,
645            entries: &[wgpu::BindGroupEntry {
646                binding: 0,
647                resource: wgpu::BindingResource::TextureView(&t.create_view(&Default::default())),
648            }],
649        });
650        let id = self.next_image;
651        self.next_image += 1;
652        self.images.insert(id, (t, group));
653        ImageId(id)
654    }
655
656    pub fn remove_image(&mut self, id: ImageId) {
657        if id.0 != 0 {
658            self.images.remove(&id.0);
659        }
660    }
661
662    #[allow(clippy::too_many_arguments)]
663    fn write_texture(
664        &self,
665        t: &wgpu::Texture,
666        mip: u32,
667        x: u32,
668        y: u32,
669        w: u32,
670        h: u32,
671        bpp: u32,
672        data: &[u8],
673    ) {
674        self.queue.write_texture(
675            wgpu::TexelCopyTextureInfo {
676                texture: t,
677                mip_level: mip,
678                origin: wgpu::Origin3d { x, y, z: 0 },
679                aspect: wgpu::TextureAspect::All,
680            },
681            data,
682            wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * bpp), rows_per_image: Some(h) },
683            wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
684        );
685    }
686
687    pub fn upload_atlas(&mut self, uploads: &mut Vec<AtlasUpload>) {
688        for u in uploads.drain(..) {
689            let (t, bpp) = if u.color { (&self.sprites, 4) } else { (&self.atlas, 1) };
690            let mut data = u.data;
691            if u.color {
692                // The sampler interpolates, so store premultiplied.
693                for p in data.as_chunks_mut::<4>().0 {
694                    let a = p[3] as u32;
695                    for c in &mut p[..3] {
696                        *c = (*c as u32 * a / 255) as u8;
697                    }
698                }
699            }
700            self.write_texture(t, 0, u.x, u.y, u.w, u.h, bpp, &data);
701        }
702    }
703
704    fn ensure_targets(&mut self, w: u32, h: u32) {
705        if self.targets.as_ref().is_some_and(|t| t.size == (w, h)) {
706            return;
707        }
708        let d = &self.device;
709        let tex = (w.next_multiple_of(PAD), h.next_multiple_of(PAD));
710        let extent = wgpu::Extent3d { width: tex.0, height: tex.1, depth_or_array_layers: 1 };
711        use wgpu::TextureUsages as T;
712        let make = |label, mips, usage| {
713            d.create_texture(&wgpu::TextureDescriptor {
714                label: Some(label),
715                size: extent,
716                mip_level_count: mips,
717                sample_count: 1,
718                dimension: wgpu::TextureDimension::D2,
719                format: SCENE_FORMAT,
720                usage,
721                view_formats: &[],
722            })
723        };
724        let scene = make("scene", 1, T::RENDER_ATTACHMENT | T::TEXTURE_BINDING | T::COPY_SRC);
725        let backdrop = make("backdrop", MIPS, T::RENDER_ATTACHMENT | T::TEXTURE_BINDING | T::COPY_DST);
726        let scene_view = scene.create_view(&Default::default());
727        let full = backdrop.create_view(&Default::default());
728        let mip_views: Vec<_> = (0..MIPS)
729            .map(|i| {
730                backdrop.create_view(&wgpu::TextureViewDescriptor {
731                    base_mip_level: i,
732                    mip_level_count: Some(1),
733                    ..Default::default()
734                })
735            })
736            .collect();
737        let blur_group = |v: &wgpu::TextureView| {
738            d.create_bind_group(&wgpu::BindGroupDescriptor {
739                label: None,
740                layout: &self.blur_layout,
741                entries: &[
742                    wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(v) },
743                    wgpu::BindGroupEntry {
744                        binding: 1,
745                        resource: wgpu::BindingResource::Sampler(&self.sampler),
746                    },
747                ],
748            })
749        };
750        let mip_groups = mip_views.iter().map(blur_group).collect();
751        let present_group = blur_group(&scene_view);
752        let glass_group = d.create_bind_group(&wgpu::BindGroupDescriptor {
753            label: Some("backdrop"),
754            layout: &self.backdrop_layout,
755            entries: &[wgpu::BindGroupEntry {
756                binding: 0,
757                resource: wgpu::BindingResource::TextureView(&full),
758            }],
759        });
760        let stats_group = d.create_bind_group(&wgpu::BindGroupDescriptor {
761            label: Some("stats"),
762            layout: &self.stats_layout,
763            entries: &[
764                wgpu::BindGroupEntry { binding: 0, resource: self.probes.as_entire_binding() },
765                wgpu::BindGroupEntry { binding: 1, resource: self.stats.as_entire_binding() },
766                wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&full) },
767                wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Sampler(&self.sampler) },
768                wgpu::BindGroupEntry {
769                    binding: 4,
770                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
771                        buffer: &self.infos,
772                        offset: 0,
773                        size: std::num::NonZeroU64::new(std::mem::size_of::<StatInfo>() as u64),
774                    }),
775                },
776            ],
777        });
778        self.targets = Some(Targets {
779            size: (w, h),
780            tex,
781            scene,
782            scene_view,
783            backdrop,
784            mip_views,
785            mip_groups,
786            present_group,
787            glass_group,
788            stats_group,
789        });
790    }
791
792    /// Split the command list into passes, see the module docs.
793    ///
794    /// Every command gets the earliest pass that still draws it after everything
795    /// it overlaps. Glass additionally needs a pass after the content it covers,
796    /// so that content is part of its capture. Overlap is tracked on a coarse
797    /// tile grid, which keeps planning linear in the painted area.
798    fn plan(data: &DrawData, screen: Px, grid: &mut Grid) -> Plan {
799        grid.reset(screen);
800        let mut plan = Plan::default();
801        let mut work: Vec<Work> = vec![Work::default()];
802        let grow = |n: usize, work: &mut Vec<Work>| {
803            while work.len() <= n {
804                work.push(Work::default());
805            }
806        };
807        for cmd in &data.cmds {
808            match *cmd {
809                Cmd::Shapes { start, end, image } => {
810                    for s in &data.shapes[start as usize..end as usize] {
811                        let e = s.soft * 2.5 + s.stroke + 1.0;
812                        let r = Px {
813                            x0: s.rect[0].min(s.rect[2]) - e,
814                            y0: s.rect[1].min(s.rect[3]) - e,
815                            x1: s.rect[0].max(s.rect[2]) + e,
816                            y1: s.rect[1].max(s.rect[3]) + e,
817                        }
818                        .intersect(&Px::new(s.clip))
819                        .intersect(&screen);
820                        if r.empty() {
821                            continue;
822                        }
823                        let (drawn, shade) = grid.query(&r);
824                        let level = drawn.saturating_sub(1).max(shade);
825                        grid.mark(&r, level + 1);
826                        grow(level as usize, &mut work);
827                        let w = &mut work[level as usize];
828                        let at = w.shapes.len() as u32;
829                        w.shapes.push(*s);
830                        match w.pass.items.last_mut() {
831                            Some(Item::Shapes { end, image: im, .. }) if *im == image => *end = at + 1,
832                            _ => w.pass.items.push(Item::Shapes { start: at, end: at + 1, image }),
833                        }
834                    }
835                }
836                Cmd::Glass { index, probe } => {
837                    let g = &data.glasses[index as usize];
838                    let mut body = Px::NONE;
839                    for s in &data.gshapes[g.shape_start as usize..(g.shape_start + g.shape_count) as usize] {
840                        body = body.union(&Px {
841                            x0: s.center[0] - s.half[0],
842                            y0: s.center[1] - s.half[1],
843                            x1: s.center[0] + s.half[0],
844                            y1: s.center[1] + s.half[1],
845                        });
846                    }
847                    let clip = Px::new(g.clip).intersect(&screen);
848                    let b = body.grow(1.0).intersect(&clip);
849                    if b.empty() {
850                        continue;
851                    }
852                    let (drawn, shade) = grid.query(&b);
853                    let level = drawn.max(shade).max(1).min(MAX_PASSES as u8 - 1);
854                    // Later shapes stay on top of the visible part of the shadow.
855                    let mut sh = body.grow(g.shadow_radius * 0.55);
856                    sh.y1 += g.shadow_y;
857                    grid.shade(&sh.intersect(&clip), level);
858                    grid.mark(&b, level + 1);
859                    grow(level as usize, &mut work);
860                    let w = &mut work[level as usize];
861                    w.pass.items.push(Item::Glass(index));
862                    let half = (b.x1 - b.x0).min(b.y1 - b.y0) * 0.5;
863                    let mut r = g.blur;
864                    if g.light_spill > 0.0 {
865                        r = r.max(14.0 * data.ppp);
866                    }
867                    if g.shadow > 0.0 && g.shadow_tint > 0.0 {
868                        r = r.max((half * 1.6).max(10.0 * data.ppp));
869                    }
870                    if g.dark_edge > 0.0 {
871                        r = r.max((half * 0.85).max(6.0 * data.ppp));
872                    }
873                    let mut lod = (1.0 + r * 0.75).log2().ceil();
874                    if probe != u32::MAX {
875                        w.probes.push(probe);
876                        lod = lod.max(((b.x1 - b.x0).max(b.y1 - b.y0) / 8.0).log2().ceil().min(4.0));
877                    }
878                    let lod = lod.clamp(0.0, (MIPS - 1) as f32) as u32;
879                    w.pass.max_lod = w.pass.max_lod.max(lod);
880                    let reach =
881                        3.0 * (1u32 << lod) as f32 + g.inner_height * 0.8 + g.outer_amount + 6.0 * data.ppp;
882                    let c = w.pass.capture.unwrap_or(Px::NONE);
883                    w.pass.capture = Some(c.union(&b.grow(reach)));
884                }
885            }
886        }
887        for mut w in work {
888            let base = plan.shapes.len() as u32;
889            plan.shapes.append(&mut w.shapes);
890            for i in &mut w.pass.items {
891                if let Item::Shapes { start, end, .. } = i {
892                    *start += base;
893                    *end += base;
894                }
895            }
896            let first = plan.probes.len() as u32;
897            plan.probes.append(&mut w.probes);
898            w.pass.probes = first..plan.probes.len() as u32;
899            plan.passes.push(w.pass);
900        }
901        plan
902    }
903
904    /// Collect finished backdrop measurements: (key, mean, deviation).
905    pub fn poll_stats(&mut self) -> Vec<(u64, f32, f32)> {
906        let _ = self.device.poll(wgpu::PollType::Poll);
907        let mut out = Vec::new();
908        for r in &mut self.readbacks {
909            match r.state.load(Ordering::Acquire) {
910                2 => {
911                    if let Ok(view) = r.buffer.slice(..).get_mapped_range() {
912                        let v: &[[f32; 2]] = bytemuck::cast_slice(&view);
913                        out.extend(r.keys.iter().zip(v).map(|(k, s)| (*k, s[0], s[1])));
914                    }
915                    r.buffer.unmap();
916                    r.state.store(0, Ordering::Release);
917                }
918                3 => r.state.store(0, Ordering::Release),
919                _ => {}
920            }
921        }
922        if let Some(t) = &self.timing
923            && t.state.load(Ordering::Acquire) == 2
924        {
925            if let Ok(view) = t.read.slice(..).get_mapped_range() {
926                let v: &[u64] = bytemuck::cast_slice(&view);
927                let ms = v[1].saturating_sub(v[0]) as f32 * t.period / 1e6;
928                let s = &mut self.frame_stats.gpu_ms;
929                *s = Some(s.map_or(ms, |old| old * 0.9 + ms * 0.1));
930            }
931            t.read.unmap();
932            t.state.store(0, Ordering::Release);
933        }
934        out
935    }
936
937    /// Measurements are still in flight.
938    pub fn stats_pending(&self) -> bool {
939        self.readbacks.iter().any(|r| r.state.load(Ordering::Acquire) != 0)
940    }
941
942    pub fn render(&mut self, data: &DrawData, target: &wgpu::TextureView, w: u32, h: u32) {
943        self.ensure_targets(w, h);
944        let (dev, q) = (self.device.clone(), self.queue.clone());
945        let tex = self.targets.as_ref().unwrap().tex;
946        let screen = Px { x0: 0.0, y0: 0.0, x1: tex.0 as f32, y1: tex.1 as f32 };
947        let mut grid = std::mem::take(&mut self.grid);
948        let plan = Self::plan(data, screen, &mut grid);
949        self.grid = grid;
950        let masks_new = self.masks.write(&dev, &q, &data.masks);
951        if self.shapes.write(&dev, &q, &plan.shapes) | masks_new {
952            self.shape_group = Self::group4(
953                &dev,
954                &self.shape_layout,
955                &self.globals,
956                &self.masks,
957                &self.sampler,
958                &[&self.shapes],
959            );
960        }
961        if self.glasses.write(&dev, &q, &data.glasses)
962            | self.gshapes.write(&dev, &q, &data.gshapes)
963            | masks_new
964        {
965            self.glass_group = Self::group4(
966                &dev,
967                &self.glass_layout,
968                &self.globals,
969                &self.masks,
970                &self.sampler,
971                &[&self.glasses, &self.gshapes],
972            );
973        }
974        let t = self.targets.as_ref().unwrap();
975        let size = [w as f32, h as f32];
976        let tex_size = [t.tex.0 as f32, t.tex.1 as f32];
977        q.write_buffer(
978            &self.globals,
979            0,
980            bytemuck::bytes_of(&Globals {
981                size,
982                tex_size,
983                light: data.light,
984                time: data.time,
985                ppp: data.ppp,
986            }),
987        );
988        let n_probes = plan.probes.len().min(MAX_PROBES as usize);
989        if n_probes > 0 {
990            let rects: Vec<[f32; 4]> =
991                plan.probes[..n_probes].iter().map(|p| data.probes[*p as usize].1).collect();
992            q.write_buffer(&self.probes, 0, bytemuck::cast_slice(&rects));
993        }
994
995        let passes = &plan.passes;
996        let mut infos = vec![0u8; passes.len().min(MAX_PASSES as usize) * INFO_STRIDE as usize];
997        for (i, p) in passes.iter().take(MAX_PASSES as usize).enumerate() {
998            let info = StatInfo { tex_size, size, first: p.probes.start, pad: [0; 3] };
999            let at = i * INFO_STRIDE as usize;
1000            infos[at..at + std::mem::size_of::<StatInfo>()].copy_from_slice(bytemuck::bytes_of(&info));
1001        }
1002        q.write_buffer(&self.infos, 0, &infos);
1003
1004        let mut enc = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") });
1005        let time_this = self.timing.as_ref().filter(|t| t.state.load(Ordering::Acquire) == 0);
1006        let mut fs = FrameStats {
1007            passes: passes.len() as u32,
1008            shapes: plan.shapes.len() as u32,
1009            glasses: data.glasses.len() as u32,
1010            gpu_ms: self.frame_stats.gpu_ms,
1011            captured_px: 0,
1012        };
1013
1014        for (pi, p) in passes.iter().enumerate() {
1015            if let Some(c) = p.capture {
1016                let align = |v: f32| (v.max(0.0) as u32) / PAD * PAD;
1017                let x0 = align(c.x0).min(t.tex.0);
1018                let y0 = align(c.y0).min(t.tex.1);
1019                let x1 = (c.x1.max(0.0).ceil() as u32).next_multiple_of(PAD).min(t.tex.0);
1020                let y1 = (c.y1.max(0.0).ceil() as u32).next_multiple_of(PAD).min(t.tex.1);
1021                if x1 > x0 && y1 > y0 {
1022                    fs.captured_px += (x1 - x0) as u64 * (y1 - y0) as u64;
1023                    let origin = wgpu::Origin3d { x: x0, y: y0, z: 0 };
1024                    let info = |texture| wgpu::TexelCopyTextureInfo {
1025                        texture,
1026                        mip_level: 0,
1027                        origin,
1028                        aspect: wgpu::TextureAspect::All,
1029                    };
1030                    enc.copy_texture_to_texture(
1031                        info(&t.scene),
1032                        info(&t.backdrop),
1033                        wgpu::Extent3d { width: x1 - x0, height: y1 - y0, depth_or_array_layers: 1 },
1034                    );
1035                    for lod in 1..=p.max_lod {
1036                        let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
1037                            label: Some("blur"),
1038                            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1039                                view: &t.mip_views[lod as usize],
1040                                depth_slice: None,
1041                                resolve_target: None,
1042                                ops: wgpu::Operations {
1043                                    load: wgpu::LoadOp::Load,
1044                                    store: wgpu::StoreOp::Store,
1045                                },
1046                            })],
1047                            ..Default::default()
1048                        });
1049                        rp.set_scissor_rect(
1050                            x0 >> lod,
1051                            y0 >> lod,
1052                            ((x1 - x0) >> lod).max(1),
1053                            ((y1 - y0) >> lod).max(1),
1054                        );
1055                        rp.set_pipeline(&self.blur_pipe);
1056                        rp.set_bind_group(0, &t.mip_groups[lod as usize - 1], &[]);
1057                        rp.draw(0..3, 0..1);
1058                    }
1059                    let probes = p.probes.start..p.probes.end.min(n_probes as u32);
1060                    if !probes.is_empty() && pi < MAX_PASSES as usize {
1061                        let mut cp = enc.begin_compute_pass(&Default::default());
1062                        cp.set_pipeline(&self.stats_pipe);
1063                        cp.set_bind_group(0, &t.stats_group, &[(pi as u64 * INFO_STRIDE) as u32]);
1064                        cp.dispatch_workgroups(probes.len() as u32, 1, 1);
1065                    }
1066                }
1067            }
1068            let load = if pi == 0 {
1069                let c = data.clear;
1070                wgpu::LoadOp::Clear(wgpu::Color { r: c[0] as f64, g: c[1] as f64, b: c[2] as f64, a: 1.0 })
1071            } else {
1072                wgpu::LoadOp::Load
1073            };
1074            let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
1075                label: Some("scene"),
1076                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1077                    view: &t.scene_view,
1078                    depth_slice: None,
1079                    resolve_target: None,
1080                    ops: wgpu::Operations { load, store: wgpu::StoreOp::Store },
1081                })],
1082                timestamp_writes: match (time_this, pi) {
1083                    (Some(tm), 0) => Some(wgpu::RenderPassTimestampWrites {
1084                        query_set: &tm.set,
1085                        beginning_of_pass_write_index: Some(0),
1086                        end_of_pass_write_index: None,
1087                    }),
1088                    _ => None,
1089                },
1090                ..Default::default()
1091            });
1092            let mut mode = 0;
1093            for item in &p.items {
1094                match *item {
1095                    Item::Shapes { start, end, image } => {
1096                        if mode != 1 {
1097                            mode = 1;
1098                            rp.set_pipeline(&self.shape_pipe);
1099                            rp.set_bind_group(0, &self.shape_group, &[]);
1100                            rp.set_bind_group(1, &self.atlas_group, &[]);
1101                        }
1102                        let img = self.images.get(&image.0).or_else(|| self.images.get(&0));
1103                        if let Some((_, g)) = img {
1104                            rp.set_bind_group(2, g, &[]);
1105                            rp.draw(0..4, start..end);
1106                        }
1107                    }
1108                    Item::Glass(index) => {
1109                        let g = &data.glasses[index as usize];
1110                        let vis = Px::new(g.bounds).intersect(&Px::new(g.clip)).intersect(&screen);
1111                        if vis.empty() {
1112                            continue;
1113                        }
1114                        if mode != 2 {
1115                            mode = 2;
1116                            rp.set_pipeline(&self.glass_pipe);
1117                            rp.set_bind_group(0, &self.glass_group, &[]);
1118                            rp.set_bind_group(1, &t.glass_group, &[]);
1119                        }
1120                        rp.draw(0..4, index..index + 1);
1121                    }
1122                }
1123            }
1124        }
1125
1126        {
1127            let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
1128                label: Some("present"),
1129                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1130                    view: target,
1131                    depth_slice: None,
1132                    resolve_target: None,
1133                    ops: wgpu::Operations {
1134                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
1135                        store: wgpu::StoreOp::Store,
1136                    },
1137                })],
1138                timestamp_writes: time_this.map(|tm| wgpu::RenderPassTimestampWrites {
1139                    query_set: &tm.set,
1140                    beginning_of_pass_write_index: None,
1141                    end_of_pass_write_index: Some(1),
1142                }),
1143                ..Default::default()
1144            });
1145            rp.set_pipeline(&self.present_pipe);
1146            rp.set_bind_group(0, &t.present_group, &[]);
1147            rp.draw(0..3, 0..1);
1148        }
1149
1150        if let Some(tm) = time_this {
1151            enc.resolve_query_set(&tm.set, 0..2, &tm.resolve, 0);
1152            enc.copy_buffer_to_buffer(&tm.resolve, 0, &tm.read, 0, 16);
1153        }
1154        let slot = (n_probes > 0)
1155            .then(|| self.readbacks.iter().position(|r| r.state.load(Ordering::Acquire) == 0))
1156            .flatten();
1157        if let Some(i) = slot {
1158            enc.copy_buffer_to_buffer(&self.stats, 0, &self.readbacks[i].buffer, 0, n_probes as u64 * 8);
1159        }
1160        let timed = time_this.is_some();
1161        q.submit([enc.finish()]);
1162
1163        let arm = |buffer: &wgpu::Buffer, state: &Arc<AtomicU8>| {
1164            state.store(1, Ordering::Release);
1165            let s = state.clone();
1166            buffer.slice(..).map_async(wgpu::MapMode::Read, move |r| {
1167                s.store(if r.is_ok() { 2 } else { 3 }, Ordering::Release);
1168            });
1169        };
1170        if let Some(i) = slot {
1171            let r = &mut self.readbacks[i];
1172            r.keys = plan.probes[..n_probes].iter().map(|p| data.probes[*p as usize].0).collect();
1173            arm(&r.buffer, &r.state);
1174        }
1175        if timed && let Some(tm) = &self.timing {
1176            arm(&tm.read, &tm.state);
1177        }
1178        self.frame_stats = fs;
1179    }
1180}
1181
1182/// Box filtered half size image.
1183fn halve(src: &[u8], w: u32, h: u32) -> (u32, u32, Vec<u8>) {
1184    let (nw, nh) = ((w / 2).max(1), (h / 2).max(1));
1185    let mut out = Vec::with_capacity((nw * nh * 4) as usize);
1186    for y in 0..nh {
1187        for x in 0..nw {
1188            let (x0, y0) = ((x * 2).min(w - 1), (y * 2).min(h - 1));
1189            let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
1190            for c in 0..4 {
1191                let at = |x: u32, y: u32| src[((y * w + x) * 4 + c) as usize] as u32;
1192                out.push(((at(x0, y0) + at(x1, y0) + at(x0, y1) + at(x1, y1) + 2) / 4) as u8);
1193            }
1194        }
1195    }
1196    (nw, nh, out)
1197}
1198
1199#[cfg(test)]
1200mod tests {
1201    use super::*;
1202
1203    fn glass_at(data: &mut DrawData, x: f32, probe: bool) {
1204        let mut g: GlassInst = Zeroable::zeroed();
1205        g.clip = [-1e6, -1e6, 1e6, 1e6];
1206        g.shape_start = data.gshapes.len() as u32;
1207        g.shape_count = 1;
1208        let mut s: GShapeInst = Zeroable::zeroed();
1209        s.center = [x, 50.0];
1210        s.half = [20.0, 20.0];
1211        data.gshapes.push(s);
1212        let p = if probe {
1213            data.probes.push((1, [0.0; 4]));
1214            data.probes.len() as u32 - 1
1215        } else {
1216            u32::MAX
1217        };
1218        data.cmds.push(Cmd::Glass { index: data.glasses.len() as u32, probe: p });
1219        data.glasses.push(g);
1220    }
1221
1222    const SCREEN: Px = Px { x0: 0.0, y0: 0.0, x1: 400.0, y1: 400.0 };
1223
1224    fn plan(d: &DrawData) -> Plan {
1225        Renderer::plan(d, SCREEN, &mut Grid::default())
1226    }
1227
1228    fn shape_at(data: &mut DrawData, x: f32, w: f32) {
1229        let mut s: ShapeInst = Zeroable::zeroed();
1230        s.rect = [x, 45.0, x + w, 55.0];
1231        s.clip = [-1e6, -1e6, 1e6, 1e6];
1232        let at = data.shapes.len() as u32;
1233        data.shapes.push(s);
1234        data.cmds.push(Cmd::Shapes { start: at, end: at + 1, image: ImageId(0) });
1235    }
1236
1237    #[test]
1238    fn halving_averages_and_stops_at_one_pixel() {
1239        let (w, h, px) = halve(&[0, 0, 0, 255, 200, 100, 50, 255], 2, 1);
1240        assert_eq!((w, h), (1, 1));
1241        assert_eq!(px, [100, 50, 25, 255]);
1242    }
1243
1244    #[test]
1245    fn separate_glass_shares_one_capture() {
1246        let mut d = DrawData { ppp: 1.0, ..Default::default() };
1247        glass_at(&mut d, 50.0, true);
1248        glass_at(&mut d, 150.0, true);
1249        let p = plan(&d);
1250        assert_eq!(p.passes.len(), 2);
1251        assert_eq!(p.passes[1].probes, 0..2);
1252    }
1253
1254    #[test]
1255    fn stacked_glass_gets_its_own_capture() {
1256        let mut d = DrawData { ppp: 1.0, ..Default::default() };
1257        glass_at(&mut d, 50.0, true);
1258        glass_at(&mut d, 55.0, true);
1259        let p = plan(&d);
1260        assert_eq!(p.passes.len(), 3);
1261        assert_eq!(p.passes[2].probes, 1..2);
1262        assert_eq!(p.probes, [0, 1]);
1263    }
1264
1265    #[test]
1266    fn offscreen_glass_costs_nothing() {
1267        let mut d = DrawData { ppp: 1.0, ..Default::default() };
1268        glass_at(&mut d, -500.0, true);
1269        glass_at(&mut d, 50.0, true);
1270        let p = plan(&d);
1271        assert_eq!(p.passes.len(), 2);
1272        assert_eq!(p.probes, [1]);
1273    }
1274
1275    #[test]
1276    fn track_and_thumb_pairs_do_not_chain() {
1277        // Track, thumb, track, thumb: later tracks move before all thumbs.
1278        let mut d = DrawData { ppp: 1.0, ..Default::default() };
1279        for x in [60.0, 200.0, 340.0] {
1280            shape_at(&mut d, x - 40.0, 80.0);
1281            glass_at(&mut d, x, true);
1282        }
1283        assert_eq!(plan(&d).passes.len(), 2);
1284    }
1285
1286    #[test]
1287    fn label_stays_above_its_glass() {
1288        let mut d = DrawData { ppp: 1.0, ..Default::default() };
1289        glass_at(&mut d, 50.0, true);
1290        shape_at(&mut d, 45.0, 10.0);
1291        let p = plan(&d);
1292        assert!(matches!(p.passes[1].items[..], [Item::Glass(0), Item::Shapes { .. }]));
1293    }
1294
1295    #[test]
1296    fn shape_between_two_glasses_is_refracted() {
1297        let mut d = DrawData { ppp: 1.0, ..Default::default() };
1298        glass_at(&mut d, 50.0, true);
1299        shape_at(&mut d, 45.0, 10.0);
1300        glass_at(&mut d, 50.0, true);
1301        let p = plan(&d);
1302        assert_eq!(p.passes.len(), 3);
1303        assert!(matches!(p.passes[2].items[..], [Item::Glass(1)]));
1304    }
1305}