Skip to content

Commit bd7f28d

Browse files
committed
Buildings: depth buffer where wgpu presents; tilted views load ahead
- Each building vertex carries its nearness (inverse view depth). Where the interface is presented by wgpu the app draws the blocks into their own 4x multisampled picture with a depth buffer and shows it as a texture, so a block behind never covers one in front; it is drawn again only when the mesh changes. The OpenGL fallback keeps the far-to-near faces. - Vector tiles (buildings, roads, transport, places) of a tilted view are taken from a disc ahead of the looked-at point, between the bottom and the top edge of the screen, instead of a larger disc around it that spent most tiles behind the camera. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KenNVpGqarXCfD9mvMtRLQ
1 parent 051af5b commit bd7f28d

12 files changed

Lines changed: 372 additions & 40 deletions

File tree

Lines changed: 220 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,250 @@
11
//! 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.
36
use eframe::egui;
47
use globecraft_data::buildings::BuildingSnapshot;
5-
use globecraft_render::live_layers::BuildingMesh;
8+
use globecraft_render::live_layers::{BuildingMesh, LiveView};
69
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;
720

821
#[derive(Default)]
922
pub(super) struct BuildingOverlay {
1023
/// Overture's building tiles.
1124
pub(super) tiles: globecraft_data::buildings::BuildingTiles,
1225
/// The tiles of blocks drawn.
1326
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.
1531
drawn: Option<(Arc<BuildingMesh>, egui::Shape)>,
1632
}
1733

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+
1844
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+
) {
2051
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+
}
2158
return;
2259
}
2360
if self
2461
.drawn
2562
.as_ref()
2663
.is_none_or(|(old, _)| !Arc::ptr_eq(old, mesh))
2764
{
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+
}),
4084
};
41-
self.drawn = Some((mesh.clone(), egui::Shape::mesh(shape)));
85+
self.drawn = Some((mesh.clone(), shape));
4286
}
4387
if let Some((_, shape)) = &self.drawn {
4488
painter.add(shape.clone());
4589
}
4690
}
4791
}
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+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Blocks with a depth buffer: positions arrive in clip space, colours as egui's
2+
// premultiplied gamma bytes, which egui reads back unchanged from the picture.
3+
struct Corner {
4+
@builtin(position) position: vec4<f32>,
5+
@location(0) colour: vec4<f32>,
6+
}
7+
8+
@vertex
9+
fn vertex(
10+
@location(0) at: vec2<f32>,
11+
@location(1) nearness: f32,
12+
@location(2) colour: vec4<f32>,
13+
) -> Corner {
14+
return Corner(vec4<f32>(at, nearness, 1.0), colour);
15+
}
16+
17+
@fragment
18+
fn fragment(corner: Corner) -> @location(0) vec4<f32> {
19+
return corner.colour;
20+
}

‎apps/globecraft/src/app/globe.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -728,7 +728,9 @@ impl App {
728728
if self.layer(MapLayer::Buildings)
729729
&& let Some(geometry) = &live_geometry
730730
{
731-
self.map_data.buildings.draw(painter, &geometry.buildings);
731+
self.map_data
732+
.buildings
733+
.draw(painter, &geometry.buildings, &geometry.input.view);
732734
}
733735
if self.layer(MapLayer::Traffic)
734736
&& let Some(geometry) = &live_geometry

‎apps/globecraft/src/app/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,7 @@ impl App {
331331
time: globecraft_core::time::AppTime::default(),
332332
runtime,
333333
};
334+
app.map_data.buildings.gpu = cc.wgpu_render_state.clone();
334335
app.restore_kml_session();
335336
if let Some(error) = &app.updates.restart.error {
336337
app.status = error.clone();

‎crates/globecraft-core/src/camera.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,11 @@ impl Basis {
165165
ground + ground.normalize() * (km / crate::EARTH_RADIUS_KM)
166166
}
167167
/// Any point in front of the camera, in f64 screen points, hidden or not.
168+
/// How far `p` lies in front of the camera along its view axis (mean Earth
169+
/// radii): the depth a depth buffer orders by.
170+
pub fn view_depth(&self, p: DVec3) -> f64 {
171+
-(self.view_from_world * (p - self.c)).z
172+
}
168173
fn screen_point(&self, p: DVec3, rect: Rect) -> Option<DVec2> {
169174
let v = p - self.c;
170175
let local = self.view_from_world * v;

‎crates/globecraft-data/src/boundaries/osm_tiles/pick.rs‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,38 @@ pub(crate) fn view_radius_deg(altitude_km: f64, tilt_deg: f64) -> f64 {
108108
((altitude_km * RADIUS_PER_ALTITUDE).max(reach_km) / KM_PER_DEGREE).min(horizon_deg)
109109
}
110110

111+
/// The disc of ground a view sees: its centre and radius (degrees). Straight down
112+
/// that is [`view_radius_deg`] around the view's centre. A tilted view sees far
113+
/// ahead and little behind, so its disc lies ahead, between the ground at the
114+
/// bottom and at the top edge of the screen: a disc around the centre spent most
115+
/// of its tiles behind the camera, and the cap on tiles left the far ground empty
116+
/// (reported 2026-11-16).
117+
/// shortcut: the far corners of a wide, steeply tilted view lie outside the disc;
118+
/// take the view's ground outline if empty corners show.
119+
pub(crate) fn seen_disc(view: crate::ViewQuery) -> ((f64, f64), f64) {
120+
let centre = (view.latitude, view.longitude);
121+
let whole = view_radius_deg(view.altitude_km, view.tilt_deg);
122+
if view.tilt_deg <= 0.0 {
123+
return (centre, whole);
124+
}
125+
let altitude_km = view.altitude_km.max(0.05);
126+
let tilt = view.tilt_deg.to_radians();
127+
let half_view = globecraft_core::VERTICAL_FOV_HALF_TAN.atan();
128+
// Along the ground from under the camera, whose height is `altitude · cos tilt`.
129+
let height_km = altitude_km * tilt.cos();
130+
let looked_at = height_km * tilt.tan();
131+
let far = height_km * (tilt + half_view).min(TILTED_REACH_MAX_RAD).tan();
132+
let near = height_km * (tilt - half_view).tan();
133+
let radius_km = ((far - near) / 2.0).max(altitude_km * RADIUS_PER_ALTITUDE);
134+
let ahead_km = ((far + near) / 2.0 - looked_at).max(0.0);
135+
let radius = (radius_km / KM_PER_DEGREE).min(whole);
136+
let ahead_km = ahead_km.min(whole * KM_PER_DEGREE);
137+
(
138+
globecraft_core::math::destination(centre.0, centre.1, view.heading_deg, ahead_km),
139+
radius,
140+
)
141+
}
142+
111143
/// The highest camera altitude at `lat` whose tiles hold municipal lines (the
112144
/// inverse of the detail choice in [`wanted`], which rounds the ideal zoom).
113145
pub(super) fn max_altitude_km_for_municipal(lat: f64) -> f64 {
@@ -158,6 +190,34 @@ pub(crate) fn around(zoom: u8, lat: f64, lon: f64, radius_deg: f64) -> Vec<TileK
158190
mod tests {
159191
use super::*;
160192

193+
#[test]
194+
fn a_tilted_view_loads_ahead_of_where_it_looks() {
195+
let mut view = crate::ViewQuery {
196+
latitude: 48.0,
197+
longitude: 11.0,
198+
altitude_km: 2.0,
199+
tilt_deg: 0.0,
200+
heading_deg: 0.0,
201+
};
202+
let (centre, straight_down) = seen_disc(view);
203+
assert_eq!(centre, (48.0, 11.0));
204+
assert_eq!(straight_down, view_radius_deg(2.0, 0.0));
205+
// Looking north at 65°: the disc is north of the view's centre, reaches the
206+
// ground at the top of the screen and little behind the camera, with far
207+
// fewer tiles than the disc around the centre.
208+
view.tilt_deg = 65.0;
209+
let ((latitude, longitude), radius) = seen_disc(view);
210+
assert!(latitude > 48.0 && (longitude - 11.0).abs() < 1e-9);
211+
let around_centre = view_radius_deg(2.0, 65.0);
212+
assert!(radius < 0.6 * around_centre, "{radius} {around_centre}");
213+
assert!(latitude + radius > 48.0 + 0.9 * around_centre * 0.8);
214+
assert!(latitude - radius < 48.0, "the looked-at point stays inside");
215+
// Looking east it lies east.
216+
view.heading_deg = 90.0;
217+
let ((latitude, longitude), _) = seen_disc(view);
218+
assert!(longitude > 11.0 && (latitude - 48.0).abs() < 1e-3);
219+
}
220+
161221
#[test]
162222
fn state_lines_keep_tiles_at_zoom_five_or_finer() {
163223
// Without state lines a view from 3,000 km uses coarser tiles.

0 commit comments

Comments
 (0)