use std::any::Any;
use std::borrow::Cow;
use std::rc::Rc;
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use geojson::GeoJson;
use glam::Vec2 as GlamVec2;
use mln_gfx::color_mode::ColorMode as GfxColorMode;
use mln_gfx::cull_face_mode::CullFaceMode as GfxCullFaceMode;
use mln_gfx::draw_mode::DrawMode as GfxDrawMode;
use mln_gfx::gfx_types::DrawModeType;
use mln_gfx::gpu::TextureFormat as GfxTextureFormat;
use mln_gfx::projection_variant::ProjectionVariant as GfxProjectionVariant;
use mln_gfx::shaders::bindings::MAX_TEXTURES;
use mln_gfx::shaders::layer_ubo::ProjectionUBO;
use mln_gfx::shaders::program::Program as GfxProgram;
use mln_gfx::texture2d::SamplerState as GfxSamplerState;
use mln_gfx::types::{
CullFaceSideType, CullFaceWindingType, DepthMaskType, TextureChannelDataType, TextureFilterType, TextureWrapType,
};
use mln_gfx::{Rgba, Size};
use mln_plugin::backend::{
DrawGroupBackend, DrawsBackend, EvaluateCxBackend, EvaluatedLayerBackend, FrameBackend, FrameQueryCxMutBackend,
FrameQueryCxReadBackend, GroundHeightsHandle, HitCxBackend, HostBackend, IndexBufferHandle, MeshHandle,
PaintAttributesHandle, PrepareCxMutBackend, PrepareCxReadBackend, ResourcesBackend, TargetHandle, TextureHandle,
TileBackend, TileBuildCxBackend, TileGeometryBackend, TileGeometryBuilderBackend, UpdateCxMutBackend,
UpdateCxReadBackend, VertexBufferHandle, ViewBackend,
};
use mln_plugin::{
Alignment, CollisionShape, CollisionShapeKind, Color as PluginColor, ColorMode, Composite as PluginComposite,
CullFaceMode, CullFaceSide, CullFaceWinding, DepthMode, DrawGroup, DrawMode, DrawOptions,
DrawRange as PluginDrawRange, Draws as PluginDraws, Error as PluginError, EvaluateCx, EvaluatedLayer,
Evaluation as PluginEvaluation, FeatureType as PluginFeatureType, Frame as PluginFrame, FrameInfo, FrameQueryCx,
GroundHeights as PluginGroundHeights, Hit as PluginHit, HitCx, HitInfo, Host, IndexBuffer as PluginIndexBuffer,
LatLng as PluginLatLng, LayerBlend, LayerInput, LayerInstance, LayerPlugin, LendAt as PluginLendAt,
LoadedFeatureInfo, MapMode as PluginMapMode, Mesh as PluginMesh, MeshDesc as PluginMeshDesc,
PaintAttributes as PluginPaintAttributes, PointI16, PrepareCx, ProjectedPoint, ProjectionUbo, ProjectionVariant,
PropertyDefault, PropertyScope, RasterTileInfo, RenderPasses, Resources as PluginResources, Result as PluginResult,
SamplerState, ScreenPoint, Status, Target as PluginTarget, TerrainMode, Texture as PluginTexture,
TextureChannelType, TextureFilter, TextureFormat, TextureWrap, Tile, TileBuildCx, TileChanges, TileCx,
TileGeometry, TileGeometryBuilder, TileId, TileOrder as PluginTileOrder, TileTransform as PluginTileTransform,
UpdateCx, Vec2 as PluginVec2, VertexBinding as PluginVertexBinding, VertexBuffer as PluginVertexBuffer,
View as PluginView, ViewInfo,
};
use mln_style::PropertyEvaluationParameters;
use mln_style::color::Color;
use mln_style::crs::WorldMapping;
use mln_style::error::Error as StyleError;
use mln_style::expression::{EvaluationContext, ValueConverter};
use mln_style::feature::{FeatureState, GeometryCollection, GeometryCoordinate, GeometryTileFeature};
use mln_style::geo::{LatLng, WrapMode};
use mln_style::geometry::{FeatureType, Point};
use mln_style::hash::HashSet;
use mln_style::layer::dynamic::{
DynamicDefault, DynamicEvaluated, DynamicLayerDesc, DynamicPropertyDesc, DynamicPropertyValue,
DynamicStyleLayerType, MAX_DYNAMIC_DATA_DRIVEN_PAINT, MAX_DYNAMIC_PROPERTIES,
};
use mln_style::layer::{LayerTypeInfo, PropertyScope as StylePropertyScope, SourceKind};
use mln_style::property::evaluated::Evaluated;
use mln_style::property::value::PropertyValue;
use mln_style::range::Range;
use mln_style::tile_id::CanonicalTileID;
use mln_style::time::Instant;
use mln_style::types::{AlignmentType, CirclePitchScaleType, LayerBlendType, Rotation, TranslateAnchorType};
use crate::camera::{TileProjector, View};
use crate::draw::draws::{Draws, Group, LayerFrame};
use crate::draw::ground::{FrameGround, GroundHeights, height_binding};
use crate::draw::projection::{TileTransform, globe_extrude_scale, tile_projection};
use crate::draw::{
Composite, Depth, Draw, DrawRange, IndexBuffer, Mesh, MeshDesc, Resources, Target, Texture, Textures, Uniforms,
VertexAttribute, VertexBinding, VertexBuffer,
};
use crate::layer::binders::{PaintAttributes, PaintBinders as _};
use crate::layer::bucket_geometry::{bucket_indexes, bucket_vertices};
use crate::layer::dynamic::{
DynamicBucket, DynamicBuildCx, DynamicEvaluateCx, DynamicEvaluatedLayer, DynamicFrameQuery, DynamicFrameTile,
DynamicLayerConfig, DynamicLayerHandler, DynamicLayerInstance, DynamicLayerType, DynamicLayerValues,
DynamicPrepareCx, DynamicTileCx, DynamicTileData, DynamicUpdateCx,
};
use crate::layer::layer_drawing::TileMap;
use crate::layer::render_layer::{Evaluation, OnTerrain};
use crate::map::MapMode;
use crate::placement::{Shape, TestedShape};
use crate::plugin::program::{
EngineProgram, create_program, resolve_attribute_name, resolve_uniform_block, to_attribute_format,
};
use crate::query::feature_index::{Hit, QueryRegion};
use crate::query::translate_query_geometry;
use crate::render::pass::RenderPass;
use crate::render::shared_targets::SharedTargets;
use crate::render::tile::RenderTile;
use crate::source::render_source::TileOrder;
use crate::tile::feature::Feature;
use crate::tile::{OverscaledTileID, TileLayer, UnwrappedTileID};
use crate::tile_store::TileLodMode;
use crate::tile_store::tile_cover::{TileCoverParameters, tile_cover};
static TIME_ORIGIN: LazyLock<Instant> = LazyLock::new(Instant::now);
fn instant_to_ns(instant: Instant) -> i64 {
let origin = *TIME_ORIGIN;
if let Some(after) = instant.checked_duration_since(origin) {
i64::try_from(after.as_nanos()).unwrap_or(i64::MAX)
} else if let Some(before) = origin.checked_duration_since(instant) {
let nanos = i64::try_from(before.as_nanos()).unwrap_or(i64::MAX);
nanos.saturating_neg()
} else {
0
}
}
fn to_color(c: PluginColor) -> Color {
Color::rgba(c.r, c.g, c.b, c.a.clamp(0.0, 1.0))
}
fn from_color(c: Color) -> PluginColor {
let [r, g, b, a] = c.straight_rgba();
PluginColor::rgba(r, g, b, a)
}
fn to_lat_lng(ll: PluginLatLng) -> PluginResult<LatLng> {
if !ll.latitude.is_finite() || !ll.longitude.is_finite() {
return Err(PluginError::invalid_argument("latitude and longitude must be finite"));
}
Ok(LatLng::saturating(ll.latitude, ll.longitude, WrapMode::Unwrapped))
}
fn from_lat_lng(ll: LatLng) -> PluginLatLng {
PluginLatLng::new(ll.latitude(), ll.longitude())
}
fn from_overscaled_tile_id(id: OverscaledTileID) -> TileId {
TileId {
overscaled_z: u32::from(id.overscaled_z),
wrap: i32::from(id.wrap),
canonical_z: u32::from(id.canonical.z),
canonical_x: id.canonical.x,
canonical_y: id.canonical.y,
}
}
fn from_unwrapped_tile_id(id: UnwrappedTileID) -> TileId {
TileId {
overscaled_z: u32::from(id.canonical.z),
wrap: i32::from(id.wrap),
canonical_z: u32::from(id.canonical.z),
canonical_x: id.canonical.x,
canonical_y: id.canonical.y,
}
}
fn overscaled_tile_id(id: TileId) -> PluginResult<OverscaledTileID> {
let oz = u8::try_from(id.overscaled_z).map_err(|_| PluginError::invalid_argument("overscaled_z out of range"))?;
let wrap = i16::try_from(id.wrap).map_err(|_| PluginError::invalid_argument("tile wrap out of range"))?;
let cz = u8::try_from(id.canonical_z).map_err(|_| PluginError::invalid_argument("canonical_z out of range"))?;
Ok(OverscaledTileID::new(oz, wrap, CanonicalTileID::new(cz, id.canonical_x, id.canonical_y)))
}
fn unwrapped_tile_id(id: TileId) -> PluginResult<UnwrappedTileID> {
let wrap = i16::try_from(id.wrap).map_err(|_| PluginError::invalid_argument("tile wrap out of range"))?;
let cz = u8::try_from(id.canonical_z).map_err(|_| PluginError::invalid_argument("canonical_z out of range"))?;
Ok(UnwrappedTileID::with_wrap(wrap, CanonicalTileID::new(cz, id.canonical_x, id.canonical_y)))
}
fn from_projection_variant(v: GfxProjectionVariant) -> ProjectionVariant {
match v {
GfxProjectionVariant::Mercator => ProjectionVariant::Mercator,
GfxProjectionVariant::Globe => ProjectionVariant::Globe,
GfxProjectionVariant::Terrain => ProjectionVariant::MercatorStanding,
GfxProjectionVariant::GlobeTerrain => ProjectionVariant::GlobeStanding,
}
}
fn to_projection_variant(v: ProjectionVariant) -> GfxProjectionVariant {
match v {
ProjectionVariant::Mercator => GfxProjectionVariant::Mercator,
ProjectionVariant::Globe => GfxProjectionVariant::Globe,
ProjectionVariant::MercatorStanding => GfxProjectionVariant::Terrain,
ProjectionVariant::GlobeStanding => GfxProjectionVariant::GlobeTerrain,
}
}
fn from_projection_ubo(u: ProjectionUBO) -> ProjectionUbo {
ProjectionUbo {
matrix: u.matrix,
fallback_matrix: u.fallback_matrix,
tile_mercator_coords: u.tile_mercator_coords,
clipping_plane: u.clipping_plane,
projection_transition: u.projection_transition,
depth_offset: u.depth_offset,
translate: u.translate,
anchor: u.anchor,
anchor_angles: u.anchor_angles,
}
}
fn to_projection_ubo(u: &ProjectionUbo) -> ProjectionUBO {
ProjectionUBO {
matrix: u.matrix,
fallback_matrix: u.fallback_matrix,
tile_mercator_coords: u.tile_mercator_coords,
clipping_plane: u.clipping_plane,
projection_transition: u.projection_transition,
depth_offset: u.depth_offset,
translate: u.translate,
anchor: u.anchor,
anchor_angles: u.anchor_angles,
}
}
fn to_translate_anchor(a: Alignment) -> TranslateAnchorType {
match a {
Alignment::Map => TranslateAnchorType::Map,
Alignment::Viewport => TranslateAnchorType::Viewport,
}
}
fn to_alignment_type(a: Alignment) -> AlignmentType {
match a {
Alignment::Map => AlignmentType::Map,
Alignment::Viewport => AlignmentType::Viewport,
}
}
fn to_pitch_scale_type(a: Alignment) -> CirclePitchScaleType {
match a {
Alignment::Map => CirclePitchScaleType::Map,
Alignment::Viewport => CirclePitchScaleType::Viewport,
}
}
fn from_feature_type(t: FeatureType) -> PluginFeatureType {
match t {
FeatureType::Unknown => PluginFeatureType::Unknown,
FeatureType::Point => PluginFeatureType::Point,
FeatureType::LineString => PluginFeatureType::LineString,
FeatureType::Polygon => PluginFeatureType::Polygon,
}
}
fn from_map_mode(m: MapMode) -> PluginMapMode {
match m {
MapMode::Continuous => PluginMapMode::Continuous,
MapMode::Static => PluginMapMode::Static,
MapMode::Tile => PluginMapMode::Tile,
}
}
fn from_render_pass(pass: RenderPass) -> RenderPasses {
let mut out = RenderPasses::NONE;
if pass & RenderPass::OPAQUE != RenderPass::NONE {
out = out.union(RenderPasses::OPAQUE);
}
if pass & RenderPass::TRANSLUCENT != RenderPass::NONE {
out = out.union(RenderPasses::TRANSLUCENT);
}
out
}
fn to_render_pass(pass: RenderPasses) -> RenderPass {
let mut out = RenderPass::NONE;
if pass.contains(RenderPasses::OPAQUE) {
out |= RenderPass::OPAQUE;
}
if pass.contains(RenderPasses::TRANSLUCENT) {
out |= RenderPass::TRANSLUCENT;
}
out
}
fn to_color_mode(m: ColorMode) -> GfxColorMode {
match m {
ColorMode::AlphaBlended => GfxColorMode::alpha_blended(),
ColorMode::Unblended => GfxColorMode::unblended(),
ColorMode::Additive => GfxColorMode::additive(),
ColorMode::Disabled => GfxColorMode::disabled(),
}
}
fn to_cull_face_mode(m: CullFaceMode) -> GfxCullFaceMode {
let side = match m.side {
CullFaceSide::Back => CullFaceSideType::Back,
CullFaceSide::Front => CullFaceSideType::Front,
CullFaceSide::FrontAndBack => CullFaceSideType::FrontAndBack,
};
let winding = match m.winding {
CullFaceWinding::Ccw => CullFaceWindingType::CounterClockwise,
CullFaceWinding::Cw => CullFaceWindingType::Clockwise,
};
GfxCullFaceMode { enabled: m.enabled, side, winding }
}
fn to_draw_mode(m: DrawMode) -> GfxDrawMode {
match m {
DrawMode::Triangles => GfxDrawMode::Triangles(),
DrawMode::TriangleStrip => GfxDrawMode::TriangleStrip(),
DrawMode::TriangleFan => GfxDrawMode { kind: DrawModeType::TriangleFan, size: 0.0 },
DrawMode::Lines(w) => GfxDrawMode::Lines(if w > 0.0 { w } else { 1.0 }),
DrawMode::LineLoop(w) => GfxDrawMode { kind: DrawModeType::LineLoop, size: if w > 0.0 { w } else { 1.0 } },
DrawMode::LineStrip(w) => GfxDrawMode { kind: DrawModeType::LineStrip, size: if w > 0.0 { w } else { 1.0 } },
DrawMode::Points(s) => GfxDrawMode { kind: DrawModeType::Points, size: if s > 0.0 { s } else { 1.0 } },
}
}
fn to_draw_options(o: DrawOptions) -> Draw {
let depth = match o.depth {
DepthMode::Layer { sub_layer, write } => {
Depth::Layer { sub_layer, mask: if write { DepthMaskType::ReadWrite } else { DepthMaskType::ReadOnly } }
}
DepthMode::Off => Depth::Off,
DepthMode::Volume { write } => {
Depth::Volume { mask: if write { DepthMaskType::ReadWrite } else { DepthMaskType::ReadOnly } }
}
};
Draw { order: o.order, opaque: o.opaque, depth, clip: o.clip }
}
fn to_layer_blend(b: LayerBlend) -> LayerBlendType {
match b {
LayerBlend::Normal => LayerBlendType::Normal,
LayerBlend::Multiply => LayerBlendType::Multiply,
LayerBlend::Screen => LayerBlendType::Screen,
LayerBlend::Overlay => LayerBlendType::Overlay,
LayerBlend::Darken => LayerBlendType::Darken,
LayerBlend::Lighten => LayerBlendType::Lighten,
LayerBlend::ColorDodge => LayerBlendType::ColorDodge,
LayerBlend::ColorBurn => LayerBlendType::ColorBurn,
LayerBlend::HardLight => LayerBlendType::HardLight,
LayerBlend::SoftLight => LayerBlendType::SoftLight,
LayerBlend::Difference => LayerBlendType::Difference,
LayerBlend::Exclusion => LayerBlendType::Exclusion,
LayerBlend::Hue => LayerBlendType::Hue,
LayerBlend::Saturation => LayerBlendType::Saturation,
LayerBlend::Color => LayerBlendType::Color,
LayerBlend::Luminosity => LayerBlendType::Luminosity,
LayerBlend::PlusLighter => LayerBlendType::PlusLighter,
}
}
fn to_texture_format(f: TextureFormat) -> GfxTextureFormat {
match f {
TextureFormat::Rgba8Unorm => GfxTextureFormat::Rgba8Unorm,
TextureFormat::R8Unorm => GfxTextureFormat::R8Unorm,
TextureFormat::A8Unorm => GfxTextureFormat::A8Unorm,
TextureFormat::R16Float => GfxTextureFormat::R16Float,
TextureFormat::R32Float => GfxTextureFormat::R32Float,
TextureFormat::Rgba16Float => GfxTextureFormat::Rgba16Float,
TextureFormat::Rgba32Float => GfxTextureFormat::Rgba32Float,
}
}
fn to_channel_type(c: TextureChannelType) -> TextureChannelDataType {
match c {
TextureChannelType::UnsignedByte => TextureChannelDataType::UnsignedByte,
TextureChannelType::HalfFloat => TextureChannelDataType::HalfFloat,
TextureChannelType::Float => TextureChannelDataType::Float,
}
}
fn to_sampler(s: SamplerState) -> GfxSamplerState {
GfxSamplerState {
filter: match s.filter {
TextureFilter::Nearest => TextureFilterType::Nearest,
TextureFilter::Linear => TextureFilterType::Linear,
},
wrap_u: match s.wrap_u {
TextureWrap::Clamp => TextureWrapType::Clamp,
TextureWrap::Repeat => TextureWrapType::Repeat,
},
wrap_v: match s.wrap_v {
TextureWrap::Clamp => TextureWrapType::Clamp,
TextureWrap::Repeat => TextureWrapType::Repeat,
},
max_anisotropy: s.max_anisotropy.max(1),
mipmapped: s.mipmapped,
}
}
fn to_evaluation(ev: PluginEvaluation, time_point: Option<Instant>) -> Evaluation {
let opaque = ev.passes.contains(RenderPasses::OPAQUE);
let draws = opaque || ev.passes.contains(RenderPasses::TRANSLUCENT);
let solid = ev.solid_color.map(to_color);
let repaint_at = ev.repaint_after_ns.and_then(|ns| {
let t = time_point?;
t.checked_add(Duration::from_nanos(ns))
});
Evaluation {
draws,
opaque,
solid,
drapes_by_bearing: ev.drapes_by_bearing,
drapes_by_zoom: ev.drapes_by_zoom,
needs_repaint: ev.needs_repaint,
repaint_at,
reads_collision_shapes: ev.reads_collision_shapes,
}
}
fn to_draw_range(r: PluginDrawRange) -> DrawRange {
DrawRange {
first_index: r.first_index,
index_count: r.index_count,
base_vertex: r.base_vertex,
first_instance: r.first_instance,
instance_count: r.instance_count,
}
}
fn from_draw_range(r: DrawRange) -> PluginDrawRange {
PluginDrawRange {
first_index: r.first_index,
index_count: r.index_count,
base_vertex: r.base_vertex,
first_instance: r.first_instance,
instance_count: r.instance_count,
}
}
fn convert_vertex_binding(
program: &'static GfxProgram,
binding: &PluginVertexBinding<'_>,
) -> PluginResult<VertexBinding> {
let buf = downcast_vertex_buffer(binding.buffer)?;
if binding.stride == 0 {
return Err(PluginError::invalid_argument("vertex_binding.stride must not be zero"));
}
let mut attrs = Vec::with_capacity(binding.attributes.len());
for attr in binding.attributes {
let static_name = resolve_attribute_name(program, attr.name)?;
attrs.push(VertexAttribute {
name: static_name,
format: to_attribute_format(attr.format),
offset: attr.offset,
});
}
Ok(VertexBinding::new(buf, binding.stride, attrs).starting_at(binding.first_vertex))
}
struct EngineHost;
impl HostBackend for EngineHost {
fn create_program(&self, desc: &mln_plugin::ProgramDesc<'_>) -> PluginResult<mln_plugin::Program> {
create_program(desc)
}
fn create_ground_heights(&self) -> PluginResult<PluginGroundHeights> {
Ok(PluginGroundHeights::from_handle(Box::new(EngineGroundHeights { inner: GroundHeights::default() })))
}
}
#[derive(Debug)]
struct EngineVertexBuffer {
inner: VertexBuffer,
}
impl VertexBufferHandle for EngineVertexBuffer {
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Debug)]
struct EngineIndexBuffer {
inner: IndexBuffer,
}
impl IndexBufferHandle for EngineIndexBuffer {
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Debug)]
struct EngineTexture {
inner: Texture,
}
impl TextureHandle for EngineTexture {
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Debug)]
struct EngineTarget {
inner: Target,
}
impl TargetHandle for EngineTarget {
fn texture(&self) -> Option<PluginTexture> {
Some(PluginTexture::from_handle(Box::new(EngineTexture { inner: self.inner.texture().clone() })))
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Debug)]
struct EnginePaintAttributes {
inner: PaintAttributes,
}
impl PaintAttributesHandle for EnginePaintAttributes {
fn as_any(&self) -> &dyn Any {
self
}
}
struct EngineMesh {
inner: Mesh,
}
impl std::fmt::Debug for EngineMesh {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EngineMesh").field("seq", &self.inner.seq()).finish_non_exhaustive()
}
}
impl MeshHandle for EngineMesh {
fn seq(&self) -> i64 {
self.inner.seq()
}
fn as_any(&self) -> &dyn Any {
self
}
}
struct EngineGroundHeights {
inner: GroundHeights,
}
impl std::fmt::Debug for EngineGroundHeights {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EngineGroundHeights").finish_non_exhaustive()
}
}
impl GroundHeightsHandle for EngineGroundHeights {
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
fn downcast_program(p: &mln_plugin::Program) -> PluginResult<&'static GfxProgram> {
p.handle()
.as_any()
.downcast_ref::<EngineProgram>()
.map(EngineProgram::inner)
.ok_or_else(|| PluginError::invalid_argument("program was not created by the mln_engine host"))
}
fn downcast_vertex_buffer(vb: &PluginVertexBuffer) -> PluginResult<&VertexBuffer> {
vb.handle()
.as_any()
.downcast_ref::<EngineVertexBuffer>()
.map(|b| &b.inner)
.ok_or_else(|| PluginError::invalid_argument("vertex buffer was not created by the mln_engine host"))
}
fn downcast_index_buffer(ib: &PluginIndexBuffer) -> PluginResult<&IndexBuffer> {
ib.handle()
.as_any()
.downcast_ref::<EngineIndexBuffer>()
.map(|b| &b.inner)
.ok_or_else(|| PluginError::invalid_argument("index buffer was not created by the mln_engine host"))
}
fn downcast_texture(tex: &PluginTexture) -> PluginResult<&Texture> {
tex.handle()
.as_any()
.downcast_ref::<EngineTexture>()
.map(|t| &t.inner)
.ok_or_else(|| PluginError::invalid_argument("texture was not created by the mln_engine host"))
}
fn downcast_target(target: &PluginTarget) -> PluginResult<&Target> {
target
.handle()
.as_any()
.downcast_ref::<EngineTarget>()
.map(|t| &t.inner)
.ok_or_else(|| PluginError::invalid_argument("target was not created by the mln_engine host"))
}
fn downcast_paint_attributes(paint: &PluginPaintAttributes) -> PluginResult<&PaintAttributes> {
paint
.handle()
.as_any()
.downcast_ref::<EnginePaintAttributes>()
.map(|p| &p.inner)
.ok_or_else(|| PluginError::invalid_argument("paint attributes were not created by the mln_engine host"))
}
fn downcast_mesh(mesh: &PluginMesh) -> PluginResult<&Mesh> {
mesh.handle()
.as_any()
.downcast_ref::<EngineMesh>()
.map(|m| &m.inner)
.ok_or_else(|| PluginError::invalid_argument("mesh was not created by the mln_engine host"))
}
fn downcast_ground_heights_mut(heights: &mut PluginGroundHeights) -> PluginResult<&mut GroundHeights> {
heights
.handle_mut()
.as_any_mut()
.downcast_mut::<EngineGroundHeights>()
.map(|h| &mut h.inner)
.ok_or_else(|| PluginError::invalid_argument("ground heights were not created by the mln_engine host"))
}
fn eval_paint_is_constant(layer: &DynamicEvaluatedLayer, slot: u32) -> bool {
layer.paint.get(slot as usize).is_some_and(DynamicEvaluated::is_constant)
}
fn eval_paint_f32(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<f32> {
layer
.paint
.get(slot as usize)
.and_then(DynamicEvaluated::uniform_float)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a float property")))
}
fn eval_paint_f32_constant_or(layer: &DynamicEvaluatedLayer, slot: u32, fallback: f32) -> PluginResult<f32> {
let prop = layer
.paint
.get(slot as usize)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} out of range")))?;
if prop.as_float().is_none() {
return Err(PluginError::invalid_argument(format!("paint slot {slot} is not a float property")));
}
Ok(prop.constant_or_float(fallback))
}
fn eval_paint_bool(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<bool> {
layer
.paint
.get(slot as usize)
.and_then(DynamicEvaluated::uniform_bool)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a bool property")))
}
fn eval_paint_color(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<PluginColor> {
layer
.paint
.get(slot as usize)
.and_then(DynamicEvaluated::uniform_color)
.map(from_color)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a color property")))
}
fn eval_paint_color_constant_or(
layer: &DynamicEvaluatedLayer,
slot: u32,
fallback: PluginColor,
) -> PluginResult<PluginColor> {
let prop = layer
.paint
.get(slot as usize)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} out of range")))?;
if prop.as_color().is_none() {
return Err(PluginError::invalid_argument(format!("paint slot {slot} is not a color property")));
}
Ok(from_color(prop.constant_or_color(to_color(fallback))))
}
fn eval_paint_vec2(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<PluginVec2> {
let [x, y] = layer
.paint
.get(slot as usize)
.and_then(DynamicEvaluated::uniform_vec2)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a vec2 property")))?;
Ok(PluginVec2::new(x, y))
}
fn eval_paint_lat_lng(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<PluginLatLng> {
layer
.paint
.get(slot as usize)
.and_then(DynamicEvaluated::uniform_lat_lng)
.map(from_lat_lng)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a lat_lng property")))
}
fn eval_paint_rotation_degrees(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<f32> {
layer
.paint
.get(slot as usize)
.and_then(DynamicEvaluated::uniform_rotation)
.map(|r| r.angle() as f32)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a rotation property")))
}
fn eval_paint_str(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<&str> {
layer
.paint
.get(slot as usize)
.and_then(|v| v.uniform_str())
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a string/enum property")))
}
fn eval_paint_enum(layer: &DynamicEvaluatedLayer, slot: u32) -> PluginResult<u32> {
let idx = slot as usize;
let desc = layer
.style
.dynamic_type()
.paint_property(idx)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} out of range")))?;
let DynamicDefault::Enum { variants, default } = &desc.default else {
return Err(PluginError::invalid_argument(format!("paint slot {slot} is not an enum property")));
};
layer
.paint
.get(idx)
.and_then(|v| v.enum_index(variants, *default))
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not an enum property")))
}
struct EngineArcEvaluatedLayer {
inner: Arc<DynamicEvaluatedLayer>,
}
impl EvaluatedLayerBackend for EngineArcEvaluatedLayer {
fn id(&self) -> &str {
&self.inner.style.id
}
fn paint_is_constant(&self, slot: u32) -> bool {
eval_paint_is_constant(&self.inner, slot)
}
fn paint_f32(&self, slot: u32) -> PluginResult<f32> {
eval_paint_f32(&self.inner, slot)
}
fn paint_f32_constant_or(&self, slot: u32, fallback: f32) -> PluginResult<f32> {
eval_paint_f32_constant_or(&self.inner, slot, fallback)
}
fn paint_bool(&self, slot: u32) -> PluginResult<bool> {
eval_paint_bool(&self.inner, slot)
}
fn paint_color(&self, slot: u32) -> PluginResult<PluginColor> {
eval_paint_color(&self.inner, slot)
}
fn paint_color_constant_or(&self, slot: u32, fallback: PluginColor) -> PluginResult<PluginColor> {
eval_paint_color_constant_or(&self.inner, slot, fallback)
}
fn paint_vec2(&self, slot: u32) -> PluginResult<PluginVec2> {
eval_paint_vec2(&self.inner, slot)
}
fn paint_lat_lng(&self, slot: u32) -> PluginResult<PluginLatLng> {
eval_paint_lat_lng(&self.inner, slot)
}
fn paint_rotation_degrees(&self, slot: u32) -> PluginResult<f32> {
eval_paint_rotation_degrees(&self.inner, slot)
}
fn paint_str(&self, slot: u32) -> PluginResult<&str> {
eval_paint_str(&self.inner, slot)
}
fn paint_enum(&self, slot: u32) -> PluginResult<u32> {
eval_paint_enum(&self.inner, slot)
}
fn as_any(&self) -> Option<&dyn Any> {
Some(self)
}
}
struct EngineRefEvaluatedLayer<'a> {
inner: &'a DynamicEvaluatedLayer,
}
impl EvaluatedLayerBackend for EngineRefEvaluatedLayer<'_> {
fn id(&self) -> &str {
&self.inner.style.id
}
fn paint_is_constant(&self, slot: u32) -> bool {
eval_paint_is_constant(self.inner, slot)
}
fn paint_f32(&self, slot: u32) -> PluginResult<f32> {
eval_paint_f32(self.inner, slot)
}
fn paint_f32_constant_or(&self, slot: u32, fallback: f32) -> PluginResult<f32> {
eval_paint_f32_constant_or(self.inner, slot, fallback)
}
fn paint_bool(&self, slot: u32) -> PluginResult<bool> {
eval_paint_bool(self.inner, slot)
}
fn paint_color(&self, slot: u32) -> PluginResult<PluginColor> {
eval_paint_color(self.inner, slot)
}
fn paint_color_constant_or(&self, slot: u32, fallback: PluginColor) -> PluginResult<PluginColor> {
eval_paint_color_constant_or(self.inner, slot, fallback)
}
fn paint_vec2(&self, slot: u32) -> PluginResult<PluginVec2> {
eval_paint_vec2(self.inner, slot)
}
fn paint_lat_lng(&self, slot: u32) -> PluginResult<PluginLatLng> {
eval_paint_lat_lng(self.inner, slot)
}
fn paint_rotation_degrees(&self, slot: u32) -> PluginResult<f32> {
eval_paint_rotation_degrees(self.inner, slot)
}
fn paint_str(&self, slot: u32) -> PluginResult<&str> {
eval_paint_str(self.inner, slot)
}
fn paint_enum(&self, slot: u32) -> PluginResult<u32> {
eval_paint_enum(self.inner, slot)
}
}
struct EngineEvaluateCx<'a> {
evaluated: EngineRefEvaluatedLayer<'a>,
time_point: Option<Instant>,
}
impl EvaluateCxBackend for EngineEvaluateCx<'_> {
fn evaluated(&self) -> EvaluatedLayer<'_> {
EvaluatedLayer::from_backend(&self.evaluated)
}
fn time_point_ns(&self) -> Option<i64> {
self.time_point.map(instant_to_ns)
}
}
struct EngineView<'a> {
inner: &'a View,
}
impl ViewBackend for EngineView<'_> {
fn info(&self) -> ViewInfo {
let v = self.inner;
let size = v.size();
ViewInfo {
width: size.width,
height: size.height,
zoom: v.zoom(),
integer_zoom: v.integer_zoom(),
angle_rad: v.angle(),
pitch_rad: v.pitch(),
camera_to_center_distance: v.camera_to_center_distance(),
is_globe: v.is_globe(),
world_wraps: v.world().wraps(),
}
}
fn world_from_lat_lng(&self, lat_lng: PluginLatLng) -> PluginResult<(f64, f64)> {
let ll = to_lat_lng(lat_lng)?;
let p = self.inner.world().world_from_lat_lng(&ll);
Ok((p.x, p.y))
}
fn lat_lng_near_center(&self, lat_lng: PluginLatLng) -> PluginResult<PluginLatLng> {
let ll = to_lat_lng(lat_lng)?;
Ok(from_lat_lng(self.inner.lat_lng_near_center(&ll)))
}
fn ground_meters_per_world_unit_at(&self, lat_lng: PluginLatLng) -> f64 {
let Ok(ll) = to_lat_lng(lat_lng) else {
return 0.0;
};
self.inner.ground_meters_per_world_unit_at(&ll)
}
fn world_copies(&self) -> PluginResult<Vec<i16>> {
let parameters = TileCoverParameters {
view: self.inner.clone(),
tile_lod_min_radius: 3.0,
tile_lod_scale: 1.0,
tile_lod_pitch_threshold: std::f64::consts::FRAC_PI_3,
tile_lod_mode: TileLodMode::Default,
requested_zoom: None,
round_zoom: false,
max_content_elevation: 0.0,
content_overflows: false,
};
Ok(tile_cover(¶meters, 0, Range::new(0, 0), None).iter().map(|t| t.wrap).collect())
}
fn project_tile_point(&self, tile_id: TileId, x: f64, y: f64, elevation_m: f64) -> PluginResult<ProjectedPoint> {
let tile = unwrapped_tile_id(tile_id)?;
let projected = TileProjector::new(self.inner, &tile).project_as_drawn(&Point::new(x, y), elevation_m);
Ok(ProjectedPoint {
clip_x: projected.point.x,
clip_y: projected.point.y,
signed_distance_from_camera: projected.signed_distance_from_camera,
occluded: projected.occluded,
})
}
fn map_aligned_scale_at(&self, tile_id: TileId, x: f64, y: f64) -> f64 {
let Ok(tile) = unwrapped_tile_id(tile_id) else {
return 1.0;
};
TileProjector::new(self.inner, &tile).map_aligned_scale_at(&Point::new(x, y))
}
fn globe_extrude_scale(&self, tile_id: TileId) -> f32 {
let Ok(tile) = unwrapped_tile_id(tile_id) else {
return 0.0;
};
globe_extrude_scale(self.inner, &tile)
}
fn tile_unit_translation(
&self,
tile_id: TileId,
translate: PluginVec2,
anchor: Alignment,
) -> PluginResult<PluginVec2> {
let tile = unwrapped_tile_id(tile_id)?;
let [tx, ty] = RenderTile::tile_unit_translation(
&tile,
[translate.x, translate.y],
to_translate_anchor(anchor),
self.inner,
);
Ok(PluginVec2::new(tx, ty))
}
}
pub(crate) fn with_view<R>(view: &View, f: impl FnOnce(PluginView<'_>) -> R) -> R {
let backend = EngineView { inner: view };
f(PluginView::from_backend(&backend))
}
struct EngineFrame<'a, 'f> {
inner: &'a LayerFrame<'f>,
view: EngineView<'f>,
}
impl<'a, 'f> EngineFrame<'a, 'f> {
fn new(inner: &'a LayerFrame<'f>) -> Self {
Self { inner, view: EngineView { inner: inner.view } }
}
}
impl FrameBackend for EngineFrame<'_, '_> {
fn info(&self) -> FrameInfo {
let f = self.inner;
let size = f.size();
FrameInfo {
width: size.width,
height: size.height,
pixel_ratio: f.pixel_ratio(),
pixel_scale: f.pixel_scale(),
pixels_to_gl_units: f.pixels_to_gl_units,
camera_moving: f.camera_moving,
terrain: f.terrain,
composites_with_frame_depth: f.composites_with_frame_depth,
drape_lit: f.drape_lit(),
has_ground: f.ground.is_some(),
time_point_ns: f.time_point().map(instant_to_ns),
}
}
fn view(&self) -> PluginView<'_> {
PluginView::from_backend(&self.view)
}
fn tile_projection(&self, tile_id: TileId, transform: PluginTileTransform) -> PluginResult<ProjectionUbo> {
let tile = unwrapped_tile_id(tile_id)?;
let tf = TileTransform {
translate: transform.translate,
anchor: to_translate_anchor(transform.translate_anchor),
near_clipped: transform.near_clipped,
pixel_aligned: transform.pixel_aligned,
};
Ok(from_projection_ubo(tile_projection(&tile, self.inner, tf).ubo()))
}
fn ground_height(&self, tile_id: TileId, x: f32, y: f32) -> f32 {
let Some(ground) = self.inner.ground.as_deref() else {
return 0.0;
};
let Ok(tile) = unwrapped_tile_id(tile_id) else {
return 0.0;
};
ground.tile(tile).height(GlamVec2::new(x, y))
}
fn ground_depth_texture(&self) -> Option<PluginTexture> {
let tex = self.inner.ground.as_deref().and_then(|g| g.depth()).cloned()?;
Some(PluginTexture::from_handle(Box::new(EngineTexture { inner: tex })))
}
fn collision_shape_count(&self) -> usize {
self.inner.collision_shapes.len()
}
fn collision_shape(&self, index: usize) -> Option<CollisionShape> {
self.inner.collision_shapes.get(index).map(|&tested| from_tested_shape(tested))
}
fn ground_token(&self) -> Option<Box<dyn Any>> {
self.inner.ground.clone().map(|g| -> Box<dyn Any> { Box::new(g) })
}
}
fn from_tested_shape(tested: TestedShape) -> CollisionShape {
let kind = match tested.shape {
Shape::Box(aabb) => CollisionShapeKind::Box {
min: PluginVec2::new(aabb.min.x, aabb.min.y),
max: PluginVec2::new(aabb.max.x, aabb.max.y),
},
Shape::Circle { center, radius } => {
CollisionShapeKind::Circle { center: PluginVec2::new(center.x, center.y), radius }
}
};
CollisionShape { kind, placed: tested.placed }
}
struct EngineTileGeometry<'a> {
inner: &'a DynamicBucket,
}
impl TileGeometryBackend for EngineTileGeometry<'_> {
fn vertex_stream_count(&self) -> usize {
self.inner.vertices.len()
}
fn vertex_count(&self, stream_index: usize) -> usize {
self.inner.vertices.get(stream_index).map_or(0, |s| s.vertex_count)
}
fn vertex_stride(&self, stream_index: usize) -> u32 {
self.inner.vertices.get(stream_index).map_or(0, |s| s.stride)
}
fn index_stream_count(&self) -> usize {
self.inner.indexes.len()
}
fn index_count(&self, stream_index: usize) -> usize {
self.inner.indexes.get(stream_index).map_or(0, crate::layer::bucket_geometry::GeometryVec::len)
}
fn draw_ranges(&self) -> Cow<'_, [PluginDrawRange]> {
Cow::Owned(self.inner.ranges.iter().copied().map(from_draw_range).collect())
}
fn metadata(&self) -> &[u8] {
&self.inner.metadata
}
fn max_elevation(&self) -> f32 {
self.inner.max_elevation
}
fn binder_interpolation_factor(&self, layer_id: &str, paint_slot: u32, zoom: f32) -> f32 {
let Ok(slot) = u16::try_from(paint_slot) else {
return 0.0;
};
self.inner.binders.get(layer_id).map_or(0.0, |b| b.interpolation_factor(slot, zoom))
}
fn binder_statistics_max_f32(&self, layer_id: &str, paint_slot: u32) -> Option<f32> {
let slot = u16::try_from(paint_slot).ok()?;
let binder = self.inner.binders.get(layer_id)?;
binder.statistics_max_f32(slot)
}
}
struct EngineTile<'a> {
inner: DynamicFrameTile<'a>,
bucket: Option<EngineTileGeometry<'a>>,
}
impl<'a> EngineTile<'a> {
fn new(inner: DynamicFrameTile<'a>) -> Self {
let bucket = match inner.data() {
DynamicTileData::Geometry { bucket, .. } => Some(EngineTileGeometry { inner: bucket }),
_ => None,
};
Self { inner, bucket }
}
}
impl TileBackend for EngineTile<'_> {
fn id(&self) -> TileId {
from_overscaled_tile_id(self.inner.id())
}
fn draw_id(&self) -> TileId {
from_overscaled_tile_id(self.inner.draw_id())
}
fn render_passes(&self) -> RenderPasses {
from_render_pass(self.inner.render_passes())
}
fn has_data_for_pass(&self, pass: RenderPasses) -> bool {
self.inner.has_data_for_pass(to_render_pass(pass))
}
fn geometry(&self) -> Option<TileGeometry<'_>> {
self.bucket.as_ref().map(|b| TileGeometry::from_backend(b))
}
fn geometry_vertices(&self, stream_index: usize) -> Option<PluginVertexBuffer> {
let DynamicTileData::Geometry { bucket, geometry, .. } = self.inner.data() else {
return None;
};
let stream = bucket.vertices.get(stream_index)?;
let buf = bucket_vertices(geometry, &stream.bytes)?;
Some(PluginVertexBuffer::from_handle(Box::new(EngineVertexBuffer { inner: buf })))
}
fn geometry_indexes(&self, stream_index: usize) -> Option<PluginIndexBuffer> {
let DynamicTileData::Geometry { bucket, geometry, .. } = self.inner.data() else {
return None;
};
let indexes = bucket.indexes.get(stream_index)?;
let buf = bucket_indexes(geometry, indexes)?;
Some(PluginIndexBuffer::from_handle(Box::new(EngineIndexBuffer { inner: buf })))
}
fn paint_attributes(
&self,
res: &mut PluginResources<'_>,
evaluated: EvaluatedLayer<'_>,
) -> Option<PluginPaintAttributes> {
let DynamicTileData::Geometry { bucket, geometry, .. } = self.inner.data() else {
return None;
};
let eval = evaluated.backend().as_any()?.downcast_ref::<EngineArcEvaluatedLayer>()?;
let binders = bucket.binders.get(&eval.inner.style.id)?;
let vertices = if binders.depends_on_feature_state() {
let data = binders.interleaved_vertex_buffer.shared_vertex_vector.data();
let stride = u32::try_from(binders.interleaved_vertex_buffer.stride).unwrap_or(0);
if stride == 0 {
None
} else {
let vb = res.create_vertices(&data, binders.interleaved_vertex_buffer.vertex_count, stride).ok()?;
downcast_vertex_buffer(&vb).ok().cloned()
}
} else {
bucket_vertices(geometry, &binders.interleaved_vertex_buffer.shared_vertex_vector)
};
let paint = binders.paint(eval.inner.style.dynamic_type(), &eval.inner.paint, vertices.as_ref());
Some(PluginPaintAttributes::from_handle(Box::new(EnginePaintAttributes { inner: paint })))
}
fn raster_info(&self) -> Option<RasterTileInfo<'_>> {
let DynamicTileData::Raster(raster) = self.inner.data() else {
return None;
};
let img = raster.image();
let image_id = {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
raster.id().hash(&mut h);
h.finish()
};
Some(RasterTileInfo { image_id, width: img.size.width, height: img.size.height, pixels: &img.data })
}
}
struct EngineUpdateCxRo<'t> {
evaluated: EngineArcEvaluatedLayer,
source_max_zoom: Option<u8>,
tiles: Vec<EngineTile<'t>>,
}
impl UpdateCxReadBackend for EngineUpdateCxRo<'_> {
fn evaluated(&self) -> EvaluatedLayer<'_> {
EvaluatedLayer::from_backend(&self.evaluated)
}
fn source_max_zoom(&self) -> Option<u8> {
self.source_max_zoom
}
fn tile_count(&self) -> usize {
self.tiles.len()
}
fn tile(&self, index: usize) -> Option<Tile<'_>> {
self.tiles.get(index).map(|t| Tile::from_backend(t))
}
}
struct EngineUpdateCxRw<'r, 'a, 'p> {
cx: &'r mut DynamicUpdateCx<'a, 'p>,
}
impl UpdateCxMutBackend for EngineUpdateCxRw<'_, '_, '_> {
fn pick_tiles(&mut self, tiles: &[TileId]) -> PluginResult<()> {
let parsed: PluginResult<Vec<OverscaledTileID>> = tiles.iter().copied().map(overscaled_tile_id).collect();
self.cx.pick_tiles(parsed?);
Ok(())
}
}
struct EngineResources<'r, 'a> {
inner: &'r mut Resources<'a>,
}
impl ResourcesBackend for EngineResources<'_, '_> {
fn create_program(&mut self, desc: &mln_plugin::ProgramDesc<'_>) -> PluginResult<mln_plugin::Program> {
create_program(desc)
}
fn create_ground_heights(&mut self) -> PluginResult<PluginGroundHeights> {
Ok(PluginGroundHeights::from_handle(Box::new(EngineGroundHeights { inner: GroundHeights::default() })))
}
fn create_vertices(&mut self, bytes: &[u8], vertex_count: usize, stride: u32) -> PluginResult<PluginVertexBuffer> {
if stride == 0 {
return Err(PluginError::invalid_argument("stride must not be zero"));
}
let expected = vertex_count
.checked_mul(stride as usize)
.ok_or_else(|| PluginError::invalid_argument("vertex_count * stride overflow"))?;
if bytes.len() != expected {
return Err(PluginError::invalid_argument(format!(
"vertex bytes length {} does not match vertex_count ({vertex_count}) * stride ({stride})",
bytes.len()
)));
}
let buf = self.inner.vertices(bytes);
Ok(PluginVertexBuffer::from_handle(Box::new(EngineVertexBuffer { inner: buf })))
}
fn create_dynamic_vertices(
&mut self,
bytes: &[u8],
vertex_count: usize,
stride: u32,
) -> PluginResult<PluginVertexBuffer> {
if stride == 0 {
return Err(PluginError::invalid_argument("stride must not be zero"));
}
let expected = vertex_count
.checked_mul(stride as usize)
.ok_or_else(|| PluginError::invalid_argument("vertex_count * stride overflow"))?;
if bytes.len() != expected {
return Err(PluginError::invalid_argument(format!(
"vertex bytes length {} does not match vertex_count ({vertex_count}) * stride ({stride})",
bytes.len()
)));
}
let buf = self.inner.dynamic_vertices(bytes);
Ok(PluginVertexBuffer::from_handle(Box::new(EngineVertexBuffer { inner: buf })))
}
fn update_vertices(&mut self, buffer: &PluginVertexBuffer, bytes: &[u8]) -> bool {
let Ok(vb) = downcast_vertex_buffer(buffer) else {
return false;
};
self.inner.update_vertices(vb, bytes)
}
fn create_indexes(&mut self, indexes: &[u16]) -> PluginResult<PluginIndexBuffer> {
let buf = self.inner.indexes(indexes);
Ok(PluginIndexBuffer::from_handle(Box::new(EngineIndexBuffer { inner: buf })))
}
fn quad_indexes(&mut self) -> PluginResult<PluginIndexBuffer> {
let buf = self.inner.quad_indexes();
Ok(PluginIndexBuffer::from_handle(Box::new(EngineIndexBuffer { inner: buf })))
}
fn create_texture(&mut self, format: TextureFormat, sampler: SamplerState) -> PluginResult<PluginTexture> {
let tex = self.inner.texture(to_texture_format(format), to_sampler(sampler));
Ok(PluginTexture::from_handle(Box::new(EngineTexture { inner: tex })))
}
fn write_texture(&mut self, texture: &PluginTexture, data: &[u8], width: u32, height: u32) -> PluginResult<()> {
let tex = downcast_texture(texture)?;
self.inner
.write_texture(tex, data, Size::new(width, height))
.map_err(|e| PluginError::native(format!("write_texture failed: {e}")))
}
fn create_target(
&mut self,
width: u32,
height: u32,
channel_type: TextureChannelType,
clear_color: PluginColor,
) -> PluginResult<PluginTarget> {
let clear = Rgba::new(clear_color.r, clear_color.g, clear_color.b, clear_color.a);
let target = self.inner.target(Size::new(width, height), to_channel_type(channel_type), clear);
Ok(PluginTarget::from_handle(Box::new(EngineTarget { inner: target })))
}
fn create_mesh(&mut self, desc: &PluginMeshDesc<'_>) -> PluginResult<PluginMesh> {
let program = downcast_program(desc.program)?;
let variant = to_projection_variant(desc.projection_variant);
let color_mode = to_color_mode(desc.color_mode);
let cull_face_mode = to_cull_face_mode(desc.cull_face_mode);
let mode = to_draw_mode(desc.draw_mode);
let indexes = downcast_index_buffer(desc.indexes)?.clone();
let mut vertices = Vec::with_capacity(desc.vertex_bindings.len() + 1);
for binding in desc.vertex_bindings {
vertices.push(convert_vertex_binding(program, binding)?);
}
let instances = if desc.instance_bindings.is_empty() {
None
} else {
let mut inst = Vec::with_capacity(desc.instance_bindings.len());
for binding in desc.instance_bindings {
inst.push(convert_vertex_binding(program, binding)?);
}
Some(inst)
};
let mut uniforms = Uniforms::default();
if let Some(paint) = desc.paint_attributes {
let paint = downcast_paint_attributes(paint)?;
uniforms = paint.uniforms;
if let Some(ref paint_binding) = paint.vertices {
vertices.push(paint_binding.clone());
}
}
let mut shader = self.inner.shader_key(program, uniforms, variant);
for &define in desc.extra_defines {
if !define.is_empty() {
shader = shader.with_define(define);
}
}
let ranges: Vec<DrawRange> = desc.ranges.iter().copied().map(to_draw_range).collect();
if desc.textures.len() > MAX_TEXTURES {
return Err(PluginError::invalid_argument(format!(
"mesh_desc.textures length ({}) exceeds maximum ({MAX_TEXTURES})",
desc.textures.len()
)));
}
let mut textures = Textures::default();
for (slot, tex_opt) in desc.textures.iter().enumerate() {
if let Some(tex) = tex_opt {
textures[slot] = Some(downcast_texture(tex)?.clone());
}
}
let mesh = self.inner.mesh(MeshDesc {
shader,
color_mode,
cull_face_mode,
mode,
vertices,
vertex_count: desc.vertex_count,
instances,
indexes,
ranges,
textures,
});
Ok(PluginMesh::from_handle(Box::new(EngineMesh { inner: mesh })))
}
fn mesh_set_texture(&mut self, mesh: &PluginMesh, slot: u32, texture: Option<&PluginTexture>) -> PluginResult<()> {
let slot = slot as usize;
if slot >= MAX_TEXTURES {
return Err(PluginError::invalid_argument(format!("texture slot {slot} exceeds maximum ({MAX_TEXTURES})")));
}
let mesh = downcast_mesh(mesh)?;
let tex = texture.map(downcast_texture).transpose()?;
mesh.set_texture(self.inner, slot, tex);
Ok(())
}
fn mesh_set_sampler(&mut self, mesh: &PluginMesh, slot: u32, sampler: SamplerState) -> PluginResult<()> {
let slot = slot as usize;
if slot >= MAX_TEXTURES {
return Err(PluginError::invalid_argument(format!("texture slot {slot} exceeds maximum ({MAX_TEXTURES})")));
}
let mesh = downcast_mesh(mesh)?;
mesh.set_sampler(self.inner, slot, Some(to_sampler(sampler)));
Ok(())
}
fn mesh_set_paint(&mut self, mesh: &PluginMesh, paint: &PluginPaintAttributes) -> PluginResult<()> {
let mesh = downcast_mesh(mesh)?;
let paint = downcast_paint_attributes(paint)?;
if let Some(ref binding) = paint.vertices {
mesh.set_paint(self.inner, binding);
}
Ok(())
}
fn mesh_bind_vertices(&mut self, mesh: &PluginMesh, binding: &PluginVertexBinding<'_>) -> PluginResult<()> {
let mesh = downcast_mesh(mesh)?;
let converted = convert_vertex_binding(mesh.program(), binding)?;
mesh.bind_vertices(self.inner, &converted);
Ok(())
}
fn apply_ground_heights(
&mut self,
heights: &mut PluginGroundHeights,
mesh: &PluginMesh,
frame: PluginFrame<'_>,
tile_id: TileId,
attribute_name: &str,
centers: &[PointI16],
) -> PluginResult<()> {
let heights = downcast_ground_heights_mut(heights)?;
let mesh = downcast_mesh(mesh)?;
let static_attr = resolve_attribute_name(mesh.program(), attribute_name)?;
let tile = unwrapped_tile_id(tile_id)?;
let Some(token) = frame.backend().ground_token() else {
return Ok(());
};
let Some(ground) = token.downcast_ref::<Rc<FrameGround>>() else {
return Err(PluginError::invalid_argument("frame does not belong to the mln_engine host"));
};
if heights.are_of(ground) {
return Ok(());
}
let tile_ground = ground.tile(tile);
let sampled: Vec<f32> =
centers.iter().map(|c| tile_ground.height(GlamVec2::new(f32::from(c.x), f32::from(c.y)))).collect();
if let Some(vb) = heights.write(self.inner, ground, &sampled) {
let binding = height_binding(&vb, static_attr);
mesh.bind_vertices(self.inner, &binding);
}
Ok(())
}
}
struct EnginePrepareCxRo<'a, 't> {
tiles: Vec<EngineTile<'t>>,
picked: &'a [OverscaledTileID],
}
impl PrepareCxReadBackend for EnginePrepareCxRo<'_, '_> {
fn tile_count(&self) -> usize {
self.tiles.len()
}
fn tile(&self, index: usize) -> Option<Tile<'_>> {
self.tiles.get(index).map(|t| Tile::from_backend(t))
}
fn picked_tiles(&self) -> Vec<TileId> {
self.picked.iter().copied().map(from_overscaled_tile_id).collect()
}
}
struct EnginePrepareCxRw<'r, 'a> {
layer_id: &'r str,
tiles: &'r mut TileMap<Box<dyn Any>>,
res: EngineResources<'r, 'a>,
targets: Option<&'r mut SharedTargets>,
}
impl PrepareCxMutBackend for EnginePrepareCxRw<'_, '_> {
fn resources(&mut self) -> PluginResources<'_> {
PluginResources::from_backend(&mut self.res)
}
fn tile_resources_mut(&mut self, tile_id: TileId) -> Option<&mut dyn Any> {
let id = overscaled_tile_id(tile_id).ok()?;
self.tiles.get_mut(&id).map(Box::as_mut)
}
fn tile_resources_and_allocator(&mut self, tile_id: TileId) -> (Option<&mut dyn Any>, PluginResources<'_>) {
let tile = overscaled_tile_id(tile_id).ok().and_then(|id| self.tiles.get_mut(&id)).map(Box::as_mut);
(tile, PluginResources::from_backend(&mut self.res))
}
fn take_tile_changes(&mut self, tile_id: TileId) -> TileChanges {
let Ok(id) = overscaled_tile_id(tile_id) else {
return TileChanges::default();
};
let Some(mut entry) = self.tiles.entry(&id) else {
return TileChanges::default();
};
let c = entry.take_changes();
let mut bits = 0u32;
if c.paint {
bits |= TileChanges::PAINT;
}
if c.opacity {
bits |= TileChanges::OPACITY;
}
if c.dynamic {
bits |= TileChanges::DYNAMIC;
}
if c.sort {
bits |= TileChanges::SORT;
}
TileChanges::from_bits(bits)
}
fn read_shared_target(&mut self, name: &str) -> Option<PluginTexture> {
let tex = self.targets.as_deref_mut()?.read(self.layer_id, name)?;
Some(PluginTexture::from_handle(Box::new(EngineTexture { inner: tex })))
}
}
struct InvalidTargetGroup;
impl DrawGroupBackend for InvalidTargetGroup {
fn push(&mut self, _mesh: &PluginMesh, _options: DrawOptions, _blocks: &[&[u8]]) -> PluginResult<()> {
Err(PluginError::invalid_argument("target was not created by the mln_engine host"))
}
fn push_at(
&mut self,
_mesh: &PluginMesh,
_tile_id: TileId,
_projection: &ProjectionUbo,
_options: DrawOptions,
_blocks: &[&[u8]],
) -> PluginResult<()> {
Err(PluginError::invalid_argument("target was not created by the mln_engine host"))
}
fn set_block(&mut self, _program: &mln_plugin::Program, _buffer_name: &str, _bytes: &[u8]) -> PluginResult<()> {
Err(PluginError::invalid_argument("target was not created by the mln_engine host"))
}
fn set_composite(&mut self, _composite: PluginComposite) -> PluginResult<()> {
Err(PluginError::invalid_argument("target was not created by the mln_engine host"))
}
}
struct EngineDraws<'a> {
inner: &'a mut Draws,
invalid: InvalidTargetGroup,
}
impl DrawsBackend for EngineDraws<'_> {
fn main(&mut self) -> DrawGroup<'_> {
DrawGroup::from_backend(self.inner.main())
}
fn target(&mut self, target: &PluginTarget) -> DrawGroup<'_> {
match downcast_target(target) {
Ok(target) => DrawGroup::from_backend(self.inner.target(target)),
Err(_) => DrawGroup::from_backend(&mut self.invalid),
}
}
fn lend(&mut self, _at: PluginLendAt) -> PluginResult<()> {
Err(PluginError::new(Status::Unsupported, "raw GPU lending requires the C Plugin ABI host"))
}
}
impl DrawGroupBackend for Group {
fn push(&mut self, mesh: &PluginMesh, options: DrawOptions, blocks: &[&[u8]]) -> PluginResult<()> {
let mesh = downcast_mesh(mesh)?;
self.push_raw(mesh, to_draw_options(options), blocks)
.map(|_| ())
.map_err(|e| PluginError::invalid_argument(e.to_string()))
}
fn push_at(
&mut self,
mesh: &PluginMesh,
tile_id: TileId,
projection: &ProjectionUbo,
options: DrawOptions,
blocks: &[&[u8]],
) -> PluginResult<()> {
let mesh = downcast_mesh(mesh)?;
let tile = overscaled_tile_id(tile_id)?;
let ubo = to_projection_ubo(projection);
self.push_at_raw(mesh, tile, &ubo, to_draw_options(options), blocks)
.map(|_| ())
.map_err(|e| PluginError::invalid_argument(e.to_string()))
}
fn set_block(&mut self, program: &mln_plugin::Program, buffer_name: &str, bytes: &[u8]) -> PluginResult<()> {
let program = downcast_program(program)?;
let block = resolve_uniform_block(program, buffer_name)?;
self.block_raw(block, bytes).map(|_| ()).map_err(|e| PluginError::invalid_argument(e.to_string()))
}
fn set_composite(&mut self, composite: PluginComposite) -> PluginResult<()> {
let blend = to_layer_blend(composite.blend);
self.composite(Some(Composite { opacity: composite.opacity, blend, frame_depth: composite.frame_depth }));
Ok(())
}
}
struct LoadedFeature<'a> {
feature_index: usize,
feature: crate::tile::Feature<'a>,
geometry: GeometryCollection,
rings: Vec<Vec<PointI16>>,
}
struct EngineTileBuildCx<'r, 'a> {
tile: OverscaledTileID,
canonical: CanonicalTileID,
world: &'a WorldMapping,
zoom: f64,
params: PropertyEvaluationParameters,
mode: MapMode,
pixel_ratio: f32,
first_load: bool,
selected_features: &'a [usize],
source_layer: &'r TileLayer<'a>,
layers: Vec<EngineArcEvaluatedLayer>,
cx: &'r mut DynamicBuildCx<'a>,
current: Option<LoadedFeature<'r>>,
layout_text: String,
}
impl<'r, 'a> EngineTileBuildCx<'r, 'a> {
fn new(cx: &'r mut DynamicBuildCx<'a>, source_layer: &'r TileLayer<'a>) -> Self {
let tile = cx.tile();
let canonical = *cx.canonical();
let world = cx.world();
let zoom = cx.zoom();
let params = cx.parameters();
let mode = cx.mode();
let pixel_ratio = cx.pixel_ratio();
let first_load = cx.first_load();
let selected_features = cx.selected_features();
let layers = cx.layers().iter().map(|l| EngineArcEvaluatedLayer { inner: Arc::clone(l) }).collect();
Self {
tile,
canonical,
world,
zoom,
params,
mode,
pixel_ratio,
first_load,
selected_features,
source_layer,
layers,
cx,
current: None,
layout_text: String::new(),
}
}
fn eval_layout_value<T>(
&self,
layer_index: usize,
layout_slot: u32,
for_current_feature: bool,
extract: impl for<'p> FnOnce(&'p DynamicPropertyValue, &'p DynamicDefault) -> Option<(&'p PropertyValue<T>, T)>,
) -> PluginResult<T>
where
T: Clone + Default + std::fmt::Debug + ValueConverter + 'static,
{
let layer = self
.layers
.get(layer_index)
.ok_or_else(|| PluginError::not_found(format!("layer_index {layer_index} out of range")))?;
let slot = layout_slot as usize;
let style = &layer.inner.style;
let prop = style
.layout
.get(slot)
.ok_or_else(|| PluginError::invalid_argument(format!("layout slot {layout_slot} out of range")))?;
let desc = style
.dynamic_type()
.layout_property(slot)
.ok_or_else(|| PluginError::invalid_argument(format!("layout slot {layout_slot} out of range")))?;
let (pv, default) = extract(prop, &desc.default).ok_or_else(|| {
PluginError::invalid_argument(format!("layout slot {layout_slot} has mismatched property type"))
})?;
let evaluated = Evaluated::plain(pv, &self.params, default);
if let Some(val) = evaluated.constant() {
return Ok(val);
}
if for_current_feature {
let loaded = self
.current
.as_ref()
.ok_or_else(|| PluginError::invalid_state("no feature loaded; call load_feature first"))?;
let ctx = EvaluationContext::with_zoom_feature(self.zoom, Some(&loaded.feature))
.with_global_state(self.params.global_state.as_deref())
.with_canonical_tile_id(Some(&self.canonical))
.with_world(Some(self.world));
Ok(evaluated.evaluate(&ctx))
} else {
let ctx = EvaluationContext::new(self.zoom)
.with_global_state(self.params.global_state.as_deref())
.with_canonical_tile_id(Some(&self.canonical))
.with_world(Some(self.world));
Ok(evaluated.evaluate(&ctx))
}
}
}
impl TileBuildCxBackend for EngineTileBuildCx<'_, '_> {
fn tile_id(&self) -> TileId {
from_overscaled_tile_id(self.tile)
}
fn zoom(&self) -> f64 {
self.zoom
}
fn mode(&self) -> PluginMapMode {
from_map_mode(self.mode)
}
fn pixel_ratio(&self) -> f32 {
self.pixel_ratio
}
fn first_load(&self) -> bool {
self.first_load
}
fn layer_count(&self) -> usize {
self.layers.len()
}
fn layer(&self, index: usize) -> Option<EvaluatedLayer<'_>> {
self.layers.get(index).map(|l| EvaluatedLayer::from_backend(l))
}
fn eval_layout_f32(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> PluginResult<f32> {
self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
(DynamicPropertyValue::Float(pv), DynamicDefault::Float(d)) => Some((pv, *d)),
_ => None,
})
}
fn eval_layout_bool(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> PluginResult<bool> {
self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
(DynamicPropertyValue::Bool(pv), DynamicDefault::Bool(d)) => Some((pv, *d)),
_ => None,
})
}
fn eval_layout_color(
&self,
layer_index: usize,
layout_slot: u32,
for_current_feature: bool,
) -> PluginResult<PluginColor> {
self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
(DynamicPropertyValue::Color(pv), DynamicDefault::Color(d)) => Some((pv, *d)),
_ => None,
})
.map(from_color)
}
fn eval_layout_vec2(
&self,
layer_index: usize,
layout_slot: u32,
for_current_feature: bool,
) -> PluginResult<PluginVec2> {
self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
(DynamicPropertyValue::Vec2(pv), DynamicDefault::Vec2(d)) => Some((pv, *d)),
_ => None,
})
.map(|[x, y]| PluginVec2::new(x, y))
}
fn eval_layout_lat_lng(
&self,
layer_index: usize,
layout_slot: u32,
for_current_feature: bool,
) -> PluginResult<PluginLatLng> {
self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
(DynamicPropertyValue::LatLng(pv), DynamicDefault::LatLng(d)) => Some((pv, *d)),
_ => None,
})
.map(from_lat_lng)
}
fn eval_layout_rotation_degrees(
&self,
layer_index: usize,
layout_slot: u32,
for_current_feature: bool,
) -> PluginResult<f32> {
self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
(DynamicPropertyValue::Rotation(pv), DynamicDefault::Rotation(d)) => Some((pv, *d)),
_ => None,
})
.map(|r| r.angle() as f32)
}
fn eval_layout_str(
&mut self,
layer_index: usize,
layout_slot: u32,
for_current_feature: bool,
) -> PluginResult<&str> {
let val =
self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
(DynamicPropertyValue::String(pv), DynamicDefault::String(d)) => Some((pv, (*d).to_owned())),
_ => None,
})?;
self.layout_text = val;
Ok(self.layout_text.as_str())
}
fn eval_layout_enum(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> PluginResult<u32> {
let layer = self
.layers
.get(layer_index)
.ok_or_else(|| PluginError::not_found(format!("layer_index {layer_index} out of range")))?;
let slot = layout_slot as usize;
let desc = layer
.inner
.style
.dynamic_type()
.layout_property(slot)
.ok_or_else(|| PluginError::invalid_argument(format!("layout slot {layout_slot} out of range")))?;
let DynamicDefault::Enum { variants, default } = desc.default else {
return Err(PluginError::invalid_argument(format!("layout slot {layout_slot} is not an enum property")));
};
let val =
self.eval_layout_value(layer_index, layout_slot, for_current_feature, |prop, def| match (prop, def) {
(DynamicPropertyValue::Enum(pv), DynamicDefault::Enum { variants, default }) => {
let s = variants.get(*default as usize).copied().unwrap_or_default();
Some((pv, s.to_owned()))
}
_ => None,
})?;
Ok(variants.iter().position(|v| *v == val.as_str()).map_or(default, |i| i as u32))
}
fn feature_count(&self) -> usize {
self.selected_features.len()
}
fn load_feature(&mut self, selected_index: usize) -> PluginResult<LoadedFeatureInfo> {
let &feature_index = self
.selected_features
.get(selected_index)
.ok_or_else(|| PluginError::not_found("selected_index out of range"))?;
let feature = self
.source_layer
.feature(feature_index)
.map_err(|e| PluginError::native(format!("failed to decode feature {feature_index}: {e}")))?;
let feature_type = from_feature_type(feature.feature_type());
let geometry = feature
.geometry()
.map_err(|e| PluginError::native(format!("failed to decode feature {feature_index} geometry: {e}")))?
.into_owned();
let rings: Vec<Vec<PointI16>> =
geometry.iter().map(|ring| ring.iter().map(|p| PointI16::new(p.x, p.y)).collect()).collect();
let ring_count = rings.len();
self.current = Some(LoadedFeature { feature_index, feature, geometry, rings });
Ok(LoadedFeatureInfo { feature_index, feature_type, ring_count })
}
fn feature_ring(&self, ring_index: usize) -> Option<Cow<'_, [PointI16]>> {
self.current.as_ref()?.rings.get(ring_index).map(|r| Cow::Borrowed(r.as_slice()))
}
fn populate_binders(&mut self, vertex_count: usize) -> PluginResult<()> {
let loaded = self
.current
.as_ref()
.ok_or_else(|| PluginError::invalid_state("no feature loaded; call load_feature first"))?;
self.cx.populate_binders(loaded.feature_index, &loaded.feature, vertex_count);
Ok(())
}
fn index_current_feature(&mut self) -> PluginResult<()> {
let loaded = self
.current
.as_ref()
.ok_or_else(|| PluginError::invalid_state("no feature loaded; call load_feature first"))?;
self.cx.index_feature(loaded.feature_index, &loaded.geometry);
Ok(())
}
}
struct EngineTileGeometryBuilder {
bucket: DynamicBucket,
}
impl EngineTileGeometryBuilder {
fn new() -> Self {
Self { bucket: DynamicBucket::default() }
}
}
impl TileGeometryBuilderBackend for EngineTileGeometryBuilder {
fn add_vertices(&mut self, bytes: &[u8], vertex_count: usize, stride: u32) -> PluginResult<usize> {
if stride == 0 {
return Err(PluginError::invalid_argument("stride must not be zero"));
}
let expected = vertex_count
.checked_mul(stride as usize)
.ok_or_else(|| PluginError::invalid_argument("vertex_count * stride overflow"))?;
if bytes.len() != expected {
return Err(PluginError::invalid_argument(format!(
"vertex bytes length {} does not match vertex_count ({vertex_count}) * stride ({stride})",
bytes.len()
)));
}
Ok(self.bucket.add_vertices(bytes.to_vec(), vertex_count, stride))
}
fn add_indexes(&mut self, indexes: &[u16]) -> PluginResult<usize> {
Ok(self.bucket.add_indexes(indexes.to_vec()))
}
fn add_draw_range(&mut self, range: PluginDrawRange) -> PluginResult<()> {
self.bucket.ranges.push(to_draw_range(range));
Ok(())
}
fn set_metadata(&mut self, bytes: &[u8]) -> PluginResult<()> {
self.bucket.metadata = bytes.to_vec();
Ok(())
}
fn set_max_elevation(&mut self, max_elevation: f32) -> PluginResult<()> {
self.bucket.max_elevation = max_elevation;
Ok(())
}
}
struct EngineHitCx<'a> {
evaluated: EngineArcEvaluatedLayer,
view: EngineView<'a>,
region: &'a QueryRegion<'a>,
feature: &'a dyn GeometryTileFeature,
feature_state: &'a FeatureState,
query_geometry: Vec<PointI16>,
screen_geometry: Vec<ScreenPoint>,
feature_rings: Vec<Vec<PointI16>>,
}
impl<'a> EngineHitCx<'a> {
fn new(
values: &'a DynamicLayerValues,
region: &'a QueryRegion<'a>,
feature: &'a dyn GeometryTileFeature,
geometry: &'a GeometryCollection,
feature_state: &'a FeatureState,
) -> Self {
let query_geometry = region.geometry.iter().map(|p| PointI16::new(p.x, p.y)).collect();
let screen_geometry = region.screen.iter().map(|p| ScreenPoint { x: p.x, y: p.y }).collect();
let feature_rings =
geometry.iter().map(|ring| ring.iter().map(|p| PointI16::new(p.x, p.y)).collect()).collect();
Self {
evaluated: EngineArcEvaluatedLayer { inner: Arc::clone(&values.evaluated) },
view: EngineView { inner: region.view },
region,
feature,
feature_state,
query_geometry,
screen_geometry,
feature_rings,
}
}
fn eval_context(&self) -> EvaluationContext<'_> {
EvaluationContext::with_zoom_feature_state(
self.region.view.zoom(),
Some(self.feature),
Some(self.feature_state),
)
}
}
impl HitCxBackend for EngineHitCx<'_> {
fn info(&self) -> HitInfo<'_> {
HitInfo {
tile_id: from_unwrapped_tile_id(*self.region.projector.tile_id()),
pixels_to_tile_units: self.region.pixels_to_tile_units,
has_ground: self.region.ground.is_some(),
query_geometry: Cow::Borrowed(&self.query_geometry),
screen_geometry: Cow::Borrowed(&self.screen_geometry),
feature_ring_count: self.feature_rings.len(),
}
}
fn evaluated(&self) -> EvaluatedLayer<'_> {
EvaluatedLayer::from_backend(&self.evaluated)
}
fn view(&self) -> PluginView<'_> {
PluginView::from_backend(&self.view)
}
fn feature_ring(&self, index: usize) -> Option<Cow<'_, [PointI16]>> {
self.feature_rings.get(index).map(|r| Cow::Borrowed(r.as_slice()))
}
fn eval_paint_f32(&self, slot: u32) -> PluginResult<f32> {
let eval_cx = self.eval_context();
self.evaluated
.inner
.paint
.get(slot as usize)
.and_then(|v| v.evaluate_float(&eval_cx))
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a float property")))
}
fn eval_paint_bool(&self, slot: u32) -> PluginResult<bool> {
let eval_cx = self.eval_context();
self.evaluated
.inner
.paint
.get(slot as usize)
.and_then(|v| v.evaluate_bool(&eval_cx))
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a bool property")))
}
fn eval_paint_color(&self, slot: u32) -> PluginResult<PluginColor> {
let eval_cx = self.eval_context();
self.evaluated
.inner
.paint
.get(slot as usize)
.and_then(|v| v.evaluate_color(&eval_cx))
.map(from_color)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a color property")))
}
fn eval_paint_vec2(&self, slot: u32) -> PluginResult<PluginVec2> {
let eval_cx = self.eval_context();
let [x, y] = self
.evaluated
.inner
.paint
.get(slot as usize)
.and_then(|v| v.evaluate_vec2(&eval_cx))
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a vec2 property")))?;
Ok(PluginVec2::new(x, y))
}
fn eval_paint_enum(&self, slot: u32) -> PluginResult<u32> {
let idx = slot as usize;
let desc = self
.evaluated
.inner
.style
.dynamic_type()
.paint_property(idx)
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} out of range")))?;
let DynamicDefault::Enum { variants, default } = &desc.default else {
return Err(PluginError::invalid_argument(format!("paint slot {slot} is not an enum property")));
};
let eval_cx = self.eval_context();
self.evaluated
.inner
.paint
.get(idx)
.and_then(|v| v.evaluate_enum_index(&eval_cx, variants, *default))
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not an enum property")))
}
fn eval_paint_string(&self, slot: u32) -> PluginResult<String> {
let eval_cx = self.eval_context();
self.evaluated
.inner
.paint
.get(slot as usize)
.and_then(|v| v.evaluate_string(&eval_cx))
.ok_or_else(|| PluginError::invalid_argument(format!("paint slot {slot} is not a string/enum property")))
}
fn ground_height(&self, point: PointI16) -> f64 {
self.region.ground_height(GeometryCoordinate::new(point.x, point.y))
}
fn translated_query_geometry(&self, translate: PluginVec2, anchor: Alignment) -> PluginResult<Vec<PointI16>> {
let bearing = self.region.view.angle() as f32;
let translated = translate_query_geometry(
self.region.geometry,
[translate.x, translate.y],
to_translate_anchor(anchor),
bearing,
self.region.pixels_to_tile_units,
);
let src = translated.as_deref().unwrap_or(self.region.geometry);
Ok(src.iter().map(|p| PointI16::new(p.x, p.y)).collect())
}
fn plane_geometry(
&self,
elevation_m: f64,
translate: PluginVec2,
anchor: Alignment,
) -> PluginResult<Vec<PointI16>> {
let plane = self.region.plane_geometry(elevation_m, [translate.x, translate.y], to_translate_anchor(anchor));
Ok(plane.iter().map(|p| PointI16::new(p.x, p.y)).collect())
}
fn viewport_point(&self, x: f64, y: f64, elevation_m: f64) -> Option<PluginVec2> {
let p = self.region.viewport_point(Point::new(x, y), elevation_m);
Some(PluginVec2::new(p.x, p.y))
}
fn map_aligned_scale_at(&self, x: f64, y: f64) -> f64 {
self.region.projector.map_aligned_scale_at(&Point::new(x, y))
}
fn pitch_scaled_size(
&self,
size: f32,
point: PointI16,
elevation_m: f64,
pitch_scale: Alignment,
pitch_alignment: Alignment,
) -> f32 {
self.region.pitch_scaled_size(
size,
GeometryCoordinate::new(point.x, point.y),
elevation_m,
to_pitch_scale_type(pitch_scale),
to_alignment_type(pitch_alignment),
)
}
fn shows(&self, x: f64, y: f64, elevation_m: f64) -> bool {
self.region.shows(Point::new(x, y), elevation_m)
}
}
struct EngineFrameQueryCxRo<'a> {
evaluated: EngineArcEvaluatedLayer,
view: EngineView<'a>,
query: &'a DynamicFrameQuery<'a>,
screen_geometry: Vec<ScreenPoint>,
}
impl<'a> EngineFrameQueryCxRo<'a> {
fn new(query: &'a DynamicFrameQuery<'a>) -> Self {
let screen_geometry = query.geometry().iter().map(|p| ScreenPoint { x: p.x, y: p.y }).collect();
Self {
evaluated: EngineArcEvaluatedLayer { inner: Arc::clone(&query.values().evaluated) },
view: EngineView { inner: query.view() },
query,
screen_geometry,
}
}
}
impl FrameQueryCxReadBackend for EngineFrameQueryCxRo<'_> {
fn evaluated(&self) -> EvaluatedLayer<'_> {
EvaluatedLayer::from_backend(&self.evaluated)
}
fn view(&self) -> PluginView<'_> {
PluginView::from_backend(&self.view)
}
fn geometry(&self) -> Cow<'_, [ScreenPoint]> {
Cow::Borrowed(&self.screen_geometry)
}
fn has_ground(&self) -> bool {
self.query.ground(UnwrappedTileID::new(0, 0, 0)).is_some()
}
fn ground_height(&self, tile_id: TileId, x: f32, y: f32) -> f32 {
let Ok(tile) = unwrapped_tile_id(tile_id) else {
return 0.0;
};
self.query.ground(tile).map_or(0.0, |g| g.height(GlamVec2::new(x, y)))
}
fn ground_visibility(&self, tile_id: TileId, x: f64, y: f64, elevation_m: f64) -> f64 {
let Ok(tile) = unwrapped_tile_id(tile_id) else {
return 1.0;
};
self.query.ground(tile).map_or(1.0, |g| g.visibility(self.query.view(), Point::new(x, y), elevation_m))
}
}
struct EngineFrameQueryCxRw<'a> {
hits: &'a mut Vec<Feature>,
}
impl FrameQueryCxMutBackend for EngineFrameQueryCxRw<'_> {
fn push_feature_json(&mut self, geojson_feature: &str) -> PluginResult<()> {
let parsed: GeoJson = serde_json::from_str(geojson_feature)
.map_err(|e| PluginError::invalid_argument(format!("invalid GeoJSON: {e}")))?;
let GeoJson::Feature(feat) = parsed else {
return Err(PluginError::invalid_argument("geojson_feature must be a GeoJSON Feature object"));
};
let mut features = mln_style::feature::geojson::features(GeoJson::Feature(feat))
.map_err(|e| PluginError::invalid_argument(format!("invalid GeoJSON feature: {e}")))?;
if let Some(converted) = features.pop() {
self.hits.push(Feature::from(converted));
}
Ok(())
}
fn push_point_feature(&mut self, position: PluginLatLng) -> PluginResult<()> {
let ll = to_lat_lng(position)?;
let point = geo_types::Point::new(ll.longitude(), ll.latitude());
self.hits.push(Feature { geometry: Some(point.into()), ..Feature::default() });
Ok(())
}
}
struct DisabledLayerInstance;
impl DynamicLayerInstance for DisabledLayerInstance {
fn evaluate(&mut self, _cx: &mut DynamicEvaluateCx<'_>) -> Evaluation {
Evaluation::NONE
}
}
struct PluginLayerHandler<P: LayerPlugin> {
name: &'static str,
plugin: P,
}
struct PluginLayerInstance<I: LayerInstance> {
instance: I,
}
impl<P: LayerPlugin> DynamicLayerHandler for PluginLayerHandler<P> {
fn create_instance(&self, values: &DynamicLayerValues) -> Box<dyn DynamicLayerInstance> {
let evaluated = EngineArcEvaluatedLayer { inner: Arc::clone(&values.evaluated) };
match self.plugin.create_instance(EvaluatedLayer::from_backend(&evaluated)) {
Ok(instance) => Box::new(PluginLayerInstance { instance }),
Err(err) => {
tracing::error!(
target: crate::log_target::RENDER,
layer_type = self.name,
error = %err,
"plugin layer create_instance failed; disabling layer instance"
);
Box::new(DisabledLayerInstance)
}
}
}
fn tile_fade(&self, layer: &DynamicEvaluatedLayer) -> Duration {
let evaluated = EngineRefEvaluatedLayer { inner: layer };
Duration::from_nanos(self.plugin.tile_fade_ns(EvaluatedLayer::from_backend(&evaluated)))
}
fn build_bucket(&self, cx: &mut DynamicBuildCx<'_>) -> Result<Option<DynamicBucket>, StyleError> {
let source_layer = cx.source_layer()?;
let mut build_cx = EngineTileBuildCx::new(cx, &source_layer);
let mut builder = EngineTileGeometryBuilder::new();
let res = {
let mut api_cx = TileBuildCx::from_backend(&mut build_cx);
let mut api_builder = TileGeometryBuilder::from_backend(&mut builder);
self.plugin.build_tile_geometry(&mut api_cx, &mut api_builder)
};
drop(build_cx);
if let Err(err) = res {
return Err(StyleError::failed(format!("plugin layer '{}' build_tile_geometry failed: {err}", self.name)));
}
if builder.bucket.vertices.is_empty() {
return Ok(None);
}
builder.bucket.binders = cx.take_binders();
Ok(Some(builder.bucket))
}
fn query_radius(&self, bucket: &DynamicBucket, layer: &DynamicEvaluatedLayer) -> f32 {
let geom = EngineTileGeometry { inner: bucket };
let eval = EngineRefEvaluatedLayer { inner: layer };
self.plugin.query_radius(TileGeometry::from_backend(&geom), EvaluatedLayer::from_backend(&eval))
}
}
impl<I: LayerInstance> DynamicLayerInstance for PluginLayerInstance<I> {
fn evaluate(&mut self, cx: &mut DynamicEvaluateCx<'_>) -> Evaluation {
let time_point = cx.time_point();
let backend = EngineEvaluateCx { evaluated: EngineRefEvaluatedLayer { inner: cx.evaluated }, time_point };
let res = self.instance.evaluate(EvaluateCx::from_backend(&backend));
to_evaluation(res, time_point)
}
fn update(&mut self, cx: &mut DynamicUpdateCx<'_, '_>, tiles: &[DynamicFrameTile<'_>]) {
let ro = EngineUpdateCxRo {
evaluated: EngineArcEvaluatedLayer { inner: Arc::clone(&cx.values.evaluated) },
source_max_zoom: cx.source_max_zoom(),
tiles: tiles.iter().copied().map(EngineTile::new).collect(),
};
let mut rw = EngineUpdateCxRw { cx };
let mut api_cx = UpdateCx::from_backends(&ro, &mut rw);
self.instance.update(&mut api_cx);
}
fn tile(
&mut self,
cx: &mut DynamicTileCx<'_, '_>,
tile: &DynamicFrameTile<'_>,
previous: Option<Box<dyn Any>>,
) -> Option<Box<dyn Any>> {
let evaluated = EngineArcEvaluatedLayer { inner: Arc::clone(&cx.values.evaluated) };
let frame = EngineFrame::new(cx.frame);
let tile_backend = EngineTile::new(*tile);
let projection_variant = from_projection_variant(cx.projection_variant());
let mut res = EngineResources { inner: &mut cx.res };
let mut api_cx = TileCx::new(
EvaluatedLayer::from_backend(&evaluated),
projection_variant,
PluginFrame::from_backend(&frame),
Tile::from_backend(&tile_backend),
&mut res,
);
let mut prev = previous.and_then(|b| b.downcast::<I::TileResources>().ok());
match self.instance.create_tile_resources(&mut api_cx, prev.as_deref_mut()) {
Ok(Some(state)) => Some(Box::new(state)),
Ok(None) => None,
Err(err) => {
tracing::error!(
target: crate::log_target::RENDER,
error = %err,
"plugin layer create_tile_resources failed"
);
None
}
}
}
fn prepare(&mut self, cx: &mut DynamicPrepareCx<'_, '_>, tiles: &[DynamicFrameTile<'_>], out: &mut Draws) {
let evaluated = EngineArcEvaluatedLayer { inner: Arc::clone(&cx.values.evaluated) };
let frame = EngineFrame::new(cx.frame);
let projection_variant = from_projection_variant(cx.projection_variant());
let layer_id = cx.base.style.base().id.as_str();
let ro = EnginePrepareCxRo { tiles: tiles.iter().copied().map(EngineTile::new).collect(), picked: cx.picked };
let mut rw = EnginePrepareCxRw {
layer_id,
tiles: cx.tiles,
res: EngineResources { inner: &mut cx.res },
targets: cx.targets.as_deref_mut(),
};
let mut api_cx = PrepareCx::<I::TileResources>::new(
EvaluatedLayer::from_backend(&evaluated),
PluginFrame::from_backend(&frame),
projection_variant,
&ro,
&mut rw,
);
let mut draws_backend = EngineDraws { inner: out, invalid: InvalidTargetGroup };
let mut api_draws = PluginDraws::from_backend(&mut draws_backend);
self.instance.prepare(&mut api_cx, &mut api_draws);
}
fn hit(
&self,
values: &DynamicLayerValues,
region: &QueryRegion<'_>,
feature: &dyn GeometryTileFeature,
geometry: &GeometryCollection,
feature_state: &FeatureState,
) -> Hit {
let backend = EngineHitCx::new(values, region, feature, geometry, feature_state);
match self.instance.hit(HitCx::from_backend(&backend)) {
PluginHit::Miss => Hit::Miss,
PluginHit::InPlace => Hit::InPlace,
PluginHit::AtDistance(d) => Hit::At(d),
}
}
fn hit_frame(&self, query: &DynamicFrameQuery<'_>, hits: &mut Vec<Feature>) {
let ro = EngineFrameQueryCxRo::new(query);
let mut rw = EngineFrameQueryCxRw { hits };
let mut api_cx = FrameQueryCx::from_backends(&ro, &mut rw);
self.instance.hit_frame(&mut api_cx);
}
}
enum ValidatedDefault {
Float(f32),
Bool(bool),
Color(Color),
Vec2([f32; 2]),
LatLng(LatLng),
Rotation(Rotation),
String(String),
Enum { variants: Vec<String>, default: u32 },
}
impl ValidatedDefault {
fn supports_paint_binder(&self) -> bool {
matches!(self, Self::Float(_) | Self::Color(_))
}
}
struct ValidatedProperty {
name: String,
scope: StylePropertyScope,
data_driven: bool,
paint_lays_out: bool,
attribute: Option<String>,
default: ValidatedDefault,
}
fn leak_str(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
pub fn build_layer_type<P: LayerPlugin>(mut plugin: P) -> PluginResult<&'static DynamicLayerType> {
let desc = plugin.desc();
if desc.name.is_empty() {
return Err(PluginError::invalid_argument("layer.name must not be empty"));
}
let (source_kind, picks_tiles) = match desc.input {
LayerInput::Frame => (SourceKind::None, false),
LayerInput::ViewportTiles => (SourceKind::None, true),
LayerInput::GeometryTiles => (SourceKind::Geometry, false),
LayerInput::RasterTiles => (SourceKind::Raster, false),
LayerInput::RasterDemTiles => (SourceKind::RasterDem, false),
LayerInput::SourceTiles => (SourceKind::Any, false),
};
let tile_order = match desc.tile_order {
PluginTileOrder::ById => TileOrder::ById,
PluginTileOrder::ByY => TileOrder::ByY,
};
let terrain = match desc.terrain_mode {
TerrainMode::Flat => OnTerrain::Flat,
TerrainMode::Stands => OnTerrain::Stands { hides_behind_ground: false },
TerrainMode::StandsHidingBehindGround => OnTerrain::Stands { hides_behind_ground: true },
TerrainMode::Drapes => OnTerrain::Drapes,
};
if desc.properties.len() > MAX_DYNAMIC_PROPERTIES {
return Err(PluginError::invalid_argument(format!(
"layer '{}' declares {} properties, exceeding maximum ({MAX_DYNAMIC_PROPERTIES})",
desc.name,
desc.properties.len()
)));
}
let mut properties = Vec::with_capacity(desc.properties.len());
let mut names = HashSet::default();
let mut paint_names = HashSet::default();
let mut attributes = HashSet::default();
let mut data_driven_paint = 0usize;
for p in desc.properties {
if p.name.is_empty() {
return Err(PluginError::invalid_argument(format!(
"layer '{}' has a property with an empty name",
desc.name
)));
}
if !names.insert(p.name.to_owned()) {
return Err(PluginError::invalid_argument(format!(
"layer '{}' has duplicate property '{}'",
desc.name, p.name
)));
}
let scope = match p.scope {
PropertyScope::Paint => StylePropertyScope::Paint,
PropertyScope::Layout => StylePropertyScope::Layout,
};
if scope == StylePropertyScope::Paint {
paint_names.insert(p.name.to_owned());
if p.data_driven {
data_driven_paint += 1;
}
}
let default = match p.default {
PropertyDefault::Float(v) => {
if !v.is_finite() {
return Err(PluginError::invalid_argument(format!(
"property '{}' default float must be finite",
p.name
)));
}
ValidatedDefault::Float(v)
}
PropertyDefault::Bool(v) => ValidatedDefault::Bool(v),
PropertyDefault::Color(c) => ValidatedDefault::Color(to_color(c)),
PropertyDefault::Vec2(v) => {
if !v.x.is_finite() || !v.y.is_finite() {
return Err(PluginError::invalid_argument(format!(
"property '{}' default vec2 must be finite",
p.name
)));
}
ValidatedDefault::Vec2([v.x, v.y])
}
PropertyDefault::LatLng(ll) => ValidatedDefault::LatLng(to_lat_lng(ll)?),
PropertyDefault::RotationDegrees(deg) => {
if !deg.is_finite() {
return Err(PluginError::invalid_argument(format!(
"property '{}' default rotation_degrees must be finite",
p.name
)));
}
ValidatedDefault::Rotation(Rotation::new(f64::from(deg)))
}
PropertyDefault::String(s) => ValidatedDefault::String(s.to_owned()),
PropertyDefault::Enum { variants, default_index } => {
if variants.is_empty() {
return Err(PluginError::invalid_argument(format!(
"enum property '{}' must declare at least one variant",
p.name
)));
}
if (default_index as usize) >= variants.len() {
return Err(PluginError::invalid_argument(format!(
"enum property '{}' default index {default_index} is out of range for {} variants",
p.name,
variants.len()
)));
}
let mut seen = HashSet::default();
let mut owned = Vec::with_capacity(variants.len());
for &v in variants {
if !seen.insert(v.to_owned()) {
return Err(PluginError::invalid_argument(format!(
"enum property '{}' has duplicate variant '{v}'",
p.name
)));
}
owned.push(v.to_owned());
}
ValidatedDefault::Enum { variants: owned, default: default_index }
}
};
let attribute = if p.attribute_name.is_empty() {
None
} else {
let attr = p.attribute_name;
if scope != StylePropertyScope::Paint {
return Err(PluginError::invalid_argument(format!(
"property '{}': attribute_name is only supported on paint properties",
p.name
)));
}
if !p.data_driven {
return Err(PluginError::invalid_argument(format!(
"property '{}': attribute_name requires data_driven",
p.name
)));
}
if !default.supports_paint_binder() {
return Err(PluginError::invalid_argument(format!(
"property '{}': attribute_name is only supported on Float and Color paint properties",
p.name
)));
}
if !attributes.insert(attr.to_owned()) {
return Err(PluginError::invalid_argument(format!(
"layer '{}' has duplicate attribute '{attr}'",
desc.name
)));
}
Some(attr.to_owned())
};
properties.push(ValidatedProperty {
name: p.name.to_owned(),
scope,
data_driven: p.data_driven,
paint_lays_out: p.paint_lays_out,
attribute,
default,
});
}
if data_driven_paint > MAX_DYNAMIC_DATA_DRIVEN_PAINT {
return Err(PluginError::invalid_argument(format!(
"layer '{}' has {data_driven_paint} data-driven paint properties, exceeding maximum ({MAX_DYNAMIC_DATA_DRIVEN_PAINT})",
desc.name
)));
}
for prop in &properties {
if let Some(base) = prop.name.strip_suffix("-transition")
&& paint_names.contains(base)
{
return Err(PluginError::invalid_argument(format!(
"property '{}' collides with paint transition property for '{base}'",
prop.name
)));
}
}
let name_owned = desc.name.to_owned();
let is_volume = desc.is_volume;
plugin.init(&Host::from_backend(&EngineHost))?;
let name = leak_str(name_owned);
let dyn_properties: Vec<DynamicPropertyDesc> = properties
.into_iter()
.map(|p| {
let default = match p.default {
ValidatedDefault::Float(v) => DynamicDefault::Float(v),
ValidatedDefault::Bool(v) => DynamicDefault::Bool(v),
ValidatedDefault::Color(v) => DynamicDefault::Color(v),
ValidatedDefault::Vec2(v) => DynamicDefault::Vec2(v),
ValidatedDefault::LatLng(v) => DynamicDefault::LatLng(v),
ValidatedDefault::Rotation(v) => DynamicDefault::Rotation(v),
ValidatedDefault::String(v) => DynamicDefault::String(leak_str(v)),
ValidatedDefault::Enum { variants, default } => {
let leaked_variants: Vec<&'static str> = variants.into_iter().map(leak_str).collect();
DynamicDefault::Enum { variants: Box::leak(leaked_variants.into_boxed_slice()), default }
}
};
DynamicPropertyDesc {
name: leak_str(p.name),
scope: p.scope,
data_driven: p.data_driven,
default,
attribute: p.attribute.map(leak_str),
paint_lays_out: p.paint_lays_out,
}
})
.collect();
let style_type = DynamicStyleLayerType::leak(DynamicLayerDesc {
info: LayerTypeInfo { name, source: source_kind, from_json: true },
properties: dyn_properties,
})
.map_err(|e| PluginError::invalid_argument(e.to_string()))?;
let config = DynamicLayerConfig { style: style_type, tile_order, terrain, volume: is_volume, picks_tiles };
let handler = Arc::new(PluginLayerHandler { name, plugin });
Ok(DynamicLayerType::leak(config, handler))
}