Skip to main content

mln_engine/layer/
paint_property_binder.rs

1// The binders of a layer's data-driven paint properties, which write each
2// feature's values into the vertices its draws read: `PaintPropertyBinder<T>`
3// for a constant, source or composite function, and
4// `CrossFadedPaintPropertyBinder<T>` for the cross-faded (pattern) ones.
5// `paint_property_binders!` declares a layer type's set of them.
6//
7// The binders write into the bucket's `InterleavedVertexBuffer`, which is
8// passed in, in the vertices' in-memory layout (native-endian floats and
9// u16s), so the buffer is the GPU vertex data as it uploads.
10
11use mln_gfx::gfx_types::AttributeDataType;
12use mln_style::collections::VecMap;
13use mln_style::color::Color;
14use mln_style::expression::{Dependency, EvaluationContext, Image, Value, ValueConverter};
15use mln_style::feature::GeometryTileFeature;
16use mln_style::property::evaluated::{Evaluated, Faded};
17use mln_style::property::expression::PropertyExpression;
18use mln_style::range::Range;
19use mln_style::tile_id::CanonicalTileID;
20
21use crate::draw::vertex_attribute::{SharedAttribute, Uniforms, VertexAttributeArray};
22use crate::draw::vertices::SharedVertices;
23use crate::layer::bucket_geometry::GeometryVec;
24use crate::layer::paint_property_statistics::{PaintPropertyStatistics, StatisticValue};
25use crate::text::atlas::ImagePositions;
26use crate::tile::TileLayer;
27use crate::tile::feature::feature_id_to_string;
28
29/// Maps vertex range to feature index.
30#[derive(Clone, Copy, Debug, PartialEq, Eq, mln_wire::Wire)]
31pub(crate) struct FeatureVertexRange {
32    pub(crate) feature_index: usize,
33    pub(crate) start: usize,
34    pub(crate) end: usize,
35}
36
37pub(crate) type FeatureVertexRangeMap = VecMap<String, Vec<FeatureVertexRange>>;
38
39/// The data-driven attribute values of all the binders of one
40/// `paint_property_binders!` struct, one interleaved vertex per layout
41/// vertex.
42#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
43pub struct InterleavedVertexBuffer {
44    pub stride: usize,
45    pub vertex_count: usize,
46    pub shared_vertex_vector: GeometryVec<u8>,
47}
48
49impl InterleavedVertexBuffer {
50    /// Writes `value` at `offset` in each of the vertices `indexes`.
51    pub fn fill(&mut self, indexes: std::ops::Range<usize>, offset: usize, value: &[u8]) {
52        // Taking the vertices copies a worker's buffer into wasm memory.
53        if indexes.is_empty() {
54            return;
55        }
56        let stride = self.stride;
57        let data = self.shared_vertex_vector.get_mut();
58        for index in indexes {
59            let start = stride * index + offset;
60            debug_assert!(start + value.len() <= data.len());
61            data[start..start + value.len()].copy_from_slice(value);
62        }
63    }
64
65    /// Appends a field of `size` bytes, aligned to `alignment`, to the vertex
66    /// format and returns its offset.
67    pub fn extend_vertex_format(&mut self, size: usize, alignment: usize) -> usize {
68        let mut offset = self.stride & (alignment - 1);
69        if offset != 0 {
70            offset = alignment - offset;
71        }
72
73        let vertex_offset = self.stride + offset;
74        self.stride += size + offset;
75
76        vertex_offset
77    }
78}
79
80/// The value types of data-driven paint properties with a single attribute
81/// (`float` and `Color` in circle, fill and line): the attribute's value of
82/// a value ([`attribute_value`](Self::attribute_value)), and its type.
83pub trait BinderValue: Clone + Default + ValueConverter + StatisticValue + std::fmt::Debug {
84    /// The number of floats `attribute_value` uses.
85    const DIMENSIONS: usize;
86    /// The attribute's type for a value that doesn't change with the zoom.
87    const BASE_DATA_TYPE: AttributeDataType;
88    /// The attribute's type for a value interpolated between two zooms.
89    const INTERPOLATED_DATA_TYPE: AttributeDataType;
90
91    /// The attribute's floats; only the first `DIMENSIONS` entries are used.
92    fn attribute_value(&self) -> [f32; 2];
93}
94
95impl BinderValue for f32 {
96    const DIMENSIONS: usize = 1;
97    const BASE_DATA_TYPE: AttributeDataType = AttributeDataType::Float;
98    const INTERPOLATED_DATA_TYPE: AttributeDataType = AttributeDataType::Float2;
99
100    fn attribute_value(&self) -> [f32; 2] {
101        [*self, 0.0]
102    }
103}
104
105/// Packs two values into a `u16`: `a as u16 * 256 + b as u16`, computed as an
106/// `i32` and truncated.
107fn pack_uint8_pair(a: f32, b: f32) -> u16 {
108    (i32::from(a as u16) * 256 + i32::from(b as u16)) as u16
109}
110
111impl BinderValue for Color {
112    const DIMENSIONS: usize = 2;
113    const BASE_DATA_TYPE: AttributeDataType = AttributeDataType::Float2;
114    const INTERPOLATED_DATA_TYPE: AttributeDataType = AttributeDataType::Float4;
115
116    /// Encode a four-component color value into a pair of floats, with 8
117    /// bits for each component: for each float we use the upper 8 bits for
118    /// one component (e.g. (color.r * 255) * 256), and the lower 8 for
119    /// another.
120    ///
121    /// Also note that colors come in as floats 0..1, so we scale by 255.
122    fn attribute_value(&self) -> [f32; 2] {
123        [
124            f32::from(pack_uint8_pair(255.0 * self.r, 255.0 * self.g)),
125            f32::from(pack_uint8_pair(255.0 * self.b, 255.0 * self.a)),
126        ]
127    }
128}
129
130/// The attribute values of a property that the shader interpolates between
131/// `min` and `max`, its values at the zoom stops: `min`'s, then `max`'s, in
132/// the first `2 * T::DIMENSIONS` floats.
133fn zoom_stop_values<T: BinderValue>(min: &T, max: &T) -> [f32; 4] {
134    let mut values = [0.0; 4];
135    values[..T::DIMENSIONS].copy_from_slice(&min.attribute_value()[..T::DIMENSIONS]);
136    values[T::DIMENSIONS..2 * T::DIMENSIONS].copy_from_slice(&max.attribute_value()[..T::DIMENSIONS]);
137    values
138}
139
140/// The data of a `PaintPropertyBinder` subclass.
141#[derive(Clone, Debug, mln_wire::Wire)]
142pub(crate) enum PaintPropertyBinderKind<T> {
143    Constant {
144        constant: T,
145    },
146    SourceFunction {
147        expression: PropertyExpression<T>,
148        default_value: T,
149        feature_map: FeatureVertexRangeMap,
150        vertex_data: InterleavedVertexData,
151    },
152    CompositeFunction {
153        expression: PropertyExpression<T>,
154        default_value: T,
155        zoom_range: Range<f32>,
156        feature_map: FeatureVertexRangeMap,
157        vertex_data: InterleavedVertexData,
158    },
159}
160
161/// Where a binder's values are in the interleaved vertex: not yet placed,
162/// or at a byte offset.
163#[derive(Clone, Debug, mln_wire::Wire, PartialEq, Eq)]
164pub enum InterleavedVertexData {
165    Uninitialized,
166    Interleaved { offset: usize },
167}
168
169impl InterleavedVertexData {
170    /// The byte offset of the values, once they are placed.
171    #[must_use]
172    pub fn offset(&self) -> Option<usize> {
173        match self {
174            Self::Uninitialized => None,
175            Self::Interleaved { offset } => Some(*offset),
176        }
177    }
178}
179
180impl<T: BinderValue> PaintPropertyBinderKind<T> {
181    fn vertex_offset(&self) -> Option<usize> {
182        match self {
183            Self::Constant { .. } => None,
184            Self::SourceFunction { vertex_data, .. } | Self::CompositeFunction { vertex_data, .. } => {
185                vertex_data.offset()
186            }
187        }
188    }
189
190    fn update_vertex_vector(
191        &self,
192        statistics: &mut PaintPropertyStatistics<T>,
193        buffer: &mut InterleavedVertexBuffer,
194        vertex_offset: usize,
195        range: &FeatureVertexRange,
196        feature: &dyn GeometryTileFeature,
197        state: &mln_style::feature::FeatureState,
198    ) {
199        match self {
200            Self::Constant { .. } => {}
201            Self::SourceFunction { expression, default_value, .. } => {
202                let evaluated = expression.evaluate(
203                    &EvaluationContext::from_feature(Some(feature)).with_feature_state(Some(state)),
204                    default_value.clone(),
205                );
206                statistics.add(&evaluated);
207                let value = evaluated.attribute_value();
208                buffer.fill(range.start..range.end, vertex_offset, bytemuck::cast_slice(&value[..T::DIMENSIONS]));
209            }
210            Self::CompositeFunction { expression, default_value, zoom_range, .. } => {
211                let min = expression.evaluate(
212                    &EvaluationContext::with_zoom_feature_state(zoom_range.min, Some(feature), Some(state)),
213                    default_value.clone(),
214                );
215                let max = expression.evaluate(
216                    &EvaluationContext::with_zoom_feature_state(zoom_range.max, Some(feature), Some(state)),
217                    default_value.clone(),
218                );
219                statistics.add(&min);
220                statistics.add(&max);
221                let value = zoom_stop_values(&min, &max);
222                buffer.fill(range.start..range.end, vertex_offset, bytemuck::cast_slice(&value[..2 * T::DIMENSIONS]));
223            }
224        }
225    }
226}
227
228/// The binder of a data-driven paint property of a single attribute: its
229/// constant, or each feature's value, or each feature's values at the two
230/// zooms its expression interpolates between, in the bucket's interleaved
231/// vertices, with their statistics.
232#[derive(Clone, Debug, mln_wire::Wire)]
233pub struct PaintPropertyBinder<T> {
234    pub(crate) kind: PaintPropertyBinderKind<T>,
235    pub statistics: PaintPropertyStatistics<T>,
236}
237
238impl<T: BinderValue> PaintPropertyBinder<T> {
239    /// The binder of `value`, a property evaluated for a tile at `zoom`.
240    pub fn create(value: &Evaluated<T>, zoom: f32) -> Self {
241        let kind = match value {
242            Evaluated::Constant(constant) | Evaluated::CrossFaded(Faded { to: constant, .. }) => {
243                PaintPropertyBinderKind::Constant { constant: constant.clone() }
244            }
245            Evaluated::PerFeature { expression, default } => {
246                let default_value = default.clone();
247                if expression.is_zoom_constant() {
248                    PaintPropertyBinderKind::SourceFunction {
249                        expression: expression.clone(),
250                        default_value,
251                        feature_map: FeatureVertexRangeMap::new(),
252                        vertex_data: InterleavedVertexData::Uninitialized,
253                    }
254                } else {
255                    PaintPropertyBinderKind::CompositeFunction {
256                        expression: expression.clone(),
257                        default_value,
258                        zoom_range: Range::new(zoom, zoom + 1.0),
259                        feature_map: FeatureVertexRangeMap::new(),
260                        vertex_data: InterleavedVertexData::Uninitialized,
261                    }
262                }
263            }
264        };
265        PaintPropertyBinder { kind, statistics: PaintPropertyStatistics::default() }
266    }
267
268    /// The size in bytes of the zoom-interpolated vertex: `2 * DIMENSIONS`
269    /// floats.
270    fn zoom_interpolated_size() -> usize {
271        2 * T::DIMENSIONS * 4
272    }
273
274    /// Adds the binder's zoom-interpolated vertex to the vertex format. The
275    /// constant binder has no vertex data and does nothing.
276    pub(crate) fn set_interleaved_buffer(&mut self, buffer: &mut InterleavedVertexBuffer) {
277        let vertex_data = match &mut self.kind {
278            PaintPropertyBinderKind::Constant { .. } => return,
279            PaintPropertyBinderKind::SourceFunction { vertex_data, .. }
280            | PaintPropertyBinderKind::CompositeFunction { vertex_data, .. } => vertex_data,
281        };
282        let new_vertex_offset = buffer.extend_vertex_format(Self::zoom_interpolated_size(), align_of::<f32>());
283        if matches!(vertex_data, InterleavedVertexData::Uninitialized) {
284            *vertex_data = InterleavedVertexData::Interleaved { offset: new_vertex_offset };
285        }
286    }
287
288    pub(crate) fn vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
289        if self.kind.vertex_offset().is_some() { buffer.vertex_count } else { 0 }
290    }
291
292    pub(crate) fn is_interpolated(&self) -> bool {
293        matches!(self.kind, PaintPropertyBinderKind::CompositeFunction { .. })
294    }
295
296    pub(crate) fn populate_vertex_vector(
297        &mut self,
298        buffer: &mut InterleavedVertexBuffer,
299        feature: &dyn GeometryTileFeature,
300        length: usize,
301        index: usize,
302        canonical: &CanonicalTileID,
303        formatted_section: &Value,
304    ) {
305        let Some(vertex_offset) = self.kind.vertex_offset() else { return };
306        let elements = self.vertex_count(buffer);
307        match &mut self.kind {
308            PaintPropertyBinderKind::Constant { .. } => {}
309            PaintPropertyBinderKind::SourceFunction { expression, default_value, feature_map, .. } => {
310                let evaluated = expression.evaluate(
311                    &EvaluationContext::from_feature(Some(feature))
312                        .with_formatted_section(Some(formatted_section))
313                        .with_canonical_tile_id(Some(canonical)),
314                    default_value.clone(),
315                );
316                self.statistics.add(&evaluated);
317                let value = evaluated.attribute_value();
318                // The base attribute only.
319                buffer.fill(elements..length, vertex_offset, bytemuck::cast_slice(&value[..T::DIMENSIONS]));
320                if let Some(id_str) = feature_id_to_string(&feature.get_id()) {
321                    feature_map.entry(id_str).or_default().push(FeatureVertexRange {
322                        feature_index: index,
323                        start: elements,
324                        end: length,
325                    });
326                }
327            }
328            PaintPropertyBinderKind::CompositeFunction {
329                expression, default_value, zoom_range, feature_map, ..
330            } => {
331                let min = expression.evaluate(
332                    &EvaluationContext::with_zoom_feature(zoom_range.min, Some(feature))
333                        .with_formatted_section(Some(formatted_section))
334                        .with_canonical_tile_id(Some(canonical)),
335                    default_value.clone(),
336                );
337                let max = expression.evaluate(
338                    &EvaluationContext::with_zoom_feature(zoom_range.max, Some(feature))
339                        .with_formatted_section(Some(formatted_section))
340                        .with_canonical_tile_id(Some(canonical)),
341                    default_value.clone(),
342                );
343                self.statistics.add(&min);
344                self.statistics.add(&max);
345                let value = zoom_stop_values(&min, &max);
346                buffer.fill(elements..length, vertex_offset, bytemuck::cast_slice(&value[..2 * T::DIMENSIONS]));
347                if let Some(id_str) = feature_id_to_string(&feature.get_id()) {
348                    feature_map.entry(id_str).or_default().push(FeatureVertexRange {
349                        feature_index: index,
350                        start: elements,
351                        end: length,
352                    });
353                }
354            }
355        }
356    }
357
358    pub(crate) fn update_vertex_vectors(
359        &mut self,
360        buffer: &mut InterleavedVertexBuffer,
361        states: &crate::layer::bucket::FeatureStates,
362        layer: &TileLayer<'_>,
363    ) {
364        let Self { kind, statistics } = self;
365        let (feature_map, vertex_data) = match &*kind {
366            PaintPropertyBinderKind::Constant { .. } => return,
367            PaintPropertyBinderKind::SourceFunction { feature_map, vertex_data, .. }
368            | PaintPropertyBinderKind::CompositeFunction { feature_map, vertex_data, .. } => (feature_map, vertex_data),
369        };
370        let Some(vertex_offset) = vertex_data.offset() else {
371            return;
372        };
373        for (id, state) in states {
374            let Some(positions) = feature_map.get(id) else {
375                continue;
376            };
377            for pos in positions {
378                // The worker read the feature from the same data, so it
379                // can be read again.
380                let Ok(feature) = layer.feature(pos.feature_index) else {
381                    continue;
382                };
383                kind.update_vertex_vector(statistics, buffer, vertex_offset, pos, &feature, state);
384            }
385        }
386    }
387
388    /// The factor that interpolates between the vertex's two zoom stops; 0
389    /// unless the binder is a composite function.
390    pub fn interpolation_factor(&self, current_zoom: f32) -> f32 {
391        match &self.kind {
392            PaintPropertyBinderKind::Constant { .. } | PaintPropertyBinderKind::SourceFunction { .. } => 0.0,
393            PaintPropertyBinderKind::CompositeFunction { expression, zoom_range, .. } => {
394                let possibly_rounded_zoom =
395                    if expression.get_use_integer_zoom() { current_zoom.floor() } else { current_zoom };
396
397                mln_style::math::fmaxf(
398                    0.0,
399                    mln_style::math::fminf(1.0, expression.interpolation_factor(*zoom_range, possibly_rounded_zoom)),
400                )
401            }
402        }
403    }
404
405    /// Where the property's attribute reads its values in `shared`, the
406    /// vertices of `buffer`; `None` without values.
407    pub(crate) fn apply_paint_property(
408        &self,
409        buffer: &InterleavedVertexBuffer,
410        shared: &SharedVertices,
411    ) -> Option<SharedAttribute> {
412        if let Some(vertex_offset) = self.kind.vertex_offset() {
413            let raw_size = buffer.stride as u32;
414            let data_type = if self.is_interpolated() { T::INTERPOLATED_DATA_TYPE } else { T::BASE_DATA_TYPE };
415
416            debug_assert_eq!(shared.count() / buffer.stride.max(1), self.vertex_count(buffer));
417            Some(shared_paint(shared, vertex_offset, raw_size, data_type))
418        } else {
419            // Without an interleaved buffer there are no vertices to read.
420            debug_assert_eq!(self.vertex_count(buffer), 0);
421            None
422        }
423    }
424}
425
426/// The data of a cross-faded `PaintPropertyBinder` subclass.
427#[derive(Clone, Debug, mln_wire::Wire)]
428pub(crate) enum CrossFadedPaintPropertyBinderKind<T> {
429    Constant {
430        constant: Faded<T>,
431    },
432    Composite {
433        expression: PropertyExpression<T>,
434        default_value: T,
435        zoom_range: Range<f32>,
436        vertex_data: InterleavedVertexData,
437        /// The number of vertices `populate_vertex_vector` has written. It
438        /// lags the buffer's count when a feature's patterns are missing,
439        /// so the next feature's pattern also covers those vertices.
440        #[wire(skip)]
441        populated_count: usize,
442    },
443}
444
445impl<T> CrossFadedPaintPropertyBinderKind<T> {
446    fn vertex_offset(&self) -> Option<usize> {
447        match self {
448            Self::Constant { .. } => None,
449            Self::Composite { vertex_data, .. } => vertex_data.offset(),
450        }
451    }
452}
453
454/// The binder of a `*-pattern` property, whose two attributes are four `u16`s
455/// each.
456#[derive(Clone, Debug, mln_wire::Wire)]
457pub struct CrossFadedPaintPropertyBinder<T> {
458    pub(crate) kind: CrossFadedPaintPropertyBinderKind<T>,
459}
460
461/// The size of a zoom-interpolated pattern vertex: eight `u16`s.
462const PATTERN_ZOOM_INTERPOLATED_SIZE: usize = 16;
463
464impl CrossFadedPaintPropertyBinder<Image> {
465    /// The binder of `value`, a pattern property evaluated for a tile at
466    /// `zoom`.
467    #[must_use]
468    pub fn create(value: &Evaluated<Image>, zoom: f32) -> Self {
469        let kind = match value {
470            Evaluated::Constant(constant) => CrossFadedPaintPropertyBinderKind::Constant {
471                constant: Faded { from: constant.clone(), to: constant.clone() },
472            },
473            Evaluated::CrossFaded(constant) => {
474                CrossFadedPaintPropertyBinderKind::Constant { constant: constant.clone() }
475            }
476            Evaluated::PerFeature { expression, default } => CrossFadedPaintPropertyBinderKind::Composite {
477                expression: expression.clone(),
478                default_value: default.clone(),
479                zoom_range: Range::new(zoom, zoom + 1.0),
480                vertex_data: InterleavedVertexData::Uninitialized,
481                populated_count: 0,
482            },
483        };
484        CrossFadedPaintPropertyBinder { kind }
485    }
486
487    /// Adds the binder's vertex data to the vertex format; only the composite
488    /// binder has any.
489    pub(crate) fn set_interleaved_buffer(&mut self, buffer: &mut InterleavedVertexBuffer) {
490        let CrossFadedPaintPropertyBinderKind::Composite { vertex_data, .. } = &mut self.kind else {
491            return;
492        };
493        let new_vertex_offset = buffer.extend_vertex_format(PATTERN_ZOOM_INTERPOLATED_SIZE, align_of::<u16>());
494        if matches!(vertex_data, InterleavedVertexData::Uninitialized) {
495            *vertex_data = InterleavedVertexData::Interleaved { offset: new_vertex_offset };
496        }
497    }
498
499    pub(crate) fn vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
500        if self.kind.vertex_offset().is_some() { buffer.vertex_count } else { 0 }
501    }
502
503    pub(crate) fn populate_vertex_vector(
504        &mut self,
505        buffer: &mut InterleavedVertexBuffer,
506        length: usize,
507        pattern_positions: &ImagePositions,
508        pattern_dependencies: Option<&PatternDependency>,
509    ) {
510        let CrossFadedPaintPropertyBinderKind::Composite { populated_count, vertex_data, .. } = &mut self.kind else {
511            return;
512        };
513        let InterleavedVertexData::Interleaved { offset: vertex_offset } = vertex_data else {
514            return;
515        };
516        match pattern_dependencies {
517            Some(dependencies) if !dependencies.mid.is_empty() => {
518                if !pattern_positions.is_empty() {
519                    // Only the middle pattern reaches the GPU, but a feature
520                    // needs all three.
521                    let (Some(_), Some(image_mid), Some(_)) = (
522                        pattern_positions.get(&dependencies.min),
523                        pattern_positions.get(&dependencies.mid),
524                        pattern_positions.get(&dependencies.max),
525                    ) else {
526                        return;
527                    };
528
529                    buffer.fill(*populated_count..length, *vertex_offset, bytemuck::cast_slice(&image_mid.tlbr()));
530                    *populated_count = (*populated_count).max(length);
531                }
532            }
533            _ => {
534                // Unlike other properties with expressions that evaluate to
535                // null, the default value for `*-pattern` properties is an
536                // empty string and will not have a valid entry in the
537                // pattern positions. We still need to populate the attribute
538                // buffers to avoid crashes when we try to draw the layer
539                // because we don't know at draw time if all features were
540                // evaluated to valid pattern dependencies.
541                buffer.fill(*populated_count..length, *vertex_offset, bytemuck::cast_slice(&[0u16; 4]));
542                *populated_count = (*populated_count).max(length);
543            }
544        }
545    }
546
547    /// The zoom interpolation factors, always (0, 0) for pattern binders.
548    #[must_use]
549    pub fn interpolation_factor(&self, _current_zoom: f32) -> (f32, f32) {
550        (0.0, 0.0)
551    }
552
553    /// Where the property's attributes read the pattern values in `shared`,
554    /// the vertices of `buffer`: both read the same values. `None` without
555    /// values.
556    pub(crate) fn apply_paint_property(
557        &self,
558        buffer: &InterleavedVertexBuffer,
559        shared: &SharedVertices,
560    ) -> Option<SharedAttribute> {
561        if let Some(vertex_offset) = self.kind.vertex_offset() {
562            let raw_size = buffer.stride as u32;
563            // Patterns don't interpolate: one value of four shorts.
564            Some(shared_paint(shared, vertex_offset, raw_size, AttributeDataType::UShort4))
565        } else {
566            None
567        }
568    }
569}
570
571/// What a layer's set of binders and [`bind_paint_property`] do
572/// with either binder enum.
573pub trait PaintPropertyBinderBase {
574    /// Places the binder's values in `buffer`'s interleaved vertex.
575    fn set_interleaved(&mut self, buffer: &mut InterleavedVertexBuffer);
576    #[expect(
577        clippy::too_many_arguments,
578        reason = "the vertex buffer, the feature and its index range, its patterns, the tile and the formatted section that evaluate a property"
579    )]
580    /// Writes the values of `feature`, the feature at `index`, into `buffer`
581    /// for the vertices up to `length`.
582    fn populate(
583        &mut self,
584        buffer: &mut InterleavedVertexBuffer,
585        feature: &dyn GeometryTileFeature,
586        length: usize,
587        index: usize,
588        pattern_positions: &ImagePositions,
589        pattern_dependencies: Option<&PatternDependency>,
590        canonical: &CanonicalTileID,
591        formatted_section: &Value,
592    );
593    /// Rewrites the vertex data that depends on feature state. The default,
594    /// for the constant and cross-faded binders, does nothing.
595    fn update_vectors(
596        &mut self,
597        _buffer: &mut InterleavedVertexBuffer,
598        _states: &crate::layer::bucket::FeatureStates,
599        _layer: &TileLayer<'_>,
600    ) {
601    }
602    /// True if a feature state change rewrites this binder's vertex data.
603    fn depends_on_feature_state(&self) -> bool {
604        false
605    }
606    /// The number of vertices whose values `buffer` holds for the binder.
607    fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize;
608    /// The attribute that reads the binder's values in `shared`, the
609    /// buffer's vertices in the context's store; `None` for a constant.
610    fn apply(&self, buffer: &InterleavedVertexBuffer, shared: &SharedVertices) -> Option<SharedAttribute>;
611}
612
613impl<T: BinderValue> PaintPropertyBinderBase for PaintPropertyBinder<T> {
614    fn set_interleaved(&mut self, buffer: &mut InterleavedVertexBuffer) {
615        self.set_interleaved_buffer(buffer);
616    }
617    /// Writes the values of `feature`, the feature at `index`, into `buffer`
618    /// for the vertices up to `length`.
619    fn populate(
620        &mut self,
621        buffer: &mut InterleavedVertexBuffer,
622        feature: &dyn GeometryTileFeature,
623        length: usize,
624        index: usize,
625        _pattern_positions: &ImagePositions,
626        _pattern_dependencies: Option<&PatternDependency>,
627        canonical: &CanonicalTileID,
628        formatted_section: &Value,
629    ) {
630        self.populate_vertex_vector(buffer, feature, length, index, canonical, formatted_section);
631    }
632    fn update_vectors(
633        &mut self,
634        buffer: &mut InterleavedVertexBuffer,
635        states: &crate::layer::bucket::FeatureStates,
636        layer: &TileLayer<'_>,
637    ) {
638        self.update_vertex_vectors(buffer, states, layer);
639    }
640    fn depends_on_feature_state(&self) -> bool {
641        match &self.kind {
642            PaintPropertyBinderKind::Constant { .. } => false,
643            PaintPropertyBinderKind::SourceFunction { expression, .. }
644            | PaintPropertyBinderKind::CompositeFunction { expression, .. } => {
645                expression.get_expression().has(Dependency::FEATURE_STATE)
646            }
647        }
648    }
649    fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
650        self.vertex_count(buffer)
651    }
652    fn apply(&self, buffer: &InterleavedVertexBuffer, shared: &SharedVertices) -> Option<SharedAttribute> {
653        self.apply_paint_property(buffer, shared)
654    }
655}
656
657impl PaintPropertyBinderBase for CrossFadedPaintPropertyBinder<Image> {
658    fn set_interleaved(&mut self, buffer: &mut InterleavedVertexBuffer) {
659        self.set_interleaved_buffer(buffer);
660    }
661    /// Writes the values of `feature`, the feature at `index`, into `buffer`
662    /// for the vertices up to `length`.
663    fn populate(
664        &mut self,
665        buffer: &mut InterleavedVertexBuffer,
666        _feature: &dyn GeometryTileFeature,
667        length: usize,
668        _index: usize,
669        pattern_positions: &ImagePositions,
670        pattern_dependencies: Option<&PatternDependency>,
671        _canonical: &CanonicalTileID,
672        _formatted_section: &Value,
673    ) {
674        self.populate_vertex_vector(buffer, length, pattern_positions, pattern_dependencies);
675    }
676    fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize {
677        self.vertex_count(buffer)
678    }
679    fn apply(&self, buffer: &InterleavedVertexBuffer, shared: &SharedVertices) -> Option<SharedAttribute> {
680        self.apply_paint_property(buffer, shared)
681    }
682}
683
684/// An attribute that reads the values at `offset` in each of the `stride`
685/// bytes of `shared`, the vertices of a bucket's paint values, as
686/// `data_type`.
687#[must_use]
688pub fn shared_paint(
689    shared: &SharedVertices,
690    offset: usize,
691    stride: u32,
692    data_type: AttributeDataType,
693) -> SharedAttribute {
694    SharedAttribute::new(shared.clone(), data_type, offset as u32, stride)
695}
696
697/// Binds `binder`'s values, `shared`, the vertices of `buffer`, to the
698/// attributes `attributes` in `attrs`, or records the properties of those
699/// names in `uniforms` if the property is constant or has no values.
700pub fn bind_paint_property(
701    binder: &dyn PaintPropertyBinderBase,
702    buffer: &InterleavedVertexBuffer,
703    shared: Option<&SharedVertices>,
704    attributes: &[&'static str],
705    is_constant: bool,
706    attrs: &mut VertexAttributeArray,
707    uniforms: &mut Uniforms,
708) {
709    if is_constant || binder.binder_vertex_count(buffer) == 0 {
710        for &attribute in attributes {
711            uniforms.insert(attribute);
712        }
713    } else if let Some(values) = shared.and_then(|shared| binder.apply(buffer, shared)) {
714        for &attribute in attributes {
715            attrs.set_shared(attribute, values.clone());
716        }
717    }
718}
719
720/// A layer type's binders of its data-driven paint properties, one per
721/// property, sharing one [`InterleavedVertexBuffer`]: what
722/// `paint_property_binders!` declares.
723pub trait PaintBinders: Clone + Send + mln_wire::Wire + 'static {
724    /// The evaluated paint values whose data-driven properties the binders
725    /// write.
726    type Paint: 'static;
727
728    /// The binders of `paint` in a tile at `zoom`.
729    fn new(paint: &Self::Paint, zoom: f32) -> Self;
730
731    /// The values, one interleaved vertex per vertex of the bucket.
732    fn vertices_mut(&mut self) -> &mut InterleavedVertexBuffer;
733
734    /// Writes the values of `feature`, the feature at `index` of the tile
735    /// `canonical`, in its text's formatted section `section`, with the
736    /// images of its patterns `pattern` among `positions`, into the
737    /// vertices up to `length`.
738    #[expect(clippy::too_many_arguments, reason = "the feature, its vertices, its tile, its section and its patterns")]
739    fn populate(
740        &mut self,
741        feature: &dyn GeometryTileFeature,
742        length: usize,
743        index: usize,
744        positions: &ImagePositions,
745        pattern: Option<&PatternDependency>,
746        canonical: &CanonicalTileID,
747        section: &Value,
748    );
749
750    /// Rewrites the values that read feature state for `states`, the states
751    /// of the features of `layer`.
752    fn feature_state(&mut self, states: &crate::layer::bucket::FeatureStates, layer: &TileLayer<'_>);
753
754    /// Whether a feature state change rewrites the values.
755    fn depends_on_feature_state(&self) -> bool;
756}
757
758/// A set of binders `P` for each layer of a layout's group, which their
759/// bucket holds.
760#[derive(Clone, Debug, mln_wire::Wire)]
761#[wire(bound = "P: mln_wire::Wire")]
762pub struct LayerBinders<P> {
763    /// Each layer's id and binders, in the group's order.
764    layers: Vec<(String, P)>,
765}
766
767impl<P> Default for LayerBinders<P> {
768    /// The binders of no layer.
769    fn default() -> Self {
770        LayerBinders { layers: Vec::new() }
771    }
772}
773
774impl<P> LayerBinders<P> {
775    /// The binders of the layer `id`, if it is one of the group's.
776    #[must_use]
777    pub fn get(&self, id: &str) -> Option<&P> {
778        self.layers.iter().find(|(layer, _)| layer == id).map(|(_, binders)| binders)
779    }
780
781    /// Each layer's binders.
782    pub fn values(&self) -> impl Iterator<Item = &P> {
783        self.layers.iter().map(|(_, binders)| binders)
784    }
785
786    /// Each layer's binders, to change.
787    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut P> {
788        self.layers.iter_mut().map(|(_, binders)| binders)
789    }
790
791    /// Each layer's id and binders, to change.
792    pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut P)> {
793        self.layers.iter_mut().map(|(id, binders)| (id.as_str(), binders))
794    }
795}
796
797impl<P: PaintBinders> LayerBinders<P> {
798    /// The binders of each of `layers`, the first of each id, of their
799    /// paint values at `zoom`.
800    pub fn new<T>(layers: &[std::sync::Arc<crate::layer::layer_type::EvaluatedLayer<T>>], zoom: f32) -> Self
801    where
802        T: mln_style::layer::StyleLayerType<PaintProperties: mln_style::layer::PaintSet<Evaluated = P::Paint>>,
803    {
804        let mut binders: Vec<(String, P)> = Vec::with_capacity(layers.len());
805        for layer in layers {
806            if !binders.iter().any(|(id, _)| *id == layer.style.id) {
807                binders.push((layer.style.id.clone(), P::new(&layer.paint, zoom)));
808            }
809        }
810        LayerBinders { layers: binders }
811    }
812
813    /// Writes `feature`'s values into each layer's binders, with each
814    /// layer's of `patterns` among `positions`, as [`PaintBinders::populate`]
815    /// does.
816    #[expect(clippy::too_many_arguments, reason = "the feature, its vertices, its tile, its section and its patterns")]
817    pub fn populate(
818        &mut self,
819        feature: &dyn GeometryTileFeature,
820        length: usize,
821        index: usize,
822        positions: &ImagePositions,
823        patterns: Option<&PatternLayerMap>,
824        canonical: &CanonicalTileID,
825        section: &Value,
826    ) {
827        for (id, binders) in &mut self.layers {
828            let pattern = patterns.and_then(|patterns| patterns.get(id));
829            binders.populate(feature, length, index, positions, pattern, canonical, section);
830        }
831    }
832}
833
834/// Declares the binders of one layer type's data-driven paint properties: a
835/// struct with one binder per property, each with the names of the attributes
836/// a program reads its values from (fields in the interleaved vertex order),
837/// and the shared `InterleavedVertexBuffer`, and its [`PaintBinders`].
838#[macro_export]
839macro_rules! paint_property_binders {
840    (
841        $(#[$meta:meta])*
842        pub struct $name:ident for $props:path {
843            $($field:ident: $binder:ty => [$($attribute:expr),+]),+ $(,)?
844        }
845    ) => {
846        $(#[$meta])*
847        #[derive(Clone, Debug, $crate::__private::mln_wire::Wire)]
848        #[wire(crate = $crate::__private::mln_wire)]
849        pub(crate) struct $name {
850            pub interleaved_vertex_buffer: $crate::layer::binders::InterleavedVertexBuffer,
851            $(pub $field: $binder,)+
852        }
853
854        impl $crate::layer::binders::PaintBinders for $name {
855            type Paint = $props;
856
857            fn new(properties: &$props, z: f32) -> Self {
858                let mut result = $name {
859                    interleaved_vertex_buffer: Default::default(),
860                    $($field: <$binder>::create(&properties.$field, z),)+
861                };
862                $($crate::layer::binders::PaintPropertyBinderBase::set_interleaved(
863                    &mut result.$field, &mut result.interleaved_vertex_buffer);)+
864                result
865            }
866
867            fn vertices_mut(&mut self) -> &mut $crate::layer::binders::InterleavedVertexBuffer {
868                &mut self.interleaved_vertex_buffer
869            }
870
871            fn populate(
872                &mut self,
873                feature: &dyn $crate::__private::mln_style::feature::GeometryTileFeature,
874                length: usize,
875                index: usize,
876                pattern_positions: &$crate::draw::ImagePositions,
877                pattern_dependencies: Option<&$crate::layer::binders::PatternDependency>,
878                canonical: &$crate::__private::mln_style::tile_id::CanonicalTileID,
879                formatted_section: &$crate::__private::mln_style::expression::Value,
880            ) {
881                let buffer = &mut self.interleaved_vertex_buffer;
882                let added = (length - buffer.vertex_count) * buffer.stride;
883                let data = buffer.shared_vertex_vector.get_mut();
884                data.resize(data.len() + added, 0);
885
886                $($crate::layer::binders::PaintPropertyBinderBase::populate(
887                    &mut self.$field,
888                    &mut self.interleaved_vertex_buffer,
889                    feature,
890                    length,
891                    index,
892                    pattern_positions,
893                    pattern_dependencies,
894                    canonical,
895                    formatted_section,
896                );)+
897
898                let buffer = &mut self.interleaved_vertex_buffer;
899                buffer.vertex_count += length - buffer.vertex_count;
900                // The render thread copies the vector when it builds draws.
901            }
902
903            fn feature_state(
904                &mut self,
905                states: &$crate::layer::bucket::FeatureStates,
906                layer: &$crate::tile::TileLayer<'_>,
907            ) {
908                // Values that moved to the render thread don't depend on
909                // feature state (`depends_on_feature_state`).
910                if self.interleaved_vertex_buffer.shared_vertex_vector.is_moved() {
911                    return;
912                }
913                $($crate::layer::binders::PaintPropertyBinderBase::update_vectors(
914                    &mut self.$field, &mut self.interleaved_vertex_buffer, states, layer);)+
915            }
916
917            fn depends_on_feature_state(&self) -> bool {
918                false $(|| $crate::layer::binders::PaintPropertyBinderBase::depends_on_feature_state(
919                    &self.$field))+
920            }
921        }
922
923        impl $name {
924            /// Binds each property's values, `shared`, the vertices of the
925            /// paint values, to its attributes in `attrs`, or records the
926            /// properties of its attributes' names in `uniforms` where
927            /// `evaluated` is constant.
928            pub(crate) fn bind(
929                &self,
930                evaluated: &$props,
931                shared: Option<&$crate::draw::SharedVertices>,
932                attrs: &mut $crate::draw::VertexAttributeArray,
933                uniforms: &mut $crate::draw::Uniforms,
934            ) {
935                $($crate::layer::binders::bind_paint_property(
936                    &self.$field,
937                    &self.interleaved_vertex_buffer,
938                    shared,
939                    &[$($attribute),+],
940                    evaluated.$field.is_constant(),
941                    attrs,
942                    uniforms,
943                );)+
944            }
945        }
946    };
947}
948
949/// The images of a feature's pattern at the zooms its cross-fade reads: a
950/// pattern property's dependency, which its binder takes the positions of.
951#[derive(Clone, Debug, Default, PartialEq, Eq)]
952pub struct PatternDependency {
953    pub min: String,
954    pub mid: String,
955    pub max: String,
956}
957
958/// Each layer's [`PatternDependency`] of a feature, by layer id.
959pub type PatternLayerMap = mln_style::hash::HashMap<String, PatternDependency>;