Skip to main content

strata_render/
terrain3d.rs

1//! Incremental mesh construction for tiled terrain, relief walls, building
2//! prisms, and their roofs.
3//!
4//! The reference rebuilds per-tile height fields and building geometry every
5//! frame. `Geometry3D` can already carry arbitrary vertices, but a scene built
6//! from hundreds of tiles and thousands of buildings must not reallocate in the
7//! frame hot path. [`MeshBuilder`] owns reusable vertex and index capacity; a
8//! rebuild clears and refills it, so steady-state frames allocate nothing.
9//!
10//! Coordinates are f64 because tiled geometry is authored at Earth scale.
11//! [`MeshBuilder::finish`] subtracts an RTC origin before narrowing, which is
12//! the same contract as [`crate::camera64::RenderFrame64`].
13
14use crate::camera64::DVec3;
15use crate::geometry3d::TEXTURED_VERTEX_STRIDE;
16use crate::scene3d::Geometry3D;
17
18/// Reusable builder for a textured mesh at Earth scale.
19///
20/// Vertex layout is the eight-float stride `x, y, z, nx, ny, nz, u, v` that
21/// [`Geometry3D::CustomTextured`] consumes.
22#[derive(Debug, Clone, Default)]
23pub struct MeshBuilder {
24    vertices: Vec<f32>,
25    indices: Vec<u32>,
26    /// RTC origin subtracted when the mesh is finished.
27    origin: DVec3,
28}
29
30impl MeshBuilder {
31    pub fn new() -> Self {
32        Self::default()
33    }
34
35    /// Reserves capacity for `vertices` vertices and `triangles` triangles.
36    pub fn with_capacity(vertices: usize, triangles: usize) -> Self {
37        Self {
38            vertices: Vec::with_capacity(vertices * TEXTURED_VERTEX_STRIDE),
39            indices: Vec::with_capacity(triangles * 3),
40            origin: DVec3::ZERO,
41        }
42    }
43
44    /// Sets the point subtracted before narrowing to f32.
45    pub fn set_origin(&mut self, origin: DVec3) {
46        self.origin = origin;
47    }
48
49    /// Empties the builder while keeping its allocation.
50    pub fn clear(&mut self) {
51        self.vertices.clear();
52        self.indices.clear();
53    }
54
55    /// Capacity currently held by the vertex buffer, in floats.
56    pub fn vertex_capacity(&self) -> usize {
57        self.vertices.capacity()
58    }
59
60    /// Capacity currently held by the index buffer, in indices.
61    pub fn index_capacity(&self) -> usize {
62        self.indices.capacity()
63    }
64
65    pub fn vertex_count(&self) -> usize {
66        self.vertices.len() / TEXTURED_VERTEX_STRIDE
67    }
68
69    pub fn triangle_count(&self) -> usize {
70        self.indices.len() / 3
71    }
72
73    /// Number of indices appended so far, for batching index ranges.
74    pub fn index_count(&self) -> usize {
75        self.indices.len()
76    }
77
78    pub fn is_empty(&self) -> bool {
79        self.indices.is_empty()
80    }
81
82    /// Appends a vertex at world scale, relative to the builder origin, and
83    /// returns its local index.
84    pub fn push_vertex(&mut self, position: DVec3, normal: [f32; 3], uv: (f32, f32)) -> u32 {
85        let local = position.sub(self.origin);
86        self.vertices.push(local.x as f32);
87        self.vertices.push(local.y as f32);
88        self.vertices.push(local.z as f32);
89        self.vertices.extend_from_slice(&normal);
90        self.vertices.push(uv.0);
91        self.vertices.push(uv.1);
92        (self.vertex_count() - 1) as u32
93    }
94
95    /// Appends a triangle. Degenerate index triplets are dropped.
96    pub fn push_triangle(&mut self, a: u32, b: u32, c: u32) {
97        if a == b || b == c || a == c {
98            return;
99        }
100        self.indices.extend_from_slice(&[a, b, c]);
101    }
102
103    /// Appends a quad as two triangles.
104    pub fn push_quad(&mut self, a: u32, b: u32, c: u32, d: u32) {
105        self.push_triangle(a, b, c);
106        self.push_triangle(a, c, d);
107    }
108
109    /// Appends a terrain patch from a height field.
110    ///
111    /// `heights` is a `(cols x rows)` grid of world-space positions in
112    /// row-major order; `uv_rect` is the tile's sub-rectangle of the source
113    /// image, expressed in the quad's own 0..1 space and mapped across the
114    /// patch. The patch is two triangles per grid cell.
115    pub fn push_grid(
116        &mut self,
117        heights: &[DVec3],
118        cols: usize,
119        rows: usize,
120        uv_rect: (f32, f32, f32, f32),
121    ) {
122        if cols < 2 || rows < 2 || heights.len() != cols * rows {
123            return;
124        }
125        let (u0, v0, u1, v1) = uv_rect;
126        let base = self.vertex_count() as u32;
127        for row in 0..rows {
128            let v = v0 + (v1 - v0) * (row as f32 / (rows - 1) as f32);
129            for col in 0..cols {
130                let u = u0 + (u1 - u0) * (col as f32 / (cols - 1) as f32);
131                let position = heights[row * cols + col];
132                self.push_vertex(position, [0.0, 0.0, 1.0], (u, v));
133            }
134        }
135        for row in 0..rows - 1 {
136            for col in 0..cols - 1 {
137                let i = base + (row * cols + col) as u32;
138                let right = i + 1;
139                let down = i + cols as u32;
140                let down_right = down + 1;
141                self.push_quad(i, right, down_right, down);
142            }
143        }
144    }
145
146    /// Appends a grid patch with explicit per-vertex normals.
147    ///
148    /// Use this for relief, where the surface normal is derived from the
149    /// height field rather than being the sphere radial.
150    pub fn push_grid_with_normals(
151        &mut self,
152        positions: &[DVec3],
153        normals: &[[f32; 3]],
154        cols: usize,
155        rows: usize,
156        uv_rect: (f32, f32, f32, f32),
157    ) {
158        if cols < 2 || rows < 2 || positions.len() != cols * rows || normals.len() != cols * rows {
159            return;
160        }
161        let (u0, v0, u1, v1) = uv_rect;
162        let base = self.vertex_count() as u32;
163        for row in 0..rows {
164            let v = v0 + (v1 - v0) * (row as f32 / (rows - 1) as f32);
165            for col in 0..cols {
166                let u = u0 + (u1 - u0) * (col as f32 / (cols - 1) as f32);
167                let index = row * cols + col;
168                self.push_vertex(positions[index], normals[index], (u, v));
169            }
170        }
171        for row in 0..rows - 1 {
172            for col in 0..cols - 1 {
173                let i = base + (row * cols + col) as u32;
174                let right = i + 1;
175                let down = i + cols as u32;
176                let down_right = down + 1;
177                self.push_quad(i, right, down_right, down);
178            }
179        }
180    }
181
182    /// Appends a vertical relief wall from a top edge to a bottom edge.
183    ///
184    /// This is the side skirt that hides the gap between a raised terrain tile
185    /// and the tile behind it. `top` and `bottom` are equal-length edge points.
186    pub fn push_wall(&mut self, top: &[DVec3], bottom: &[DVec3], uv_rect: (f32, f32, f32, f32)) {
187        if top.len() < 2 || top.len() != bottom.len() {
188            return;
189        }
190        let (u0, v0, u1, v1) = uv_rect;
191        let segments = top.len() - 1;
192        for segment in 0..segments {
193            let t0 = segment as f32 / segments as f32;
194            let t1 = (segment + 1) as f32 / segments as f32;
195            let ua = u0 + (u1 - u0) * t0;
196            let ub = u0 + (u1 - u0) * t1;
197            let a = self.push_vertex(top[segment], [0.0, 0.0, 1.0], (ua, v1));
198            let b = self.push_vertex(top[segment + 1], [0.0, 0.0, 1.0], (ub, v1));
199            let c = self.push_vertex(bottom[segment + 1], [0.0, 0.0, 1.0], (ub, v0));
200            let d = self.push_vertex(bottom[segment], [0.0, 0.0, 1.0], (ua, v0));
201            self.push_quad(a, b, c, d);
202        }
203    }
204
205    /// Appends a boundary skirt between a top edge and an extruded bottom edge.
206    ///
207    /// Skirts occlude crack seams between adjacent tiles of differing LOD levels.
208    /// `top` and `bottom` must have equal lengths >= 2, and `uvs` must match `top.len()`.
209    /// The triangles are wound counter-clockwise when viewed from the outside with outward normals.
210    pub fn push_skirt(&mut self, top: &[DVec3], bottom: &[DVec3], uvs: &[(f32, f32)]) {
211        if top.len() < 2 || top.len() != bottom.len() || top.len() != uvs.len() {
212            return;
213        }
214        let segments = top.len() - 1;
215        for i in 0..segments {
216            let edge = top[i + 1].sub(top[i]);
217            let down = bottom[i].sub(top[i]);
218            let cross = down.cross(edge);
219            let normal = if cross.length() > 1e-9 {
220                cross.normalize().as_f32()
221            } else {
222                [0.0, 0.0, 1.0]
223            };
224            let a = self.push_vertex(top[i], normal, uvs[i]);
225            let b = self.push_vertex(bottom[i], normal, uvs[i]);
226            let c = self.push_vertex(bottom[i + 1], normal, uvs[i + 1]);
227            let d = self.push_vertex(top[i + 1], normal, uvs[i + 1]);
228            self.push_quad(a, b, c, d);
229        }
230    }
231
232    /// Appends vertical skirts along all four perimeter edges of a terrain grid (South, East, North, West).
233    ///
234    /// `grid_positions` contains `cols * rows` vertices in row-major order (row 0 is South, col 0 is West).
235    /// `skirt_depth` specifies the vertical extrusion distance downward along the -Z axis (or radial inward).
236    /// `uv_rect` specifies `(u0, v0, u1, v1)` texture coordinates.
237    #[allow(clippy::needless_range_loop)]
238    pub fn push_grid_perimeter_skirts(
239        &mut self,
240        grid_positions: &[DVec3],
241        cols: usize,
242        rows: usize,
243        skirt_depth: f64,
244        uv_rect: (f32, f32, f32, f32),
245    ) {
246        if cols < 2 || rows < 2 || grid_positions.len() != cols * rows || skirt_depth <= 0.0 {
247            return;
248        }
249        let (u0, v0, u1, v1) = uv_rect;
250        let get_down = |pos: DVec3| -> DVec3 {
251            let len = pos.length();
252            if len > 1000.0 {
253                // Spherical / ellipsoidal radial downward
254                pos.scale(-skirt_depth / len)
255            } else {
256                // Cartesian downward along -Z
257                DVec3::new(0.0, 0.0, -skirt_depth)
258            }
259        };
260
261        // 1. South edge: row = 0, col from 0 to cols - 1 (West to East)
262        let mut south_top = Vec::with_capacity(cols);
263        let mut south_bot = Vec::with_capacity(cols);
264        let mut south_uvs = Vec::with_capacity(cols);
265        for col in 0..cols {
266            let pos = grid_positions[col];
267            let u = u0 + (u1 - u0) * (col as f32 / (cols - 1) as f32);
268            south_top.push(pos);
269            south_bot.push(pos.add(get_down(pos)));
270            south_uvs.push((u, v0));
271        }
272        self.push_skirt(&south_top, &south_bot, &south_uvs);
273
274        // 2. East edge: col = cols - 1, row from 0 to rows - 1 (South to North)
275        let mut east_top = Vec::with_capacity(rows);
276        let mut east_bot = Vec::with_capacity(rows);
277        let mut east_uvs = Vec::with_capacity(rows);
278        for row in 0..rows {
279            let pos = grid_positions[row * cols + (cols - 1)];
280            let v = v0 + (v1 - v0) * (row as f32 / (rows - 1) as f32);
281            east_top.push(pos);
282            east_bot.push(pos.add(get_down(pos)));
283            east_uvs.push((u1, v));
284        }
285        self.push_skirt(&east_top, &east_bot, &east_uvs);
286
287        // 3. North edge: row = rows - 1, col from cols - 1 down to 0 (East to West)
288        let mut north_top = Vec::with_capacity(cols);
289        let mut north_bot = Vec::with_capacity(cols);
290        let mut north_uvs = Vec::with_capacity(cols);
291        for col in (0..cols).rev() {
292            let pos = grid_positions[(rows - 1) * cols + col];
293            let u = u0 + (u1 - u0) * (col as f32 / (cols - 1) as f32);
294            north_top.push(pos);
295            north_bot.push(pos.add(get_down(pos)));
296            north_uvs.push((u, v1));
297        }
298        self.push_skirt(&north_top, &north_bot, &north_uvs);
299
300        // 4. West edge: col = 0, row from rows - 1 down to 0 (North to South)
301        let mut west_top = Vec::with_capacity(rows);
302        let mut west_bot = Vec::with_capacity(rows);
303        let mut west_uvs = Vec::with_capacity(rows);
304        for row in (0..rows).rev() {
305            let pos = grid_positions[row * cols];
306            let v = v0 + (v1 - v0) * (row as f32 / (rows - 1) as f32);
307            west_top.push(pos);
308            west_bot.push(pos.add(get_down(pos)));
309            west_uvs.push((u0, v));
310        }
311        self.push_skirt(&west_top, &west_bot, &west_uvs);
312    }
313
314    /// Appends a building prism plus its roof cap.
315    ///
316    /// `base` is the footprint centre on the ground, `half` the footprint half
317    /// extents in the local X and Z axes, and `height` the extrusion. Walls use
318    /// the side of `facade_uv` and the roof uses `roof_uv`, both sub-rectangles
319    /// of one atlas.
320    pub fn push_building(
321        &mut self,
322        base: DVec3,
323        half: (f64, f64),
324        height: f64,
325        facade_uv: (f32, f32, f32, f32),
326        roof_uv: (f32, f32, f32, f32),
327    ) {
328        if half.0 <= 0.0 || half.1 <= 0.0 || height <= 0.0 {
329            return;
330        }
331        let (hx, hz) = half;
332        let corners = [
333            base.add(DVec3::new(-hx, -hz, 0.0)),
334            base.add(DVec3::new(hx, -hz, 0.0)),
335            base.add(DVec3::new(hx, hz, 0.0)),
336            base.add(DVec3::new(-hx, hz, 0.0)),
337        ];
338        let top: Vec<DVec3> = corners
339            .iter()
340            .map(|c| c.add(DVec3::new(0.0, 0.0, height)))
341            .collect();
342
343        let (u0, v0, u1, v1) = facade_uv;
344        let normals = [
345            [0.0, -1.0, 0.0],
346            [1.0, 0.0, 0.0],
347            [0.0, 1.0, 0.0],
348            [-1.0, 0.0, 0.0],
349        ];
350        for side in 0..4 {
351            let next = (side + 1) % 4;
352            let normal = normals[side];
353            let a = self.push_vertex(corners[side], normal, (u0, v0));
354            let b = self.push_vertex(corners[next], normal, (u1, v0));
355            let c = self.push_vertex(top[next], normal, (u1, v1));
356            let d = self.push_vertex(top[side], normal, (u0, v1));
357            self.push_quad(a, b, c, d);
358        }
359
360        let (ru0, rv0, ru1, rv1) = roof_uv;
361        let r0 = self.push_vertex(top[0], [0.0, 0.0, 1.0], (ru0, rv1));
362        let r1 = self.push_vertex(top[1], [0.0, 0.0, 1.0], (ru1, rv1));
363        let r2 = self.push_vertex(top[2], [0.0, 0.0, 1.0], (ru1, rv0));
364        let r3 = self.push_vertex(top[3], [0.0, 0.0, 1.0], (ru0, rv0));
365        self.push_quad(r0, r1, r2, r3);
366    }
367
368    /// Freezes the builder into a scene geometry, narrowing to f32 after the
369    /// RTC subtraction. Returns `None` when nothing was appended.
370    pub fn finish(&self) -> Option<Geometry3D> {
371        if self.indices.is_empty() {
372            return None;
373        }
374        Some(Geometry3D::CustomTextured {
375            vertices: self.vertices.clone(),
376            indices: self.indices.clone(),
377        })
378    }
379
380    /// Appends a vertex storing double-single high and low components without RTC origin subtraction.
381    /// Returns the vertex index along with the split high and low position triples.
382    pub fn push_rte_vertex(
383        &mut self,
384        position: DVec3,
385        normal: [f32; 3],
386        uv: (f32, f32),
387    ) -> (u32, [f32; 3], [f32; 3]) {
388        let (high, low) = position.split_high_low();
389        let idx = self.push_vertex(position, normal, uv);
390        (idx, high, low)
391    }
392}
393
394/// Builder for GPU Relative-To-Eye (RTE) mesh buffers storing interleaved
395/// `[pos_high: 3, pos_low: 3, norm: 3, uv: 2]` = 11 floats per vertex.
396#[derive(Debug, Clone, Default)]
397pub struct RteMeshBuilder {
398    vertices: Vec<f32>,
399    indices: Vec<u32>,
400}
401
402impl RteMeshBuilder {
403    pub const STRIDE: usize = 11;
404
405    pub fn new() -> Self {
406        Self::default()
407    }
408
409    pub fn with_capacity(vertex_count: usize, triangle_count: usize) -> Self {
410        Self {
411            vertices: Vec::with_capacity(vertex_count * Self::STRIDE),
412            indices: Vec::with_capacity(triangle_count * 3),
413        }
414    }
415
416    pub fn clear(&mut self) {
417        self.vertices.clear();
418        self.indices.clear();
419    }
420
421    pub fn vertex_count(&self) -> usize {
422        self.vertices.len() / Self::STRIDE
423    }
424
425    pub fn triangle_count(&self) -> usize {
426        self.indices.len() / 3
427    }
428
429    pub fn push_vertex(&mut self, position: DVec3, normal: [f32; 3], uv: (f32, f32)) -> u32 {
430        let (high, low) = position.split_high_low();
431        self.vertices.extend_from_slice(&high);
432        self.vertices.extend_from_slice(&low);
433        self.vertices.extend_from_slice(&normal);
434        self.vertices.push(uv.0);
435        self.vertices.push(uv.1);
436        (self.vertex_count() - 1) as u32
437    }
438
439    pub fn push_triangle(&mut self, a: u32, b: u32, c: u32) {
440        if a == b || b == c || a == c {
441            return;
442        }
443        self.indices.extend_from_slice(&[a, b, c]);
444    }
445
446    pub fn push_quad(&mut self, a: u32, b: u32, c: u32, d: u32) {
447        self.push_triangle(a, b, c);
448        self.push_triangle(a, c, d);
449    }
450
451    pub fn vertices(&self) -> &[f32] {
452        &self.vertices
453    }
454
455    pub fn indices(&self) -> &[u32] {
456        &self.indices
457    }
458}