mln-rs-plugin 0.0.23

Safe Rust SDK for writing MapLibre layer, source, and expression plugins
Documentation
//! Host-agnostic custom expression function plugin API (`ExpressionPlugin`).
//!
//! Implement [`ExpressionPlugin`] to define a custom MapLibre style expression
//! function that can be registered either directly in-process via
//! `mln_engine::RegistryBuilder::add_expression_plugin` (native and Wasm) or
//! over the MapLibre Native C Plugin ABI via `mln_plugin_c::RegistryBuilder`.

use core::ops::{BitAnd, BitOr, BitOrAssign};

use crate::types::{CanonicalTileId, Color, LatLng};

/// Capability flags declaring which runtime inputs an expression overload
/// reads beyond its explicit arguments.
///
/// Pure functions (`ExprCapabilities::NONE`) may be constant-folded by the
/// style parser when all of their arguments are constant.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct ExprCapabilities(u32);

impl ExprCapabilities {
    /// Pure function: depends only on its arguments.
    pub const NONE: Self = Self(0);
    /// Reads the live camera context (`ExprEvalCx::camera`).
    pub const CAMERA: Self = Self(1 << 0);
    /// Reads mutable host or platform state invalidated via
    /// `invalidate_expression_functions`.
    pub const HOST: Self = Self(1 << 1);
    /// Reads the canonical tile ID (`ExprEvalCx::tile`).
    pub const TILE: Self = Self(1 << 2);
    /// Depends on the evaluated feature (prevents constant folding and
    /// feature-group sharing).
    pub const FEATURE: Self = Self(1 << 3);

    /// Mask of all capability bits defined by this SDK.
    pub const ALL: Self = Self(Self::CAMERA.0 | Self::HOST.0 | Self::TILE.0 | Self::FEATURE.0);

    /// Creates a capability set from raw bitflags.
    #[must_use]
    pub const fn from_bits(bits: u32) -> Self {
        Self(bits)
    }

    /// Returns the raw bitmask value.
    #[must_use]
    pub const fn bits(self) -> u32 {
        self.0
    }

    /// Returns `true` when no capabilities are set.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// Returns `true` when all bits in `other` are set in `self`.
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    /// Combines two capability sets.
    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }
}

impl BitOr for ExprCapabilities {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl BitOrAssign for ExprCapabilities {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

impl BitAnd for ExprCapabilities {
    type Output = Self;

    fn bitand(self, rhs: Self) -> Self {
        Self(self.0 & rhs.0)
    }
}

/// Static expression type for an overload parameter or return value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExprType {
    Null,
    Boolean,
    Number,
    String,
    Color,
    Object,
    Value,
    Array { item: Box<ExprType>, len: Option<usize> },
}

impl ExprType {
    /// Variable-length array of `item`.
    #[must_use]
    pub fn array(item: Self) -> Self {
        Self::Array { item: Box::new(item), len: None }
    }

    /// Fixed-length array of `len` elements of `item`.
    #[must_use]
    pub fn array_n(item: Self, len: usize) -> Self {
        Self::Array { item: Box::new(item), len: Some(len) }
    }
}

/// Parameter list signature for an expression overload.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ExprParams {
    /// Fixed arity with explicit parameter types.
    Fixed(Vec<ExprType>),
    /// Zero or more arguments, each matching the given element type.
    Varargs(ExprType),
}

/// Static signature and declared capabilities of one expression overload.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExprOverloadDesc {
    pub params: ExprParams,
    pub result: ExprType,
    pub capabilities: ExprCapabilities,
}

impl ExprOverloadDesc {
    /// Creates a pure overload descriptor (`ExprCapabilities::NONE`).
    #[must_use]
    pub const fn new(params: ExprParams, result: ExprType) -> Self {
        Self { params, result, capabilities: ExprCapabilities::NONE }
    }

    /// Sets the capability flags for this overload.
    #[must_use]
    pub const fn with_capabilities(mut self, capabilities: ExprCapabilities) -> Self {
        self.capabilities = capabilities;
        self
    }
}

/// Read-only camera state supplied to `ExprCapabilities::CAMERA` overloads.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ExprCamera {
    pub zoom: f64,
    /// Bearing in degrees clockwise from north.
    pub bearing: f64,
    /// Pitch in degrees from nadir.
    pub pitch: f64,
    /// Roll in degrees.
    pub roll: f64,
    /// Vertical field of view in degrees.
    pub field_of_view: f64,
    /// Camera center in WGS84 degrees.
    pub center: LatLng,
    /// Center altitude in meters above sea level.
    pub center_altitude: f64,
    /// Viewport width in logical pixels.
    pub viewport_width: f64,
    /// Viewport height in logical pixels.
    pub viewport_height: f64,
    /// Ground resolution at the camera center in meters per logical pixel.
    pub meters_per_pixel: f64,
    /// Whether the map is currently rendering in globe projection.
    pub is_globe: bool,
}

/// Read-only context passed to [`ExpressionPlugin::evaluate`].
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ExprEvalCx<'a> {
    /// Live camera state when available.
    pub camera: Option<&'a ExprCamera>,
    /// Canonical tile ID when evaluating in a tiled context.
    pub tile: Option<CanonicalTileId>,
}

/// Evaluated argument passed to [`ExpressionPlugin::evaluate`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ExprArg<'a> {
    Null,
    Bool(bool),
    Number(f64),
    String(&'a str),
    Color(Color),
    /// Compact UTF-8 JSON array.
    ArrayJson(&'a str),
    /// Compact UTF-8 JSON object.
    ObjectJson(&'a str),
}

/// Value returned by [`ExpressionPlugin::evaluate`].
#[derive(Clone, Debug, Default, PartialEq)]
pub enum ExprValue {
    #[default]
    Null,
    Bool(bool),
    Number(f64),
    String(String),
    Color(Color),
    /// Arbitrary JSON value (commonly an array or object).
    Json(String),
}

impl From<bool> for ExprValue {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<f64> for ExprValue {
    fn from(value: f64) -> Self {
        Self::Number(value)
    }
}

impl From<String> for ExprValue {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<&str> for ExprValue {
    fn from(value: &str) -> Self {
        Self::String(value.to_owned())
    }
}

impl From<Color> for ExprValue {
    fn from(value: Color) -> Self {
        Self::Color(value)
    }
}

/// A custom MapLibre style expression function implemented in Rust.
///
/// Implementations must be thread-safe (`Send + Sync + 'static`) because
/// evaluation may run on the render thread, tile layout worker threads, or
/// standalone expression evaluation threads concurrently.
pub trait ExpressionPlugin: Send + Sync + 'static {
    /// Operator name as written in style JSON (for example `"acme:scale"`).
    fn name(&self) -> &str;

    /// One or more overload signatures accepted by this function.
    fn overloads(&self) -> Vec<ExprOverloadDesc>;

    /// Evaluates the overload at `overload_index` against already-evaluated
    /// `args` and optional runtime context `cx`.
    fn evaluate(&self, overload_index: usize, args: &[ExprArg<'_>], cx: &ExprEvalCx<'_>) -> Result<ExprValue, String>;
}