facett-core 0.1.19

facett — visual kernel: render a node/edge Scene into egui (wgpu fast path to come)
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
//! **THE shared instanced graph-cloud GPU lane** (feature `wgpu`) — an instanced
//! emissive node/edge renderer with real GPU **bloom**, and the ONE renderer every
//! facett graph surface paints its node/edge cloud through.
//!
//! # Why it lives in facett-core (L5)
//!
//! This lane was born inside `facett-graph3d` (as `graph3d::graph_gpu`) to take the
//! measured single-core rotation wall off the CPU: egui tessellates 2.47 M triangles
//! for a 30 000-node cloud on **one** thread (33.75 ms/frame — see
//! `facett/.nornir/graph3d-rotate-perf-design.md`), while the projection that feeds it
//! costs 0.02 ms. The tessellation is the wall, and the cure is to stop tessellating:
//! upload the cloud as **instances** and issue two draw calls.
//!
//! That cure is not 3-D. Every input this module takes is already **screen-space
//! pixels** — a node is a centre + radius, an edge is two endpoints + a half-width. The
//! whole 2-D graph family (`facett-graphpan`, `facett-graphview`, `facett-graphnav`,
//! `facett-graph`) hits exactly the same wall for exactly the same reason, so the
//! renderer moved DOWN here and every graph crate consumes it. `facett_graph3d::graph_gpu`
//! remains as a re-export — the public path is unchanged, and there is still exactly one
//! renderer.
//!
//! It reuses two shared facett-core L0 pieces:
//!
//! - [`OffscreenColorDepth`](crate::render::gpu::OffscreenColorDepth) — the HDR
//!   (`Rgba16Float`) colour+depth offscreen target. Nodes/edges draw into its colour
//!   attachment with **additive blend** (`src = ONE, dst = ONE`), so a fragment that
//!   lands on a texel another already lit **sums** its linear radiance (edge crossings
//!   accumulate past 1.0, which the HDR target keeps).
//! - [`GaussianBlur`](crate::render::gpu::GaussianBlur) — the separable blur
//!   substrate that spreads the bright-pass output for the bloom.
//!
//! The post chain is bright-pass (soft-knee threshold) → blur → composite (scene +
//! bloom·intensity → Reinhard tonemap → LDR). Emissive node/edge colours carry linear
//! radiance **above 1.0**, so the bright pass isolates exactly the glowing graph and
//! dense crossings bloom hottest.
//!
//! Two entry points:
//! - [`render_graph_offscreen`] — the **headless** render-proof: draws a graph and reads
//!   back the LDR framebuffer + the instance draw counts, so the lane is validated as
//!   DATA without a windowing host.
//! - [`cloud`] — the **live** `egui_wgpu` paint callback + the install-once lifecycle.
//!   Read [`cloud::cloud_renderer_installed`] before you skip a CPU painter.

#![allow(clippy::too_many_lines, reason = "self-contained instanced+bloom pipeline set")]

use egui_wgpu::wgpu;
use crate::render::gpu::offscreen::{OffscreenColorDepth, OFFSCREEN_FORMAT};
use crate::render::gpu::GaussianBlur;

/// One instanced emissive node — a screen-space disc. Matches `NodeInst` in
/// `graph_gpu.wgsl`. 32 bytes.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct NodeInstance {
    /// Centre in physical px (top-left origin, y down).
    pub center: [f32; 2],
    /// Radius in px.
    pub radius: f32,
    pub _pad: f32,
    /// Emissive linear radiance `[r, g, b, a]` (rgb may exceed 1.0 to bloom).
    pub color: [f32; 4],
}

/// One instanced emissive edge — a thick screen-space line segment. Matches
/// `EdgeInst` in `graph_gpu.wgsl`. 40 bytes.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct EdgeInstance {
    /// Endpoint A in physical px.
    pub a: [f32; 2],
    /// Endpoint B in physical px.
    pub b: [f32; 2],
    /// Half-width in px.
    pub width: f32,
    pub _pad: f32,
    /// Emissive linear radiance `[r, g, b, a]`.
    pub color: [f32; 4],
}

/// A graph to draw on the GPU lane: a background clear colour + the node + edge
/// instance batches (already projected to screen px by the caller).
#[derive(Clone, Default)]
pub struct GraphScene {
    /// Background clear colour (linear, `[r, g, b, a]`).
    pub background: [f32; 4],
    pub nodes: Vec<NodeInstance>,
    pub edges: Vec<EdgeInstance>,
}

/// Bloom post-stack tuning (threshold/knee/intensity/exposure). The defaults keep
/// sub-1.0 scene radiance untouched and bloom only the emissive graph.
#[derive(Clone, Copy, Debug)]
pub struct BloomParams {
    pub threshold: f32,
    pub knee: f32,
    pub intensity: f32,
    pub exposure: f32,
    /// Blur σ (texels) for the glow spread.
    pub sigma: f32,
}

impl Default for BloomParams {
    fn default() -> Self {
        Self { threshold: 1.0, knee: 0.6, intensity: 1.3, exposure: 1.0, sigma: 3.0 }
    }
}

impl BloomParams {
    /// Bloom disabled (intensity 0) — the A/B reference for the render-proof.
    #[must_use]
    pub fn off(self) -> Self {
        Self { intensity: 0.0, ..self }
    }
}

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct SceneUniforms {
    viewport: [f32; 4],
}

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct PostUniforms {
    params: [f32; 4],
}

/// The result of a headless GPU graph render — the read-back LDR framebuffer plus the
/// instance draw counts (the render-proof asserts on these as DATA).
pub struct GraphRender {
    pub width: u32,
    pub height: u32,
    /// Straight RGBA8, row-major (length `width*height*4`).
    pub rgba: Vec<u8>,
    /// Node instances actually issued to the draw call.
    pub node_instances: u32,
    /// Edge instances actually issued to the draw call.
    pub edge_instances: u32,
}

impl GraphRender {
    /// Mean per-pixel luminance (Rec.601) over the LDR frame — the energy measure the
    /// bloom A/B oracle compares (bloom on vs off).
    #[must_use]
    pub fn mean_luma(&self) -> f64 {
        let mut sum = 0.0f64;
        for px in self.rgba.chunks_exact(4) {
            sum += 0.299 * px[0] as f64 + 0.587 * px[1] as f64 + 0.114 * px[2] as f64;
        }
        let n = (self.width * self.height) as f64;
        if n > 0.0 { sum / (n * 255.0) } else { 0.0 }
    }

    /// Luminance (0..1) of the pixel at `(x, y)` — for the additive-accumulation probe.
    #[must_use]
    pub fn luma_at(&self, x: u32, y: u32) -> f64 {
        if x >= self.width || y >= self.height {
            return 0.0;
        }
        let i = ((y * self.width + x) * 4) as usize;
        (0.299 * self.rgba[i] as f64 + 0.587 * self.rgba[i + 1] as f64 + 0.114 * self.rgba[i + 2] as f64) / 255.0
    }
}

/// The reusable graph GPU pipelines (node + edge instanced draws + the bloom post
/// stack). Built once from a device + the LDR target format; drive it with
/// [`GraphGpu::render`] (headless) — or, in the follow-up, from an `egui_wgpu`
/// callback.
pub struct GraphGpu {
    node_pipeline: wgpu::RenderPipeline,
    edge_pipeline: wgpu::RenderPipeline,
    bright_pipeline: wgpu::RenderPipeline,
    composite_pipeline: wgpu::RenderPipeline,
    scene_bgl: wgpu::BindGroupLayout,
    sample_bgl: wgpu::BindGroupLayout,
    composite_bgl: wgpu::BindGroupLayout,
    sampler: wgpu::Sampler,
    scene_u: wgpu::Buffer,
    post_u: wgpu::Buffer,
    /// Persistent scene bind group (`group(0) = { scene_u }`) for the node/edge passes.
    /// Held so the LIVE `egui_wgpu` callback ([`cloud`]) can encode the instanced draw
    /// without rebuilding a bind group per frame.
    scene_bg: wgpu::BindGroup,
    blur: GaussianBlur,
    ldr_format: wgpu::TextureFormat,
}

impl GraphGpu {
    /// Build the node/edge/bloom pipelines for an `ldr_format` colour target (the
    /// composite's output format — the host surface, or `Rgba8Unorm` headless).
    pub fn new(device: &wgpu::Device, ldr_format: wgpu::TextureFormat) -> Self {
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("graph3d_gpu"),
            source: wgpu::ShaderSource::Wgsl(crate::render::wgsl::GRAPHCLOUD_WGSL.into()),
        });

        // group(0) = { scene uniform } for the node/edge passes.
        let scene_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("graph3d_scene_bgl"),
            entries: &[uniform_entry(0, wgpu::ShaderStages::VERTEX)],
        });
        // group(0) = { post uniform, src tex, sampler } for the bright pass.
        let sample_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("graph3d_sample_bgl"),
            entries: &[
                uniform_entry(0, wgpu::ShaderStages::FRAGMENT),
                tex_entry(1),
                sampler_entry(2),
            ],
        });
        // group(0) = { post uniform, scene tex, sampler, bloom tex } for composite.
        let composite_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("graph3d_composite_bgl"),
            entries: &[
                uniform_entry(0, wgpu::ShaderStages::FRAGMENT),
                tex_entry(1),
                sampler_entry(2),
                tex_entry(3),
            ],
        });

        let additive = wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Add,
            },
        };

        let node_pll = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("graph3d_node_pll"),
            bind_group_layouts: &[Some(&scene_bgl)],
            immediate_size: 0,
        });
        let node_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("graph3d_node_pipeline"),
            layout: Some(&node_pll),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("node_vs"),
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: std::mem::size_of::<NodeInstance>() as u64,
                    step_mode: wgpu::VertexStepMode::Instance,
                    // EXPLICIT offsets: `NodeInstance` has a `_pad` after `radius`, so `color`
                    // lives at byte 16 — the auto-packed `vertex_attr_array` would place it at
                    // 12 (over the pad), shifting every channel and zeroing red. (Was a latent
                    // bug the luma-only render-proof never caught.)
                    attributes: &[
                        wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 0, shader_location: 0 },
                        wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32, offset: 8, shader_location: 1 },
                        wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x4, offset: 16, shader_location: 2 },
                    ],
                }],
                compilation_options: Default::default(),
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: None,
            multisample: crate::render::gpu::msaa_state(),
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("node_fs"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: OFFSCREEN_FORMAT,
                    blend: Some(additive),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            multiview_mask: None,
            cache: None,
        });

        let edge_pll = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("graph3d_edge_pll"),
            bind_group_layouts: &[Some(&scene_bgl)],
            immediate_size: 0,
        });
        let edge_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("graph3d_edge_pipeline"),
            layout: Some(&edge_pll),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("edge_vs"),
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: std::mem::size_of::<EdgeInstance>() as u64,
                    step_mode: wgpu::VertexStepMode::Instance,
                    // EXPLICIT offsets: `EdgeInstance` has a `_pad` after `width`, so `color`
                    // lives at byte 24 (auto-packing would put it at 20 over the pad).
                    attributes: &[
                        wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 0, shader_location: 0 },
                        wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 8, shader_location: 1 },
                        wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32, offset: 16, shader_location: 2 },
                        wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x4, offset: 24, shader_location: 3 },
                    ],
                }],
                compilation_options: Default::default(),
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: None,
            multisample: crate::render::gpu::msaa_state(),
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("edge_fs"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: OFFSCREEN_FORMAT,
                    blend: Some(additive),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            multiview_mask: None,
            cache: None,
        });

        let bright_pll = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("graph3d_bright_pll"),
            bind_group_layouts: &[Some(&sample_bgl)],
            immediate_size: 0,
        });
        let bright_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("graph3d_bright_pipeline"),
            layout: Some(&bright_pll),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("post_vs"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: None,
            multisample: crate::render::gpu::msaa_state(),
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("bright_fs"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: OFFSCREEN_FORMAT,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            multiview_mask: None,
            cache: None,
        });

        let composite_pll = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("graph3d_composite_pll"),
            bind_group_layouts: &[Some(&composite_bgl)],
            immediate_size: 0,
        });
        let composite_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("graph3d_composite_pipeline"),
            layout: Some(&composite_pll),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("post_vs"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
            depth_stencil: None,
            multisample: crate::render::gpu::msaa_state(),
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("composite_fs"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: ldr_format,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            multiview_mask: None,
            cache: None,
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("graph3d_sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            ..Default::default()
        });
        let mkbuf = |label: &str, size: u64| device.create_buffer(&wgpu::BufferDescriptor {
            label: Some(label),
            size,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let scene_u = mkbuf("graph3d_scene_u", std::mem::size_of::<SceneUniforms>() as u64);
        let scene_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("graph3d_scene_bg"),
            layout: &scene_bgl,
            entries: &[wgpu::BindGroupEntry { binding: 0, resource: scene_u.as_entire_binding() }],
        });
        Self {
            node_pipeline,
            edge_pipeline,
            bright_pipeline,
            composite_pipeline,
            scene_bgl,
            sample_bgl,
            composite_bgl,
            sampler,
            scene_u,
            post_u: mkbuf("graph3d_post_u", std::mem::size_of::<PostUniforms>() as u64),
            scene_bg,
            blur: GaussianBlur::new(device, OFFSCREEN_FORMAT),
            ldr_format,
        }
    }

    /// Write the viewport uniform (physical px) — the live callback ([`cloud`]) calls
    /// this once per frame before [`encode_scene`](Self::encode_scene).
    pub fn write_viewport(&self, queue: &wgpu::Queue, w: u32, h: u32) {
        queue.write_buffer(&self.scene_u, 0, bytemuck::bytes_of(&SceneUniforms { viewport: [w.max(1) as f32, h.max(1) as f32, 0.0, 0.0] }));
    }

    /// **Live-lane scene encode** — record the instanced emissive edge+node draw into
    /// `color_view` (an [`OFFSCREEN_FORMAT`] HDR target) on the caller's `encoder`, with
    /// the additive-blend accumulation the offscreen path uses. This is the SAME
    /// node/edge pipelines the headless [`render`](Self::render) drives (L5 reuse — no
    /// second renderer); the caller (the `egui_wgpu` callback) then blits `color_view`
    /// into egui's pass. Instance buffers are owned by the caller (kept alive until the
    /// frame is submitted). Edges draw first (under the nodes); both accumulate.
    #[allow(clippy::too_many_arguments)]
    pub fn encode_scene(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        color_view: &wgpu::TextureView,
        node_buf: Option<&wgpu::Buffer>,
        node_count: u32,
        edge_buf: Option<&wgpu::Buffer>,
        edge_count: u32,
        background: [f32; 4],
    ) {
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("graph3d_cloud_scene_pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: color_view,
                resolve_target: None,
                depth_slice: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(wgpu::Color {
                        r: background[0] as f64,
                        g: background[1] as f64,
                        b: background[2] as f64,
                        a: background[3] as f64,
                    }),
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        if let (Some(eb), true) = (edge_buf, edge_count > 0) {
            pass.set_pipeline(&self.edge_pipeline);
            pass.set_bind_group(0, &self.scene_bg, &[]);
            pass.set_vertex_buffer(0, eb.slice(..));
            pass.draw(0..6, 0..edge_count);
        }
        if let (Some(nb), true) = (node_buf, node_count > 0) {
            pass.set_pipeline(&self.node_pipeline);
            pass.set_bind_group(0, &self.scene_bg, &[]);
            pass.set_vertex_buffer(0, nb.slice(..));
            pass.draw(0..6, 0..node_count);
        }
    }

    /// Render `scene` at `w×h` px into an LDR texture and read it back. `bloom` tunes
    /// the post stack (use [`BloomParams::off`] for the A/B reference). Returns the
    /// LDR frame + the instance draw counts.
    pub fn render(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        w: u32,
        h: u32,
        scene: &GraphScene,
        bloom: BloomParams,
    ) -> GraphRender {
        use wgpu::util::DeviceExt;
        let w = w.max(1);
        let h = h.max(1);

        // Uniforms.
        queue.write_buffer(&self.scene_u, 0, bytemuck::bytes_of(&SceneUniforms { viewport: [w as f32, h as f32, 0.0, 0.0] }));
        queue.write_buffer(
            &self.post_u,
            0,
            bytemuck::bytes_of(&PostUniforms { params: [bloom.threshold, bloom.knee, bloom.intensity, bloom.exposure] }),
        );

        // Shared HDR scene offscreen (facett-core L0).
        let mut offscreen = OffscreenColorDepth::new(device, self.ldr_format);
        offscreen.ensure(device, w, h);
        let scene_view = offscreen.color_view().expect("offscreen ensured");

        // Bright-pass target + LDR present target (owned here).
        let bright = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("graph3d_bright"),
            size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
            mip_level_count: 1,
            sample_count: crate::render::gpu::NO_MSAA_SAMPLES,
            dimension: wgpu::TextureDimension::D2,
            format: OFFSCREEN_FORMAT,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let bright_view = bright.create_view(&Default::default());
        let ldr = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("graph3d_ldr"),
            size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
            mip_level_count: 1,
            sample_count: crate::render::gpu::NO_MSAA_SAMPLES,
            dimension: wgpu::TextureDimension::D2,
            format: self.ldr_format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let ldr_view = ldr.create_view(&Default::default());

        self.blur.ensure(device, queue, w, h, bloom.sigma);

        // Instance buffers.
        let node_buf = (!scene.nodes.is_empty()).then(|| {
            device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("graph3d_nodes"),
                contents: bytemuck::cast_slice(&scene.nodes),
                usage: wgpu::BufferUsages::VERTEX,
            })
        });
        let edge_buf = (!scene.edges.is_empty()).then(|| {
            device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("graph3d_edges"),
                contents: bytemuck::cast_slice(&scene.edges),
                usage: wgpu::BufferUsages::VERTEX,
            })
        });

        // Bind groups.
        let scene_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("graph3d_scene_bg"),
            layout: &self.scene_bgl,
            entries: &[wgpu::BindGroupEntry { binding: 0, resource: self.scene_u.as_entire_binding() }],
        });
        let bright_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("graph3d_bright_bg"),
            layout: &self.sample_bgl,
            entries: &[
                wgpu::BindGroupEntry { binding: 0, resource: self.post_u.as_entire_binding() },
                wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(scene_view) },
                wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) },
            ],
        });

        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("graph3d_enc") });

        // ── P1: scene pass — additive emissive nodes + edges into the HDR offscreen ──
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("graph3d_scene_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: scene_view,
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color {
                            r: scene.background[0] as f64,
                            g: scene.background[1] as f64,
                            b: scene.background[2] as f64,
                            a: scene.background[3] as f64,
                        }),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            // Edges first (under the nodes), then nodes — both accumulate additively.
            if let Some(eb) = &edge_buf {
                pass.set_pipeline(&self.edge_pipeline);
                pass.set_bind_group(0, &scene_bg, &[]);
                pass.set_vertex_buffer(0, eb.slice(..));
                pass.draw(0..6, 0..scene.edges.len() as u32);
            }
            if let Some(nb) = &node_buf {
                pass.set_pipeline(&self.node_pipeline);
                pass.set_bind_group(0, &scene_bg, &[]);
                pass.set_vertex_buffer(0, nb.slice(..));
                pass.draw(0..6, 0..scene.nodes.len() as u32);
            }
        }

        // ── P2: bright pass — isolate >threshold radiance into `bright` ──
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("graph3d_bright_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &bright_view,
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            pass.set_pipeline(&self.bright_pipeline);
            pass.set_bind_group(0, &bright_bg, &[]);
            pass.draw(0..3, 0..1);
        }

        // ── P3: blur the bright pass (separable Gaussian; facett-core L0) ──
        let bloom_view = self.blur.blur(device, &mut encoder, &bright_view).expect("blur ensured");

        // ── P4: composite — scene + bloom·intensity → tonemap → LDR ──
        let composite_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("graph3d_composite_bg"),
            layout: &self.composite_bgl,
            entries: &[
                wgpu::BindGroupEntry { binding: 0, resource: self.post_u.as_entire_binding() },
                wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(scene_view) },
                wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) },
                wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(bloom_view) },
            ],
        });
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("graph3d_composite_pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &ldr_view,
                    resolve_target: None,
                    depth_slice: None,
                    ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            pass.set_pipeline(&self.composite_pipeline);
            pass.set_bind_group(0, &composite_bg, &[]);
            pass.draw(0..3, 0..1);
        }

        // Read back the LDR present target.
        let bytes_per_pixel = 4u32;
        let unpadded = w * bytes_per_pixel;
        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
        let padded = unpadded.div_ceil(align) * align;
        let readback = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("graph3d_readback"),
            size: (padded * h) as u64,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &ldr,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback,
                layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(padded), rows_per_image: Some(h) },
            },
            wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
        );
        queue.submit(Some(encoder.finish()));

        let slice = readback.slice(..);
        let (tx, rx) = std::sync::mpsc::channel();
        slice.map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); });
        device.poll(wgpu::PollType::wait_indefinitely()).ok();
        rx.recv().ok();

        let data = slice.get_mapped_range();
        let mut rgba = Vec::with_capacity((w * h * 4) as usize);
        for row in 0..h {
            let start = (row * padded) as usize;
            rgba.extend_from_slice(&data[start..start + unpadded as usize]);
        }
        drop(data);
        readback.unmap();

        GraphRender {
            width: w,
            height: h,
            rgba,
            node_instances: scene.nodes.len() as u32,
            edge_instances: scene.edges.len() as u32,
        }
    }
}

/// **The LIVE `egui_wgpu` lane** — the follow-up the module header promised: wire the
/// same [`GraphGpu`] instanced node/edge pipelines into an `egui_wgpu` paint callback
/// so a host (korp) draws a 30 000-node cloud as GPU **instances** instead of egui
/// tessellating 30 000 discs + edges on ONE CPU core every frame (the measured
/// single-core rotation wall — see `examples/rotate_bench.rs`). Mirrors
/// `facett_graph3d::logo3d::gpu`: a persistent `*Renderer` in `callback_resources`, installed
/// once via [`install_cloud_renderer`], driven by a [`CallbackTrait`](egui_wgpu::CallbackTrait)
/// that draws into the shared [`OffscreenColorDepth`] colour target and blits it into
/// egui's pass. Behind `with_gpu(true)` opt-in — the CPU painter (the snapshot
/// golden path) is the untouched default fallback.
pub mod cloud {
    use super::{GraphGpu, GraphScene};
    use egui_wgpu::wgpu;
    use crate::render::gpu::offscreen::OffscreenColorDepth;

    /// Persistent GPU resources for the live cloud lane: the reused [`GraphGpu`]
    /// pipelines + a shared offscreen colour target (+ blit) + the per-frame instance
    /// buffers (kept here so they outlive the frame's submit).
    pub struct CloudRenderer {
        gpu: GraphGpu,
        offscreen: OffscreenColorDepth,
        node_buf: Option<wgpu::Buffer>,
        edge_buf: Option<wgpu::Buffer>,
        node_count: u32,
        edge_count: u32,
    }

    impl CloudRenderer {
        pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
            Self {
                gpu: GraphGpu::new(device, target_format),
                offscreen: OffscreenColorDepth::new(device, target_format),
                node_buf: None,
                edge_buf: None,
                node_count: 0,
                edge_count: 0,
            }
        }
    }

    /// One live cloud frame: the projected [`GraphScene`] + the pane size in physical px.
    pub struct CloudPaintCallback {
        pub scene: GraphScene,
        pub px_w: u32,
        pub px_h: u32,
    }

    impl egui_wgpu::CallbackTrait for CloudPaintCallback {
        fn prepare(
            &self,
            device: &wgpu::Device,
            queue: &wgpu::Queue,
            sd: &egui_wgpu::ScreenDescriptor,
            encoder: &mut wgpu::CommandEncoder,
            resources: &mut egui_wgpu::CallbackResources,
        ) -> Vec<wgpu::CommandBuffer> {
            use wgpu::util::DeviceExt;
            let Some(r) = resources.get_mut::<CloudRenderer>() else {
                return vec![];
            };
            let (w, h) = if self.px_w > 0 && self.px_h > 0 { (self.px_w, self.px_h) } else { (sd.size_in_pixels[0], sd.size_in_pixels[1]) };
            r.offscreen.ensure(device, w, h);
            r.gpu.write_viewport(queue, w, h);
            // (Re)build the instance buffers for THIS frame — kept on the persistent
            // renderer so they stay alive until egui submits the encoder.
            r.node_buf = (!self.scene.nodes.is_empty()).then(|| {
                device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("graph3d_cloud_nodes"),
                    contents: bytemuck::cast_slice(&self.scene.nodes),
                    usage: wgpu::BufferUsages::VERTEX,
                })
            });
            r.edge_buf = (!self.scene.edges.is_empty()).then(|| {
                device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("graph3d_cloud_edges"),
                    contents: bytemuck::cast_slice(&self.scene.edges),
                    usage: wgpu::BufferUsages::VERTEX,
                })
            });
            r.node_count = self.scene.nodes.len() as u32;
            r.edge_count = self.scene.edges.len() as u32;
            let Some(color_view) = r.offscreen.color_view() else {
                return vec![];
            };
            // Immutable co-borrows of distinct fields (gpu / offscreen / *_buf) — the
            // instanced draw the CPU no longer tessellates.
            r.gpu.encode_scene(
                encoder,
                color_view,
                r.node_buf.as_ref(),
                r.node_count,
                r.edge_buf.as_ref(),
                r.edge_count,
                self.scene.background,
            );
            // LANE ATTRIBUTION (`crate::render::lane`): the instanced scene is encoded
            // against a real device, after every fail-safe early-return above. Counted
            // so an About box can say IN USE for this lane instead of leaving the whole
            // app's answer at `unknown` — korp installs THIS renderer beside the map's,
            // and one silent lane is enough to make the honest answer unknowable.
            crate::render::lane::note_frame(std::any::type_name::<CloudRenderer>());
            vec![]
        }

        fn paint(
            &self,
            info: egui::PaintCallbackInfo,
            render_pass: &mut wgpu::RenderPass<'static>,
            resources: &egui_wgpu::CallbackResources,
        ) {
            let Some(r) = resources.get::<CloudRenderer>() else { return };
            if !r.offscreen.ready() {
                return;
            }
            // Blit the instanced HDR cloud into egui's pass, scissored to the widget.
            let _scissor = r.offscreen.blit(&info, render_pass);
        }
    }

    /// Has a host installed the cloud renderer in this process?
    ///
    /// This exists because the GPU lane is **fail-dangerous** without it:
    /// `Graph3D::draw_gpu_cloud` returning `true` makes the view SKIP the CPU
    /// tessellation of the whole node/edge cloud. If a host called
    /// `with_gpu(true)` but never called [`install_cloud_renderer`], the paint
    /// callback finds no `CloudRenderer`, draws nothing — and the CPU painter has
    /// already been skipped, so the pane renders **BLANK**. That is a silent
    /// black 3D graph, and neither the pixel nor the state oracle would blame the
    /// missing install.
    ///
    /// So the fast path is gated on this flag: opt in *and* install, or the CPU
    /// painter draws unchanged. Process-global (the renderer lives in the one
    /// `RenderState` a host builds at startup) and monotonic — installing is a
    /// startup act, never undone.
    pub(crate) static CLOUD_RENDERER_INSTALLED: std::sync::atomic::AtomicBool =
        std::sync::atomic::AtomicBool::new(false);

    /// `true` once a host has installed the instanced cloud renderer, so
    /// `with_gpu(true)` will actually paint. Hosts can assert on it at
    /// startup; `Graph3D` consults it before skipping the CPU painter.
    #[must_use]
    pub fn cloud_renderer_installed() -> bool {
        CLOUD_RENDERER_INSTALLED.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Install a [`CloudRenderer`] into an egui-wgpu `RenderState`'s callback resources
    /// (call once at host startup, like `facett-map`/`logo3d`'s `install_renderer`).
    /// Idempotent. Also arms [`cloud_renderer_installed`], which is what unlocks
    /// `Graph3D`'s instanced fast path.
    /// The install-once body is the shared `crate::render::gpu::install_renderer`
    /// (LAW #5 — one writer, not a fourth hand-rolled get-or-insert), which also
    /// registers the lane with `crate::render::lane` so an About box can see it.
    pub fn install_cloud_renderer(render_state: &egui_wgpu::RenderState) {
        CLOUD_RENDERER_INSTALLED.store(true, std::sync::atomic::Ordering::Relaxed);
        // This lane counts its frames (see `CloudPaintCallback::prepare`), so a zero
        // means "installed and never painted" instead of "did not say".
        crate::render::lane::note_reports_frames(std::any::type_name::<CloudRenderer>());
        // ── AND SAY WHY THE ZERO IS THERE. A freshly installed lane has not painted for
        //    exactly one reason: nobody has drawn the pane that owns it. `facett-map`'s
        //    map lane has said so since 2026-08-02; this one stayed silent, and silence
        //    is not free — `GpuStatus::every_idle_lane_is_undrawn` cannot conclude
        //    anything from a lane that never spoke, so ONE silent lane was enough to put
        //    the About box back to "installed but UNUSED … (the CPU painter is doing the
        //    work)" on a host where nothing had drawn a map OR a graph. MEASURED on korp
        //    2026-08-03: `[(CloudRenderer, 0, None), (GpuMapRenderer, 0,
        //    pane_not_painted_yet)]`.
        //
        //    `Graph3D`/`cloud_gpu_scene` overwrite this the first time they run, so the
        //    row only says it while it is true.
        crate::render::lane::note_idle_reason(
            std::any::type_name::<CloudRenderer>(),
            Some(crate::render::lane::PANE_NOT_PAINTED_YET),
        );
        let _ = crate::render::gpu::install_renderer(render_state, CloudRenderer::new);
    }

    /// **THE one GPU-cloud entry point every graph pane calls.** Returns `true` if the
    /// instanced cloud was pushed for `rect` — and therefore, and only therefore, the
    /// caller may skip its CPU tessellation of the node/edge cloud.
    ///
    /// It performs, in one place, the whole fail-safe protocol that must not be
    /// re-derived per pane:
    ///
    /// 1. `use_gpu` off ⇒ `false`. The CPU painter runs; goldens are untouched.
    /// 2. **Renderer not installed ⇒ `false`.** This is the trap. Opting in is not
    ///    enough: without [`install_cloud_renderer`] the paint callback finds no
    ///    `CloudRenderer` and draws *nothing*, while the caller has already skipped the
    ///    CPU painter — a silently **BLANK** pane. That exact shape shipped once in
    ///    `Graph3D` (proven by tests, installed by no host) and was the whole "the 3D
    ///    graphs are missing" symptom. Falling back here makes it structurally
    ///    impossible for a *new* pane to reintroduce it: the pane cannot skip its CPU
    ///    painter without going through this function, and this function will not say
    ///    yes until a renderer really exists.
    /// 3. A degenerate rect (zero px) ⇒ `false`.
    ///
    /// `build` is only invoked once every gate has passed — so building the instance
    /// scene costs nothing on the fallback path. It receives the pane size in
    /// **physical px** (`rect` × `pixels_per_point`), which is the space
    /// [`NodeInstance::center`] / [`EdgeInstance::a`] live in.
    pub fn draw_cloud(
        ui: &egui::Ui,
        rect: egui::Rect,
        use_gpu: bool,
        build: impl FnOnce(f32, f32) -> GraphScene,
    ) -> bool {
        if !use_gpu || !cloud_renderer_installed() {
            return false;
        }
        let ppp = ui.ctx().pixels_per_point();
        let px_w = (rect.width() * ppp).round();
        let px_h = (rect.height() * ppp).round();
        if !(px_w >= 1.0 && px_h >= 1.0) {
            return false;
        }
        let scene = build(px_w, px_h);
        if scene.nodes.is_empty() && scene.edges.is_empty() {
            return false;
        }
        ui.painter().add(egui_wgpu::Callback::new_paint_callback(
            rect,
            CloudPaintCallback { scene, px_w: px_w as u32, px_h: px_h as u32 },
        ));
        true
    }
}

/// **The shared 2-D lowering** — turn already-projected screen geometry into a
/// [`GraphScene`] of emissive instances. Every 2-D graph pane
/// (`facett-graphpan` / `facett-graphview` / `facett-graphnav`) lowers through this,
/// so the look, the sRGB→linear conversion and the emissive scaling are defined once
/// (L5) rather than re-derived per crate with three slightly different gammas.
///
/// `emissive` scales peak linear radiance; `≈2.5` reads bright over a dark pane with a
/// ~1.0 bright-pass threshold, `1.0` is calm. Edges are emitted first so they sit under
/// the nodes, matching the CPU painters' order.
#[derive(Clone, Copy, Debug)]
pub struct CloudBuilder {
    /// Peak emissive multiplier for node instances.
    pub emissive: f32,
    /// Edge radiance as a fraction of the node peak (crossings still accumulate).
    pub edge_gain: f32,
    /// Clear colour behind the cloud (linear rgba).
    pub background: [f32; 4],
}

impl Default for CloudBuilder {
    fn default() -> Self {
        Self { emissive: 2.5, edge_gain: 0.6, background: [0.02, 0.022, 0.03, 1.0] }
    }
}

impl CloudBuilder {
    /// Linear radiance for one `Color32` at `mul × emissive`. sRGB is approximated by a
    /// square — the same curve `Graph3D::gpu_scene_at` has always used, kept identical
    /// so the 2-D and 3-D clouds cannot drift apart visually.
    #[must_use]
    pub fn radiance(&self, c: egui::Color32, mul: f32) -> [f32; 4] {
        let lin = |b: u8| {
            let s = b as f32 / 255.0;
            s * s
        };
        let k = self.emissive * mul;
        [lin(c.r()) * k, lin(c.g()) * k, lin(c.b()) * k, 1.0]
    }

    /// Lower `nodes` (`centre px`, `radius px`, colour) and `edges` (`a px`, `b px`,
    /// `half-width px`, colour) into an instanced [`GraphScene`]. Pure — no device, no
    /// egui painting — so a headless test can assert the instance counts and positions
    /// without a GPU.
    #[must_use]
    pub fn scene(
        &self,
        nodes: impl IntoIterator<Item = (egui::Pos2, f32, egui::Color32)>,
        edges: impl IntoIterator<Item = (egui::Pos2, egui::Pos2, f32, egui::Color32)>,
    ) -> GraphScene {
        let edges = edges
            .into_iter()
            .map(|(a, b, w, c)| EdgeInstance {
                a: [a.x, a.y],
                b: [b.x, b.y],
                width: w.max(0.5),
                _pad: 0.0,
                color: self.radiance(c, self.edge_gain),
            })
            .collect();
        let nodes = nodes
            .into_iter()
            .map(|(p, r, c)| NodeInstance {
                center: [p.x, p.y],
                radius: r.max(0.5),
                _pad: 0.0,
                color: self.radiance(c, 1.0),
            })
            .collect();
        GraphScene { background: self.background, nodes, edges }
    }
}

fn uniform_entry(binding: u32, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: vis,
        ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
        count: None,
    }
}
fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Texture {
            sample_type: wgpu::TextureSampleType::Float { filterable: true },
            view_dimension: wgpu::TextureViewDimension::D2,
            multisampled: false,
        },
        count: None,
    }
}
fn sampler_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
        count: None,
    }
}

/// **Headless render-proof entry point.** Spin up an adapter/device, render `scene`
/// at `w×h` through the full instanced + bloom lane, and read back the LDR frame +
/// the instance draw counts. `None` when no wgpu adapter is available (CPU-only CI),
/// so the caller degrades to a skip rather than a false failure.
#[must_use]
pub fn render_graph_offscreen(w: u32, h: u32, scene: &GraphScene, bloom: BloomParams) -> Option<GraphRender> {
    pollster::block_on(render_graph_offscreen_async(w, h, scene, bloom))
}

async fn render_graph_offscreen_async(w: u32, h: u32, scene: &GraphScene, bloom: BloomParams) -> Option<GraphRender> {
    // THE GPU TURN + the adapter policy, via the one bring-up writer
    // (`crate::render::gputurn::probe`). This is the device probe `facett-graph3d`,
    // `facett-helix` and `facett-graphview` all render through, so the turn taken here
    // serialises those crates' pixel tests too. `OnSoftware::Skip`, not `Refuse`: the
    // signature is already `Option` and every caller reads `None` as "no GPU, skip".
    let probe = crate::render::gputurn::probe::open(
        "graph3d-gpu-offscreen",
        crate::render::gputurn::probe::OnSoftware::Skip,
        crate::render::gputurn::probe::downlevel,
    )?;
    let (device, queue) = (&probe.device, &probe.queue);
    let mut gpu = GraphGpu::new(device, wgpu::TextureFormat::Rgba8Unorm);
    Some(gpu.render(device, queue, w, h, scene, bloom))
}