dfui 0.2.0

Declarative UI framework that draws shapes, text and icons analytically in one wgpu shader
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak};

use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;

use crate::text::Text;

use super::*;

#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct Globals {
    viewport: [f32; 2],
    _pad: [f32; 2],
}

/// Device-level state shared by window and offscreen rendering.
pub(crate) struct Gpu {
    device: wgpu::Device,
    queue: wgpu::Queue,
    pipeline: wgpu::RenderPipeline,
    globals: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
    instances: wgpu::Buffer,
    outline_layout: wgpu::BindGroupLayout,
    outline_group: wgpu::BindGroup,
    curves: wgpu::Buffer,
    bands: wgpu::Buffer,
    image_layout: wgpu::BindGroupLayout,
    sampler: wgpu::Sampler,
    /// Bound for instances that sample no bitmap.
    no_image: wgpu::BindGroup,
    /// Uploaded bitmaps by id; an entry goes once its bitmap is dropped.
    textures: HashMap<u32, (Weak<BitmapData>, wgpu::BindGroup)>,
    /// `curves`/`bands` hold nothing yet; `Outlines::dirty` only tracks
    /// uploads to whichever device came before, e.g. across an Android resume.
    empty: bool,
    timer: Option<GpuTimer>,
    /// What scenes are drawn into before [`Present`] puts them on screen.
    canvas_format: wgpu::TextureFormat,
}

/// Measures GPU time of the render pass with timestamp queries, one sample in flight.
struct GpuTimer {
    set: wgpu::QuerySet,
    resolve: wgpu::Buffer,
    read: wgpu::Buffer,
    busy: bool,
    /// A draw wrote the start time; the next present writes the end.
    began: bool,
    /// Both times are recorded; the submit reads them back.
    ended: bool,
    mapped: Arc<AtomicBool>,
    last_ns: f32,
}

impl GpuTimer {
    fn new(device: &wgpu::Device) -> GpuTimer {
        let buf = |label, usage| {
            device.create_buffer(&wgpu::BufferDescriptor {
                label: Some(label),
                size: 16,
                usage,
                mapped_at_creation: false,
            })
        };
        GpuTimer {
            set: device.create_query_set(&wgpu::QuerySetDescriptor {
                label: Some("frame timer"),
                ty: wgpu::QueryType::Timestamp,
                count: 2,
            }),
            resolve: buf(
                "timer resolve",
                wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
            ),
            read: buf(
                "timer read",
                wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            ),
            busy: false,
            began: false,
            ended: false,
            mapped: Arc::new(AtomicBool::new(false)),
            last_ns: 0.0,
        }
    }
}

fn storage(device: &wgpu::Device, label: &str, size: u64) -> wgpu::Buffer {
    device.create_buffer(&wgpu::BufferDescriptor {
        label: Some(label),
        size: size.max(256).next_power_of_two(),
        usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    })
}

fn outline_group(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    curves: &wgpu::Buffer,
    bands: &wgpu::Buffer,
) -> wgpu::BindGroup {
    device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("outlines"),
        layout,
        entries: &[
            wgpu::BindGroupEntry {
                binding: 0,
                resource: curves.as_entire_binding(),
            },
            wgpu::BindGroupEntry {
                binding: 1,
                resource: bands.as_entire_binding(),
            },
        ],
    })
}

#[cfg(not(target_arch = "wasm32"))]
static SHARED: std::sync::Mutex<Option<(wgpu::Device, wgpu::Queue)>> = std::sync::Mutex::new(None);

/// The device and queue the window draws with, once it has them: textures for
/// [`Bitmap::from_texture`] come from this device. It changes when the GPU is
/// set up again, as on an Android resume.
#[cfg(not(target_arch = "wasm32"))]
pub fn gpu() -> Option<(wgpu::Device, wgpu::Queue)> {
    SHARED.lock().unwrap_or_else(|e| e.into_inner()).clone()
}

static HDR: AtomicBool = AtomicBool::new(false);

/// Whether the window shows HDR now: the app asked ([`App::hdr`](crate::App::hdr))
/// and the screen takes HDR10. Bitmap values above 1.0 are brighter than SDR
/// white only then; otherwise they clip, so video should be tone-mapped.
pub fn hdr() -> bool {
    HDR.load(Ordering::Relaxed)
}

/// Half floats, so HDR content can go past SDR white and wide-gamut colors
/// below 0, where the GPU can render and blend them; 8-bit otherwise.
fn canvas_format(adapter: &wgpu::Adapter) -> wgpu::TextureFormat {
    let f = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba16Float);
    let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING;
    match f.allowed_usages.contains(usage)
        && f.flags.contains(wgpu::TextureFormatFeatureFlags::BLENDABLE)
    {
        true => wgpu::TextureFormat::Rgba16Float,
        false => wgpu::TextureFormat::Rgba8Unorm,
    }
}

fn canvas(gpu: &Gpu, (width, height): (u32, u32)) -> wgpu::Texture {
    gpu.device.create_texture(&wgpu::TextureDescriptor {
        label: Some("canvas"),
        size: wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: gpu.canvas_format,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
        view_formats: &[],
    })
}

/// Puts the canvas on screen, encoded for SDR or HDR10 (`present.wgsl`).
struct Present {
    pipeline: wgpu::RenderPipeline,
    tint: wgpu::Buffer,
    group: wgpu::BindGroup,
}

impl Present {
    fn new(gpu: &Gpu, canvas: &wgpu::Texture, target: wgpu::TextureFormat, pq: bool) -> Present {
        let device = &gpu.device;
        let shader = device.create_shader_module(wgpu::include_wgsl!("../present.wgsl"));
        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("present"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: None,
            bind_group_layouts: &[Some(&layout)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("present"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs"),
                compilation_options: Default::default(),
                buffers: &[],
            },
            primitive: Default::default(),
            depth_stencil: None,
            multisample: Default::default(),
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs"),
                compilation_options: wgpu::PipelineCompilationOptions {
                    constants: &[("pq", f64::from(u8::from(pq)))],
                    ..Default::default()
                },
                targets: &[Some(target.into())],
            }),
            multiview_mask: None,
            cache: None,
        });
        let tint = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("tint"),
            size: 32,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let view = canvas.create_view(&Default::default());
        let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("present"),
            layout: &layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: tint.as_entire_binding(),
                },
            ],
        });
        Present {
            pipeline,
            tint,
            group,
        }
    }
}

/// Uploads `rgba` (premultiplied) as a texture and binds it with `sampler`.
fn image_group(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    layout: &wgpu::BindGroupLayout,
    sampler: &wgpu::Sampler,
    (width, height): (u32, u32),
    rgba: &[u8],
) -> wgpu::BindGroup {
    let texture = device.create_texture_with_data(
        queue,
        &wgpu::TextureDescriptor {
            label: Some("bitmap"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            // Not sRGB: samples blend in gamma space like every other color.
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        },
        wgpu::util::TextureDataOrder::LayerMajor,
        rgba,
    );
    view_group(
        device,
        layout,
        sampler,
        &texture.create_view(&Default::default()),
    )
}

fn view_group(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    sampler: &wgpu::Sampler,
    view: &wgpu::TextureView,
) -> wgpu::BindGroup {
    device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("bitmap"),
        layout,
        entries: &[
            wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::TextureView(view),
            },
            wgpu::BindGroupEntry {
                binding: 1,
                resource: wgpu::BindingResource::Sampler(sampler),
            },
        ],
    })
}

impl Gpu {
    async fn new(adapter: &wgpu::Adapter) -> Result<Gpu, String> {
        let format = canvas_format(adapter);
        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                // Outline text needs fragment-stage storage buffers (GLES 3.1+/Vulkan/WebGPU).
                required_limits: wgpu::Limits::downlevel_defaults()
                    .using_resolution(adapter.limits()),
                // Dmabuf import lets video decoders hand frames over without a
                // copy, and 16-bit planes carry 10-bit video.
                required_features: adapter.features()
                    & (wgpu::Features::TIMESTAMP_QUERY
                        | wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF
                        | wgpu::Features::TEXTURE_FORMAT_16BIT_NORM),
                ..Default::default()
            })
            .await
            .map_err(|e| format!("the GPU can't run dfui: {e}"))?;

        let globals = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("globals"),
            size: size_of::<Globals>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: None,
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
        });
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: None,
            layout: &bgl,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: globals.as_entire_binding(),
            }],
        });

        let storage_entry = |binding| wgpu::BindGroupLayoutEntry {
            binding,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Storage { read_only: true },
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        };
        let outline_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("outlines"),
            entries: &[storage_entry(0), storage_entry(1)],
        });
        let curves = storage(&device, "curves", 0);
        let bands = storage(&device, "bands", 0);
        let outline_group = outline_group(&device, &outline_layout, &curves, &bands);

        let image_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("bitmap"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        // ponytail: no mipmaps, so bitmaps drawn far below their size alias; decode at display size.
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("bitmap"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });
        let no_image = image_group(&device, &queue, &image_layout, &sampler, (1, 1), &[0; 4]);

        let shader = device.create_shader_module(wgpu::include_wgsl!("../shader.wgsl"));
        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: None,
            bind_group_layouts: &[Some(&bgl), Some(&outline_layout), Some(&image_layout)],
            immediate_size: 0,
        });
        let show_cost = std::env::var_os("DFUI_SHOW_COST").is_some();
        let add = wgpu::BlendComponent {
            src_factor: wgpu::BlendFactor::One,
            dst_factor: wgpu::BlendFactor::One,
            operation: wgpu::BlendOperation::Add,
        };
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("sdf"),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs"),
                compilation_options: Default::default(),
                buffers: &[Some(wgpu::VertexBufferLayout {
                    array_stride: size_of::<Instance>() as u64,
                    step_mode: wgpu::VertexStepMode::Instance,
                    attributes: &wgpu::vertex_attr_array![
                        0 => Float32x4, 1 => Float32x4, 2 => Float32x4,
                        3 => Float32x4, 4 => Float32x4, 5 => Float32x4,
                    ],
                })],
            },
            primitive: Default::default(),
            depth_stencil: None,
            multisample: Default::default(),
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs"),
                compilation_options: wgpu::PipelineCompilationOptions {
                    constants: &[("show_cost", f64::from(u8::from(show_cost)))],
                    ..Default::default()
                },
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(match show_cost {
                        true => wgpu::BlendState {
                            color: add,
                            alpha: add,
                        },
                        false => wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
                    }),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });

        let instances = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("instances"),
            contents: &[0; size_of::<Instance>()],
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
        });

        let timer = device
            .features()
            .contains(wgpu::Features::TIMESTAMP_QUERY)
            .then(|| GpuTimer::new(&device));
        Ok(Gpu {
            device,
            queue,
            pipeline,
            globals,
            bind_group,
            instances,
            outline_layout,
            outline_group,
            curves,
            bands,
            image_layout,
            sampler,
            no_image,
            textures: HashMap::new(),
            empty: true,
            timer,
            canvas_format: format,
        })
    }

    /// Reads back the last timestamp sample if its mapping has completed.
    fn collect_timer(&mut self) {
        let period = self.queue.get_timestamp_period();
        if let Some(t) = &mut self.timer
            && t.mapped.swap(false, Ordering::Acquire)
        {
            if let Ok(data) = t.read.slice(..).get_mapped_range() {
                let ts: &[u64] = bytemuck::cast_slice(&data);
                t.last_ns = ts[1].saturating_sub(ts[0]) as f32 * period;
            }
            t.read.unmap();
            t.busy = false;
        }
    }

    /// `viewport` is in logical pixels; the target's physical size sets the DPI.
    /// With a `scissor` (physical px) only that area is redrawn over the target's
    /// existing contents, so the scene must paint its own background.
    fn draw(
        &mut self,
        enc: &mut wgpu::CommandEncoder,
        target: &wgpu::TextureView,
        viewport: [f32; 2],
        scene: &Scene,
        text: &mut Text,
        scissor: Option<[u32; 4]>,
    ) {
        let o = &mut text.outlines;
        let (cb, bb): (&[u8], &[u8]) = (
            bytemuck::cast_slice(&o.curves),
            bytemuck::cast_slice(&o.bands),
        );
        if cb.len() as u64 > self.curves.size() || bb.len() as u64 > self.bands.size() {
            self.curves = storage(&self.device, "curves", cb.len() as u64);
            self.bands = storage(&self.device, "bands", bb.len() as u64);
            self.outline_group = outline_group(
                &self.device,
                &self.outline_layout,
                &self.curves,
                &self.bands,
            );
            self.empty = true;
        }
        if self.empty {
            self.queue.write_buffer(&self.curves, 0, cb);
            self.queue.write_buffer(&self.bands, 0, bb);
            (o.transient_dirty, self.empty) = (false, false);
        } else {
            for r in &o.changed.0.0 {
                let r = r.start.min(o.curves.len())..r.end.min(o.curves.len());
                let data = bytemuck::cast_slice(&o.curves[r.clone()]);
                self.queue
                    .write_buffer(&self.curves, r.start as u64 * 16, data);
            }
            for r in &o.changed.1.0 {
                let r = r.start.min(o.bands.len())..r.end.min(o.bands.len());
                let data = bytemuck::cast_slice(&o.bands[r.clone()]);
                self.queue
                    .write_buffer(&self.bands, r.start as u64 * 4, data);
            }
        }
        o.changed = Default::default();
        if o.transient_dirty {
            let (c, b) = o.transient_data();
            self.queue
                .write_buffer(&self.curves, 0, bytemuck::cast_slice(c));
            self.queue
                .write_buffer(&self.bands, 0, bytemuck::cast_slice(b));
            o.transient_dirty = false;
        }

        let globals = Globals {
            viewport,
            _pad: [0.0; 2],
        };
        self.queue
            .write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals));

        let bytes: &[u8] = bytemuck::cast_slice(&scene.instances);
        if bytes.len() as u64 > self.instances.size() {
            self.instances = self.device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("instances"),
                size: (bytes.len() as u64).next_power_of_two(),
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
        }
        self.queue.write_buffer(&self.instances, 0, bytes);

        self.textures.retain(|_, (b, _)| b.strong_count() > 0);
        let max = self.device.limits().max_texture_dimension_2d;
        for (_, b) in &scene.bitmaps {
            let d = &b.0;
            self.textures.entry(d.id).or_insert_with(|| {
                let group = if let Some(view) = &d.texture {
                    view_group(&self.device, &self.image_layout, &self.sampler, &view.0)
                } else if d.width.max(d.height) > max || d.width == 0 || d.height == 0 {
                    log::warn!("bitmap {}x{} exceeds {max}px, not drawn", d.width, d.height);
                    self.no_image.clone()
                } else {
                    image_group(
                        &self.device,
                        &self.queue,
                        &self.image_layout,
                        &self.sampler,
                        (d.width, d.height),
                        &d.rgba,
                    )
                };
                (Arc::downgrade(&b.0), group)
            });
        }

        self.collect_timer();
        let timing = self.timer.as_ref().filter(|t| !t.busy);
        {
            let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: target,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: match scissor {
                            Some(_) => wgpu::LoadOp::Load,
                            None => wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                        },
                        store: wgpu::StoreOp::Store,
                    },
                })],
                timestamp_writes: timing.map(|t| wgpu::RenderPassTimestampWrites {
                    query_set: &t.set,
                    beginning_of_pass_write_index: Some(0),
                    end_of_pass_write_index: None,
                }),
                ..Default::default()
            });
            if let Some([x, y, w, h]) = scissor {
                pass.set_scissor_rect(x, y, w, h);
            }
            pass.set_pipeline(&self.pipeline);
            pass.set_bind_group(0, &self.bind_group, &[]);
            pass.set_bind_group(1, &self.outline_group, &[]);
            pass.set_vertex_buffer(0, self.instances.slice(..));
            // One draw per image, and one for each run of other instances
            // between them, so painter's order holds.
            let mut next = 0;
            for (i, b) in &scene.bitmaps {
                let i = *i as u32;
                if i > next {
                    pass.set_bind_group(2, &self.no_image, &[]);
                    pass.draw(0..24, next..i);
                }
                pass.set_bind_group(2, &self.textures[&b.0.id].1, &[]);
                pass.draw(0..24, i..i + 1);
                next = i + 1;
            }
            let n = scene.instances.len() as u32;
            if n > next {
                pass.set_bind_group(2, &self.no_image, &[]);
                pass.draw(0..24, next..n);
            }
        }
        if let Some(t) = &mut self.timer
            && !t.busy
        {
            t.began = true;
        }
    }

    /// Puts the canvas into `target` through `p`, with the damage flash `tint`
    /// (physical px) over it; ends the GPU timing a draw in the same encoder began.
    fn present(
        &mut self,
        enc: &mut wgpu::CommandEncoder,
        p: &Present,
        target: &wgpu::TextureView,
        tint: Option<([u32; 4], Color)>,
    ) {
        let (rect, color) = match tint {
            Some((r, c)) => (r.map(|v| v as f32), c.rgba()),
            None => ([0.0; 4], [0.0; 4]),
        };
        let bytes: [[f32; 4]; 2] = [rect, color];
        self.queue
            .write_buffer(&p.tint, 0, bytemuck::cast_slice(&bytes));
        let timing = self.timer.as_ref().filter(|t| !t.busy && t.began);
        {
            let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: target,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                timestamp_writes: timing.map(|t| wgpu::RenderPassTimestampWrites {
                    query_set: &t.set,
                    beginning_of_pass_write_index: None,
                    end_of_pass_write_index: Some(1),
                }),
                ..Default::default()
            });
            pass.set_pipeline(&p.pipeline);
            pass.set_bind_group(0, &p.group, &[]);
            pass.draw(0..3, 0..1);
        }
        if let Some(t) = timing {
            enc.resolve_query_set(&t.set, 0..2, &t.resolve, 0);
            enc.copy_buffer_to_buffer(&t.resolve, 0, &t.read, 0, 16);
        }
        if let Some(t) = &mut self.timer
            && t.began
        {
            t.ended = true;
        }
    }

    /// Sends `enc` to the GPU, one submit per frame, and reads back the timing
    /// it carries.
    fn submit(&mut self, enc: wgpu::CommandEncoder) {
        self.queue.submit([enc.finish()]);
        if let Some(t) = &mut self.timer
            && t.ended
        {
            (t.busy, t.began, t.ended) = (true, false, false);
            let mapped = t.mapped.clone();
            t.read.slice(..).map_async(wgpu::MapMode::Read, move |r| {
                mapped.store(r.is_ok(), Ordering::Release);
            });
        }
        let _ = self.device.poll(wgpu::PollType::Poll);
    }
}

/// The platform window a [`Renderer`] draws into.
pub(crate) trait Host {
    fn surface(
        &self,
        instance: &wgpu::Instance,
    ) -> Result<wgpu::Surface<'static>, wgpu::CreateSurfaceError>;
    /// Physical px.
    fn size(&self) -> (u32, u32);
    fn scale(&self) -> f32;
    fn request_redraw(&self);
    fn pre_present(&self) {}
    fn refresh_mhz(&self) -> Option<u32> {
        None
    }
    /// Shows the given soft keyboard, or hides it.
    fn set_ime(&self, _keyboard: Option<crate::widget::Keyboard>) {}
}

pub(crate) struct Renderer {
    surface: wgpu::Surface<'static>,
    config: wgpu::SurfaceConfiguration,
    gpu: Gpu,
    /// Retained frame for partial redraws; swapchain images don't keep their
    /// contents, so damage is redrawn here and the whole canvas presented.
    canvas: wgpu::Texture,
    present: Present,
    /// The surface's SDR format, and its HDR10 format if it has one.
    sdr_format: wgpu::TextureFormat,
    hdr_format: Option<wgpu::TextureFormat>,
    /// Output is HDR10.
    hdr: bool,
    /// Canvas contents are invalid (new or resized); next frame must be full.
    fresh: bool,
    /// `DFUI_SHOW_DAMAGE` debug overlay: frame counter cycling the tint color.
    show_damage: Option<usize>,
    /// Last presented frame carries the overlay tint; next one must present.
    tinted: bool,
    /// The app's zoom on top of the window's scale factor.
    zoom: f32,
    /// Last, so it's dropped after the surface drawing into it.
    window: Box<dyn Host>,
}

/// `d` (logical px) rounded out to physical pixels with a 2px margin for AA
/// fringes, within a `size` target; zero-sized when nothing of it is inside.
pub(super) fn scissor(d: Rect, scale: f32, (w, h): (u32, u32)) -> [u32; 4] {
    if d.w <= 0.0 || d.h <= 0.0 {
        return [0; 4];
    }
    let x0 = ((d.x - 2.0) * scale).floor().clamp(0.0, w as f32) as u32;
    let y0 = ((d.y - 2.0) * scale).floor().clamp(0.0, h as f32) as u32;
    let x1 = ((d.x + d.w + 2.0) * scale).ceil().clamp(0.0, w as f32) as u32;
    let y1 = ((d.y + d.h + 2.0) * scale).ceil().clamp(0.0, h as f32) as u32;
    [x0, y0, x1 - x0, y1 - y0]
}

impl Renderer {
    /// Async because adapter and device requests are; on native they resolve
    /// on first poll, on the web they wait for the browser.
    /// `hdr` is the app's wish, so the first swapchain is already the right one.
    pub async fn new(
        instance: wgpu::Instance,
        window: Box<dyn Host>,
        hdr: bool,
    ) -> Result<Renderer, String> {
        let surface = window
            .surface(&instance)
            .map_err(|e| format!("can't draw to this window: {e}"))?;
        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                compatible_surface: Some(&surface),
                ..Default::default()
            })
            .await
            .map_err(|e| format!("no usable GPU: {e}"))?;
        let caps = surface.get_capabilities(&adapter);
        // The canvas holds sRGB-encoded values already, so the screen format mustn't encode again.
        let sdr_format = caps
            .formats
            .iter()
            .copied()
            .find(|f| !f.is_srgb())
            .unwrap_or(caps.formats[0]);
        // 10-bit first: PQ needs the precision, and it's what TVs take.
        let hdr_format = caps
            .format_capabilities
            .iter()
            .filter(|f| f.color_spaces.contains(wgpu::SurfaceColorSpaces::BT2100_PQ))
            .map(|f| f.format)
            .max_by_key(|f| *f == wgpu::TextureFormat::Rgb10a2Unorm);
        let gpu = Gpu::new(&adapter).await?;
        log::info!(
            "canvas {:?}, screen {sdr_format:?}, HDR10 {hdr_format:?}",
            gpu.canvas_format
        );
        #[cfg(not(target_arch = "wasm32"))]
        {
            *SHARED.lock().unwrap_or_else(|e| e.into_inner()) =
                Some((gpu.device.clone(), gpu.queue.clone()));
        }
        let hdr = hdr && hdr_format.is_some();
        HDR.store(hdr, Ordering::Relaxed);
        let (width, height) = window.size();
        let (format, color_space) = match hdr_format.filter(|_| hdr) {
            Some(f) => (f, wgpu::SurfaceColorSpace::Bt2100Pq),
            None => (sdr_format, wgpu::SurfaceColorSpace::Auto),
        };
        let config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format,
            width: width.max(1),
            height: height.max(1),
            present_mode: wgpu::PresentMode::AutoVsync,
            desired_maximum_frame_latency: 2,
            alpha_mode: caps.alpha_modes[0],
            view_formats: vec![],
            color_space,
        };
        surface.configure(&gpu.device, &config);
        let canvas = canvas(&gpu, (config.width, config.height));
        let present = Present::new(&gpu, &canvas, format, hdr);
        Ok(Renderer {
            surface,
            config,
            gpu,
            canvas,
            present,
            sdr_format,
            hdr_format,
            hdr,
            fresh: true,
            show_damage: std::env::var_os("DFUI_SHOW_DAMAGE").map(|_| 0),
            tinted: false,
            zoom: 1.0,
            window,
        })
    }

    pub fn window(&self) -> &dyn Host {
        &*self.window
    }

    pub fn resize(&mut self, w: u32, h: u32) {
        self.config.width = w.max(1);
        self.config.height = h.max(1);
        self.reconfigure();
    }

    /// Applies `config` and starts over with a new canvas.
    fn reconfigure(&mut self) {
        self.surface.configure(&self.gpu.device, &self.config);
        self.canvas = canvas(&self.gpu, (self.config.width, self.config.height));
        self.present = Present::new(&self.gpu, &self.canvas, self.config.format, self.hdr);
        self.fresh = true;
    }

    /// Switches the output to HDR10 when `on` and the screen takes it, else to SDR.
    pub fn set_hdr(&mut self, on: bool) {
        let hdr = on && self.hdr_format.is_some();
        if hdr == self.hdr {
            return;
        }
        self.hdr = hdr;
        (self.config.format, self.config.color_space) = match hdr {
            true => (
                self.hdr_format.unwrap_or(self.sdr_format),
                wgpu::SurfaceColorSpace::Bt2100Pq,
            ),
            false => (self.sdr_format, wgpu::SurfaceColorSpace::Auto),
        };
        HDR.store(hdr, Ordering::Relaxed);
        log::info!(
            "output: {} in {:?}",
            if hdr { "HDR10" } else { "SDR" },
            self.config.format
        );
        self.reconfigure();
    }

    /// GPU time of the most recently measured frame, if timestamp queries are supported.
    pub fn gpu_ms(&self) -> Option<f32> {
        self.gpu.timer.as_ref().map(|t| t.last_ns / 1e6)
    }

    /// Redraws `damage` (logical px; empty redraws nothing), or everything when
    /// `None`.
    pub fn set_zoom(&mut self, zoom: f32) {
        self.zoom = zoom;
    }

    pub fn render(&mut self, scene: &Scene, text: &mut Text, damage: Option<Rect>) -> Outcome {
        let scale = self.window.scale() * self.zoom;
        let viewport = [
            self.config.width as f32 / scale,
            self.config.height as f32 / scale,
        ];
        // Content can lie past the window edge; only what's on screen counts.
        let damage = damage.map(|d| d.intersect(&Rect::new(0.0, 0.0, viewport[0], viewport[1])));
        // The window already shows the canvas: nothing to acquire, draw or present.
        let empty = damage.is_some_and(|d| d.w <= 0.0 || d.h <= 0.0);
        if empty && !self.fresh && !self.tinted {
            return Outcome::Idle;
        }
        let acquire = web_time::Instant::now();
        let frame = match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(t)
            | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,
            wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
                self.surface.configure(&self.gpu.device, &self.config);
                self.window.request_redraw();
                return Outcome::Failed;
            }
            wgpu::CurrentSurfaceTexture::Timeout => {
                self.window.request_redraw();
                return Outcome::Failed;
            }
            _ => return Outcome::Failed,
        };
        let waited = acquire.elapsed();
        let (w, h) = (self.config.width, self.config.height);
        // Area actually redrawn, physical px; `None` is the whole frame.
        let drawn = damage
            .filter(|_| !self.fresh)
            .map(|d| scissor(d, scale, (w, h)));
        let mut enc = self.gpu.device.create_command_encoder(&Default::default());
        if drawn.is_none_or(|[_, _, sw, sh]| sw > 0 && sh > 0) {
            let view = self.canvas.create_view(&Default::default());
            self.gpu.draw(&mut enc, &view, viewport, scene, text, drawn);
        }
        self.fresh = false;
        // The flash goes on the screen only, so the canvas stays clean and
        // each frame shows just its own damage.
        self.tinted = false;
        let mut tint = None;
        if let Some(n) = &mut self.show_damage
            && drawn.is_none_or(|[_, _, dw, dh]| dw > 0 && dh > 0)
        {
            const TINTS: [u32; 4] = [0xff3b30, 0x34c759, 0x007aff, 0xffcc00];
            *n += 1;
            let color = Color::hex(TINTS[*n % TINTS.len()]).alpha(0.3);
            tint = Some((drawn.unwrap_or([0, 0, w, h]), color));
            // One clean follow-up frame (empty damage) so the tint only flashes.
            self.tinted = true;
            self.window.request_redraw();
        }
        let view = frame.texture.create_view(&Default::default());
        self.gpu.present(&mut enc, &self.present, &view, tint);
        self.gpu.submit(enc);
        self.window.pre_present();
        self.gpu.queue.present(frame);
        Outcome::Presented(waited)
    }
}

/// Offscreen render target with its own device, for snapshots and benches:
/// scenes draw into a canvas and reach the 8-bit target through the same
/// present pass as the screen.
pub(crate) struct Offscreen {
    gpu: Gpu,
    canvas: wgpu::Texture,
    present: Present,
    target: wgpu::Texture,
}

impl Offscreen {
    pub(crate) fn new(size: (u32, u32)) -> Offscreen {
        // Vulkan loaders and drivers (NVIDIA's) crash creating instances on
        // several threads at once, as parallel tests do.
        static SETUP: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let format = wgpu::TextureFormat::Rgba8Unorm;
        let gpu = {
            let _setup = SETUP.lock().unwrap_or_else(|e| e.into_inner());
            let instance = wgpu::Instance::new(
                wgpu::InstanceDescriptor::new_without_display_handle_from_env(),
            );
            let adapter = pollster::block_on(instance.request_adapter(&Default::default()))
                .expect("no GPU adapter");
            pollster::block_on(Gpu::new(&adapter)).expect("request device")
        };
        let target = gpu.device.create_texture(&wgpu::TextureDescriptor {
            label: Some("offscreen"),
            size: wgpu::Extent3d {
                width: size.0,
                height: size.1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let canvas = canvas(&gpu, size);
        let present = Present::new(&gpu, &canvas, format, false);
        Offscreen {
            gpu,
            canvas,
            present,
            target,
        }
    }

    #[cfg(test)]
    pub(crate) fn device(&self) -> (&wgpu::Device, &wgpu::Queue) {
        (&self.gpu.device, &self.gpu.queue)
    }

    /// Presents as an HDR10 screen would get it, PQ codes in the 8-bit target.
    #[cfg(test)]
    pub(crate) fn hdr10(&mut self) {
        self.present = Present::new(
            &self.gpu,
            &self.canvas,
            wgpu::TextureFormat::Rgba8Unorm,
            true,
        );
    }

    /// Draws into the canvas; [`read`](Self::read) presents it.
    pub(crate) fn draw(
        &mut self,
        scene: &Scene,
        text: &mut Text,
        scale: f32,
        scissor: Option<[u32; 4]>,
    ) {
        let mut enc = self.gpu.device.create_command_encoder(&Default::default());
        self.record(&mut enc, scene, text, scale, scissor);
        self.gpu.submit(enc);
    }

    fn record(
        &mut self,
        enc: &mut wgpu::CommandEncoder,
        scene: &Scene,
        text: &mut Text,
        scale: f32,
        scissor: Option<[u32; 4]>,
    ) {
        let s = self.canvas.size();
        let viewport = [s.width as f32 / scale, s.height as f32 / scale];
        let view = self.canvas.create_view(&Default::default());
        self.gpu.draw(enc, &view, viewport, scene, text, scissor);
    }

    fn present(&mut self, enc: &mut wgpu::CommandEncoder) {
        let view = self.target.create_view(&Default::default());
        self.gpu.present(enc, &self.present, &view, None);
    }

    /// Draws, presents and waits for the GPU; returns the GPU time of both
    /// passes from timestamp queries, or wall time when the adapter lacks them.
    pub(crate) fn timed_draw(
        &mut self,
        scene: &Scene,
        text: &mut Text,
        scale: f32,
        scissor: Option<[u32; 4]>,
    ) -> std::time::Duration {
        let start = web_time::Instant::now();
        let mut enc = self.gpu.device.create_command_encoder(&Default::default());
        self.record(&mut enc, scene, text, scale, scissor);
        self.present(&mut enc);
        self.gpu.submit(enc);
        self.gpu
            .device
            .poll(wgpu::PollType::wait_indefinitely())
            .expect("poll");
        let wall = start.elapsed();
        self.gpu.collect_timer();
        match &self.gpu.timer {
            Some(t) => std::time::Duration::from_nanos(t.last_ns as u64),
            None => wall,
        }
    }

    /// Presents the canvas and reads it back as sRGB RGBA8.
    pub(crate) fn read(&mut self) -> Pixels {
        let mut enc = self.gpu.device.create_command_encoder(&Default::default());
        self.present(&mut enc);
        self.gpu.submit(enc);
        let gpu = &self.gpu;
        let s = self.target.size();
        let (w, h) = (s.width, s.height);
        let target = &self.target;
        let row = (w * 4).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
        let buf = gpu.device.create_buffer(&wgpu::BufferDescriptor {
            label: None,
            size: (row * h) as u64,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });
        let mut enc = gpu.device.create_command_encoder(&Default::default());
        enc.copy_texture_to_buffer(
            target.as_image_copy(),
            wgpu::TexelCopyBufferInfo {
                buffer: &buf,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(row),
                    rows_per_image: None,
                },
            },
            wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
        );
        gpu.queue.submit([enc.finish()]);
        buf.slice(..)
            .map_async(wgpu::MapMode::Read, |r| r.expect("map readback"));
        gpu.device
            .poll(wgpu::PollType::wait_indefinitely())
            .expect("poll");
        let data = buf.slice(..).get_mapped_range().expect("mapped range");
        let mut rgba = vec![0; (w * h * 4) as usize];
        for y in 0..h {
            let src = &data[(y * row) as usize..][..(w * 4) as usize];
            rgba[(y * w * 4) as usize..][..(w * 4) as usize].copy_from_slice(src);
        }
        Pixels {
            width: w,
            height: h,
            rgba,
        }
    }
}

/// Renders scenes offscreen in order, each optionally scissored, and reads
/// the result back as sRGB RGBA8.
pub(crate) fn render_offscreen(
    passes: &[(&Scene, Option<[u32; 4]>)],
    text: &mut Text,
    size: (u32, u32),
    scale: f32,
) -> Pixels {
    let mut off = Offscreen::new(size);
    for &(scene, scissor) in passes {
        off.draw(scene, text, scale, scissor);
    }
    off.read()
}