Skip to main content

mln_engine/layer/
bucket_geometry.rs

1// Where a bucket's vertices and indices live once the render thread draws
2// them.
3//
4// Buckets cross from the worker threads, so they hold plain vectors
5// (`GeometryVec`). A bucket's upload moves each vector into the context's
6// stores, which the draws of the bucket's tile share, so the bucket and the
7// draws don't each keep a copy; the tile keeps their handles, by the key of
8// the vector they were made of, in a `BucketGeometry`. The stores free the
9// data once it is in a GPU buffer, and the draws a layer builds again for
10// the same bucket reuse that buffer. Vertices that a layer makes of a
11// bucket's vector are kept there too, made before the vector moves.
12//
13// A copy of a vector keeps its key. The tiles of a tile's other world
14// copies hold copies of its buckets, and the upload of either takes what
15// the other already moved into the stores, freeing its own copy.
16//
17// In the browser, the arrays a bucket gets from a tile worker in another
18// wasm instance stay the JS arrays they arrived in (mln_wire::host_bytes)
19// and move to the store as they are, which uploads them from there.
20// Anything that reads or changes them first copies them into wasm memory.
21
22use std::borrow::Cow;
23
24#[cfg(target_family = "wasm")]
25use mln_wire::host_bytes::HostBytes;
26use mln_wire::payload::{Payload, pod};
27
28use crate::draw::context::Context;
29use crate::draw::identity::SimpleIdentity;
30use crate::draw::indexes::{IndexBuffer, Indexes};
31use crate::draw::resources::Resources;
32use crate::draw::vertices::VertexBuffer;
33use crate::layer::paint_property_binder::InterleavedVertexBuffer;
34
35/// A bucket's vertices or indices. The worker fills it through `get_mut`;
36/// the render thread can move the data out (`BucketGeometry`), after which
37/// `len` still counts it.
38#[derive(Clone, Debug)]
39pub struct GeometryVec<T> {
40    data: Data<T>,
41    /// What `BucketGeometry` keeps the vector's stored geometry under. A
42    /// copy keeps it, so the stored geometry of either serves both.
43    key: SimpleIdentity,
44}
45
46/// Where a [`GeometryVec`]'s data is.
47#[derive(Clone, Debug)]
48enum Data<T> {
49    /// In memory.
50    Vec(Vec<T>),
51    /// In the JS array it arrived in.
52    #[cfg(target_family = "wasm")]
53    Host(HostBytes),
54    /// Moved out, `len` elements of it.
55    Moved { len: usize },
56}
57
58impl<T> Default for GeometryVec<T> {
59    fn default() -> Self {
60        GeometryVec::new(Vec::new())
61    }
62}
63
64impl<T> GeometryVec<T> {
65    #[must_use]
66    pub(crate) fn new(v: Vec<T>) -> Self {
67        GeometryVec::of(Data::Vec(v))
68    }
69
70    fn of(data: Data<T>) -> Self {
71        GeometryVec { data, key: SimpleIdentity::new() }
72    }
73
74    /// The data, to fill. Not after it is moved out.
75    pub fn get_mut(&mut self) -> &mut Vec<T>
76    where
77        T: bytemuck::Pod,
78    {
79        debug_assert!(!self.is_moved(), "geometry modified after it moved to the render thread");
80        self.data.vec_mut()
81    }
82
83    /// The element count, which stays when the data is moved out.
84    #[must_use]
85    pub fn len(&self) -> usize {
86        match &self.data {
87            Data::Vec(v) => v.len(),
88            #[cfg(target_family = "wasm")]
89            Data::Host(bytes) => bytes.len() / size_of::<T>(),
90            Data::Moved { len } => *len,
91        }
92    }
93
94    /// Whether the vector holds no element.
95    #[must_use]
96    pub fn is_empty(&self) -> bool {
97        self.len() == 0
98    }
99
100    /// True once the data has moved to the context's store.
101    #[must_use]
102    pub fn is_moved(&self) -> bool {
103        matches!(self.data, Data::Moved { .. })
104    }
105
106    /// The data, empty once it is moved out.
107    #[must_use]
108    pub fn data(&self) -> Cow<'_, [T]>
109    where
110        T: bytemuck::Pod,
111    {
112        self.data.data()
113    }
114
115    /// The data, moved out, leaving its count.
116    fn take(&mut self) -> Data<T> {
117        let len = self.len();
118        std::mem::replace(&mut self.data, Data::Moved { len })
119    }
120}
121
122impl<T: bytemuck::Pod> Data<T> {
123    /// The data, empty once it is moved out.
124    fn data(&self) -> Cow<'_, [T]> {
125        match self {
126            Data::Vec(v) => Cow::Borrowed(v),
127            #[cfg(target_family = "wasm")]
128            Data::Host(bytes) => Cow::Owned(bytes.to_pod_vec()),
129            Data::Moved { .. } => Cow::Borrowed(&[]),
130        }
131    }
132
133    /// The data's vector, which replaces the data where it isn't in memory:
134    /// a copy of the JS array's, or an empty one where it moved out.
135    fn vec_mut(&mut self) -> &mut Vec<T> {
136        match self {
137            Data::Vec(v) => v,
138            #[cfg(target_family = "wasm")]
139            host @ Data::Host(_) => {
140                *host = Data::Vec(host.data().into_owned());
141                host.vec_mut()
142            }
143            moved @ Data::Moved { .. } => {
144                *moved = Data::Vec(Vec::new());
145                moved.vec_mut()
146            }
147        }
148    }
149}
150
151impl<T: bytemuck::Pod> GeometryVec<T> {
152    /// Frees the data, which nothing will draw. `len` still counts it.
153    pub fn discard(&mut self) {
154        self.take();
155    }
156
157    /// The data, moved out into `context`'s store.
158    fn store_vertices(&mut self, context: &mut Context) -> VertexBuffer {
159        match self.take() {
160            Data::Vec(v) => context.add_vertices(v),
161            #[cfg(target_family = "wasm")]
162            Data::Host(bytes) => context.add_host_vertices::<T>(bytes),
163            Data::Moved { .. } => context.add_vertices(Vec::<T>::new()),
164        }
165    }
166}
167
168impl GeometryVec<u16> {
169    /// Indexes of the data, moved out.
170    fn indexes(&mut self) -> Indexes {
171        match self.take() {
172            Data::Vec(v) => Indexes::new(v),
173            #[cfg(target_family = "wasm")]
174            Data::Host(bytes) => Indexes::from_host(bytes),
175            Data::Moved { .. } => Indexes::new(Vec::new()),
176        }
177    }
178}
179
180impl<T: bytemuck::Pod + PartialEq> PartialEq for GeometryVec<T> {
181    fn eq(&self, other: &Self) -> bool {
182        self.is_moved() == other.is_moved() && self.len() == other.len() && self.data() == other.data()
183    }
184}
185
186impl<T> From<Vec<T>> for GeometryVec<T> {
187    fn from(v: Vec<T>) -> Self {
188        GeometryVec::new(v)
189    }
190}
191
192/// As the plain values' bytes (`payload::pod`). Workers send buckets before
193/// the render thread moves anything out. A payload the host kept in JS
194/// stays there (`mln_wire::host_bytes`).
195impl<T: bytemuck::Pod> mln_wire::Wire for GeometryVec<T> {
196    fn write(&self, w: &mut mln_wire::Writer<'_>) {
197        debug_assert!(!self.is_moved());
198        pod::write(&self.data(), w);
199    }
200
201    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
202        Some(match pod::read_payload::<T>(r)? {
203            Payload::Bytes(bytes) => GeometryVec::new(bytemuck::pod_collect_to_vec(&bytes)),
204            #[cfg(target_family = "wasm")]
205            Payload::Host(bytes) => GeometryVec::of(Data::Host(bytes)),
206        })
207    }
208}
209
210/// The geometry of a tile's buckets in the context's stores, by the key of
211/// the bucket's vector it was made of. The tile keeps one per layout result,
212/// so it lives as long as the buckets it was made from.
213#[derive(Clone, Default)]
214pub struct BucketGeometry {
215    vertices: Kept<VertexBuffer>,
216    indexes: Kept<IndexBuffer>,
217    /// The vertices a layer made of a bucket's vector.
218    derived: Kept<VertexBuffer>,
219}
220
221impl BucketGeometry {
222    /// The vertices that `vec`, a bucket's, moved into.
223    fn vertices<V>(&self, vec: &GeometryVec<V>) -> Option<&VertexBuffer> {
224        self.vertices.get(vec.key)
225    }
226
227    /// Frees the room that the entries' lists keep for more, where it is
228    /// over a quarter of what they keep, once a tile's buckets uploaded.
229    pub(crate) fn shrink(&mut self) {
230        self.vertices.shrink();
231        self.indexes.shrink();
232        self.derived.shrink();
233    }
234}
235
236/// Entries by the key of the vector they were made of, in key order: a
237/// tile's are few, and a list takes less memory than a map.
238#[derive(Clone)]
239struct Kept<T>(Vec<(SimpleIdentity, T)>);
240
241impl<T> Default for Kept<T> {
242    fn default() -> Self {
243        Kept(Vec::new())
244    }
245}
246
247impl<T> Kept<T> {
248    fn get(&self, key: SimpleIdentity) -> Option<&T> {
249        let at = self.0.binary_search_by_key(&key, |(key, _)| *key).ok()?;
250        self.0.get(at).map(|(_, value)| value)
251    }
252
253    fn insert(&mut self, key: SimpleIdentity, value: T) {
254        match self.0.binary_search_by_key(&key, |(key, _)| *key) {
255            Ok(at) => {
256                if let Some(entry) = self.0.get_mut(at) {
257                    entry.1 = value;
258                }
259            }
260            Err(at) => self.0.insert(at, (key, value)),
261        }
262    }
263
264    /// Whether the list has an entry under `key`, taking the first of
265    /// `others`' where it has none.
266    fn has_or_takes<'a>(&mut self, key: SimpleIdentity, mut others: impl Iterator<Item = &'a Kept<T>>) -> bool
267    where
268        T: Clone + 'a,
269    {
270        if self.get(key).is_some() {
271            return true;
272        }
273        let Some(shared) = others.find_map(|other| other.get(key)) else {
274            return false;
275        };
276        self.insert(key, shared.clone());
277        true
278    }
279
280    fn shrink(&mut self) {
281        if self.0.capacity() - self.0.len() > self.0.len() / 4 {
282            self.0.shrink_to_fit();
283        }
284    }
285}
286
287/// A bucket's upload: what moves the bucket's geometry into the context's
288/// stores, and keeps its handles in its tile's [`BucketGeometry`].
289pub(crate) struct GeometryUpload<'a> {
290    geometry: &'a mut BucketGeometry,
291    /// The geometry of the tile's other world copies, whose buckets the
292    /// tile's are copies of, or they of the tile's.
293    copies: &'a [&'a BucketGeometry],
294    context: &'a mut Context,
295}
296
297impl<'a> GeometryUpload<'a> {
298    /// The upload of buckets whose geometry `geometry` keeps, into
299    /// `context`'s stores, which takes what of it `copies`, the geometry of
300    /// the tile's other world copies, keep.
301    pub(crate) fn new(
302        geometry: &'a mut BucketGeometry,
303        copies: &'a [&'a BucketGeometry],
304        context: &'a mut Context,
305    ) -> Self {
306        GeometryUpload { geometry, copies, context }
307    }
308
309    /// What the context's device allows.
310    pub(crate) fn caps(&self) -> &mln_gfx::gpu::Caps {
311        self.context.caps()
312    }
313
314    /// Moves the data of `vec`, a bucket's, into the store, unless it moved
315    /// before. Where a copy of it moved, this frees it and shares the
316    /// copy's.
317    pub(crate) fn move_vertices<V: bytemuck::Pod>(&mut self, vec: &mut GeometryVec<V>) {
318        if vec.is_moved() {
319            return;
320        }
321        if self.geometry.vertices.has_or_takes(vec.key, self.copies.iter().map(|copy| &copy.vertices)) {
322            vec.discard();
323        } else {
324            let vertices = vec.store_vertices(self.context);
325            self.geometry.vertices.insert(vec.key, vertices);
326        }
327    }
328
329    /// Moves the data of `vec`, a bucket's, into the store's indexes,
330    /// unless it moved before, as [`move_vertices`](Self::move_vertices)
331    /// does.
332    pub(crate) fn move_indexes(&mut self, vec: &mut GeometryVec<u16>) {
333        if vec.is_moved() {
334            return;
335        }
336        if self.geometry.indexes.has_or_takes(vec.key, self.copies.iter().map(|copy| &copy.indexes)) {
337            vec.discard();
338        } else {
339            let indexes = self.context.add_indexes(vec.indexes());
340            self.geometry.indexes.insert(vec.key, indexes);
341        }
342    }
343
344    /// Moves the values of `buffer`, a layer's data-driven paint values,
345    /// into the store, unless they `depend_on_feature_state`: those stay in
346    /// the bucket, where feature state rewrites them.
347    pub(crate) fn move_paint(&mut self, buffer: &mut InterleavedVertexBuffer, depends_on_feature_state: bool) {
348        if !depends_on_feature_state {
349            self.move_vertices(&mut buffer.shared_vertex_vector);
350        }
351    }
352
353    /// Keeps the vertices that `make` makes of the data of `vec`, a
354    /// bucket's, for [`derived_vertices`], unless it or a copy has some.
355    /// Before the data moves.
356    pub(crate) fn derive_vertices<V: bytemuck::Pod, D: bytemuck::Pod>(
357        &mut self,
358        vec: &GeometryVec<V>,
359        make: impl FnOnce(&[V]) -> Vec<D>,
360    ) {
361        if !self.geometry.derived.has_or_takes(vec.key, self.copies.iter().map(|copy| &copy.derived)) {
362            debug_assert!(!vec.is_moved(), "vertices derived from data that moved to the store");
363            let derived = self.context.add_vertices(make(&vec.data()));
364            self.geometry.derived.insert(vec.key, derived);
365        }
366    }
367}
368
369/// The vertices that a bucket's upload made of `vec`, one of its vectors,
370/// with `GeometryUpload::derive_vertices`, which its tile's `geometry`
371/// keeps.
372#[must_use]
373pub fn derived_vertices<V>(geometry: &BucketGeometry, vec: &GeometryVec<V>) -> Option<VertexBuffer> {
374    let derived = geometry.derived.get(vec.key);
375    debug_assert!(derived.is_some(), "vertices that the bucket's upload didn't derive");
376    derived.cloned()
377}
378
379/// The vertices that a bucket's upload moved `vec`, one of its vectors,
380/// into, which its tile's `geometry` keeps.
381#[must_use]
382pub fn bucket_vertices<V>(geometry: &BucketGeometry, vec: &GeometryVec<V>) -> Option<VertexBuffer> {
383    let vertices = geometry.vertices(vec);
384    debug_assert!(vertices.is_some(), "vertices that the bucket's upload didn't move");
385    vertices.cloned()
386}
387
388/// The indexes that a bucket's upload moved `vec`, one of its vectors,
389/// into, which its tile's `geometry` keeps and its draws share.
390#[must_use]
391pub fn bucket_indexes(geometry: &BucketGeometry, vec: &GeometryVec<u16>) -> Option<IndexBuffer> {
392    let indexes = geometry.indexes.get(vec.key);
393    debug_assert!(indexes.is_some(), "indexes that the bucket's upload didn't move");
394    indexes.cloned()
395}
396
397/// The vertices of a layer's data-driven paint values: those that a
398/// bucket's upload moved, which its tile's `geometry` keeps, or a copy,
399/// made through `res`, of the values that feature state rewrites, which
400/// stay in the bucket, and which the draws copy again each time they
401/// change.
402pub fn paint_vertices(
403    res: &mut Resources<'_>,
404    geometry: &BucketGeometry,
405    buffer: &InterleavedVertexBuffer,
406    depends_on_feature_state: bool,
407) -> Option<VertexBuffer> {
408    if depends_on_feature_state {
409        Some(res.vertices(&buffer.shared_vertex_vector.data()))
410    } else {
411        bucket_vertices(geometry, &buffer.shared_vertex_vector)
412    }
413}