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