vertra 0.3.0

A cross-platform graphics editor built with Rust and WebAssembly.
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
use std::sync::Arc;
use wgpu::{Device, PipelineCompilationOptions, Queue, Surface};
use wgpu::util::DeviceExt;
use crate::camera::Camera;
use crate::mesh::{BakedMesh, Vertex};

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct ModelUniform {
    model: [[f32; 4]; 4],
    color: [f32; 4],
}

pub struct PipelineConfig {
    pub initial_vertex_buffer_size: usize,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RenderStats {
    pub draw_calls: u32,
    pub triangle_count: u32,
}

/// A prepared text quad ready to be submitted to the GPU text pass.
pub struct TextQuad {
    /// Baked screen-space mesh (two triangles).
    pub mesh: BakedMesh,
    /// Bind group pointing at the RGBA glyph texture for this label.
    pub bind_group: wgpu::BindGroup,
    /// Keep the texture alive as long as the bind group is alive.
    #[allow(dead_code)]
    pub texture: wgpu::Texture,
}

pub struct Pipeline {
    pub render_pipeline: wgpu::RenderPipeline,
    /// Depth = Always, no culling, no depth-write.
    /// Used for both the skybox (layer 1) and gizmo overlays (layer 3).
    overlay_pipeline: wgpu::RenderPipeline,
    pub shader: wgpu::ShaderModule,
    pub device: Device,
    pub queue: Queue,
    pub surface: Surface<'static>,
    pub surface_config: wgpu::SurfaceConfiguration,
    camera_buffer: wgpu::Buffer,
    camera_bind_group: wgpu::BindGroup,
    /// Orthographic projection buffer for screen-space text rendering.
    ortho_buffer: wgpu::Buffer,
    /// Bind group for the ortho projection (same layout as the perspective one).
    ortho_bind_group: wgpu::BindGroup,
    depth_view: wgpu::TextureView,
    /// Bind group layout for `@group(1)` (texture + sampler).
    pub texture_bind_group_layout: wgpu::BindGroupLayout,
    /// Default 1×1 white texture bind group used for untextured objects.
    pub default_texture_bind_group: wgpu::BindGroup,
    /// Shared linear sampler reused when creating per-object texture bind groups.
    pub default_sampler: wgpu::Sampler,
}

// Shared vertex buffer layout: position(3) + color(3) + uv(2)
const VERTEX_ATTRS: [wgpu::VertexAttribute; 3] = [
    wgpu::VertexAttribute { offset: 0,  shader_location: 0, format: wgpu::VertexFormat::Float32x3 },
    wgpu::VertexAttribute { offset: 12, shader_location: 1, format: wgpu::VertexFormat::Float32x3 },
    wgpu::VertexAttribute { offset: 24, shader_location: 2, format: wgpu::VertexFormat::Float32x2 },
];

impl Pipeline {
    pub async fn initialize(window: Arc<winit::window::Window>) -> Self {
        // On WASM inside any bundled environment the WebGPU
        // backend's instanceof GPUCanvasContext check fails due to a JS
        // realm mismatch, causing a panic. Force WebGL2 on wasm32 to avoid
        // this until wgpu ships a proper fix.
        let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
        desc.backends = wgpu::Backends::GL;

        #[cfg(target_arch = "wasm32")]
        let instance = wgpu::Instance::new(desc);

        #[cfg(not(target_arch = "wasm32"))]
        let instance = wgpu::Instance::default();
        let surface = instance.create_surface(Arc::clone(&window)).unwrap();
        let adapter = instance.request_adapter(
            &wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: Some(&surface),
                force_fallback_adapter: false,
            },
        ).await.expect("Failed to find an appropriate adapter");

        // Get the limits actually supported by this specific hardware
        let adapter_limits = adapter.limits();

        let (device, queue) = adapter.request_device(
            &wgpu::DeviceDescriptor {
                label: None,
                required_limits: wgpu::Limits {
                    ..adapter_limits
                },
                required_features: wgpu::Features::empty(),
                memory_hints: Default::default(),
                trace: wgpu::Trace::Off,
                experimental_features: wgpu::ExperimentalFeatures::default(),
            },
        ).await.expect("Failed to create device");

        let size = window.inner_size();
        let width = if size.width > 0 { size.width } else { crate::constants::window::DEFAULT_WIDTH };
        let height = if size.height > 0 { size.height } else { crate::constants::window::DEFAULT_HEIGHT };
        let surface_config = surface
            .get_default_config(&adapter, width, height)
            .expect("Surface not supported by adapter");

        surface.configure(&device, &surface_config);
        let shader = device.create_shader_module(wgpu::include_wgsl!("shader.wgsl"));

        let camera_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Camera Uniform Buffer"),
            size: size_of::<[[f32; 4]; 4]>() as wgpu::BufferAddress,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let camera_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
            label: Some("camera_bind_group_layout"),
        });

        let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            layout: &camera_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: camera_buffer.as_entire_binding(),
            }],
            label: Some("camera_bind_group"),
        });

        // Orthographic projection buffer (screen-space text overlay, Layer 4).
        let ortho_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Ortho Uniform Buffer"),
            size: size_of::<[[f32; 4]; 4]>() as wgpu::BufferAddress,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let ortho_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            layout: &camera_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: ortho_buffer.as_entire_binding(),
            }],
            label: Some("ortho_bind_group"),
        });

        // Texture bind group layout (group 1)
        let texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("texture_bind_group_layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        multisampled: false,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

        // Shared sampler
        let default_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("default_sampler"),
            address_mode_u: wgpu::AddressMode::Repeat,
            address_mode_v: wgpu::AddressMode::Repeat,
            address_mode_w: wgpu::AddressMode::Repeat,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });

        // Default 1×1 white texture -> untextured objects render with vertex colour
        let white_texture = device.create_texture_with_data(
            &queue,
            &wgpu::TextureDescriptor {
                label: Some("Default White Texture"),
                size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8UnormSrgb,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            },
            wgpu::util::TextureDataOrder::default(),
            &[255u8, 255, 255, 255],
        );
        let white_view = white_texture.create_view(&wgpu::TextureViewDescriptor::default());
        let default_texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("default_texture_bind_group"),
            layout: &texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&white_view) },
                wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&default_sampler) },
            ],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Render Pipeline Layout"),
            bind_group_layouts: &[Some(&camera_bind_group_layout), Some(&texture_bind_group_layout)],
            immediate_size: 0,
        });

        let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("Depth Texture"),
            size: wgpu::Extent3d { width: surface_config.width, height: surface_config.height, depth_or_array_layers: 1 },
            mip_level_count: 1, sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Depth32Float,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let depth_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default());

        let vertex_buf_layout = wgpu::VertexBufferLayout {
            array_stride: size_of::<Vertex>() as wgpu::BufferAddress,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &VERTEX_ATTRS,
        };

        // Main pipeline (normal depth, back-face culled)
        let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Render Pipeline"),
            layout: Some(&pipeline_layout),
            cache: None, multiview_mask: None,
            vertex: wgpu::VertexState {
                module: &shader, entry_point: Some("vs_main"),
                compilation_options: PipelineCompilationOptions::default(),
                buffers: &[vertex_buf_layout.clone()],
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader, entry_point: Some("fs_main"),
                compilation_options: PipelineCompilationOptions::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: surface_config.format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: Some(wgpu::Face::Back),
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth32Float,
                depth_write_enabled: Some(true),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
        });

        // Used for both the skybox (rendered first) and gizmo overlays (rendered last).
        let overlay_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Overlay Pipeline"),
            layout: Some(&pipeline_layout),
            cache: None, multiview_mask: None,
            vertex: wgpu::VertexState {
                module: &shader, entry_point: Some("vs_main"),
                compilation_options: PipelineCompilationOptions::default(),
                buffers: &[vertex_buf_layout],
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader, entry_point: Some("fs_main"),
                compilation_options: PipelineCompilationOptions::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: surface_config.format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState { cull_mode: None, ..Default::default() },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth32Float,
                depth_write_enabled: Some(false),
                depth_compare: Some(wgpu::CompareFunction::Always),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
        });

        Self {
            render_pipeline,
            overlay_pipeline,
            shader,
            device,
            queue,
            surface,
            surface_config,
            camera_buffer,
            camera_bind_group,
            ortho_buffer,
            ortho_bind_group,
            depth_view,
            texture_bind_group_layout,
            default_texture_bind_group,
            default_sampler,
        }
    }

    /// Render in four layers within two render passes.
    ///
    /// * `world_batches` - slice of `(mesh, texture_bind_group)` pairs for scene objects.
    ///   Each pair may carry a different texture; they are all rendered with the main pipeline.
    /// * `skybox`  - rendered first with the overlay pipeline (depth=Always, no depth-write).
    /// * `overlay` - rendered last with the overlay pipeline (gizmos, always on top).
    /// * `text_quads` - screen-space text quads rendered after the 3D scene using an
    ///   orthographic projection (Layer 4).  Pass an empty slice when unused.
    pub fn render_scene(
        &self,
        camera: &Camera,
        world_batches: &[(&BakedMesh, &wgpu::BindGroup)],
        skybox: Option<&BakedMesh>,
        overlay: Option<&BakedMesh>,
        label_selection: Option<&BakedMesh>,
        text_quads: &[&TextQuad],
    ) -> RenderStats {
        let frame = match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(f)    => f,
            wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,
            _ => return RenderStats::default(),
        };
        let view = frame.texture.create_view(&wgpu::TextureViewDescriptor::default());

        let cam_mat = camera.build_view_projection_matrix();
        self.queue.write_buffer(&self.camera_buffer, 0, bytemuck::cast_slice(&[cam_mat.data]));

        let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
        let mut stats = RenderStats::default();
        {
            let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &view,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.05, g: 0.07, b: 0.12, a: 1.0 }),
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                    view: &self.depth_view,
                    depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Store }),
                    stencil_ops: None,
                }),
                ..Default::default()
            });

            rp.set_bind_group(0, &self.camera_bind_group, &[]);

            // Layer 1: Skybox (overlay pipeline → depth=Always, no depth write)
            if let Some(sky) = skybox {
                if sky.index_count > 0 {
                    rp.set_pipeline(&self.overlay_pipeline);
                    rp.set_bind_group(1, &self.default_texture_bind_group, &[]);
                    rp.set_vertex_buffer(0, sky.vertex_buffer.slice(..));
                    rp.set_index_buffer(sky.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                    rp.draw_indexed(0..sky.index_count, 0, 0..1);
                    stats.draw_calls += 1;
                    stats.triangle_count += sky.index_count / 3;
                }
            }

            // Layer 2: World batches (main pipeline, per-texture)
            rp.set_pipeline(&self.render_pipeline);
            for (mesh, tex_bg) in world_batches {
                if mesh.index_count > 0 {
                    rp.set_bind_group(1, *tex_bg, &[]);
                    rp.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
                    rp.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                    rp.draw_indexed(0..mesh.index_count, 0, 0..1);
                    stats.draw_calls += 1;
                    stats.triangle_count += mesh.index_count / 3;
                }
            }

            // Layer 3: Overlay / gizmos (overlay pipeline -> always on top)
            if let Some(ov) = overlay {
                if ov.index_count > 0 {
                    rp.set_pipeline(&self.overlay_pipeline);
                    rp.set_bind_group(1, &self.default_texture_bind_group, &[]);
                    rp.set_vertex_buffer(0, ov.vertex_buffer.slice(..));
                    rp.set_index_buffer(ov.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                    rp.draw_indexed(0..ov.index_count, 0, 0..1);
                    stats.draw_calls += 1;
                    stats.triangle_count += ov.index_count / 3;
                }
            }
        }

        // Layer 4: Screen-space text overlay (orthographic projection, separate pass).
        if !text_quads.is_empty() {
            let w = self.surface_config.width  as f32;
            let h = self.surface_config.height as f32;
            let ortho = build_ortho_matrix(w, h);
            self.queue.write_buffer(&self.ortho_buffer, 0, bytemuck::cast_slice(&[ortho]));

            let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Text Overlay Pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &view,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: wgpu::StoreOp::Store,
                    },
                    depth_slice: None,
                })],
                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                    view: &self.depth_view,
                    depth_ops: Some(wgpu::Operations {
                        load: wgpu::LoadOp::Clear(1.0),
                        store: wgpu::StoreOp::Discard,
                    }),
                    stencil_ops: None,
                }),
                ..Default::default()
            });
            rp.set_pipeline(&self.overlay_pipeline);
            rp.set_bind_group(0, &self.ortho_bind_group, &[]);
            for quad in text_quads {
                if quad.mesh.index_count > 0 {
                    rp.set_bind_group(1, &quad.bind_group, &[]);
                    rp.set_vertex_buffer(0, quad.mesh.vertex_buffer.slice(..));
                    rp.set_index_buffer(quad.mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                    rp.draw_indexed(0..quad.mesh.index_count, 0, 0..1);
                    stats.draw_calls += 1;
                    stats.triangle_count += quad.mesh.index_count / 3;
                }
            }
            // Label selection box / resize handle (screen-space, on top of text).
            if let Some(sel) = label_selection {
                if sel.index_count > 0 {
                    rp.set_bind_group(1, &self.default_texture_bind_group, &[]);
                    rp.set_vertex_buffer(0, sel.vertex_buffer.slice(..));
                    rp.set_index_buffer(sel.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                    rp.draw_indexed(0..sel.index_count, 0, 0..1);
                    stats.draw_calls += 1;
                    stats.triangle_count += sel.index_count / 3;
                }
            }
        }

        self.queue.submit(std::iter::once(enc.finish()));
        frame.present();
        stats
    }

    pub fn render_baked_mesh(&self, mesh: &BakedMesh, camera: &Camera) {
        self.render_scene(camera, &[(mesh, &self.default_texture_bind_group)], None, None, None, &[] as &[&TextQuad]);
    }

    pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
        if new_size.width > 0 && new_size.height > 0 {
            self.surface_config.width = new_size.width;
            self.surface_config.height = new_size.height;
            self.surface.configure(&self.device, &self.surface_config);
            self.depth_view = self.create_depth_view(new_size);
        }
    }

    fn create_depth_view(&self, size: winit::dpi::PhysicalSize<u32>) -> wgpu::TextureView {
        let depth_texture = self.device.create_texture(&wgpu::TextureDescriptor {
            label: Some("Depth Texture"),
            size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
            mip_level_count: 1, sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Depth32Float,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
    }

    pub fn create_baked_mesh(&self, vertices: &[Vertex], indices: &[u32]) -> BakedMesh {
        let vertex_buffer = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Baked Vertex Buffer"),
            contents: bytemuck::cast_slice(vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });
        let index_buffer = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Baked Index Buffer"),
            contents: bytemuck::cast_slice(indices),
            usage: wgpu::BufferUsages::INDEX,
        });
        BakedMesh { vertex_buffer, index_buffer, index_count: indices.len() as u32 }
    }

    /// Upload raw RGBA8 pixel data and return a texture bind group for use with
    /// [`render_scene`].  The texture is created as `Rgba8UnormSrgb`.
    pub fn create_texture_bind_group_from_rgba(
        &self,
        label: &str,
        width: u32,
        height: u32,
        rgba_data: &[u8],
    ) -> (wgpu::Texture, wgpu::BindGroup) {
        let texture = self.device.create_texture_with_data(
            &self.queue,
            &wgpu::TextureDescriptor {
                label: Some(label),
                size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8UnormSrgb,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            },
            wgpu::util::TextureDataOrder::default(),
            rgba_data,
        );
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some(label),
            layout: &self.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) },
                wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.default_sampler) },
            ],
        });
        (texture, bind_group)
    }

    /// Create a [`TextQuad`] from raw RGBA8 pixels and a screen-space position.
    ///
    /// `x`, `y`, `tex_width`, `tex_height` are all in pixel coordinates.
    /// The returned [`TextQuad`] owns its GPU resources and may be reused across
    /// frames for as long as you keep it. Re-create it when the underlying text
    /// image changes (for example, when the label changes), or drop it when it is
    /// no longer needed.
    pub fn create_text_quad(
        &self,
        x: f32,
        y: f32,
        tex_width: u32,
        tex_height: u32,
        rgba_data: &[u8],
    ) -> TextQuad {
        use crate::text_overlay::TextOverlay;
        use wgpu::util::DeviceExt;

        let (verts, indices) = TextOverlay::build_quad(x, y, tex_width as f32, tex_height as f32);
        let mesh = self.create_baked_mesh(&verts, &indices);

        let texture = self.device.create_texture_with_data(
            &self.queue,
            &wgpu::TextureDescriptor {
                label: Some("Text Label Texture"),
                size: wgpu::Extent3d { width: tex_width, height: tex_height, depth_or_array_layers: 1 },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8Unorm,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            },
            wgpu::util::TextureDataOrder::default(),
            rgba_data,
        );
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Text Label Bind Group"),
            layout: &self.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) },
                wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.default_sampler) },
            ],
        });

        TextQuad { mesh, bind_group, texture }
    }
}

/// Build a column-major 4×4 orthographic projection matrix that maps pixel
/// coordinates `(0, 0)` (top-left) to NDC `(-1, 1)` and
/// `(width, height)` (bottom-right) to NDC `(1, -1)`.
///
/// The z-axis is left unchanged (identity), which is fine since all text
/// quads are placed at `z = 0`.
pub fn build_ortho_matrix(width: f32, height: f32) -> [[f32; 4]; 4] {
    // Column-major, same memory layout as WGSL mat4x4<f32>.
    // col 0: (2/w, 0,     0, 0)
    // col 1: (0,   -2/h,  0, 0)
    // col 2: (0,   0,     1, 0)
    // col 3: (-1,  1,     0, 1)
    [
        [2.0 / width,  0.0,           0.0, 0.0],
        [0.0,          -2.0 / height, 0.0, 0.0],
        [0.0,          0.0,           1.0, 0.0],
        [-1.0,         1.0,           0.0, 1.0],
    ]
}