1use 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#[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#[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 pub fn fill(&mut self, indexes: std::ops::Range<usize>, offset: usize, value: &[u8]) {
54 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 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
82pub trait BinderValue: Clone + Default + ValueConverter + StatisticValue + std::fmt::Debug {
86 const DIMENSIONS: usize;
88 const BASE_DATA_TYPE: AttributeDataType;
90 const INTERPOLATED_DATA_TYPE: AttributeDataType;
92
93 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
107fn 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 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
132fn 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#[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#[derive(Clone, Debug, mln_wire::Wire, PartialEq, Eq)]
166pub enum InterleavedVertexData {
167 Uninitialized,
168 Interleaved { offset: usize },
169}
170
171impl InterleavedVertexData {
172 #[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#[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 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 fn zoom_interpolated_size() -> usize {
273 2 * T::DIMENSIONS * 4
274 }
275
276 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 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 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 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 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 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 debug_assert_eq!(self.vertex_count(buffer), 0);
406 None
407 }
408 }
409}
410
411#[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 #[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#[derive(Clone, Debug, mln_wire::Wire)]
442pub struct CrossFadedPaintPropertyBinder<T> {
443 pub(crate) kind: CrossFadedPaintPropertyBinderKind<T>,
444}
445
446const PATTERN_ZOOM_INTERPOLATED_SIZE: usize = 16;
448
449impl CrossFadedPaintPropertyBinder<Image> {
450 #[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 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 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 buffer.fill(*populated_count..length, *vertex_offset, bytemuck::cast_slice(&[0u16; 4]));
527 *populated_count = (*populated_count).max(length);
528 }
529 }
530 }
531
532 #[must_use]
534 pub fn interpolation_factor(&self, _current_zoom: f32) -> (f32, f32) {
535 (0.0, 0.0)
536 }
537
538 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
546pub trait PaintPropertyBinderBase {
549 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 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 fn update_vectors(
572 &mut self,
573 _buffer: &mut InterleavedVertexBuffer,
574 _states: &crate::layer::bucket::FeatureStates,
575 _layer: &TileLayer<'_>,
576 ) {
577 }
578 fn depends_on_feature_state(&self) -> bool {
580 false
581 }
582 fn binder_vertex_count(&self, buffer: &InterleavedVertexBuffer) -> usize;
584 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 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 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#[derive(Clone, Debug, Default)]
671pub struct PaintAttributes {
672 pub vertices: Option<VertexBinding>,
676 pub uniforms: Uniforms,
677}
678
679pub 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#[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
716pub trait PaintBinders: Clone + Send + mln_wire::Wire + 'static {
720 type Paint: 'static;
723
724 fn new(paint: &Self::Paint, zoom: f32) -> Self;
726
727 fn vertices_mut(&mut self) -> &mut InterleavedVertexBuffer;
729
730 #[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 fn feature_state(&mut self, states: &crate::layer::bucket::FeatureStates, layer: &TileLayer<'_>);
750
751 fn depends_on_feature_state(&self) -> bool;
753}
754
755#[derive(Clone, Debug, mln_wire::Wire)]
758#[wire(bound = "P: mln_wire::Wire")]
759pub struct LayerBinders<P> {
760 layers: Vec<(String, P)>,
762}
763
764impl<P> Default for LayerBinders<P> {
765 fn default() -> Self {
767 LayerBinders { layers: Vec::new() }
768 }
769}
770
771impl<P> LayerBinders<P> {
772 #[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 pub fn values(&self) -> impl Iterator<Item = &P> {
780 self.layers.iter().map(|(_, binders)| binders)
781 }
782
783 pub fn values_mut(&mut self) -> impl Iterator<Item = &mut P> {
785 self.layers.iter_mut().map(|(_, binders)| binders)
786 }
787
788 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 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 #[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#[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 }
902
903 fn feature_state(
904 &mut self,
905 states: &$crate::layer::bucket::FeatureStates,
906 layer: &$crate::tile::TileLayer<'_>,
907 ) {
908 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 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
951pub struct PatternDependency {
952 pub min: String,
953 pub mid: String,
954 pub max: String,
955}
956
957pub type PatternLayerMap = mln_style::hash::HashMap<String, PatternDependency>;