mln-rs-renderer 0.0.13

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use geometry::Point;
use mln_gfx::polyline_generator::{PolylineGenerator, PolylineGeneratorDistances, PolylineGeneratorOptions, dist};
use mln_gfx::shaders::segment::SegmentBase;
use mln_style::expression::{EvaluationContext, Image, Value};
use mln_style::layers::Line;
use mln_style::layers::line_layer_properties::{LineLayoutProperties, LinePaintProperties};
use mln_style_types::image::ImagePositions;
use mln_style_types::{LineCapType, LineJoinType};
use mln_tile_id::CanonicalTileID;
use mln_tile_id::geometry_tile_data::{GeometryCollection, GeometryCoordinates, GeometryTileFeature};
use mln_util::Color;
use mln_util::error::Error;
use mln_util::feature::numeric_value_f64;
use mln_util::geometry::FeatureType;
use mln_util::logging::{Event, Log};
use mln_util::subdivision_granularity::SubdivisionGranularitySetting;
use mln_vec_map::VecMap;
use parking_lot::RwLock;

use crate::bucket::{Bucket, BucketBase};
use crate::bucket_geometry::GeometryVec;
use crate::gfx::context::Context;
use crate::layer_type::EvaluatedLayer;
use crate::layout::pattern_layout::PatternLayerMap;
use crate::paint_property_binder::{CrossFadedPaintPropertyBinder, DashArrayBinder, PaintPropertyBinder};
use crate::util::subdivision::subdivide_vertex_line;

crate::paint_property_binders!(
    pub struct LineBinders for LinePaintProperties::PossiblyEvaluated {
        line_blur => PaintPropertyBinder<f32>,
        line_color => PaintPropertyBinder<Color>,
        line_floor_width => PaintPropertyBinder<f32>,
        line_gap_width => PaintPropertyBinder<f32>,
        line_offset => PaintPropertyBinder<f32>,
        line_opacity => PaintPropertyBinder<f32>,
        line_pattern => CrossFadedPaintPropertyBinder<Image>,
        line_width => PaintPropertyBinder<f32>,
        line_dasharray => DashArrayBinder,
    }
);

/// A line layout vertex: position and normal, then four bytes of extrusion
/// data (8 bytes in all).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub(crate) struct LineLayoutVertex {
    pub(crate) a1: [i16; 2],
    pub(crate) a2: [u8; 4],
}

#[derive(mln_wire::Wire)]
pub(crate) struct LineBucket {
    pub(crate) base: BucketBase,
    pub(crate) layout: LineLayoutProperties::PossiblyEvaluated,
    pub(crate) vertices: GeometryVec<LineLayoutVertex>,
    pub(crate) triangles: GeometryVec<u16>,
    pub(crate) segments: Vec<SegmentBase>,
    /// Behind `RwLock`s: `update` (feature state) changes them while the
    /// bucket is shared.
    pub(crate) paint_property_binders: VecMap<String, RwLock<LineBinders>>,
    zoom: f32,
    overscaling: u32,
    subdivision_granularity: SubdivisionGranularitySetting,
}

/// Scale the extrusion vector so that the normal length is this value.
/// Contains the "texture" normals (-1..1). This is distinct from the
/// extrude normals for line joins, because the x-value remains 0 for the
/// texture normal array, while the extrude normal actually moves the vertex
/// to create the acute/bevelled line join.
pub(crate) const EXTRUDE_SCALE: i8 = 63;

static WARNED_INVALID_GEOMETRY: AtomicBool = AtomicBool::new(false);

impl LineBucket {
    #[must_use]
    pub(crate) fn new(
        layout: LineLayoutProperties::PossiblyEvaluated,
        layer_paint_properties: &VecMap<String, Arc<EvaluatedLayer<Line>>>,
        zoom: f32,
        overscaling: u32,
    ) -> Self {
        let mut paint_property_binders = VecMap::new();
        for (id, properties) in layer_paint_properties {
            paint_property_binders.entry(id.clone()).or_insert_with(|| {
                let mut binders = LineBinders::new(&properties.paint, zoom);
                binders.line_dasharray.set_line_cap(&layout.line_cap);
                RwLock::new(binders)
            });
        }
        LineBucket {
            base: BucketBase::default(),
            layout,
            vertices: GeometryVec::default(),
            triangles: GeometryVec::default(),
            segments: Vec::new(),
            paint_property_binders,
            zoom,
            overscaling,
            subdivision_granularity: SubdivisionGranularitySetting::none(),
        }
    }

    /// How far outside a feature a query for `layer` still hits it, from
    /// the layer's current values and the bucket's statistics of them.
    pub(crate) fn query_radius(&self, layer: &EvaluatedLayer<Line>) -> f32 {
        let evaluated = &layer.paint;
        let binders = self.paint_property_binders.get(&layer.style.id);
        let translate = evaluated.line_translate.uniform();
        let offset = get_or_max(
            evaluated.line_offset.constant(),
            LinePaintProperties::Defaults::line_offset(),
            binders.and_then(|b| b.read().line_offset.statistics.max()),
        );
        let mut line_width = get_or_max(
            evaluated.line_width.constant(),
            LinePaintProperties::Defaults::line_width(),
            binders.and_then(|b| b.read().line_width.statistics.max()),
        );
        let gap_width = get_or_max(
            evaluated.line_gap_width.constant(),
            LinePaintProperties::Defaults::line_gap_width(),
            binders.and_then(|b| b.read().line_gap_width.statistics.max()),
        );
        if gap_width != 0.0 {
            line_width = gap_width + 2.0 * line_width;
        }

        line_width / 2.0 + offset.abs() + (translate[0] * translate[0] + translate[1] * translate[1]).sqrt()
    }

    pub(crate) fn set_subdivision_granularity(&mut self, value: &SubdivisionGranularitySetting) {
        self.subdivision_granularity = *value;
    }

    /// The layout vertex of a line point.
    ///
    /// @param p vertex position
    /// @param e extrude normal
    /// @param round whether the vertex uses a round line cap
    /// @param up whether the line normal points up or down
    /// @param dir direction of the line cap (-1/0/1)
    #[must_use]
    pub(crate) fn layout_vertex(
        p: Point<i16>,
        e: Point<f64>,
        round: bool,
        up: bool,
        dir: i8,
        linesofar: i32,
    ) -> LineLayoutVertex {
        let extrude = |v: f64| -> u8 {
            // add 128 to store a byte in an unsigned byte
            mln_math::clamp_f64((f64::from(EXTRUDE_SCALE) * v).round() + 128.0, 0.0, 255.0) as u8
        };
        let dir_value = i32::from(dir.signum());
        LineLayoutVertex {
            a1: [((i32::from(p.x) * 2) | i32::from(round)) as i16, ((i32::from(p.y) * 2) | i32::from(up)) as i16],
            a2: [
                extrude(e.x),
                extrude(e.y),
                // Encode the -1/0/1 direction value into the first two bits
                // of .z of a_data. Combine it with the lower 6 bits of
                // `linesofar` (shifted by 2 bites to make room for the
                // direction value). The upper 8 bits of `linesofar` are
                // placed in the `w` component. `linesofar` is scaled down by
                // `LINE_DISTANCE_SCALE` so that we can store longer distances
                // while sacrificing precision.
                ((dir_value + 1) | ((linesofar & 0x3F) << 2)) as u8,
                (linesofar >> 6) as u8,
            ],
        }
    }

    fn add_geometry(
        &mut self,
        input_coordinates: &GeometryCoordinates,
        feature: &dyn GeometryTileFeature,
        canonical: &CanonicalTileID,
    ) {
        // Ignore empty coordinates.
        if input_coordinates.is_empty() {
            return;
        }
        let granularity = self.subdivision_granularity.line.get_granularity_for_zoom_level(canonical.z);
        let subdivided;
        let coordinates = if granularity >= 2 {
            subdivided = subdivide_vertex_line(input_coordinates, granularity, false);
            &subdivided
        } else {
            input_coordinates
        };

        let mut options = PolylineGeneratorOptions { type_: feature.get_type(), ..Default::default() };
        let len = {
            let mut l = coordinates.len();
            // If the line has duplicate vertices at the end, adjust length to remove them.
            while l >= 2 && coordinates[l - 1] == coordinates[l - 2] {
                l -= 1;
            }
            l
        };

        let first = {
            let mut i = 0;
            // If the line has duplicate vertices at the start, adjust index to remove them.
            while i + 1 < len && coordinates[i] == coordinates[i + 1] {
                i += 1;
            }
            i
        };

        // Ignore invalid geometry.
        let min_len = if options.type_ == FeatureType::Polygon { 3 } else { 2 };
        if len < min_len {
            // Warn once, but only if the source geometry is invalid, not if
            // de-duplication made it invalid. This happens, e.g., when
            // attempting to use a GeoJSON `MultiPoint` or
            // `MLNPointCollectionFeature` as the source for a line layer.
            // Unfortunately, we cannot show the layer or source name from
            // here.
            if coordinates.len() < min_len && !WARNED_INVALID_GEOMETRY.swap(true, Ordering::Relaxed) {
                Log::warning(Event::General, "Invalid geometry in line layer");
            }
            return;
        }

        if let Some(clip_start) = feature.get_value("mapbox_clip_start")
            && let Some(clip_end) = feature.get_value("mapbox_clip_end")
        {
            let start_value = numeric_value_f64(&clip_start);
            let end_value = numeric_value_f64(&clip_end);
            if let (Some(start_value), Some(end_value)) = (start_value, end_value)
                && start_value < end_value
            {
                let mut total_length = 0.0;
                for i in first..len - 1 {
                    total_length += dist(coordinates[i], coordinates[i + 1]);
                }

                options.clip_distances = Some(PolylineGeneratorDistances::new(start_value, end_value, total_length));
            }
        }

        options.join_type = self.layout.line_join.evaluate(
            &EvaluationContext::with_zoom_feature(self.zoom, Some(feature)).with_canonical_tile_id(Some(canonical)),
        );
        options.miter_limit = if options.join_type == LineJoinType::Bevel {
            1.05
        } else {
            self.layout.line_miter_limit.evaluate(
                &EvaluationContext::with_zoom_feature(self.zoom, Some(feature)).with_canonical_tile_id(Some(canonical)),
            )
        };
        let cap = self.layout.line_cap.evaluate(
            &EvaluationContext::with_zoom_feature(self.zoom, Some(feature)).with_canonical_tile_id(Some(canonical)),
        );
        options.begin_cap = cap;
        options.end_cap = if options.type_ == FeatureType::Polygon { LineCapType::Butt } else { cap };
        options.round_limit = self.layout.line_round_limit.evaluate(
            &EvaluationContext::with_zoom_feature(self.zoom, Some(feature)).with_canonical_tile_id(Some(canonical)),
        );
        options.overscaling = self.overscaling;

        let mut generator = PolylineGenerator::new(
            self.vertices.get_mut(),
            LineBucket::layout_vertex,
            &mut self.segments,
            &SegmentBase::new,
            |segment: &mut SegmentBase| segment,
            self.triangles.get_mut(),
        );
        generator.generate(coordinates, &options);
    }
}

/// The anonymous-namespace `get<Property>(evaluated, id, binders)` of
/// `line_bucket.cpp`.
fn get_or_max(evaluated_constant: Option<f32>, default_value: f32, statistics_max: Option<f32>) -> f32 {
    match statistics_max {
        Some(max) => max,
        None => evaluated_constant.unwrap_or(default_value),
    }
}

static EMPTY_FORMATTED_SECTION: Value = Value::Null;

impl Bucket for LineBucket {
    fn base(&self) -> &BucketBase {
        &self.base
    }

    fn add_feature(
        &mut self,
        feature: &dyn GeometryTileFeature,
        geometry_collection: &GeometryCollection,
        pattern_positions: &ImagePositions,
        pattern_dependencies: &PatternLayerMap,
        index: usize,
        canonical: &CanonicalTileID,
    ) -> Result<(), Error> {
        for line in geometry_collection.iter() {
            self.add_geometry(line, feature, canonical);
        }

        let length = self.vertices.len();
        for (id, binders) in &mut self.paint_property_binders {
            binders.get_mut().populate_vertex_vectors(
                feature,
                length,
                index,
                pattern_positions,
                pattern_dependencies.get(id),
                canonical,
                &EMPTY_FORMATTED_SECTION,
            );
        }
        Ok(())
    }

    fn upload(&self, _context: &Context) {
        self.base.uploaded.store(true, Ordering::SeqCst);
    }

    fn has_data(&self) -> bool {
        !self.segments.is_empty()
    }

    fn write_wire(&self, w: &mut mln_wire::Writer) {
        mln_wire::Wire::write(self, w);
    }

    fn update(
        &self,
        states: &crate::bucket::FeatureStates,
        layer: &mln_tile::TileLayer<'_>,
        layer_id: &str,
        image_positions: &ImagePositions,
    ) {
        if let Some(binders) = self.paint_property_binders.get(layer_id) {
            binders.write().update_vertex_vectors(states, layer, image_positions);
            self.base.uploaded.store(false, Ordering::SeqCst);

            // sharedVertices->updateModified()
            self.base.version.fetch_add(1, Ordering::SeqCst);
        }
    }
}