Skip to main content

mln_plugin/
layer.rs

1//! Safe, host-agnostic traits, descriptors, contexts, and RAII GPU handles for
2//! layer plugins.
3
4use core::any::Any;
5use core::marker::PhantomData;
6use std::borrow::Cow;
7use std::sync::Arc;
8
9use crate::backend::{
10    AfterGpuHandle, AfterGpuRefBackend, DrawGroupBackend, DrawsBackend, EvaluateCxBackend, EvaluatedLayerBackend,
11    FrameBackend, FrameQueryCxMutBackend, FrameQueryCxReadBackend, GroundHeightsHandle, HitCxBackend, HostBackend,
12    IndexBufferHandle, MeshHandle, PaintAttributesHandle, PrepareCxMutBackend, PrepareCxReadBackend, ResourcesBackend,
13    TargetHandle, TextureHandle, TileBackend, TileBuildCxBackend, TileGeometryBackend, TileGeometryBuilderBackend,
14    UpdateCxMutBackend, UpdateCxReadBackend, VertexBufferHandle, ViewBackend,
15};
16use crate::error::Result;
17use crate::program::{AttributeFormat, Program, ProgramDesc};
18use crate::types::{
19    Alignment, CollisionShape, Color, ColorMode, CullFaceMode, DrawMode, DrawOptions, DrawRange, FeatureType,
20    FrameInfo, GpuEnd, LatLng, LayerInput, LendAt, LendFrame, LendStage, MapMode, PointI16, ProjectedPoint,
21    ProjectionUbo, ProjectionVariant, RenderPasses, SamplerState, ScreenPoint, TerrainMode, TextureChannelType,
22    TextureFormat, TileChanges, TileId, TileOrder, TileTransform, Vec2, ViewInfo,
23};
24
25// ---------------------------------------------------------------------------
26// Host handle for one-time plugin initialization
27// ---------------------------------------------------------------------------
28
29/// Borrowed host handle passed to [`LayerPlugin::init`] when a plugin is
30/// registered, allowing one-time creation of shared resources such as shader
31/// [`Program`]s.
32pub struct Host<'a> {
33    backend: &'a dyn HostBackend,
34}
35
36impl<'a> Host<'a> {
37    #[doc(hidden)]
38    #[must_use]
39    pub fn from_backend(backend: &'a dyn HostBackend) -> Self {
40        Self { backend }
41    }
42
43    /// Registers a multi-backend shader program with the host.
44    pub fn create_program(&self, desc: &ProgramDesc<'_>) -> Result<Program> {
45        self.backend.create_program(desc)
46    }
47
48    /// Creates a reusable ground-height sampler cache.
49    pub fn create_ground_heights(&self) -> Result<GroundHeights> {
50        self.backend.create_ground_heights()
51    }
52}
53
54// ---------------------------------------------------------------------------
55// Schema descriptors
56// ---------------------------------------------------------------------------
57
58/// Whether a custom property belongs to paint or layout.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum PropertyScope {
61    Paint,
62    Layout,
63}
64
65/// Typed default value for a custom style property.
66#[derive(Clone, Copy, Debug)]
67pub enum PropertyDefault<'a> {
68    Float(f32),
69    Bool(bool),
70    Color(Color),
71    Vec2(Vec2),
72    LatLng(LatLng),
73    RotationDegrees(f32),
74    String(&'a str),
75    Enum { variants: &'a [&'a str], default_index: u32 },
76}
77
78/// Descriptor for one custom paint or layout property.
79#[derive(Clone, Copy, Debug)]
80pub struct PropertyDesc<'a> {
81    pub name: &'a str,
82    pub scope: PropertyScope,
83    pub data_driven: bool,
84    pub paint_lays_out: bool,
85    pub attribute_name: &'a str,
86    pub default: PropertyDefault<'a>,
87}
88
89impl<'a> PropertyDesc<'a> {
90    /// Constant (non-data-driven) paint property.
91    #[must_use]
92    pub const fn paint(name: &'a str, default: PropertyDefault<'a>) -> Self {
93        Self {
94            name,
95            scope: PropertyScope::Paint,
96            data_driven: false,
97            paint_lays_out: false,
98            attribute_name: "",
99            default,
100        }
101    }
102
103    /// Data-driven paint property backed by a vertex attribute.
104    #[must_use]
105    pub const fn paint_data_driven(name: &'a str, attribute_name: &'a str, default: PropertyDefault<'a>) -> Self {
106        Self { name, scope: PropertyScope::Paint, data_driven: true, paint_lays_out: false, attribute_name, default }
107    }
108
109    /// Layout property.
110    #[must_use]
111    pub const fn layout(name: &'a str, default: PropertyDefault<'a>) -> Self {
112        Self {
113            name,
114            scope: PropertyScope::Layout,
115            data_driven: false,
116            paint_lays_out: false,
117            attribute_name: "",
118            default,
119        }
120    }
121}
122
123/// Static descriptor for a custom layer type returned by [`LayerPlugin::desc`].
124#[derive(Clone, Debug)]
125pub struct LayerDesc<'a> {
126    pub name: &'a str,
127    pub input: LayerInput,
128    pub tile_order: TileOrder,
129    pub terrain_mode: TerrainMode,
130    pub is_volume: bool,
131    pub properties: &'a [PropertyDesc<'a>],
132}
133
134/// Output of [`LayerInstance::evaluate`].
135#[derive(Clone, Copy, Debug, Default, PartialEq)]
136pub struct Evaluation {
137    pub passes: RenderPasses,
138    pub solid_color: Option<Color>,
139    pub drapes_by_bearing: bool,
140    pub drapes_by_zoom: bool,
141    pub needs_repaint: bool,
142    pub repaint_after_ns: Option<u64>,
143    /// Whether the layer reads the shapes the frame's placement tested
144    /// ([`Frame::collision_shapes`]). Placement records them only while a
145    /// layer the frame draws reads them.
146    pub reads_collision_shapes: bool,
147}
148
149impl Evaluation {
150    #[must_use]
151    pub const fn passes(passes: RenderPasses) -> Self {
152        Self {
153            passes,
154            solid_color: None,
155            drapes_by_bearing: false,
156            drapes_by_zoom: false,
157            needs_repaint: false,
158            repaint_after_ns: None,
159            reads_collision_shapes: false,
160        }
161    }
162}
163
164/// Outcome of a tile-feature hit test ([`LayerInstance::hit`]).
165#[derive(Clone, Copy, Debug, Default, PartialEq)]
166pub enum Hit {
167    #[default]
168    Miss,
169    InPlace,
170    AtDistance(f64),
171}
172
173// ---------------------------------------------------------------------------
174// Layer blend & compositing
175// ---------------------------------------------------------------------------
176
177/// Compositing blend mode for a draw group.
178#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
179pub enum LayerBlend {
180    #[default]
181    Normal,
182    Multiply,
183    Screen,
184    Overlay,
185    Darken,
186    Lighten,
187    ColorDodge,
188    ColorBurn,
189    HardLight,
190    SoftLight,
191    Difference,
192    Exclusion,
193    Hue,
194    Saturation,
195    Color,
196    Luminosity,
197    PlusLighter,
198}
199
200/// Compositing configuration for a [`DrawGroup`].
201#[derive(Clone, Copy, Debug, PartialEq)]
202pub struct Composite {
203    pub opacity: f32,
204    pub blend: LayerBlend,
205    pub frame_depth: bool,
206}
207
208// ---------------------------------------------------------------------------
209// RAII GPU handles
210// ---------------------------------------------------------------------------
211
212/// Owned GPU vertex buffer handle.
213#[derive(Debug)]
214pub struct VertexBuffer {
215    inner: Box<dyn VertexBufferHandle>,
216}
217
218impl VertexBuffer {
219    #[doc(hidden)]
220    #[must_use]
221    pub fn from_handle(inner: Box<dyn VertexBufferHandle>) -> Self {
222        Self { inner }
223    }
224
225    #[doc(hidden)]
226    #[must_use]
227    pub fn handle(&self) -> &dyn VertexBufferHandle {
228        &*self.inner
229    }
230}
231
232/// Owned GPU index buffer handle.
233#[derive(Debug)]
234pub struct IndexBuffer {
235    inner: Box<dyn IndexBufferHandle>,
236}
237
238impl IndexBuffer {
239    #[doc(hidden)]
240    #[must_use]
241    pub fn from_handle(inner: Box<dyn IndexBufferHandle>) -> Self {
242        Self { inner }
243    }
244
245    #[doc(hidden)]
246    #[must_use]
247    pub fn handle(&self) -> &dyn IndexBufferHandle {
248        &*self.inner
249    }
250}
251
252/// Owned GPU texture handle.
253#[derive(Debug)]
254pub struct Texture {
255    inner: Box<dyn TextureHandle>,
256}
257
258impl Texture {
259    #[doc(hidden)]
260    #[must_use]
261    pub fn from_handle(inner: Box<dyn TextureHandle>) -> Self {
262        Self { inner }
263    }
264
265    #[doc(hidden)]
266    #[must_use]
267    pub fn handle(&self) -> &dyn TextureHandle {
268        &*self.inner
269    }
270}
271
272/// Owned offscreen render target handle.
273#[derive(Debug)]
274pub struct Target {
275    inner: Box<dyn TargetHandle>,
276}
277
278impl Target {
279    #[doc(hidden)]
280    #[must_use]
281    pub fn from_handle(inner: Box<dyn TargetHandle>) -> Self {
282        Self { inner }
283    }
284
285    #[doc(hidden)]
286    #[must_use]
287    pub fn handle(&self) -> &dyn TargetHandle {
288        &*self.inner
289    }
290
291    /// Returns a handle to the color texture backed by this render target.
292    #[must_use]
293    pub fn texture(&self) -> Option<Texture> {
294        self.inner.texture()
295    }
296}
297
298/// Owned paint-attribute binder snapshot for a tile/layer.
299#[derive(Debug)]
300pub struct PaintAttributes {
301    inner: Box<dyn PaintAttributesHandle>,
302}
303
304impl PaintAttributes {
305    #[doc(hidden)]
306    #[must_use]
307    pub fn from_handle(inner: Box<dyn PaintAttributesHandle>) -> Self {
308        Self { inner }
309    }
310
311    #[doc(hidden)]
312    #[must_use]
313    pub fn handle(&self) -> &dyn PaintAttributesHandle {
314        &*self.inner
315    }
316}
317
318/// Owned GPU mesh handle.
319#[derive(Debug)]
320pub struct Mesh {
321    inner: Box<dyn MeshHandle>,
322}
323
324impl Mesh {
325    #[doc(hidden)]
326    #[must_use]
327    pub fn from_handle(inner: Box<dyn MeshHandle>) -> Self {
328        Self { inner }
329    }
330
331    #[doc(hidden)]
332    #[must_use]
333    pub fn handle(&self) -> &dyn MeshHandle {
334        &*self.inner
335    }
336
337    /// Monotonic sequence number suitable for [`DrawOptions::order`].
338    #[must_use]
339    pub fn seq(&self) -> i64 {
340        self.inner.seq()
341    }
342
343    /// Binds or clears a texture at `slot` on this mesh.
344    pub fn set_texture(&self, res: &mut Resources<'_>, slot: u32, texture: Option<&Texture>) -> Result<()> {
345        res.backend.mesh_set_texture(self, slot, texture)
346    }
347
348    /// Overrides the sampler state at `slot` on this mesh.
349    pub fn set_sampler(&self, res: &mut Resources<'_>, slot: u32, sampler: SamplerState) -> Result<()> {
350        res.backend.mesh_set_sampler(self, slot, sampler)
351    }
352
353    /// Updates paint attributes on this mesh after paint property changes.
354    pub fn set_paint(&self, res: &mut Resources<'_>, paint: &PaintAttributes) -> Result<()> {
355        res.backend.mesh_set_paint(self, paint)
356    }
357
358    /// Rebinds a vertex stream on this mesh.
359    pub fn bind_vertices(&self, res: &mut Resources<'_>, binding: &VertexBinding<'_>) -> Result<()> {
360        res.backend.mesh_bind_vertices(self, binding)
361    }
362}
363
364/// Owned ground-height sampler cache for standing geometry layers.
365#[derive(Debug)]
366pub struct GroundHeights {
367    inner: Box<dyn GroundHeightsHandle>,
368}
369
370impl GroundHeights {
371    #[doc(hidden)]
372    #[must_use]
373    pub fn from_handle(inner: Box<dyn GroundHeightsHandle>) -> Self {
374        Self { inner }
375    }
376
377    #[doc(hidden)]
378    #[must_use]
379    pub fn handle_mut(&mut self) -> &mut dyn GroundHeightsHandle {
380        &mut *self.inner
381    }
382
383    /// Samples terrain heights at `centers` in `tile_id` and binds them to
384    /// `attribute_name` on `mesh` when terrain data changes.
385    pub fn apply(
386        &mut self,
387        mesh: &Mesh,
388        res: &mut Resources<'_>,
389        frame: Frame<'_>,
390        tile_id: TileId,
391        attribute_name: &str,
392        centers: &[PointI16],
393    ) -> Result<()> {
394        res.backend.apply_ground_heights(self, mesh, frame, tile_id, attribute_name, centers)
395    }
396}
397
398// ---------------------------------------------------------------------------
399// Mesh descriptors
400// ---------------------------------------------------------------------------
401
402/// Attribute entry inside a [`VertexBinding`].
403#[derive(Clone, Copy, Debug)]
404pub struct VertexAttribute<'a> {
405    pub name: &'a str,
406    pub format: AttributeFormat,
407    pub offset: u32,
408}
409
410impl<'a> VertexAttribute<'a> {
411    #[must_use]
412    pub const fn new(name: &'a str, format: AttributeFormat, offset: u32) -> Self {
413        Self { name, format, offset }
414    }
415}
416
417/// Vertex buffer stream binding passed to [`MeshDesc`] or [`Mesh::bind_vertices`].
418#[derive(Clone, Copy, Debug)]
419pub struct VertexBinding<'a> {
420    pub buffer: &'a VertexBuffer,
421    pub stride: u32,
422    pub first_vertex: u32,
423    pub attributes: &'a [VertexAttribute<'a>],
424}
425
426/// Descriptor passed to [`Resources::create_mesh`].
427pub struct MeshDesc<'a> {
428    pub program: &'a Program,
429    pub projection_variant: ProjectionVariant,
430    pub extra_defines: &'a [&'a str],
431    pub paint_attributes: Option<&'a PaintAttributes>,
432    pub color_mode: ColorMode,
433    pub cull_face_mode: CullFaceMode,
434    pub draw_mode: DrawMode,
435    pub vertex_bindings: &'a [VertexBinding<'a>],
436    pub vertex_count: usize,
437    pub instance_bindings: &'a [VertexBinding<'a>],
438    pub indexes: &'a IndexBuffer,
439    pub ranges: &'a [DrawRange],
440    pub textures: &'a [Option<&'a Texture>],
441}
442
443// ---------------------------------------------------------------------------
444// Borrowed host contexts
445// ---------------------------------------------------------------------------
446
447/// Borrowed view of an evaluated custom style layer.
448#[derive(Clone, Copy)]
449pub struct EvaluatedLayer<'a> {
450    backend: &'a dyn EvaluatedLayerBackend,
451}
452
453impl<'a> EvaluatedLayer<'a> {
454    #[doc(hidden)]
455    #[must_use]
456    pub fn from_backend(backend: &'a dyn EvaluatedLayerBackend) -> Self {
457        Self { backend }
458    }
459
460    #[doc(hidden)]
461    #[must_use]
462    pub fn backend(&self) -> &'a dyn EvaluatedLayerBackend {
463        self.backend
464    }
465
466    /// Layer ID from the style.
467    #[must_use]
468    pub fn id(&self) -> &'a str {
469        self.backend.id()
470    }
471
472    /// Returns true if paint property `slot` has a constant (non-data-driven) value.
473    #[must_use]
474    pub fn paint_is_constant(&self, slot: u32) -> bool {
475        self.backend.paint_is_constant(slot)
476    }
477
478    /// Reads a constant float paint property.
479    pub fn paint_f32(&self, slot: u32) -> Result<f32> {
480        self.backend.paint_f32(slot)
481    }
482
483    /// Reads a float paint property if constant, or returns `fallback` when data-driven.
484    pub fn paint_f32_constant_or(&self, slot: u32, fallback: f32) -> Result<f32> {
485        self.backend.paint_f32_constant_or(slot, fallback)
486    }
487
488    /// Reads a constant bool paint property.
489    pub fn paint_bool(&self, slot: u32) -> Result<bool> {
490        self.backend.paint_bool(slot)
491    }
492
493    /// Reads a constant color paint property.
494    pub fn paint_color(&self, slot: u32) -> Result<Color> {
495        self.backend.paint_color(slot)
496    }
497
498    /// Reads a color paint property if constant, or returns `fallback` when data-driven.
499    pub fn paint_color_constant_or(&self, slot: u32, fallback: Color) -> Result<Color> {
500        self.backend.paint_color_constant_or(slot, fallback)
501    }
502
503    /// Reads a constant 2-vector paint property.
504    pub fn paint_vec2(&self, slot: u32) -> Result<Vec2> {
505        self.backend.paint_vec2(slot)
506    }
507
508    /// Reads a constant geographic position paint property.
509    pub fn paint_lat_lng(&self, slot: u32) -> Result<LatLng> {
510        self.backend.paint_lat_lng(slot)
511    }
512
513    /// Reads a constant rotation paint property in degrees.
514    pub fn paint_rotation_degrees(&self, slot: u32) -> Result<f32> {
515        self.backend.paint_rotation_degrees(slot)
516    }
517
518    /// Reads a constant string (or enum label) paint property.
519    pub fn paint_str(&self, slot: u32) -> Result<&'a str> {
520        self.backend.paint_str(slot)
521    }
522
523    /// Reads a constant enum paint property as its 0-based variant index.
524    pub fn paint_enum(&self, slot: u32) -> Result<u32> {
525        self.backend.paint_enum(slot)
526    }
527}
528
529/// Borrowed context for [`LayerInstance::evaluate`].
530#[derive(Clone, Copy)]
531pub struct EvaluateCx<'a> {
532    backend: &'a dyn EvaluateCxBackend,
533}
534
535impl<'a> EvaluateCx<'a> {
536    #[doc(hidden)]
537    #[must_use]
538    pub fn from_backend(backend: &'a dyn EvaluateCxBackend) -> Self {
539        Self { backend }
540    }
541
542    #[must_use]
543    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
544        self.backend.evaluated()
545    }
546
547    /// Current frame clock offset in signed nanoseconds relative to the host's
548    /// process epoch, if a frame clock is active.
549    #[must_use]
550    pub fn time_point_ns(&self) -> Option<i64> {
551        self.backend.time_point_ns()
552    }
553}
554
555/// Borrowed context for [`LayerInstance::update`].
556pub struct UpdateCx<'a> {
557    ro: &'a dyn UpdateCxReadBackend,
558    rw: &'a mut dyn UpdateCxMutBackend,
559}
560
561impl<'a> UpdateCx<'a> {
562    #[doc(hidden)]
563    #[must_use]
564    pub fn from_backends(ro: &'a dyn UpdateCxReadBackend, rw: &'a mut dyn UpdateCxMutBackend) -> Self {
565        Self { ro, rw }
566    }
567
568    #[must_use]
569    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
570        self.ro.evaluated()
571    }
572
573    #[must_use]
574    pub fn source_max_zoom(&self) -> Option<u8> {
575        self.ro.source_max_zoom()
576    }
577
578    #[must_use]
579    pub fn tile_count(&self) -> usize {
580        self.ro.tile_count()
581    }
582
583    #[must_use]
584    pub fn tile(&self, index: usize) -> Option<Tile<'a>> {
585        self.ro.tile(index)
586    }
587
588    pub fn pick_tiles(&mut self, tiles: &[TileId]) -> Result<()> {
589        self.rw.pick_tiles(tiles)
590    }
591}
592
593/// Borrowed context for [`LayerInstance::create_tile_resources`].
594pub struct TileCx<'a> {
595    evaluated: EvaluatedLayer<'a>,
596    projection_variant: ProjectionVariant,
597    frame: Frame<'a>,
598    tile: Tile<'a>,
599    resources: &'a mut dyn ResourcesBackend,
600}
601
602impl<'a> TileCx<'a> {
603    #[doc(hidden)]
604    #[must_use]
605    pub fn new(
606        evaluated: EvaluatedLayer<'a>,
607        projection_variant: ProjectionVariant,
608        frame: Frame<'a>,
609        tile: Tile<'a>,
610        resources: &'a mut dyn ResourcesBackend,
611    ) -> Self {
612        Self { evaluated, projection_variant, frame, tile, resources }
613    }
614
615    #[must_use]
616    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
617        self.evaluated
618    }
619
620    #[must_use]
621    pub fn projection_variant(&self) -> ProjectionVariant {
622        self.projection_variant
623    }
624
625    #[must_use]
626    pub fn frame(&self) -> Frame<'a> {
627        self.frame
628    }
629
630    #[must_use]
631    pub fn tile(&self) -> Tile<'a> {
632        self.tile
633    }
634
635    #[must_use]
636    pub fn resources(&mut self) -> Resources<'_> {
637        Resources::from_backend(self.resources)
638    }
639}
640
641/// Borrowed context for [`LayerInstance::prepare`].
642pub struct PrepareCx<'a, T: 'static> {
643    evaluated: EvaluatedLayer<'a>,
644    frame: Frame<'a>,
645    projection_variant: ProjectionVariant,
646    ro: &'a dyn PrepareCxReadBackend,
647    rw: &'a mut dyn PrepareCxMutBackend,
648    _marker: PhantomData<*mut T>,
649}
650
651impl<'a, T: 'static> PrepareCx<'a, T> {
652    #[doc(hidden)]
653    #[must_use]
654    pub fn new(
655        evaluated: EvaluatedLayer<'a>,
656        frame: Frame<'a>,
657        projection_variant: ProjectionVariant,
658        ro: &'a dyn PrepareCxReadBackend,
659        rw: &'a mut dyn PrepareCxMutBackend,
660    ) -> Self {
661        Self { evaluated, frame, projection_variant, ro, rw, _marker: PhantomData }
662    }
663
664    #[must_use]
665    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
666        self.evaluated
667    }
668
669    #[must_use]
670    pub fn frame(&self) -> Frame<'a> {
671        self.frame
672    }
673
674    #[must_use]
675    pub fn projection_variant(&self) -> ProjectionVariant {
676        self.projection_variant
677    }
678
679    #[must_use]
680    pub fn tile_count(&self) -> usize {
681        self.ro.tile_count()
682    }
683
684    #[must_use]
685    pub fn tile(&self, index: usize) -> Option<Tile<'a>> {
686        self.ro.tile(index)
687    }
688
689    pub fn tiles(&self) -> impl Iterator<Item = Tile<'a>> + '_ {
690        (0..self.tile_count()).filter_map(|i| self.tile(i))
691    }
692
693    #[must_use]
694    pub fn resources(&mut self) -> Resources<'_> {
695        self.rw.resources()
696    }
697
698    /// Mutably borrows the tile resources for `tile_id` together with [`Resources`].
699    #[must_use]
700    pub fn tile_resources_and_allocator(&mut self, tile_id: TileId) -> (Option<&mut T>, Resources<'_>) {
701        let (slot, res) = self.rw.tile_resources_and_allocator(tile_id);
702        (slot.and_then(<dyn Any>::downcast_mut::<T>), res)
703    }
704
705    #[must_use]
706    pub fn tile_resources_mut(&mut self, tile_id: TileId) -> Option<&mut T> {
707        self.rw.tile_resources_mut(tile_id).and_then(<dyn Any>::downcast_mut::<T>)
708    }
709
710    #[must_use]
711    pub fn take_tile_changes(&mut self, tile_id: TileId) -> TileChanges {
712        self.rw.take_tile_changes(tile_id)
713    }
714
715    #[must_use]
716    pub fn picked_tiles(&self) -> Vec<TileId> {
717        self.ro.picked_tiles()
718    }
719
720    #[must_use]
721    pub fn read_shared_target(&mut self, name: &str) -> Option<Texture> {
722        self.rw.read_shared_target(name)
723    }
724}
725
726/// Borrowed raster pixel info for a raster tile.
727#[derive(Clone, Copy, Debug)]
728pub struct RasterTileInfo<'a> {
729    pub image_id: u64,
730    pub width: u32,
731    pub height: u32,
732    pub pixels: &'a [u8],
733}
734
735/// Borrowed tile handle valid during `update`, `create_tile_resources`, and `prepare`.
736#[derive(Clone, Copy)]
737pub struct Tile<'a> {
738    backend: &'a dyn TileBackend,
739}
740
741impl<'a> Tile<'a> {
742    #[doc(hidden)]
743    #[must_use]
744    pub fn from_backend(backend: &'a dyn TileBackend) -> Self {
745        Self { backend }
746    }
747
748    #[must_use]
749    pub fn id(&self) -> TileId {
750        self.backend.id()
751    }
752
753    #[must_use]
754    pub fn draw_id(&self) -> TileId {
755        self.backend.draw_id()
756    }
757
758    #[must_use]
759    pub fn render_passes(&self) -> RenderPasses {
760        self.backend.render_passes()
761    }
762
763    #[must_use]
764    pub fn has_data_for_pass(&self, pass: RenderPasses) -> bool {
765        self.backend.has_data_for_pass(pass)
766    }
767
768    #[must_use]
769    pub fn geometry(&self) -> Option<TileGeometry<'a>> {
770        self.backend.geometry()
771    }
772
773    #[must_use]
774    pub fn geometry_vertices(&self, stream_index: usize) -> Option<VertexBuffer> {
775        self.backend.geometry_vertices(stream_index)
776    }
777
778    #[must_use]
779    pub fn geometry_indexes(&self, stream_index: usize) -> Option<IndexBuffer> {
780        self.backend.geometry_indexes(stream_index)
781    }
782
783    #[must_use]
784    pub fn paint_attributes(&self, res: &mut Resources<'_>, evaluated: EvaluatedLayer<'_>) -> Option<PaintAttributes> {
785        self.backend.paint_attributes(res, evaluated)
786    }
787
788    #[must_use]
789    pub fn raster_info(&self) -> Option<RasterTileInfo<'a>> {
790        self.backend.raster_info()
791    }
792}
793
794/// Borrowed worker-built tile geometry handle.
795#[derive(Clone, Copy)]
796pub struct TileGeometry<'a> {
797    backend: &'a dyn TileGeometryBackend,
798}
799
800impl<'a> TileGeometry<'a> {
801    #[doc(hidden)]
802    #[must_use]
803    pub fn from_backend(backend: &'a dyn TileGeometryBackend) -> Self {
804        Self { backend }
805    }
806
807    #[must_use]
808    pub fn vertex_stream_count(&self) -> usize {
809        self.backend.vertex_stream_count()
810    }
811
812    #[must_use]
813    pub fn vertex_count(&self, stream_index: usize) -> usize {
814        self.backend.vertex_count(stream_index)
815    }
816
817    #[must_use]
818    pub fn vertex_stride(&self, stream_index: usize) -> u32 {
819        self.backend.vertex_stride(stream_index)
820    }
821
822    #[must_use]
823    pub fn index_stream_count(&self) -> usize {
824        self.backend.index_stream_count()
825    }
826
827    #[must_use]
828    pub fn index_count(&self, stream_index: usize) -> usize {
829        self.backend.index_count(stream_index)
830    }
831
832    #[must_use]
833    pub fn draw_ranges(&self) -> Cow<'a, [DrawRange]> {
834        self.backend.draw_ranges()
835    }
836
837    #[must_use]
838    pub fn metadata(&self) -> &'a [u8] {
839        self.backend.metadata()
840    }
841
842    #[must_use]
843    pub fn max_elevation(&self) -> f32 {
844        self.backend.max_elevation()
845    }
846
847    #[must_use]
848    pub fn binder_interpolation_factor(&self, layer_id: &str, paint_slot: u32, zoom: f32) -> f32 {
849        self.backend.binder_interpolation_factor(layer_id, paint_slot, zoom)
850    }
851
852    #[must_use]
853    pub fn binder_statistics_max_f32(&self, layer_id: &str, paint_slot: u32) -> Option<f32> {
854        self.backend.binder_statistics_max_f32(layer_id, paint_slot)
855    }
856}
857
858/// Information about the currently loaded feature inside [`TileBuildCx`].
859#[derive(Clone, Copy, Debug, PartialEq, Eq)]
860pub struct LoadedFeatureInfo {
861    pub feature_index: usize,
862    pub feature_type: FeatureType,
863    pub ring_count: usize,
864}
865
866/// Tile-worker layout context passed to [`LayerPlugin::build_tile_geometry`].
867pub struct TileBuildCx<'a> {
868    backend: &'a mut dyn TileBuildCxBackend,
869}
870
871impl<'a> TileBuildCx<'a> {
872    #[doc(hidden)]
873    #[must_use]
874    pub fn from_backend(backend: &'a mut dyn TileBuildCxBackend) -> Self {
875        Self { backend }
876    }
877
878    #[must_use]
879    pub fn tile_id(&self) -> TileId {
880        self.backend.tile_id()
881    }
882
883    /// Tile layout zoom level (`tile_id().overscaled_z as f64`).
884    #[must_use]
885    pub fn zoom(&self) -> f64 {
886        self.backend.zoom()
887    }
888
889    #[must_use]
890    pub fn mode(&self) -> MapMode {
891        self.backend.mode()
892    }
893
894    #[must_use]
895    pub fn pixel_ratio(&self) -> f32 {
896        self.backend.pixel_ratio()
897    }
898
899    #[must_use]
900    pub fn first_load(&self) -> bool {
901        self.backend.first_load()
902    }
903
904    #[must_use]
905    pub fn layer_count(&self) -> usize {
906        self.backend.layer_count()
907    }
908
909    #[must_use]
910    pub fn layer(&self, index: usize) -> Option<EvaluatedLayer<'_>> {
911        self.backend.layer(index)
912    }
913
914    pub fn eval_layout_f32(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<f32> {
915        self.backend.eval_layout_f32(layer_index, layout_slot, for_current_feature)
916    }
917
918    pub fn eval_layout_bool(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<bool> {
919        self.backend.eval_layout_bool(layer_index, layout_slot, for_current_feature)
920    }
921
922    pub fn eval_layout_color(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<Color> {
923        self.backend.eval_layout_color(layer_index, layout_slot, for_current_feature)
924    }
925
926    pub fn eval_layout_vec2(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<Vec2> {
927        self.backend.eval_layout_vec2(layer_index, layout_slot, for_current_feature)
928    }
929
930    pub fn eval_layout_lat_lng(
931        &self,
932        layer_index: usize,
933        layout_slot: u32,
934        for_current_feature: bool,
935    ) -> Result<LatLng> {
936        self.backend.eval_layout_lat_lng(layer_index, layout_slot, for_current_feature)
937    }
938
939    pub fn eval_layout_rotation_degrees(
940        &self,
941        layer_index: usize,
942        layout_slot: u32,
943        for_current_feature: bool,
944    ) -> Result<f32> {
945        self.backend.eval_layout_rotation_degrees(layer_index, layout_slot, for_current_feature)
946    }
947
948    pub fn eval_layout_str(&mut self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<&str> {
949        self.backend.eval_layout_str(layer_index, layout_slot, for_current_feature)
950    }
951
952    pub fn eval_layout_enum(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<u32> {
953        self.backend.eval_layout_enum(layer_index, layout_slot, for_current_feature)
954    }
955
956    #[must_use]
957    pub fn feature_count(&self) -> usize {
958        self.backend.feature_count()
959    }
960
961    pub fn load_feature(&mut self, selected_index: usize) -> Result<LoadedFeatureInfo> {
962        self.backend.load_feature(selected_index)
963    }
964
965    #[must_use]
966    pub fn feature_ring(&self, ring_index: usize) -> Option<Cow<'_, [PointI16]>> {
967        self.backend.feature_ring(ring_index)
968    }
969
970    pub fn populate_binders(&mut self, vertex_count: usize) -> Result<()> {
971        self.backend.populate_binders(vertex_count)
972    }
973
974    pub fn index_current_feature(&mut self) -> Result<()> {
975        self.backend.index_current_feature()
976    }
977}
978
979/// Output builder passed to [`LayerPlugin::build_tile_geometry`].
980pub struct TileGeometryBuilder<'a> {
981    backend: &'a mut dyn TileGeometryBuilderBackend,
982}
983
984impl<'a> TileGeometryBuilder<'a> {
985    #[doc(hidden)]
986    #[must_use]
987    pub fn from_backend(backend: &'a mut dyn TileGeometryBuilderBackend) -> Self {
988        Self { backend }
989    }
990
991    pub fn add_vertices(&mut self, bytes: &[u8], vertex_count: usize, stride: u32) -> Result<usize> {
992        self.backend.add_vertices(bytes, vertex_count, stride)
993    }
994
995    pub fn add_indexes(&mut self, indexes: &[u16]) -> Result<usize> {
996        self.backend.add_indexes(indexes)
997    }
998
999    pub fn add_draw_range(&mut self, range: DrawRange) -> Result<()> {
1000        self.backend.add_draw_range(range)
1001    }
1002
1003    pub fn set_metadata(&mut self, bytes: &[u8]) -> Result<()> {
1004        self.backend.set_metadata(bytes)
1005    }
1006
1007    pub fn set_max_elevation(&mut self, max_elevation: f32) -> Result<()> {
1008        self.backend.set_max_elevation(max_elevation)
1009    }
1010}
1011
1012/// Borrowed per-frame read-only state (viewport, ground, tile projection).
1013#[derive(Clone, Copy)]
1014pub struct Frame<'a> {
1015    backend: &'a dyn FrameBackend,
1016}
1017
1018impl<'a> Frame<'a> {
1019    #[doc(hidden)]
1020    #[must_use]
1021    pub fn from_backend(backend: &'a dyn FrameBackend) -> Self {
1022        Self { backend }
1023    }
1024
1025    #[doc(hidden)]
1026    #[must_use]
1027    pub fn backend(&self) -> &'a dyn FrameBackend {
1028        self.backend
1029    }
1030
1031    #[must_use]
1032    pub fn info(&self) -> FrameInfo {
1033        self.backend.info()
1034    }
1035
1036    #[must_use]
1037    pub fn view(&self) -> View<'a> {
1038        self.backend.view()
1039    }
1040
1041    pub fn tile_projection(&self, tile_id: TileId, transform: TileTransform) -> Result<ProjectionUbo> {
1042        self.backend.tile_projection(tile_id, transform)
1043    }
1044
1045    #[must_use]
1046    pub fn ground_height(&self, tile_id: TileId, x: f32, y: f32) -> f32 {
1047        self.backend.ground_height(tile_id, x, y)
1048    }
1049
1050    #[must_use]
1051    pub fn ground_depth_texture(&self) -> Option<Texture> {
1052        self.backend.ground_depth_texture()
1053    }
1054
1055    /// The shapes the frame's placement tested for its labels and icons, in
1056    /// the order it tested them. Empty unless a layer the frame draws reads
1057    /// them ([`Evaluation::reads_collision_shapes`]).
1058    pub fn collision_shapes(&self) -> impl ExactSizeIterator<Item = CollisionShape> + 'a {
1059        let backend = self.backend;
1060        (0..backend.collision_shape_count()).map(move |index| backend.collision_shape(index).unwrap_or_default())
1061    }
1062}
1063
1064/// Borrowed camera/projection view handle.
1065#[derive(Clone, Copy)]
1066pub struct View<'a> {
1067    backend: &'a dyn ViewBackend,
1068}
1069
1070impl<'a> View<'a> {
1071    #[doc(hidden)]
1072    #[must_use]
1073    pub fn from_backend(backend: &'a dyn ViewBackend) -> Self {
1074        Self { backend }
1075    }
1076
1077    #[must_use]
1078    pub fn info(&self) -> ViewInfo {
1079        self.backend.info()
1080    }
1081
1082    pub fn world_from_lat_lng(&self, lat_lng: LatLng) -> Result<(f64, f64)> {
1083        self.backend.world_from_lat_lng(lat_lng)
1084    }
1085
1086    pub fn lat_lng_near_center(&self, lat_lng: LatLng) -> Result<LatLng> {
1087        self.backend.lat_lng_near_center(lat_lng)
1088    }
1089
1090    #[must_use]
1091    pub fn ground_meters_per_world_unit_at(&self, lat_lng: LatLng) -> f64 {
1092        self.backend.ground_meters_per_world_unit_at(lat_lng)
1093    }
1094
1095    pub fn world_copies(&self) -> Result<Vec<i16>> {
1096        self.backend.world_copies()
1097    }
1098
1099    pub fn project_tile_point(&self, tile_id: TileId, x: f64, y: f64, elevation_m: f64) -> Result<ProjectedPoint> {
1100        self.backend.project_tile_point(tile_id, x, y, elevation_m)
1101    }
1102
1103    #[must_use]
1104    pub fn map_aligned_scale_at(&self, tile_id: TileId, x: f64, y: f64) -> f64 {
1105        self.backend.map_aligned_scale_at(tile_id, x, y)
1106    }
1107
1108    #[must_use]
1109    pub fn globe_extrude_scale(&self, tile_id: TileId) -> f32 {
1110        self.backend.globe_extrude_scale(tile_id)
1111    }
1112
1113    pub fn tile_unit_translation(&self, tile_id: TileId, translate: Vec2, anchor: Alignment) -> Result<Vec2> {
1114        self.backend.tile_unit_translation(tile_id, translate, anchor)
1115    }
1116}
1117
1118/// Borrowed GPU resource allocator valid during `create_tile_resources` and `prepare`.
1119pub struct Resources<'a> {
1120    backend: &'a mut dyn ResourcesBackend,
1121}
1122
1123impl<'a> Resources<'a> {
1124    #[doc(hidden)]
1125    #[must_use]
1126    pub fn from_backend(backend: &'a mut dyn ResourcesBackend) -> Self {
1127        Self { backend }
1128    }
1129
1130    #[doc(hidden)]
1131    #[must_use]
1132    pub fn backend_mut(&mut self) -> &mut dyn ResourcesBackend {
1133        self.backend
1134    }
1135
1136    pub fn create_program(&mut self, desc: &ProgramDesc<'_>) -> Result<Program> {
1137        self.backend.create_program(desc)
1138    }
1139
1140    pub fn create_ground_heights(&mut self) -> Result<GroundHeights> {
1141        self.backend.create_ground_heights()
1142    }
1143
1144    pub fn create_vertices(&mut self, bytes: &[u8], vertex_count: usize, stride: u32) -> Result<VertexBuffer> {
1145        self.backend.create_vertices(bytes, vertex_count, stride)
1146    }
1147
1148    pub fn create_dynamic_vertices(&mut self, bytes: &[u8], vertex_count: usize, stride: u32) -> Result<VertexBuffer> {
1149        self.backend.create_dynamic_vertices(bytes, vertex_count, stride)
1150    }
1151
1152    pub fn update_vertices(&mut self, buffer: &VertexBuffer, bytes: &[u8]) -> bool {
1153        self.backend.update_vertices(buffer, bytes)
1154    }
1155
1156    pub fn create_indexes(&mut self, indexes: &[u16]) -> Result<IndexBuffer> {
1157        self.backend.create_indexes(indexes)
1158    }
1159
1160    pub fn quad_indexes(&mut self) -> Result<IndexBuffer> {
1161        self.backend.quad_indexes()
1162    }
1163
1164    pub fn create_texture(&mut self, format: TextureFormat, sampler: SamplerState) -> Result<Texture> {
1165        self.backend.create_texture(format, sampler)
1166    }
1167
1168    pub fn write_texture(&mut self, texture: &Texture, data: &[u8], width: u32, height: u32) -> Result<()> {
1169        self.backend.write_texture(texture, data, width, height)
1170    }
1171
1172    pub fn create_target(
1173        &mut self,
1174        width: u32,
1175        height: u32,
1176        channel_type: TextureChannelType,
1177        clear_color: Color,
1178    ) -> Result<Target> {
1179        self.backend.create_target(width, height, channel_type, clear_color)
1180    }
1181
1182    pub fn create_mesh(&mut self, desc: &MeshDesc<'_>) -> Result<Mesh> {
1183        self.backend.create_mesh(desc)
1184    }
1185}
1186
1187/// Borrowed draw collector passed to [`LayerInstance::prepare`].
1188pub struct Draws<'a> {
1189    backend: &'a mut dyn DrawsBackend,
1190}
1191
1192impl<'a> Draws<'a> {
1193    #[doc(hidden)]
1194    #[must_use]
1195    pub fn from_backend(backend: &'a mut dyn DrawsBackend) -> Self {
1196        Self { backend }
1197    }
1198
1199    /// Returns the main draw group targeting the map framebuffer.
1200    #[must_use]
1201    pub fn main(&mut self) -> DrawGroup<'_> {
1202        self.backend.main()
1203    }
1204
1205    /// Returns a draw group targeting an offscreen [`Target`].
1206    #[must_use]
1207    pub fn target(&mut self, target: &Target) -> DrawGroup<'_> {
1208        self.backend.target(target)
1209    }
1210
1211    /// Schedules a raw backend GPU command lending callback ([`LayerInstance::lend`])
1212    /// for this frame at stage `at`.
1213    pub fn lend(&mut self, at: LendAt) -> Result<()> {
1214        self.backend.lend(at)
1215    }
1216}
1217
1218/// Borrowed draw group for pushing draws and uniform blocks.
1219pub struct DrawGroup<'a> {
1220    backend: &'a mut dyn DrawGroupBackend,
1221}
1222
1223impl<'a> DrawGroup<'a> {
1224    #[doc(hidden)]
1225    #[must_use]
1226    pub fn from_backend(backend: &'a mut dyn DrawGroupBackend) -> Self {
1227        Self { backend }
1228    }
1229
1230    pub fn push(&mut self, mesh: &Mesh, options: DrawOptions, blocks: &[&[u8]]) -> Result<()> {
1231        self.backend.push(mesh, options, blocks)
1232    }
1233
1234    pub fn push_at(
1235        &mut self,
1236        mesh: &Mesh,
1237        tile_id: TileId,
1238        projection: &ProjectionUbo,
1239        options: DrawOptions,
1240        blocks: &[&[u8]],
1241    ) -> Result<()> {
1242        self.backend.push_at(mesh, tile_id, projection, options, blocks)
1243    }
1244
1245    pub fn set_block(&mut self, program: &Program, buffer_name: &str, bytes: &[u8]) -> Result<()> {
1246        self.backend.set_block(program, buffer_name, bytes)
1247    }
1248
1249    pub fn set_composite(&mut self, composite: Composite) -> Result<()> {
1250        self.backend.set_composite(composite)
1251    }
1252}
1253
1254// ---------------------------------------------------------------------------
1255// AfterGpu & raw GPU lending
1256// ---------------------------------------------------------------------------
1257
1258/// Owned handle to a render session's post-GPU cleanup queue.
1259///
1260/// Clone from [`LendParameters::after_gpu`] to schedule GPU resource teardown
1261/// from [`Drop`] after in-flight GPU work finishes.
1262#[derive(Debug)]
1263pub struct AfterGpu {
1264    inner: Arc<dyn AfterGpuHandle>,
1265}
1266
1267impl AfterGpu {
1268    #[doc(hidden)]
1269    #[must_use]
1270    pub fn from_handle(inner: Arc<dyn AfterGpuHandle>) -> Self {
1271        Self { inner }
1272    }
1273
1274    /// Schedules `callback` to run once after the renderer's in-flight GPU work ends.
1275    pub fn push<F>(&self, callback: F) -> Result<()>
1276    where
1277        F: FnOnce(GpuEnd) + Send + 'static,
1278    {
1279        self.inner.push(Box::new(callback))
1280    }
1281}
1282
1283impl Clone for AfterGpu {
1284    fn clone(&self) -> Self {
1285        Self { inner: self.inner.clone_handle().unwrap_or_else(|_| Arc::clone(&self.inner)) }
1286    }
1287}
1288
1289/// Borrowed reference to a render session's post-GPU cleanup queue valid during
1290/// [`LayerInstance::lend`].
1291#[derive(Clone, Copy)]
1292pub struct AfterGpuRef<'a> {
1293    backend: &'a dyn AfterGpuRefBackend,
1294}
1295
1296impl<'a> AfterGpuRef<'a> {
1297    #[doc(hidden)]
1298    #[must_use]
1299    pub fn from_backend(backend: &'a dyn AfterGpuRefBackend) -> Self {
1300        Self { backend }
1301    }
1302
1303    /// Clones an owned [`AfterGpu`] handle that can be stored on the layer instance.
1304    pub fn clone_handle(self) -> Result<AfterGpu> {
1305        self.backend.clone_handle()
1306    }
1307
1308    /// Schedules `callback` to run once after the renderer's in-flight GPU work ends.
1309    pub fn push<F>(self, callback: F) -> Result<()>
1310    where
1311        F: FnOnce(GpuEnd) + Send + 'static,
1312    {
1313        self.backend.push(Box::new(callback))
1314    }
1315}
1316
1317/// Borrowed parameters passed to [`LayerInstance::lend`].
1318#[derive(Clone, Copy)]
1319pub struct LendParameters<'a> {
1320    at: LendAt,
1321    frame: LendFrame,
1322    stage: LendStage<'a>,
1323    after_gpu: Option<AfterGpuRef<'a>>,
1324}
1325
1326impl<'a> LendParameters<'a> {
1327    #[doc(hidden)]
1328    #[must_use]
1329    pub const fn new(at: LendAt, frame: LendFrame, stage: LendStage<'a>, after_gpu: Option<AfterGpuRef<'a>>) -> Self {
1330        Self { at, frame, stage, after_gpu }
1331    }
1332
1333    /// Returns whether this lend callback runs before passes or inside the pass.
1334    #[must_use]
1335    pub const fn at(&self) -> LendAt {
1336        self.at
1337    }
1338
1339    /// Returns the frame view, projection, and attachment dimensions.
1340    #[must_use]
1341    pub const fn frame(&self) -> &LendFrame {
1342        &self.frame
1343    }
1344
1345    /// Returns the active stage and backend-specific encoder or pass handles.
1346    #[must_use]
1347    pub const fn stage(&self) -> LendStage<'a> {
1348        self.stage
1349    }
1350
1351    /// Returns the borrowed after-GPU cleanup queue for this session, if present.
1352    #[must_use]
1353    pub const fn after_gpu(&self) -> Option<AfterGpuRef<'a>> {
1354        self.after_gpu
1355    }
1356}
1357
1358// ---------------------------------------------------------------------------
1359// Query contexts (`HitCx`, `FrameQueryCx`)
1360// ---------------------------------------------------------------------------
1361
1362/// Metadata snapshot for a tile-feature hit test ([`LayerInstance::hit`]).
1363#[derive(Clone, Debug)]
1364pub struct HitInfo<'a> {
1365    pub tile_id: TileId,
1366    pub pixels_to_tile_units: f32,
1367    pub has_ground: bool,
1368    pub query_geometry: Cow<'a, [PointI16]>,
1369    pub screen_geometry: Cow<'a, [ScreenPoint]>,
1370    pub feature_ring_count: usize,
1371}
1372
1373/// Borrowed hit-test context passed to [`LayerInstance::hit`].
1374#[derive(Clone, Copy)]
1375pub struct HitCx<'a> {
1376    backend: &'a dyn HitCxBackend,
1377}
1378
1379impl<'a> HitCx<'a> {
1380    #[doc(hidden)]
1381    #[must_use]
1382    pub fn from_backend(backend: &'a dyn HitCxBackend) -> Self {
1383        Self { backend }
1384    }
1385
1386    #[must_use]
1387    pub fn info(&self) -> HitInfo<'a> {
1388        self.backend.info()
1389    }
1390
1391    #[must_use]
1392    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
1393        self.backend.evaluated()
1394    }
1395
1396    #[must_use]
1397    pub fn view(&self) -> View<'a> {
1398        self.backend.view()
1399    }
1400
1401    #[must_use]
1402    pub fn feature_ring(&self, index: usize) -> Option<Cow<'a, [PointI16]>> {
1403        self.backend.feature_ring(index)
1404    }
1405
1406    pub fn eval_paint_f32(&self, slot: u32) -> Result<f32> {
1407        self.backend.eval_paint_f32(slot)
1408    }
1409
1410    pub fn eval_paint_bool(&self, slot: u32) -> Result<bool> {
1411        self.backend.eval_paint_bool(slot)
1412    }
1413
1414    pub fn eval_paint_color(&self, slot: u32) -> Result<Color> {
1415        self.backend.eval_paint_color(slot)
1416    }
1417
1418    pub fn eval_paint_vec2(&self, slot: u32) -> Result<Vec2> {
1419        self.backend.eval_paint_vec2(slot)
1420    }
1421
1422    pub fn eval_paint_enum(&self, slot: u32) -> Result<u32> {
1423        self.backend.eval_paint_enum(slot)
1424    }
1425
1426    pub fn eval_paint_string(&self, slot: u32) -> Result<String> {
1427        self.backend.eval_paint_string(slot)
1428    }
1429
1430    #[must_use]
1431    pub fn ground_height(&self, point: PointI16) -> f64 {
1432        self.backend.ground_height(point)
1433    }
1434
1435    pub fn translated_query_geometry(&self, translate: Vec2, anchor: Alignment) -> Result<Vec<PointI16>> {
1436        self.backend.translated_query_geometry(translate, anchor)
1437    }
1438
1439    pub fn plane_geometry(&self, elevation_m: f64, translate: Vec2, anchor: Alignment) -> Result<Vec<PointI16>> {
1440        self.backend.plane_geometry(elevation_m, translate, anchor)
1441    }
1442
1443    #[must_use]
1444    pub fn viewport_point(&self, x: f64, y: f64, elevation_m: f64) -> Option<Vec2> {
1445        self.backend.viewport_point(x, y, elevation_m)
1446    }
1447
1448    #[must_use]
1449    pub fn map_aligned_scale_at(&self, x: f64, y: f64) -> f64 {
1450        self.backend.map_aligned_scale_at(x, y)
1451    }
1452
1453    #[must_use]
1454    pub fn pitch_scaled_size(
1455        &self,
1456        size: f32,
1457        point: PointI16,
1458        elevation_m: f64,
1459        pitch_scale: Alignment,
1460        pitch_alignment: Alignment,
1461    ) -> f32 {
1462        self.backend.pitch_scaled_size(size, point, elevation_m, pitch_scale, pitch_alignment)
1463    }
1464
1465    #[must_use]
1466    pub fn shows(&self, x: f64, y: f64, elevation_m: f64) -> bool {
1467        self.backend.shows(x, y, elevation_m)
1468    }
1469}
1470
1471/// Borrowed frame-query context passed to [`LayerInstance::hit_frame`].
1472pub struct FrameQueryCx<'a> {
1473    ro: &'a dyn FrameQueryCxReadBackend,
1474    rw: &'a mut dyn FrameQueryCxMutBackend,
1475}
1476
1477impl<'a> FrameQueryCx<'a> {
1478    #[doc(hidden)]
1479    #[must_use]
1480    pub fn from_backends(ro: &'a dyn FrameQueryCxReadBackend, rw: &'a mut dyn FrameQueryCxMutBackend) -> Self {
1481        Self { ro, rw }
1482    }
1483
1484    #[must_use]
1485    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
1486        self.ro.evaluated()
1487    }
1488
1489    #[must_use]
1490    pub fn view(&self) -> View<'a> {
1491        self.ro.view()
1492    }
1493
1494    #[must_use]
1495    pub fn geometry(&self) -> Cow<'a, [ScreenPoint]> {
1496        self.ro.geometry()
1497    }
1498
1499    #[must_use]
1500    pub fn has_ground(&self) -> bool {
1501        self.ro.has_ground()
1502    }
1503
1504    #[must_use]
1505    pub fn ground_height(&self, tile_id: TileId, x: f32, y: f32) -> f32 {
1506        self.ro.ground_height(tile_id, x, y)
1507    }
1508
1509    #[must_use]
1510    pub fn ground_visibility(&self, tile_id: TileId, x: f64, y: f64, elevation_m: f64) -> f64 {
1511        self.ro.ground_visibility(tile_id, x, y, elevation_m)
1512    }
1513
1514    pub fn push_feature_json(&mut self, geojson_feature: &str) -> Result<()> {
1515        self.rw.push_feature_json(geojson_feature)
1516    }
1517
1518    pub fn push_point_feature(&mut self, position: LatLng) -> Result<()> {
1519        self.rw.push_point_feature(position)
1520    }
1521}
1522
1523// ---------------------------------------------------------------------------
1524// LayerPlugin & LayerInstance traits
1525// ---------------------------------------------------------------------------
1526
1527/// Custom style layer type implemented against the MapLibre Plugin SDK.
1528///
1529/// One `LayerPlugin` value is registered once per registry builder (either
1530/// directly in `mln_engine::RegistryBuilder::add_layer_plugin` or over the C
1531/// Plugin ABI via `mln_plugin_c::RegistryBuilder::register_layer`) and lives
1532/// for the lifetime of the registered type.
1533pub trait LayerPlugin: Send + Sync + 'static {
1534    /// Per-style-layer instance state owned on the render thread.
1535    type Instance: LayerInstance;
1536
1537    /// Returns the static layer descriptor (name, input, properties, terrain mode).
1538    fn desc(&self) -> LayerDesc<'_>;
1539
1540    /// Optional one-time initialization against `host` when this plugin is
1541    /// registered (for example, registering shader [`Program`]s with
1542    /// [`Host::create_program`]).
1543    fn init(&mut self, _host: &Host<'_>) -> Result<()> {
1544        Ok(())
1545    }
1546
1547    /// Creates per-layer render state when a style adds a layer of this type.
1548    fn create_instance(&self, evaluated: EvaluatedLayer<'_>) -> Result<Self::Instance>;
1549
1550    /// Optional tile fade-in duration in nanoseconds.
1551    fn tile_fade_ns(&self, _evaluated: EvaluatedLayer<'_>) -> u64 {
1552        0
1553    }
1554
1555    /// Optional tile-worker geometry layout hook (required for `LayerInput::GeometryTiles` layers).
1556    fn build_tile_geometry(&self, _cx: &mut TileBuildCx<'_>, _out: &mut TileGeometryBuilder<'_>) -> Result<()> {
1557        Ok(())
1558    }
1559
1560    /// Optional query padding radius in pixels for worker-built tile geometry.
1561    fn query_radius(&self, _geometry: TileGeometry<'_>, _evaluated: EvaluatedLayer<'_>) -> f32 {
1562        0.0
1563    }
1564}
1565
1566/// Per-style-layer render-thread instance for a [`LayerPlugin`].
1567pub trait LayerInstance: 'static {
1568    /// Per-tile GPU resources created in [`create_tile_resources`](Self::create_tile_resources).
1569    type TileResources: 'static;
1570
1571    /// Evaluates render passes and repaint scheduling for the current frame.
1572    fn evaluate(&mut self, cx: EvaluateCx<'_>) -> Evaluation;
1573
1574    /// Optional per-frame update hook before tile resource creation / draw preparation.
1575    fn update(&mut self, _cx: &mut UpdateCx<'_>) {}
1576
1577    /// Optional per-tile GPU resource creation hook.
1578    fn create_tile_resources(
1579        &mut self,
1580        _cx: &mut TileCx<'_>,
1581        _previous: Option<&mut Self::TileResources>,
1582    ) -> Result<Option<Self::TileResources>> {
1583        Ok(None)
1584    }
1585
1586    /// Records draw calls for the current frame.
1587    fn prepare(&mut self, _cx: &mut PrepareCx<'_, Self::TileResources>, _draws: &mut Draws<'_>) {}
1588
1589    /// Tile-feature hit test for geometry layers.
1590    fn hit(&self, _cx: HitCx<'_>) -> Hit {
1591        Hit::Miss
1592    }
1593
1594    /// Frame-level hit test for sourceless (`LayerInput::Frame`) layers.
1595    fn hit_frame(&self, _cx: &mut FrameQueryCx<'_>) {}
1596
1597    /// Records raw backend GPU commands requested via [`Draws::lend`].
1598    fn lend(&mut self, _params: &LendParameters<'_>) {}
1599}