BREP_render 0.1.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
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
use super::*;

impl RenderCore {
    /// Render one frame into `resolve_view` (a single-sample view of the
    /// core's format). This is the whole engine core; every presentation shell
    /// funnels through it.
    pub fn render_to_view(
        &mut self,
        gpu_scene: &mut GpuScene,
        scene: &RenderScene,
        params: &FrameParams,
        resolve_view: &wgpu::TextureView,
    ) {
        let width = params.width.max(1);
        let height = params.height.max(1);
        self.ensure_targets(width, height);
        self.write_global_styles(params.settings);

        let globals = Globals {
            view_proj: params.camera.view_proj,
            viewport: [width as f32, height as f32, params.dpr.max(1e-3), 0.0],
            forward: [
                params.camera.forward[0],
                params.camera.forward[1],
                params.camera.forward[2],
                0.0,
            ],
        };
        self.queue
            .write_buffer(&self.globals_buf, 0, bytemuck::bytes_of(&globals));

        // World-axis helper (R20): three world-axis segments sized in CSS px.
        let axis_len = params.settings.axis_length_px as f64 * params.world_per_pixel;
        let draw_axes = params.settings.axis_length_px > 0.0 && axis_len.is_finite() && axis_len > 0.0;
        if draw_axes {
            let l = axis_len as f32;
            let segments = [
                EdgeInstance { p0: [0.0; 3], p1: [l, 0.0, 0.0] },
                EdgeInstance { p0: [0.0; 3], p1: [0.0, l, 0.0] },
                EdgeInstance { p0: [0.0; 3], p1: [0.0, 0.0, l] },
            ];
            match &gpu_scene.axis_buf {
                Some(buf) => self.queue.write_buffer(buf, 0, bytemuck::cast_slice(&segments)),
                None => {
                    gpu_scene.axis_buf = Some(self.device.create_buffer_init(
                        &wgpu::util::BufferInitDescriptor {
                            label: Some("world axes"),
                            contents: bytemuck::cast_slice(&segments),
                            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                        },
                    ));
                }
            }
        }

        // Refresh emphasis boundary buffers.
        let has_emphasis = !params.emphasis.is_empty();
        for solid in scene.solids() {
            if let Some(gpu_solid) = gpu_scene.solids.get_mut(&solid.name) {
                self.sync_boundary(gpu_solid, solid, params.emphasis);
            }
        }

        let bg = params.settings.background;
        let targets = self.targets.as_ref().expect("targets ensured");
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("brep-render frame"),
            });
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("scene"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &targets.msaa_view,
                    depth_slice: None,
                    resolve_target: Some(resolve_view),
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color {
                            r: bg[0] as f64,
                            g: bg[1] as f64,
                            b: bg[2] as f64,
                            a: 1.0,
                        }),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                    view: &targets.depth_view,
                    depth_ops: Some(wgpu::Operations {
                        load: wgpu::LoadOp::Clear(1.0),
                        store: wgpu::StoreOp::Discard,
                    }),
                    stencil_ops: None,
                }),
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            pass.set_bind_group(0, &self.globals_bind, &[]);

            let visible_solids: Vec<(&SolidDisplay, &GpuSolid)> = gpu_scene
                .order
                .iter()
                .filter_map(|name| {
                    let solid = scene.solid(name)?;
                    if !solid.visible {
                        return None;
                    }
                    Some((solid, gpu_scene.solids.get(name)?))
                })
                .collect();

            // 1a. Wireframe view: draw each solid's tessellated triangle mesh as
            //     a line list (base color, no fill), so the face triangles read
            //     as a wireframe. Picking is CPU ray-based (pick.rs), unaffected.
            //     A HIDDEN face skips its triangles' wire segments too, exactly as
            //     the shaded pass masks its triangle ranges — otherwise hiding a
            //     face (or the whole Faces group) would be a no-op in wireframe view.
            if params.settings.wireframe {
                pass.set_pipeline(&self.wire_pipeline);
                for (solid, gpu_solid) in &visible_solids {
                    if gpu_solid.wire_index_count == 0 {
                        continue;
                    }
                    pass.set_vertex_buffer(0, gpu_solid.vertex_buf.slice(..));
                    pass.set_index_buffer(
                        gpu_solid.wire_index_buf.slice(..),
                        wgpu::IndexFormat::Uint32,
                    );
                    pass.set_bind_group(1, &gpu_solid.base_style.bind, &[]);
                    // Fast path: no hidden face → one whole-buffer wire draw.
                    if !solid.visibility.any_face_hidden() {
                        pass.draw_indexed(0..gpu_solid.wire_index_count, 0, 0..1);
                        continue;
                    }
                    // Otherwise coalesce contiguous VISIBLE faces' wire ranges and
                    // skip the hidden ones. The wire buffer is a LINE LIST built per
                    // triangle (6 indices/triangle — 3 edges × 2 endpoints), in mesh
                    // triangle order, so face i occupies wire indices
                    // `tri_start*6 .. (tri_start+tri_count)*6` (NOT the shaded
                    // `gpu_solid.faces` ranges, which are ×3 for the triangle buffer).
                    let mut run: Option<(u32, u32)> = None; // first, count
                    let flush = |pass: &mut wgpu::RenderPass, run: &mut Option<(u32, u32)>| {
                        if let Some((first, count)) = run.take() {
                            if count > 0 {
                                pass.draw_indexed(first..first + count, 0, 0..1);
                            }
                        }
                    };
                    for (index, face) in solid.faces.iter().enumerate() {
                        if face.tri_count == 0 {
                            continue;
                        }
                        let first = face.tri_start * 6;
                        let count = face.tri_count * 6;
                        if !solid.visibility.is_face_visible(index) {
                            flush(&mut pass, &mut run);
                            continue;
                        }
                        match &mut run {
                            Some((run_first, run_count)) if *run_first + *run_count == first => {
                                *run_count += count;
                            }
                            _ => {
                                flush(&mut pass, &mut run);
                                run = Some((first, count));
                            }
                        }
                    }
                    flush(&mut pass, &mut run);
                }
            }

            // 1. Shaded faces, coalesced into index-range runs per emphasis
            //    state (base runs merge back into whole-solid draws). Skipped in
            //    wireframe mode (1a draws the triangle wireframe instead). Picking
            //    is CPU ray-based (pick.rs) and the overlay pass is separate.
            if !params.settings.wireframe {
                pass.set_pipeline(&self.mesh_pipeline);
                for (solid, gpu_solid) in &visible_solids {
                    if solid.mesh.indices.is_empty() {
                        continue;
                    }
                    pass.set_vertex_buffer(0, gpu_solid.vertex_buf.slice(..));
                    pass.set_index_buffer(gpu_solid.index_buf.slice(..), wgpu::IndexFormat::Uint32);
                    // Fast path: no emphasis AND no hidden faces → one whole-mesh
                    // draw. When any face is hidden we fall to the per-face loop
                    // below, which coalesces contiguous VISIBLE faces and skips
                    // the hidden ones' triangle ranges entirely.
                    let any_face_hidden = solid.visibility.any_face_hidden();
                    if !has_emphasis && !any_face_hidden {
                        pass.set_bind_group(1, &gpu_solid.base_style.bind, &[]);
                        pass.draw_indexed(0..solid.mesh.indices.len() as u32, 0, 0..1);
                        continue;
                    }
                    let style_for = |state: EmphasisState| match state {
                        EmphasisState::Base => &gpu_solid.base_style.bind,
                        EmphasisState::Selected => &self.styles.face_selected.bind,
                        EmphasisState::Hovered => &self.styles.face_hovered.bind,
                    };
                    let mut run: Option<(EmphasisState, u32, u32)> = None; // state, first, count
                    let flush = |pass: &mut wgpu::RenderPass, run: &mut Option<(EmphasisState, u32, u32)>| {
                        if let Some((state, first, count)) = run.take() {
                            if count > 0 {
                                pass.set_bind_group(1, style_for(state), &[]);
                                pass.draw_indexed(first..first + count, 0, 0..1);
                            }
                        }
                    };
                    for (index, face) in solid.faces.iter().enumerate() {
                        let range = &gpu_solid.faces[index];
                        if range.index_count == 0 {
                            continue;
                        }
                        // Hidden face: skip its triangles and break the run so
                        // the surviving neighbours don't coalesce across the gap.
                        if !solid.visibility.is_face_visible(index) {
                            flush(&mut pass, &mut run);
                            continue;
                        }
                        let state = if has_emphasis {
                            params.emphasis.face_state(&solid.name, &face.name)
                        } else {
                            EmphasisState::Base
                        };
                        match &mut run {
                            Some((run_state, first, count))
                                if *run_state == state && *first + *count == range.first_index =>
                            {
                                *count += range.index_count;
                            }
                            _ => {
                                flush(&mut pass, &mut run);
                                run = Some((state, range.first_index, range.index_count));
                            }
                        }
                    }
                    flush(&mut pass, &mut run);
                }
            }

            // 2. Occluded edge portions, dimmed (depth test inverted). Hidden
            //    edges skip their segments (their occluded portion too).
            if params.settings.hidden_edge_alpha > 0.0 {
                pass.set_pipeline(&self.edge_hidden_pipeline);
                pass.set_bind_group(1, &self.styles.edge_hidden.bind, &[]);
                for (solid, gpu_solid) in &visible_solids {
                    let Some(edge_buf) = &gpu_solid.edge_buf else { continue };
                    if gpu_solid.edge_instances == 0 {
                        continue;
                    }
                    pass.set_vertex_buffer(0, edge_buf.slice(..));
                    if solid.visibility.any_edge_hidden() {
                        // Single style already bound: draw only visible edges.
                        draw_visible_edge_ranges(&mut pass, solid, gpu_solid);
                    } else {
                        pass.draw(0..6, 0..gpu_solid.edge_instances);
                    }
                }
            }

            // 3. Visible edges, per-edge emphasis runs; hidden edges skipped.
            pass.set_pipeline(&self.edge_visible_pipeline);
            for (solid, gpu_solid) in &visible_solids {
                let Some(edge_buf) = &gpu_solid.edge_buf else { continue };
                if gpu_solid.edge_instances == 0 {
                    continue;
                }
                pass.set_vertex_buffer(0, edge_buf.slice(..));
                let any_edge_hidden = solid.visibility.any_edge_hidden();
                if !has_emphasis {
                    pass.set_bind_group(1, &self.styles.edge_base.bind, &[]);
                    if any_edge_hidden {
                        draw_visible_edge_ranges(&mut pass, solid, gpu_solid);
                    } else {
                        pass.draw(0..6, 0..gpu_solid.edge_instances);
                    }
                    continue;
                }
                let style_for = |state: EmphasisState| match state {
                    EmphasisState::Base => &self.styles.edge_base.bind,
                    EmphasisState::Selected => &self.styles.edge_selected.bind,
                    EmphasisState::Hovered => &self.styles.edge_hovered.bind,
                };
                let mut run: Option<(EmphasisState, u32, u32)> = None;
                let flush = |pass: &mut wgpu::RenderPass, run: &mut Option<(EmphasisState, u32, u32)>| {
                    if let Some((state, first, count)) = run.take() {
                        if count > 0 {
                            pass.set_bind_group(1, style_for(state), &[]);
                            pass.draw(0..6, first..first + count);
                        }
                    }
                };
                for (index, edge) in solid.edges.iter().enumerate() {
                    let range = &gpu_solid.edges[index];
                    if range.instance_count == 0 {
                        continue;
                    }
                    // Hidden edge: skip its segments and break the run.
                    if !solid.visibility.is_edge_visible(index) {
                        flush(&mut pass, &mut run);
                        continue;
                    }
                    let state = params.emphasis.edge_state(&solid.name, &edge.name);
                    match &mut run {
                        Some((run_state, first, count))
                            if *run_state == state
                                && *first + *count == range.first_instance =>
                        {
                            *count += range.instance_count;
                        }
                        _ => {
                            flush(&mut pass, &mut run);
                            run = Some((state, range.first_instance, range.instance_count));
                        }
                    }
                }
                flush(&mut pass, &mut run);
            }

            // 4. Selected/hovered face boundary outlines.
            if has_emphasis {
                pass.set_bind_group(1, &self.styles.boundary.bind, &[]);
                for (_, gpu_solid) in &visible_solids {
                    let Some(boundary) = &gpu_solid.boundary else { continue };
                    let Some(buf) = &boundary.buf else { continue };
                    if boundary.count == 0 {
                        continue;
                    }
                    pass.set_vertex_buffer(0, buf.slice(..));
                    pass.draw(0..6, 0..boundary.count);
                }
            }

            // 5. Vertex points; hidden vertices skip their point sprite.
            if params.settings.vertex_size_px > 0.0 {
                pass.set_pipeline(&self.point_pipeline);
                for (solid, gpu_solid) in &visible_solids {
                    let Some(point_buf) = &gpu_solid.point_buf else { continue };
                    if gpu_solid.point_count == 0 {
                        continue;
                    }
                    // A fully-hidden points group draws nothing — skip before touching
                    // the per-vertex loop below. When ALL vertices are hidden that loop
                    // would still iterate every one of them each frame; the O(N)/frame
                    // cost is invisible on native but throttles the WebGL backend on
                    // point-heavy models (the "can't spin after hiding points" case).
                    if solid.visibility.all_vertices_hidden(solid.vertices.len()) {
                        continue;
                    }
                    pass.set_vertex_buffer(0, point_buf.slice(..));
                    let any_vertex_hidden = solid.visibility.any_vertex_hidden();
                    if has_emphasis || any_vertex_hidden {
                        let tol = 1e-9_f64.max(params.world_per_pixel * 1e-3);
                        let mut base_run: Option<(u32, u32)> = None;
                        let mut emphasized: Vec<(EmphasisState, u32)> = Vec::new();
                        for (index, vertex) in solid.vertices.iter().enumerate() {
                            // Hidden vertex: skip its point and break the run.
                            if !solid.visibility.is_vertex_visible(index) {
                                if let Some((first, count)) = base_run.take() {
                                    pass.set_bind_group(1, &self.styles.point_base.bind, &[]);
                                    pass.draw(0..6, first..first + count);
                                }
                                continue;
                            }
                            let state = if has_emphasis {
                                params.emphasis.vertex_state(&solid.name, vertex.position, tol)
                            } else {
                                EmphasisState::Base
                            };
                            if state == EmphasisState::Base {
                                match &mut base_run {
                                    Some((first, count)) if *first + *count == index as u32 => {
                                        *count += 1
                                    }
                                    _ => {
                                        if let Some((first, count)) = base_run.take() {
                                            pass.set_bind_group(1, &self.styles.point_base.bind, &[]);
                                            pass.draw(0..6, first..first + count);
                                        }
                                        base_run = Some((index as u32, 1));
                                    }
                                }
                            } else {
                                emphasized.push((state, index as u32));
                            }
                        }
                        if let Some((first, count)) = base_run {
                            pass.set_bind_group(1, &self.styles.point_base.bind, &[]);
                            pass.draw(0..6, first..first + count);
                        }
                        for (state, index) in emphasized {
                            let style = match state {
                                EmphasisState::Selected => &self.styles.point_selected.bind,
                                _ => &self.styles.point_hovered.bind,
                            };
                            pass.set_bind_group(1, style, &[]);
                            pass.draw(0..6, index..index + 1);
                        }
                    } else {
                        pass.set_bind_group(1, &self.styles.point_base.bind, &[]);
                        pass.draw(0..6, 0..gpu_solid.point_count);
                    }
                }
            }

            // 6. World axes on top of nothing special (normal depth test).
            if draw_axes {
                if let Some(axis_buf) = &gpu_scene.axis_buf {
                    pass.set_pipeline(&self.edge_visible_pipeline);
                    pass.set_vertex_buffer(0, axis_buf.slice(..));
                    for (index, style) in [
                        &self.styles.axis_x,
                        &self.styles.axis_y,
                        &self.styles.axis_z,
                    ]
                    .iter()
                    .enumerate()
                    {
                        pass.set_bind_group(1, &style.bind, &[]);
                        let i = index as u32;
                        pass.draw(0..6, i..i + 1);
                    }
                }
            }
        }

        // --- Overlay-widget passes: the brep-gizmos overlay drawn
        //     over the solids in a depth-cleared pass so widgets read on top.
        //     The main overlay uses the scene camera + full viewport; the
        //     ViewCube uses its own mini-camera + corner viewport.
        if let Some(overlay) = params.overlay {
            let make_tris = |ov: &brep_gizmos::Overlay| -> Option<wgpu::Buffer> {
                let verts = overlay_tri_verts(ov);
                (!verts.is_empty()).then(|| {
                    self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                        label: Some("overlay tris"),
                        contents: bytemuck::cast_slice(&verts),
                        usage: wgpu::BufferUsages::VERTEX,
                    })
                })
            };
            let make_lines = |ov: &brep_gizmos::Overlay| -> Option<wgpu::Buffer> {
                let insts = overlay_line_insts(ov);
                (!insts.is_empty()).then(|| {
                    self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                        label: Some("overlay lines"),
                        contents: bytemuck::cast_slice(&insts),
                        usage: wgpu::BufferUsages::VERTEX,
                    })
                })
            };

            let main_tri_count = overlay.main.tris.len() as u32;
            let main_line_count = (overlay.main.lines.len() / 2) as u32;
            let main_tri_buf = make_tris(&overlay.main);
            let main_line_buf = make_lines(&overlay.main);
            if main_tri_buf.is_some() || main_line_buf.is_some() {
                let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("overlay-main"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: &targets.msaa_view,
                        depth_slice: None,
                        resolve_target: Some(resolve_view),
                        ops: wgpu::Operations {
                            load: wgpu::LoadOp::Load,
                            store: wgpu::StoreOp::Store,
                        },
                    })],
                    depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                        view: &targets.depth_view,
                        depth_ops: Some(wgpu::Operations {
                            load: wgpu::LoadOp::Clear(1.0),
                            store: wgpu::StoreOp::Discard,
                        }),
                        stencil_ops: None,
                    }),
                    timestamp_writes: None,
                    occlusion_query_set: None,
                    multiview_mask: None,
                });
                pass.set_bind_group(0, &self.globals_bind, &[]);
                pass.set_bind_group(1, &self.styles.overlay_line.bind, &[]);
                if let Some(buf) = &main_tri_buf {
                    pass.set_pipeline(&self.overlay_tri_pipeline);
                    pass.set_vertex_buffer(0, buf.slice(..));
                    pass.draw(0..main_tri_count, 0..1);
                }
                if let Some(buf) = &main_line_buf {
                    pass.set_pipeline(&self.overlay_line_pipeline);
                    pass.set_vertex_buffer(0, buf.slice(..));
                    pass.draw(0..6, 0..main_line_count);
                }
            }

            if let Some(vc) = &overlay.viewcube {
                let dpr = params.dpr.max(1e-3);
                let mut x = (vc.rect_css[0] * dpr).max(0.0);
                let mut y = (vc.rect_css[1] * dpr).max(0.0);
                let mut w = (vc.rect_css[2] * dpr).max(1.0);
                let mut h = (vc.rect_css[3] * dpr).max(1.0);
                // Clamp the corner viewport to the framebuffer.
                w = w.min(width as f32 - x).max(1.0);
                h = h.min(height as f32 - y).max(1.0);
                x = x.min(width as f32 - w).max(0.0);
                y = y.min(height as f32 - h).max(0.0);

                let vc_globals = Globals {
                    view_proj: vc.view_proj,
                    viewport: [w, h, dpr, 0.0],
                    forward: [vc.forward[0], vc.forward[1], vc.forward[2], 0.0],
                };
                self.queue
                    .write_buffer(&self.vc_globals_buf, 0, bytemuck::bytes_of(&vc_globals));

                let vc_tri_count = vc.overlay.tris.len() as u32;
                let vc_line_count = (vc.overlay.lines.len() / 2) as u32;
                let vc_tri_buf = make_tris(&vc.overlay);
                let vc_line_buf = make_lines(&vc.overlay);
                if vc_tri_buf.is_some() || vc_line_buf.is_some() {
                    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                        label: Some("overlay-viewcube"),
                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                            view: &targets.msaa_view,
                            depth_slice: None,
                            resolve_target: Some(resolve_view),
                            ops: wgpu::Operations {
                                load: wgpu::LoadOp::Load,
                                store: wgpu::StoreOp::Store,
                            },
                        })],
                        depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                            view: &targets.depth_view,
                            depth_ops: Some(wgpu::Operations {
                                load: wgpu::LoadOp::Clear(1.0),
                                store: wgpu::StoreOp::Discard,
                            }),
                            stencil_ops: None,
                        }),
                        timestamp_writes: None,
                        occlusion_query_set: None,
                        multiview_mask: None,
                    });
                    pass.set_viewport(x, y, w, h, 0.0, 1.0);
                    pass.set_scissor_rect(x as u32, y as u32, w as u32, h as u32);
                    pass.set_bind_group(0, &self.vc_globals_bind, &[]);
                    pass.set_bind_group(1, &self.styles.overlay_line.bind, &[]);
                    if let Some(buf) = &vc_tri_buf {
                        pass.set_pipeline(&self.overlay_tri_pipeline);
                        pass.set_vertex_buffer(0, buf.slice(..));
                        pass.draw(0..vc_tri_count, 0..1);
                    }
                    if let Some(buf) = &vc_line_buf {
                        pass.set_pipeline(&self.overlay_line_pipeline);
                        pass.set_vertex_buffer(0, buf.slice(..));
                        pass.draw(0..6, 0..vc_line_count);
                    }
                }
            }
        }

        self.queue.submit([encoder.finish()]);
    }

    /// Headless capture (R32/R34): render the scene and return PNG bytes
    /// (8-bit RGB, no ancillary chunks — deterministic, R33).
    #[cfg(not(target_arch = "wasm32"))]
    pub fn render_to_png(
        &mut self,
        scene: &RenderScene,
        camera: &Camera,
        width: u32,
        height: u32,
    ) -> Result<Vec<u8>, String> {
        let settings = RenderSettings::artifact();
        let emphasis = Emphasis::default();
        let mut gpu_scene = self.upload_scene_with(scene, &settings);
        let params = FrameParams {
            camera,
            width,
            height,
            dpr: 1.0,
            settings: &settings,
            emphasis: &emphasis,
            world_per_pixel: 0.0,
            overlay: None,
        };
        let resolve = self.device.create_texture(&wgpu::TextureDescriptor {
            label: Some("resolve"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: self.format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let resolve_view = resolve.create_view(&Default::default());
        self.render_to_view(&mut gpu_scene, scene, &params, &resolve_view);

        // Readback: rows padded to 256 bytes per wgpu's copy alignment.
        let bytes_per_row = (width * 4).div_ceil(256) * 256;
        let readback = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("readback"),
            size: bytes_per_row as u64 * height as u64,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("readback"),
            });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &resolve,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(bytes_per_row),
                    rows_per_image: None,
                },
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        self.queue.submit([encoder.finish()]);

        let slice = readback.slice(..);
        let (sender, receiver) = std::sync::mpsc::channel();
        slice.map_async(wgpu::MapMode::Read, move |result| {
            let _ = sender.send(result);
        });
        self.device
            .poll(wgpu::PollType::wait_indefinitely())
            .map_err(|error| format!("wgpu poll: {error:?}"))?;
        receiver
            .recv()
            .map_err(|_| "readback callback dropped".to_string())?
            .map_err(|error| format!("readback map failed: {error:?}"))?;

        let data = slice.get_mapped_range();
        let mut rgb = Vec::with_capacity((width * height * 3) as usize);
        for row in 0..height {
            let start = (row * bytes_per_row) as usize;
            for col in 0..width as usize {
                let px = start + col * 4;
                rgb.extend_from_slice(&data[px..px + 3]);
            }
        }
        drop(data);
        readback.unmap();

        encode_png(&rgb, width, height)
    }
}

/// Issue draw calls for a solid's VISIBLE edge instances only, coalescing
/// contiguous edge ranges into as few `draw`s as possible. Used by the
/// single-style edge passes (occluded/hidden, and the no-emphasis visible pass)
/// when the solid has any hidden edge — the caller has already bound the style.
fn draw_visible_edge_ranges(
    pass: &mut wgpu::RenderPass<'_>,
    solid: &SolidDisplay,
    gpu_solid: &GpuSolid,
) {
    let mut run: Option<(u32, u32)> = None; // first_instance, count
    for (index, _edge) in solid.edges.iter().enumerate() {
        let range = &gpu_solid.edges[index];
        if range.instance_count == 0 {
            continue;
        }
        if !solid.visibility.is_edge_visible(index) {
            if let Some((first, count)) = run.take() {
                pass.draw(0..6, first..first + count);
            }
            continue;
        }
        match &mut run {
            Some((first, count)) if *first + *count == range.first_instance => {
                *count += range.instance_count;
            }
            _ => {
                if let Some((first, count)) = run.take() {
                    pass.draw(0..6, first..first + count);
                }
                run = Some((range.first_instance, range.instance_count));
            }
        }
    }
    if let Some((first, count)) = run {
        pass.draw(0..6, first..first + count);
    }
}

/// Convert a gizmo `Overlay`'s triangles into GPU vertices (per-vertex color).
fn overlay_tri_verts(ov: &brep_gizmos::Overlay) -> Vec<OverlayTriVertex> {
    ov.tris
        .iter()
        .map(|v| OverlayTriVertex {
            position: v.pos,
            normal: v.normal,
            color: v.color,
        })
        .collect()
}

/// Convert a gizmo `Overlay`'s line segments (vertex pairs) into GPU instances
/// (per-instance color; both endpoints of a gizmo segment share a color).
fn overlay_line_insts(ov: &brep_gizmos::Overlay) -> Vec<OverlayLineInstance> {
    ov.lines
        .chunks_exact(2)
        .map(|pair| OverlayLineInstance {
            p0: pair[0].pos,
            p1: pair[1].pos,
            color: pair[0].color,
        })
        .collect()
}