|
1 | 1 | //! Buildings as blocks close up (roadmap 8.6); the geometry is projected by the |
2 | | -//! live-layer worker (`globecraft_render::live_layers::BuildingMesh`). |
| 2 | +//! live-layer worker (`globecraft_render::live_layers::BuildingMesh`). Where the |
| 3 | +//! interface is presented by wgpu the blocks are drawn into their own picture with a |
| 4 | +//! depth buffer, so a block behind never shows through one in front; the OpenGL |
| 5 | +//! fallback draws the faces far to near, which big roofs can get wrong. |
3 | 6 | use eframe::egui; |
4 | 7 | use globecraft_data::buildings::BuildingSnapshot; |
5 | | -use globecraft_render::live_layers::BuildingMesh; |
| 8 | +use globecraft_render::live_layers::{BuildingMesh, LiveView}; |
6 | 9 | use std::sync::Arc; |
| 10 | +use wgpu::util::DeviceExt; |
| 11 | + |
| 12 | +/// Samples per pixel of the blocks' picture: smooth edges. |
| 13 | +const SAMPLES: u32 = 4; |
| 14 | +/// Not sRGB: egui takes a texture's values as the gamma bytes it draws with (an |
| 15 | +/// sRGB picture came out dark, 2026-11-16). |
| 16 | +const COLOUR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; |
| 17 | +const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float; |
| 18 | +/// A vertex in the buffer: clip position (two `f32`), nearness (`f32`), colour. |
| 19 | +const VERTEX_BYTES: u64 = 16; |
7 | 20 |
|
8 | 21 | #[derive(Default)] |
9 | 22 | pub(super) struct BuildingOverlay { |
10 | 23 | /// Overture's building tiles. |
11 | 24 | pub(super) tiles: globecraft_data::buildings::BuildingTiles, |
12 | 25 | /// The tiles of blocks drawn. |
13 | 26 | pub(super) current: Option<Arc<BuildingSnapshot>>, |
14 | | - /// The mesh last drawn, and what it was built from. |
| 27 | + /// The interface's GPU, when wgpu presents it. |
| 28 | + pub(super) gpu: Option<egui_wgpu::RenderState>, |
| 29 | + picture: Option<Picture>, |
| 30 | + /// The mesh last drawn, and the shape made from it. |
15 | 31 | drawn: Option<(Arc<BuildingMesh>, egui::Shape)>, |
16 | 32 | } |
17 | 33 |
|
| 34 | +/// The blocks' own picture on the GPU, shown as an egui texture. |
| 35 | +struct Picture { |
| 36 | + pipeline: wgpu::RenderPipeline, |
| 37 | + size: [u32; 2], |
| 38 | + samples: wgpu::TextureView, |
| 39 | + depth: wgpu::TextureView, |
| 40 | + shown: wgpu::TextureView, |
| 41 | + id: egui::TextureId, |
| 42 | +} |
| 43 | + |
18 | 44 | impl BuildingOverlay { |
19 | | - pub(super) fn draw(&mut self, painter: &egui::Painter, mesh: &Arc<BuildingMesh>) { |
| 45 | + pub(super) fn draw( |
| 46 | + &mut self, |
| 47 | + painter: &egui::Painter, |
| 48 | + mesh: &Arc<BuildingMesh>, |
| 49 | + view: &LiveView, |
| 50 | + ) { |
20 | 51 | if mesh.indices.is_empty() { |
| 52 | + // The picture is as large as the window, several times over: not kept |
| 53 | + // while there is nothing to show. |
| 54 | + self.drawn = None; |
| 55 | + if let (Some(gpu), Some(picture)) = (&self.gpu, self.picture.take()) { |
| 56 | + gpu.renderer.write().free_texture(&picture.id); |
| 57 | + } |
21 | 58 | return; |
22 | 59 | } |
23 | 60 | if self |
24 | 61 | .drawn |
25 | 62 | .as_ref() |
26 | 63 | .is_none_or(|(old, _)| !Arc::ptr_eq(old, mesh)) |
27 | 64 | { |
28 | | - let shape = egui::Mesh { |
29 | | - vertices: mesh |
30 | | - .vertices |
31 | | - .iter() |
32 | | - .map(|&(pos, [r, g, b, a])| egui::epaint::Vertex { |
33 | | - pos, |
34 | | - uv: egui::epaint::WHITE_UV, |
35 | | - color: egui::Color32::from_rgba_unmultiplied(r, g, b, a), |
36 | | - }) |
37 | | - .collect(), |
38 | | - indices: mesh.indices.clone(), |
39 | | - ..Default::default() |
| 65 | + let shape = match &self.gpu { |
| 66 | + Some(gpu) => { |
| 67 | + let id = render(gpu, &mut self.picture, mesh, view); |
| 68 | + let whole = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)); |
| 69 | + egui::Shape::image(id, view.rect, whole, egui::Color32::WHITE) |
| 70 | + } |
| 71 | + None => egui::Shape::mesh(egui::Mesh { |
| 72 | + vertices: mesh |
| 73 | + .vertices |
| 74 | + .iter() |
| 75 | + .map(|vertex| egui::epaint::Vertex { |
| 76 | + pos: vertex.at, |
| 77 | + uv: egui::epaint::WHITE_UV, |
| 78 | + color: premultiplied(vertex.colour), |
| 79 | + }) |
| 80 | + .collect(), |
| 81 | + indices: mesh.indices.clone(), |
| 82 | + ..Default::default() |
| 83 | + }), |
40 | 84 | }; |
41 | | - self.drawn = Some((mesh.clone(), egui::Shape::mesh(shape))); |
| 85 | + self.drawn = Some((mesh.clone(), shape)); |
42 | 86 | } |
43 | 87 | if let Some((_, shape)) = &self.drawn { |
44 | 88 | painter.add(shape.clone()); |
45 | 89 | } |
46 | 90 | } |
47 | 91 | } |
| 92 | + |
| 93 | +fn premultiplied([r, g, b, a]: [u8; 4]) -> egui::Color32 { |
| 94 | + egui::Color32::from_rgba_unmultiplied(r, g, b, a) |
| 95 | +} |
| 96 | + |
| 97 | +/// Draws `mesh` into the picture (made, or made again at a new size) and returns |
| 98 | +/// the texture showing it. |
| 99 | +fn render( |
| 100 | + gpu: &egui_wgpu::RenderState, |
| 101 | + picture: &mut Option<Picture>, |
| 102 | + mesh: &BuildingMesh, |
| 103 | + view: &LiveView, |
| 104 | +) -> egui::TextureId { |
| 105 | + let device = &gpu.device; |
| 106 | + let limit = device.limits().max_texture_dimension_2d; |
| 107 | + let size = [view.rect.width(), view.rect.height()] |
| 108 | + .map(|points| ((points * view.pixels_per_point).round() as u32).clamp(1, limit)); |
| 109 | + if picture.as_ref().is_some_and(|old| old.size != size) |
| 110 | + && let Some(old) = picture.take() |
| 111 | + { |
| 112 | + // Its pipeline is cheap to make again; a window is seldom resized. |
| 113 | + gpu.renderer.write().free_texture(&old.id); |
| 114 | + } |
| 115 | + let picture = picture.get_or_insert_with(|| Picture::new(gpu, size)); |
| 116 | + |
| 117 | + let mut vertices = Vec::with_capacity(mesh.vertices.len() * VERTEX_BYTES as usize); |
| 118 | + let (min, span) = (view.rect.min, view.rect.size()); |
| 119 | + for vertex in &mesh.vertices { |
| 120 | + let clip = [ |
| 121 | + (vertex.at.x - min.x) / span.x * 2.0 - 1.0, |
| 122 | + 1.0 - (vertex.at.y - min.y) / span.y * 2.0, |
| 123 | + vertex.nearness, |
| 124 | + ]; |
| 125 | + vertices.extend(clip.iter().flat_map(|value| value.to_ne_bytes())); |
| 126 | + vertices.extend(premultiplied(vertex.colour).to_array()); |
| 127 | + } |
| 128 | + let buffer = |label, contents: &[u8], usage| { |
| 129 | + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { |
| 130 | + label: Some(label), |
| 131 | + contents, |
| 132 | + usage, |
| 133 | + }) |
| 134 | + }; |
| 135 | + let vertices = buffer("building corners", &vertices, wgpu::BufferUsages::VERTEX); |
| 136 | + let indices: Vec<u8> = mesh |
| 137 | + .indices |
| 138 | + .iter() |
| 139 | + .flat_map(|index| index.to_ne_bytes()) |
| 140 | + .collect(); |
| 141 | + let indices = buffer("building triangles", &indices, wgpu::BufferUsages::INDEX); |
| 142 | + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { |
| 143 | + label: Some("buildings"), |
| 144 | + }); |
| 145 | + { |
| 146 | + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { |
| 147 | + label: Some("buildings"), |
| 148 | + color_attachments: &[Some(wgpu::RenderPassColorAttachment { |
| 149 | + view: &picture.samples, |
| 150 | + depth_slice: None, |
| 151 | + resolve_target: Some(&picture.shown), |
| 152 | + ops: wgpu::Operations { |
| 153 | + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), |
| 154 | + store: wgpu::StoreOp::Discard, |
| 155 | + }, |
| 156 | + })], |
| 157 | + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { |
| 158 | + view: &picture.depth, |
| 159 | + // Greater is nearer: nothing is at zero. |
| 160 | + depth_ops: Some(wgpu::Operations { |
| 161 | + load: wgpu::LoadOp::Clear(0.0), |
| 162 | + store: wgpu::StoreOp::Discard, |
| 163 | + }), |
| 164 | + stencil_ops: None, |
| 165 | + }), |
| 166 | + ..Default::default() |
| 167 | + }); |
| 168 | + pass.set_pipeline(&picture.pipeline); |
| 169 | + pass.set_vertex_buffer(0, vertices.slice(..)); |
| 170 | + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); |
| 171 | + pass.draw_indexed(0..mesh.indices.len() as u32, 0, 0..1); |
| 172 | + } |
| 173 | + gpu.queue.submit([encoder.finish()]); |
| 174 | + picture.id |
| 175 | +} |
| 176 | + |
| 177 | +impl Picture { |
| 178 | + fn new(gpu: &egui_wgpu::RenderState, size: [u32; 2]) -> Self { |
| 179 | + let device = &gpu.device; |
| 180 | + let shader = device.create_shader_module(wgpu::include_wgsl!("buildings_depth.wgsl")); |
| 181 | + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { |
| 182 | + label: Some("buildings"), |
| 183 | + layout: None, |
| 184 | + vertex: wgpu::VertexState { |
| 185 | + module: &shader, |
| 186 | + entry_point: Some("vertex"), |
| 187 | + compilation_options: Default::default(), |
| 188 | + buffers: &[Some(wgpu::VertexBufferLayout { |
| 189 | + array_stride: VERTEX_BYTES, |
| 190 | + step_mode: wgpu::VertexStepMode::Vertex, |
| 191 | + attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32, 2 => Unorm8x4], |
| 192 | + })], |
| 193 | + }, |
| 194 | + primitive: wgpu::PrimitiveState::default(), |
| 195 | + depth_stencil: Some(wgpu::DepthStencilState { |
| 196 | + format: DEPTH_FORMAT, |
| 197 | + depth_write_enabled: Some(true), |
| 198 | + depth_compare: Some(wgpu::CompareFunction::Greater), |
| 199 | + stencil: Default::default(), |
| 200 | + bias: Default::default(), |
| 201 | + }), |
| 202 | + multisample: wgpu::MultisampleState { |
| 203 | + count: SAMPLES, |
| 204 | + ..Default::default() |
| 205 | + }, |
| 206 | + fragment: Some(wgpu::FragmentState { |
| 207 | + module: &shader, |
| 208 | + entry_point: Some("fragment"), |
| 209 | + compilation_options: Default::default(), |
| 210 | + // No blending: the depth test leaves the nearest face, already |
| 211 | + // premultiplied, and egui blends the picture over the globe. |
| 212 | + targets: &[Some(COLOUR_FORMAT.into())], |
| 213 | + }), |
| 214 | + multiview_mask: None, |
| 215 | + cache: None, |
| 216 | + }); |
| 217 | + let texture = |label, format, sample_count| { |
| 218 | + device |
| 219 | + .create_texture(&wgpu::TextureDescriptor { |
| 220 | + label: Some(label), |
| 221 | + size: wgpu::Extent3d { |
| 222 | + width: size[0], |
| 223 | + height: size[1], |
| 224 | + depth_or_array_layers: 1, |
| 225 | + }, |
| 226 | + mip_level_count: 1, |
| 227 | + sample_count, |
| 228 | + dimension: wgpu::TextureDimension::D2, |
| 229 | + format, |
| 230 | + usage: wgpu::TextureUsages::RENDER_ATTACHMENT |
| 231 | + | wgpu::TextureUsages::TEXTURE_BINDING, |
| 232 | + view_formats: &[], |
| 233 | + }) |
| 234 | + .create_view(&Default::default()) |
| 235 | + }; |
| 236 | + let shown = texture("buildings", COLOUR_FORMAT, 1); |
| 237 | + let id = |
| 238 | + gpu.renderer |
| 239 | + .write() |
| 240 | + .register_native_texture(device, &shown, wgpu::FilterMode::Linear); |
| 241 | + Self { |
| 242 | + pipeline, |
| 243 | + size, |
| 244 | + samples: texture("building samples", COLOUR_FORMAT, SAMPLES), |
| 245 | + depth: texture("building depth", DEPTH_FORMAT, SAMPLES), |
| 246 | + shown, |
| 247 | + id, |
| 248 | + } |
| 249 | + } |
| 250 | +} |
0 commit comments