Skip to main content

mln_engine/draw/
draws.rs

1//! A layer's draws of a frame, which the engine holds, writes, uploads and
2//! draws.
3//!
4//! Each frame, a layer pushes its draws into its [`Draws`]' main
5//! [`Group`]: each a [`Draw`] of one of its [`Mesh`]es, placed in the
6//! group's order, with how it tests depth and whether it clips to its tile,
7//! with the values of its program's blocks of each draw ([`DrawBlocks`]),
8//! and, for a draw of a tile, the tile's projection. The blocks the group's
9//! draws share go in once ([`Group::block`]), and the group may composite
10//! onto the frame as one surface ([`Group::composite`]). A layer can also
11//! push draws into textures of its own ([`Draws::target`]), which its draws
12//! of the frame sample, and have the frame lend it the backend's commands
13//! at its time in the frame ([`Draws::lend`]). The engine then
14//! sorts the draws, writes the buffers they read once for the group, with
15//! a drape's paint parameters where the frame is a drape's, uploads their
16//! meshes, places the group in the layers' order and depth, and draws it in
17//! the frame's passes, with the masks of the layer's tiles in the stencil
18//! where its draws clip. A layer sees its frame as a [`LayerFrame`]: the
19//! map's, or a drape's.
20
21use std::any::Any;
22use std::ops::Range;
23use std::rc::Rc;
24
25use mln_gfx::Size;
26use mln_gfx::cull_face_mode::CullFaceMode;
27use mln_gfx::depth_mode::DepthMode;
28use mln_gfx::gpu::Gpu;
29use mln_gfx::shaders::bindings::{BUFFER_IDS, PAINT_PARAMS_ID, PROJECTION_ID};
30use mln_gfx::shaders::block::{Block, DrawBlocks, UniformBlock};
31use mln_gfx::shaders::layer_ubo::{GlobalPaintParamsUBO, ProjectionUBO};
32use mln_gfx::shaders::program::{BufferKind, Program, Projection};
33use mln_gfx::stencil_mode::StencilMode;
34use mln_gfx::types::{CullFaceWindingType, DepthMaskType};
35
36use crate::camera::{FrameProjection, ProjectionData, View, ViewportMode};
37use crate::draw::after_gpu::AfterGpu;
38use crate::draw::context::Context;
39use crate::draw::identity::SimpleIdentity;
40use crate::draw::objects::{DrawBuffers, Mesh};
41use crate::draw::target::Target;
42use crate::render::layer_composite::Composite;
43use crate::render::light::EvaluatedLight;
44use crate::render::paint_parameters::{Composited, PaintParameters, StencilClear, TransformParameters};
45use crate::render::pass::RenderPass;
46use crate::render::terrain::FrameGround;
47use crate::tile::{OverscaledTileID, UnwrappedTileID};
48
49/// What a layer's frame draws into.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub(crate) enum DrawsInto {
52    /// The map.
53    Map,
54    /// A drape of a terrain tile, whose shading the terrain's surface adds
55    /// where `lit` ([`SurfaceLight`](crate::render::terrain::SurfaceLight)).
56    Drape { lit: bool },
57}
58
59/// The frame a layer makes its draws for, as it reads it: the camera, the
60/// target's size and scale, the light and ground, and what it draws into.
61#[derive(Clone)]
62pub struct LayerFrame<'a> {
63    pub view: &'a View,
64    pub(crate) transform_params: &'a TransformParameters,
65    /// Whether a gesture or an animation moves the camera: draws favor speed
66    /// over crispness then.
67    pub camera_moving: bool,
68    pub light: &'a EvaluatedLight,
69    pub pixel_ratio: f32,
70    pub renderable_size: Size,
71    pub pixels_to_gl_units: [f32; 2],
72    /// Whether the frame draws terrain, under which 2D layers draw without
73    /// depth.
74    pub terrain: bool,
75    /// Whether a group drawn as a whole ([`Group::composite`]) can draw
76    /// with the frame's depth and stencil: the frame has them, and a pass can
77    /// draw into them together with the layer composite's texture.
78    pub composites_with_frame_depth: bool,
79    /// The ground that the layers that stand on terrain stand on, where the
80    /// frame has terrain and such layers.
81    pub ground: Option<Rc<FrameGround>>,
82    pub(crate) into: DrawsInto,
83}
84
85impl LayerFrame<'_> {
86    /// The frame's camera.
87    #[must_use]
88    pub fn view(&self) -> &View {
89        self.view
90    }
91
92    /// The device pixels of the frame's target per logical pixel.
93    #[must_use]
94    pub fn pixel_ratio(&self) -> f32 {
95        self.pixel_ratio
96    }
97
98    /// The size of the frame's target, in device pixels.
99    #[must_use]
100    pub fn size(&self) -> Size {
101        self.renderable_size
102    }
103
104    /// Whether the frame is a drape whose shading the terrain's surface
105    /// adds: a hillshade draws its slopes there, unlit.
106    #[must_use]
107    pub fn drape_lit(&self) -> bool {
108        matches!(self.into, DrawsInto::Drape { lit: true })
109    }
110
111    /// See `TransformParameters::projection_data_for_tile`.
112    #[must_use]
113    pub fn projection_data_for_tile(&self, tile_id: &UnwrappedTileID, aligned: bool) -> ProjectionData {
114        self.transform_params.projection_data_for_tile(tile_id, aligned)
115    }
116
117    /// Culling of the faces turned away from the camera, whose triangles
118    /// wind clockwise on screen, or counterclockwise where a viewport
119    /// flipped upside down turns every triangle round. The globe's
120    /// projection draws the right way up in either mode.
121    #[must_use]
122    pub fn cull_back_faces(&self) -> CullFaceMode {
123        let turned = self.view.viewport_mode() == ViewportMode::FlippedY && !self.view.is_globe();
124        let winding = if turned { CullFaceWindingType::Clockwise } else { CullFaceWindingType::CounterClockwise };
125        CullFaceMode { winding, ..CullFaceMode::back_ccw() }
126    }
127}
128
129/// How a draw tests and writes depth.
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub enum Depth {
132    /// It draws without a depth test.
133    Off,
134    /// It tests the depth of a sub-layer of the layer's depth, and writes it
135    /// as `mask` says.
136    Layer { sub_layer: u8, mask: DepthMaskType },
137    /// It tests the depth range of 3D geometry, which the 3D draws of all
138    /// layers share, and writes it as `mask` says.
139    Volume { mask: DepthMaskType },
140}
141
142/// How a draw of a mesh draws: its place among its group's draws, its pass,
143/// its depth and whether it clips.
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub struct Draw {
146    /// Where the draw is among its group's draws: lower orders draw first,
147    /// and draws of one order in the order they were pushed. A layer that
148    /// draws its meshes in the order they were made gives each draw its
149    /// mesh's [`seq`](Mesh::seq).
150    pub order: i64,
151    /// Whether the draw may draw in the opaque pass, where its layer draws
152    /// there, rather than in the translucent pass. It draws in one of the
153    /// two.
154    pub opaque: bool,
155    pub depth: Depth,
156    /// Whether the draw clips: a draw at the layer's depth to the mask of
157    /// its tile ([`Group::push_at`]), a 3D one to where none of the group's
158    /// 3D draws of the pass drew before it, so no pixel blends twice. A
159    /// group with a draw that clips draws the masks of its layer's tiles.
160    pub clip: bool,
161}
162
163impl Draw {
164    /// A draw of order 0 in the translucent pass that tests, and doesn't
165    /// write, the nearest depth of its layer, and doesn't clip.
166    pub const DEFAULT: Draw = Draw {
167        order: 0,
168        opaque: false,
169        depth: Depth::Layer { sub_layer: 0, mask: DepthMaskType::ReadOnly },
170        clip: false,
171    };
172
173    /// The passes the draw draws in.
174    fn passes(self) -> RenderPass {
175        if self.opaque { RenderPass::Opaque | RenderPass::Translucent } else { RenderPass::Translucent }
176    }
177}
178
179impl Default for Draw {
180    fn default() -> Self {
181        Draw::DEFAULT
182    }
183}
184
185/// One of a group's draws as the engine draws it. Its uniform values are
186/// the entries at its index in the storage buffers of its group.
187struct GroupDraw {
188    mesh: Mesh,
189    /// The tile whose mask it clips to.
190    tile: Option<OverscaledTileID>,
191    pass: RenderPass,
192    depth: Depth,
193    clip: bool,
194}
195
196/// Where a program's blocks of each draw are in the bytes a draw was pushed
197/// with, by the ids of their buffers: each block with its offset.
198struct ProgramBlocks {
199    program: &'static Program,
200    at: [Option<(usize, &'static Block)>; BUFFER_IDS],
201    /// Whether one of the draws whose buffers a write writes draws with it.
202    drawn: bool,
203}
204
205impl ProgramBlocks {
206    fn of(program: &'static Program) -> ProgramBlocks {
207        let mut at = [None; BUFFER_IDS];
208        let mut offset = 0;
209        for buffer in program.buffers {
210            if let BufferKind::Storage { block, .. } | BufferKind::DrawUniform(block) = buffer.kind {
211                at[buffer.id] = Some((offset, block));
212                offset += block.size;
213            }
214        }
215        ProgramBlocks { program, at, drawn: false }
216    }
217}
218
219/// A draw as it was pushed: the index of its program's blocks, its
220/// projection, and where its blocks start in the pushes' bytes.
221struct Pushed {
222    program: usize,
223    projection: ProjectionUBO,
224    blocks: usize,
225}
226
227/// A frame's draws as a layer pushed them, by the index it pushed them at,
228/// with the bytes of their blocks and of the blocks they share, which the
229/// engine writes to the buffers of the group's draws.
230#[derive(Default)]
231struct Pushes {
232    pushed: Vec<Pushed>,
233    /// The bytes of the pushed draws' blocks.
234    bytes: Vec<u8>,
235    /// The blocks of each draw of the pushed draws' programs.
236    programs: Vec<ProgramBlocks>,
237    /// The blocks the draws share, each its layout and where its bytes are
238    /// in `shared_bytes`.
239    shared: Vec<(&'static Block, Range<usize>)>,
240    shared_bytes: Vec<u8>,
241    /// Where a write of one of the draws' buffers gathers its bytes.
242    scratch: Vec<u8>,
243}
244
245/// Whether `a` and `b` are the layout of one block.
246fn same_block(a: &Block, b: &Block) -> bool {
247    std::ptr::eq(a, b) || a.name == b.name
248}
249
250impl Pushes {
251    fn clear(&mut self) {
252        self.pushed.clear();
253        self.bytes.clear();
254        self.shared.clear();
255        self.shared_bytes.clear();
256    }
257
258    /// Adds a draw of `program` with `projection`, whose blocks, of the
259    /// layouts `layouts`, are the pushes' bytes from `start`.
260    fn push(
261        &mut self,
262        program: &'static Program,
263        projection: Option<&ProjectionUBO>,
264        start: usize,
265        layouts: &'static [&'static Block],
266    ) {
267        debug_assert!(
268            program
269                .buffers
270                .iter()
271                .filter_map(|buffer| match buffer.kind {
272                    BufferKind::Storage { block, .. } | BufferKind::DrawUniform(block) => Some(block),
273                    _ => None,
274                })
275                .map(|block| block.name)
276                .eq(layouts.iter().map(|block| block.name)),
277            "a draw of {} pushed with blocks other than its program's of each draw",
278            program.name
279        );
280        debug_assert!(program.projection != Projection::Own, "a draw of {} with a projection of its own", program.name);
281        let index = self.programs.iter().position(|of| std::ptr::eq(of.program, program)).unwrap_or_else(|| {
282            self.programs.push(ProgramBlocks::of(program));
283            self.programs.len() - 1
284        });
285        self.pushed.push(Pushed { program: index, projection: projection.copied().unwrap_or_default(), blocks: start });
286    }
287
288    /// Makes `bytes` the value of the shared block of the layout `layout`.
289    fn block(&mut self, layout: &'static Block, bytes: &[u8]) {
290        if let Some((_, range)) = self.shared.iter().find(|(given, _)| same_block(given, layout)) {
291            self.shared_bytes[range.clone()].copy_from_slice(bytes);
292        } else {
293            let start = self.shared_bytes.len();
294            self.shared_bytes.extend_from_slice(bytes);
295            self.shared.push((layout, start..self.shared_bytes.len()));
296        }
297    }
298
299    /// Writes to `buffers` the buffers that the pushed draws at `order`'s
300    /// indexes, in drawing order, read: at the id of each of their
301    /// programs' uniform blocks, the block of its layout that they share; at
302    /// the id of each storage buffer of an element per draw, each draw's
303    /// block, or zeros for a draw whose program reads none there; at the id
304    /// of a uniform block of a draw's own, which one draw reads, its block;
305    /// the draws' projections, or a projection of zeros where none reads
306    /// one, which every program declares; and the frame's paint parameters,
307    /// `paint_params`, where it has its own.
308    fn write(
309        &mut self,
310        gpu: &mut dyn Gpu,
311        context: &mut Context,
312        order: &[(i64, usize)],
313        paint_params: Option<&GlobalPaintParamsUBO>,
314        buffers: &mut DrawBuffers,
315    ) {
316        let Pushes { pushed, bytes, programs, shared, shared_bytes, scratch } = self;
317        for of in programs.iter_mut() {
318            of.drawn = false;
319        }
320        for &(_, index) in order {
321            programs[pushed[index].program].drawn = true;
322        }
323        let mut written = [false; BUFFER_IDS];
324        let (mut per_draw_projection, mut reads_paint_params) = (false, false);
325        for of in programs.iter().filter(|of| of.drawn) {
326            per_draw_projection |= of.program.projection == Projection::PerDraw;
327            reads_paint_params |= of.program.paint_params.is_some();
328        }
329        // The shared blocks first, then the draws': a backend joins writes
330        // to buffers next to each other into one copy, and the shared
331        // blocks' buffers, whose size doesn't change, stay where the first
332        // frame made them, before the draws' buffers.
333        let shared_first = programs.iter().filter(|of| of.drawn).flat_map(|of| {
334            let shared = of.program.buffers.iter().filter(|buffer| matches!(buffer.kind, BufferKind::Uniform(_)));
335            shared.map(move |buffer| (of, buffer))
336        });
337        let per_draw = programs.iter().filter(|of| of.drawn).flat_map(|of| {
338            let per_draw = of.program.buffers.iter().filter(|buffer| !matches!(buffer.kind, BufferKind::Uniform(_)));
339            per_draw.map(move |buffer| (of, buffer))
340        });
341        for (of, buffer) in shared_first.chain(per_draw) {
342            // A mesh binds its vertices read as storage buffers.
343            if matches!(buffer.kind, BufferKind::Vertices(_)) || std::mem::replace(&mut written[buffer.id], true) {
344                continue;
345            }
346            match buffer.kind {
347                BufferKind::Uniform(block) => {
348                    let Some((_, range)) = shared.iter().find(|(given, _)| same_block(given, block)) else {
349                        debug_assert!(false, "draws of {} without their uniform block {}", of.program.name, block.name);
350                        continue;
351                    };
352                    buffers.write_uniform(gpu, buffer.id, &shared_bytes[range.clone()], context.device());
353                }
354                BufferKind::Storage { stride, .. } => {
355                    scratch.clear();
356                    for &(_, index) in order {
357                        let Pushed { program, blocks, .. } = pushed[index];
358                        let end = scratch.len() + stride;
359                        if let Some((offset, block)) = programs[program].at[buffer.id] {
360                            let at = blocks + offset;
361                            scratch.extend_from_slice(&bytes[at..at + block.size]);
362                        }
363                        scratch.resize(end, 0);
364                    }
365                    buffers.write_storage(gpu, buffer.id, scratch, context.device());
366                }
367                BufferKind::DrawUniform(block) => {
368                    let mut own = order.iter().map(|&(_, index)| &pushed[index]).filter(|draw| {
369                        programs[draw.program].at[buffer.id].is_some_and(|(_, of)| same_block(of, block))
370                    });
371                    let Some(&Pushed { program, blocks, .. }) = own.next() else { continue };
372                    debug_assert!(own.next().is_none(), "two draws of a block of {}'s own", block.name);
373                    if let Some((offset, _)) = programs[program].at[buffer.id] {
374                        let at = blocks + offset;
375                        buffers.write_uniform(gpu, buffer.id, &bytes[at..at + block.size], context.device());
376                    }
377                }
378                BufferKind::Vertices(_) => {}
379            }
380        }
381        if per_draw_projection {
382            scratch.clear();
383            for &(_, index) in order {
384                scratch.extend_from_slice(bytemuck::bytes_of(&pushed[index].projection));
385            }
386            buffers.write_storage(gpu, PROJECTION_ID, scratch, context.device());
387        } else if buffers.get(PROJECTION_ID).is_none() {
388            // GL's programs declare the block whether they read it or not,
389            // so a draw binds it all the same.
390            let none = ProjectionUBO::default();
391            buffers.write_storage(gpu, PROJECTION_ID, bytemuck::bytes_of(&none), context.device());
392        }
393        if let Some(paint_params) = paint_params.filter(|_| reads_paint_params) {
394            buffers.write_pod(gpu, PAINT_PARAMS_ID, paint_params, context.device());
395        }
396    }
397}
398
399/// A layer's draws of a frame in one place in the layers' order and depth,
400/// which the engine writes, uploads and draws in each of the frame's
401/// passes, and what they share.
402pub struct Group {
403    /// Tells the group apart in the layer composite.
404    id: SimpleIdentity,
405    /// The draws, in their order. A draw's index is the index of its
406    /// entries in the storage buffers, which shaders read as `globalIndex`.
407    draws: Vec<GroupDraw>,
408    /// The buffers the draws bind, by id, and the bindings of the meshes
409    /// they draw.
410    buffers: DrawBuffers,
411    /// How the draws composite onto the frame in the translucent pass, as one
412    /// surface, after they draw into a texture of their own; `None` where
413    /// they draw straight onto the frame.
414    composite: Option<Composite>,
415    /// The tiles whose masks the stencil buffer holds when the draws draw:
416    /// none where no draw clips.
417    stencil_tiles: Vec<UnwrappedTileID>,
418    /// The draws pushed for the next frame, by the index they were pushed
419    /// at, until [`finish`](Self::finish) makes them the frame's.
420    pending: Vec<Option<GroupDraw>>,
421    /// The pushed draws' orders, each with the draw's index in `pending`.
422    order: Vec<(i64, usize)>,
423    pushes: Pushes,
424}
425
426impl Default for Group {
427    /// No draws, with an id of their own.
428    fn default() -> Self {
429        Group {
430            id: SimpleIdentity::new(),
431            draws: Vec::new(),
432            buffers: DrawBuffers::default(),
433            composite: None,
434            stencil_tiles: Vec::new(),
435            pending: Vec::new(),
436            order: Vec::new(),
437            pushes: Pushes::default(),
438        }
439    }
440}
441
442impl Group {
443    /// Adds a draw of `mesh`, not of a tile, to the next frame's, with
444    /// `blocks`, the values of the draw's own of the blocks of each draw
445    /// that the mesh's program reads, in its order. The draw's projection,
446    /// where its program reads one, is zeros.
447    pub fn push<B: DrawBlocks>(&mut self, mesh: &Mesh, draw: Draw, blocks: B) -> &mut Self {
448        self.add(mesh, None, None, draw, blocks)
449    }
450
451    /// Adds a draw of `mesh` of the tile `tile` with `projection`, as
452    /// [`push`](Self::push) does: the draw reads `projection` where its
453    /// program reads a projection of each draw, and clips to `tile` where it
454    /// clips.
455    pub fn push_at<B: DrawBlocks>(
456        &mut self,
457        mesh: &Mesh,
458        tile: OverscaledTileID,
459        projection: &ProjectionUBO,
460        draw: Draw,
461        blocks: B,
462    ) -> &mut Self {
463        self.add(mesh, Some(tile), Some(projection), draw, blocks)
464    }
465
466    fn add<B: DrawBlocks>(
467        &mut self,
468        mesh: &Mesh,
469        tile: Option<OverscaledTileID>,
470        projection: Option<&ProjectionUBO>,
471        draw: Draw,
472        blocks: B,
473    ) -> &mut Self {
474        debug_assert!(
475            !draw.clip || tile.is_some() || matches!(draw.depth, Depth::Volume { .. }),
476            "a draw that clips without a tile"
477        );
478        let start = self.pushes.bytes.len();
479        blocks.each_bytes(|block| self.pushes.bytes.extend_from_slice(block));
480        self.pushes.push(mesh.program(), projection, start, B::BLOCKS);
481        self.order.push((draw.order, self.pending.len()));
482        self.pending.push(Some(GroupDraw {
483            mesh: mesh.clone(),
484            tile,
485            pass: draw.passes(),
486            depth: draw.depth,
487            clip: draw.clip,
488        }));
489        self
490    }
491
492    /// Makes `block` the value that the next frame's draws read of their
493    /// programs' uniform block of its layout, the last given. A draw whose
494    /// program has none ignores it.
495    pub fn block<T: UniformBlock>(&mut self, block: &T) -> &mut Self {
496        self.pushes.block(T::BLOCK, bytemuck::bytes_of(block));
497        self
498    }
499
500    /// Makes the draws composite onto the frame as `composite` says, or
501    /// draw straight onto it for `None`.
502    pub fn composite(&mut self, composite: Option<Composite>) -> &mut Self {
503        self.composite = composite;
504        self
505    }
506
507    /// Drops the draws, those pushed too, and the bindings of the meshes
508    /// that dropped.
509    pub(crate) fn clear(&mut self) {
510        self.draws.clear();
511        self.clear_pushed();
512        self.buffers.sweep();
513    }
514
515    fn clear_pushed(&mut self) {
516        self.pending.clear();
517        self.order.clear();
518        self.pushes.clear();
519    }
520
521    /// Makes the pushed draws the frame's, in their order and in the order
522    /// they were pushed among draws of the same order. Where there are any,
523    /// it first writes the buffers they read, with `paint_params` where the
524    /// frame has paint parameters of its own (a drape's). Where a draw
525    /// clips, the group clips to the masks of `tiles`.
526    pub(crate) fn finish(
527        &mut self,
528        gpu: &mut dyn Gpu,
529        context: &mut Context,
530        paint_params: Option<&GlobalPaintParamsUBO>,
531        tiles: impl IntoIterator<Item = UnwrappedTileID>,
532    ) {
533        self.order.sort_unstable();
534        if !self.order.is_empty() {
535            self.pushes.write(gpu, context, &self.order, paint_params, &mut self.buffers);
536        }
537        let Group { draws, pending, order, stencil_tiles, .. } = self;
538        draws.clear();
539        draws.extend(order.iter().filter_map(|&(_, index)| pending[index].take()));
540        stencil_tiles.clear();
541        if draws.iter().any(|draw| draw.clip) {
542            stencil_tiles.extend(tiles);
543        }
544        self.buffers.sweep();
545        self.clear_pushed();
546    }
547
548    /// The tiles whose masks the stencil buffer holds when the group draws;
549    /// `None` for a group that needs no masks.
550    #[must_use]
551    pub(crate) fn stencil_tiles(&self) -> Option<&[UnwrappedTileID]> {
552        Some(&self.stencil_tiles[..]).filter(|tiles| !tiles.is_empty())
553    }
554
555    /// Whether the group draws anything.
556    #[must_use]
557    pub(crate) fn draws(&self) -> bool {
558        !self.draws.is_empty()
559    }
560
561    /// How the draws composite onto the frame, with the id that tells them
562    /// apart in the layer composite, if there are any and they composite.
563    #[must_use]
564    pub(crate) fn composited(&self) -> Option<(SimpleIdentity, Composite)> {
565        self.composite.filter(|_| !self.draws.is_empty()).map(|composite| (self.id, composite))
566    }
567
568    /// The meshes of the draws, in drawing order.
569    #[cfg(test)]
570    pub(crate) fn meshes(&self) -> impl Iterator<Item = &Mesh> {
571        self.draws.iter().map(|draw| &draw.mesh)
572    }
573
574    /// Uploads the meshes of the draws, in drawing order.
575    pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
576        for draw in &self.draws {
577            draw.mesh.upload(gpu, context);
578        }
579    }
580
581    /// Draws the draws of `parameters`' pass into the open pass of `gpu`,
582    /// the context's: into the layer composite's texture in the translucent
583    /// pass where they composite, and onto the frame otherwise. Where none
584    /// of the pass's draws is 3D, this first draws the masks of the tiles
585    /// that those that clip clip to; 3D draws that clip share one stencil
586    /// value of their own. Returns whether no draw failed.
587    pub(crate) fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) -> bool {
588        if self.draws.is_empty() || parameters.pass_target().is_none() {
589            return true;
590        }
591        let composited = (self.composite.is_some() && parameters.pass == RenderPass::Translucent)
592            .then(|| parameters.begin_composited(gpu, self.id))
593            .flatten();
594        let drawing = composited.as_ref().is_none_or(Composited::draws);
595        let draws = if drawing { &self.draws[..] } else { &[] };
596        // A draw for both the opaque and the translucent pass draws in one:
597        // the opaque where its layer draws there, and the translucent
598        // otherwise. Drawn in both, it would cover itself.
599        let both = RenderPass::Opaque | RenderPass::Translucent;
600        let drawn_in =
601            if parameters.opaque_pass_enabled_for_layer() { RenderPass::Opaque } else { RenderPass::Translucent };
602        let pass = parameters.pass;
603        let skip = if pass & both != RenderPass::None && pass != drawn_in { both } else { RenderPass::None };
604        let in_pass = |draw: &&GroupDraw| {
605            draw.pass & pass != RenderPass::None && (skip == RenderPass::None || draw.pass & skip != skip)
606        };
607        let (volume, volume_clips) =
608            draws.iter().filter(in_pass).fold((false, false), |(volume, clips), draw| match draw.depth {
609                Depth::Volume { .. } => (true, clips || draw.clip),
610                _ => (volume, clips),
611            });
612        let mut volume_stencil = None;
613        if volume {
614            volume_stencil = volume_clips.then(|| parameters.stencil_mode_for_3d(gpu));
615        } else if drawing && !self.stencil_tiles.is_empty() {
616            parameters.render_tile_clipping_masks(gpu, &self.stencil_tiles);
617        }
618        let mut drawn = true;
619        for (index, draw) in draws.iter().enumerate().filter(|(_, draw)| in_pass(draw)) {
620            let tile_stencil = || match draw.tile.filter(|_| draw.clip) {
621                Some(tile) => parameters.stencil_mode_for_clipping(&tile.to_unwrapped()),
622                None => StencilMode::disabled(),
623            };
624            let (depth, stencil) = match draw.depth {
625                Depth::Off => (DepthMode::disabled(), tile_stencil()),
626                Depth::Layer { sub_layer, mask } => {
627                    (parameters.depth_mode_for_sublayer(sub_layer, mask), tile_stencil())
628                }
629                Depth::Volume { mask } => (
630                    parameters.depth_mode_for_3d(mask),
631                    volume_stencil.filter(|_| draw.clip).unwrap_or_else(StencilMode::disabled),
632                ),
633            };
634            let Some(mut objects) = parameters.context.take_mesh(&draw.mesh) else {
635                debug_assert!(false, "a draw of a mesh the context doesn't have");
636                continue;
637            };
638            drawn &= objects.draw(gpu, parameters, &mut self.buffers, depth, stencil, index as u32);
639            parameters.context.put_mesh(&draw.mesh, objects);
640        }
641        if let Some(composited) = composited {
642            parameters.end_composited(gpu, composited);
643        }
644        drawn
645    }
646}
647
648/// When a frame lends a layer the backend's commands ([`Draws::lend`]).
649#[derive(Clone, Copy, Debug, PartialEq, Eq)]
650pub enum LendAt {
651    /// Before the frame's passes, after the layer drew into its targets
652    /// ([`Draws::target`]): the frame's commands outside a pass.
653    BeforePasses,
654    /// In the frame's translucent pass, at the layer's place in the layers'
655    /// order and depth, after the layer's draws there: the open pass.
656    Pass,
657}
658
659/// What a frame lends a layer
660/// ([`Layer::lend`](crate::layer::Layer::lend)).
661pub struct Lent<'a> {
662    /// The backend's commands, as its `Gpu` lends them
663    /// ([`Gpu::lend`]): before the passes `mln_vulkan::CustomLayerEncoder`,
664    /// `mln_mtl::CustomLayerEncoder`, `mln_gl::CustomLayerEncoder`,
665    /// `mln_webgpu::CustomLayerEncoder` or `mln_d3d12::CustomLayerEncoder`,
666    /// and in a pass the same crate's `CustomLayerPass`, whose docs say what
667    /// the layer may change.
668    pub raw: &'a mut dyn Any,
669    /// The frame.
670    pub frame: &'a LayerFrame<'a>,
671    /// Where the frame draws the map, and the depth it writes there.
672    pub projection: &'a FrameProjection,
673    /// The depth that the frame's 2D layers write at the layer's place in
674    /// the layers' order, in a pass; `None` before the passes.
675    pub layer_depth: Option<f64>,
676    /// Where the layer queues what waits for the GPU to finish what it
677    /// drew with the commands, such as the freeing of what it made with
678    /// them. A clone stays usable for as long as the layer.
679    pub after_gpu: &'a AfterGpu,
680}
681
682/// A layer's draws of a frame, the map's or a drape's, which the engine
683/// keeps between frames: its main group, which takes a place in the layers'
684/// order and depth from the first frame that the layer has something to
685/// draw in, even with no draws; a group of draws into each target of the
686/// layer's that the frame draws into ([`target`](Self::target)); and where
687/// the frame lends the layer the backend's commands ([`lend`](Self::lend)).
688#[derive(Default)]
689pub struct Draws {
690    main: Group,
691    /// The groups of the draws into the layer's targets, each with its
692    /// target: the frame's, in the order the layer first pushed into them,
693    /// then those of the last frame that the frame hasn't drawn into yet,
694    /// which keep their buffers for it until the draws are written.
695    targets: Vec<(Target, Group)>,
696    /// How many of `targets` are the frame's.
697    frame_targets: usize,
698    /// Whether the frame lends the layer the backend's commands, at each
699    /// [`LendAt`].
700    lends: [bool; 2],
701    /// Whether a frame started the draws, from which the main group takes
702    /// its place.
703    started: bool,
704}
705
706impl Draws {
707    /// The layer's main group, which draws in its place in the layers' order
708    /// and depth.
709    pub fn main(&mut self) -> &mut Group {
710        &mut self.main
711    }
712
713    /// The group of the frame's draws into `target`, a target of the
714    /// layer's own. Once the frame's draws are written, the engine clears
715    /// the target and draws the group into it, before the frame's passes
716    /// or, in a drape, the drape's: in the opaque pass and then the
717    /// translucent one, without depth from the frame, and without clipping
718    /// to tiles. A target the frame asks for draws, cleared, even without
719    /// draws. The frame's draws sample what it drew.
720    pub fn target(&mut self, target: &Target) -> &mut Group {
721        let frame = self.frame_targets;
722        let at = match self.targets.iter().position(|(given, _)| given == target) {
723            Some(at) if at < frame => return &mut self.targets[at].1,
724            Some(at) => at,
725            None => {
726                self.targets.push((target.clone(), Group::default()));
727                self.targets.len() - 1
728            }
729        };
730        self.targets.swap(at, frame);
731        self.frame_targets += 1;
732        &mut self.targets[frame].1
733    }
734
735    /// Makes the frame lend the layer the backend's commands `at` its time
736    /// in the frame
737    /// ([`Layer::lend`](crate::layer::Layer::lend)).
738    pub fn lend(&mut self, at: LendAt) -> &mut Self {
739        self.lends[at as usize] = true;
740        self
741    }
742
743    /// Whether the frame lends the layer the backend's commands `at` its
744    /// time in the frame.
745    #[must_use]
746    pub(crate) fn lends(&self, at: LendAt) -> bool {
747        self.lends[at as usize]
748    }
749
750    /// Starts the draws of a frame the layer has something to draw in: none
751    /// yet, and the main group from now on takes its place.
752    pub(crate) fn begin(&mut self) {
753        self.started = true;
754        self.reset();
755    }
756
757    /// Drops the frame's draws, and the groups of the draws into targets.
758    /// The main group keeps its place.
759    pub(crate) fn clear(&mut self) {
760        self.reset();
761        self.targets.clear();
762    }
763
764    /// Drops the frame's draws and lends.
765    fn reset(&mut self) {
766        for (_, group) in &mut self.targets {
767            group.clear();
768        }
769        self.frame_targets = 0;
770        self.lends = [false; 2];
771        self.main.clear();
772    }
773
774    /// See [`Group::finish`], for every group: the draws into the frame's
775    /// targets, which don't clip, first, whose targets then hold what the
776    /// draws draw ([`Context::declare_target`]). The groups of the targets
777    /// the frame doesn't draw into go.
778    pub(crate) fn finish(
779        &mut self,
780        gpu: &mut dyn Gpu,
781        context: &mut Context,
782        paint_params: Option<&GlobalPaintParamsUBO>,
783        tiles: impl IntoIterator<Item = UnwrappedTileID>,
784    ) {
785        self.finish_targets(gpu, context, paint_params);
786        self.main.finish(gpu, context, paint_params, tiles);
787    }
788
789    /// The targets' part of [`finish`](Self::finish), which doesn't depend
790    /// on the type of the tiles.
791    fn finish_targets(
792        &mut self,
793        gpu: &mut dyn Gpu,
794        context: &mut Context,
795        paint_params: Option<&GlobalPaintParamsUBO>,
796    ) {
797        self.targets.truncate(self.frame_targets);
798        for (target, group) in &mut self.targets {
799            debug_assert!(group.composite.is_none(), "draws into a target that composite");
800            group.finish(gpu, context, paint_params, []);
801            context.declare_target(target);
802        }
803    }
804
805    /// Visits the groups that take a place in the layers' order and depth,
806    /// in drawing order.
807    pub(crate) fn visit_groups<'a>(&'a self, visit: &mut dyn FnMut(&'a Group)) {
808        if self.started {
809            visit(&self.main);
810        }
811    }
812
813    /// Uploads the meshes of the groups' draws: those into the frame's
814    /// targets, then the main group's.
815    pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
816        if self.started {
817            for (_, group) in &self.targets[..self.frame_targets] {
818                group.upload(gpu, context);
819            }
820            self.main.upload(gpu, context);
821        }
822    }
823
824    /// Clears each of the frame's targets and draws the draws into it
825    /// ([`Target::render`]), outside any pass of `gpu`, the context's.
826    pub(crate) fn render_targets(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
827        for (target, group) in &mut self.targets[..self.frame_targets] {
828            target.render(gpu, parameters, |gpu, parameters| group.render(gpu, parameters));
829        }
830    }
831
832    /// Draws the pass's draws of the groups into the open pass of `gpu`,
833    /// the context's, each at its depth, in `order`; `in_pass`, if any, runs
834    /// where the main group draws, after it, before the depth steps on.
835    pub(crate) fn render(
836        &mut self,
837        gpu: &mut dyn Gpu,
838        parameters: &mut PaintParameters<'_>,
839        order: DrawOrder,
840        in_pass: Option<&mut InPass<'_>>,
841    ) {
842        if self.started {
843            self.main.render(gpu, parameters);
844            if let Some(in_pass) = in_pass {
845                in_pass(gpu, parameters);
846            }
847            order.step(parameters);
848        }
849    }
850}
851
852impl Draws {
853    /// Moves `parameters` past the depth that [`render`](Self::render)
854    /// would draw the groups at, in `order`, without drawing them.
855    pub(crate) fn skip(&self, parameters: &mut PaintParameters<'_>, order: DrawOrder) {
856        if self.started {
857            order.step(parameters);
858        }
859    }
860}
861
862/// What [`Draws::render`] runs where the main group draws, in the open pass.
863pub(crate) type InPass<'a> = dyn FnMut(&mut dyn Gpu, &mut PaintParameters<'_>) + 'a;
864
865/// One mesh and a frame's draw of it, with the buffers it binds: a draw of
866/// the engine's own.
867pub(crate) struct SingleDraw {
868    pub(crate) mesh: Mesh,
869    /// How the draw draws.
870    draw: Draw,
871    group: Group,
872}
873
874impl SingleDraw {
875    /// A draw of `mesh`, as `draw` draws, which draws once its blocks are
876    /// written ([`write`](Self::write)).
877    #[must_use]
878    pub(crate) fn new(mesh: Mesh, draw: Draw) -> SingleDraw {
879        SingleDraw { mesh, draw, group: Group::default() }
880    }
881
882    /// Makes `block` the value the draw reads of its program's uniform
883    /// block of its layout, as [`Group::block`] does, from the next
884    /// [`write`](Self::write).
885    pub(crate) fn block<T: UniformBlock>(&mut self, block: &T) -> &mut Self {
886        self.group.block(block);
887        self
888    }
889
890    /// Writes the buffers the draw reads, with `blocks`, its values of its
891    /// program's blocks of each draw, as [`Group::finish`] does.
892    pub(crate) fn write<B: DrawBlocks>(&mut self, gpu: &mut dyn Gpu, context: &mut Context, blocks: B) {
893        let SingleDraw { mesh, draw, group } = self;
894        group.push(mesh, *draw, blocks);
895        group.finish(gpu, context, None, []);
896    }
897
898    /// Uploads the mesh, if the draw's blocks were written.
899    pub(crate) fn upload(&self, gpu: &mut dyn Gpu, context: &mut Context) {
900        self.group.upload(gpu, context);
901    }
902
903    /// Draws the draw, if it draws in the pass, into the open pass of `gpu`,
904    /// the context's. Returns whether it didn't fail.
905    pub(crate) fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) -> bool {
906        self.group.render(gpu, parameters)
907    }
908}
909
910/// What a frame's groups, or a drape's, need of the passes: their number,
911/// which sets the passes' depth range; the masks of the tiles they clip to
912/// and of the tiles that clear the stencil buffer; and the groups drawn as
913/// a whole, each into the layer composite's texture and then onto the
914/// frame.
915#[derive(Default)]
916pub(crate) struct DrawGroups {
917    pub(crate) count: usize,
918    pub(crate) clip_tiles: Vec<UnwrappedTileID>,
919    /// The tiles whose masks clear the stencil buffer, also in
920    /// `clip_tiles` ([`PaintParameters::stencil_clear_tiles`]).
921    pub(crate) stencil_clear: StencilClear,
922    pub(crate) composited: Vec<(SimpleIdentity, Composite)>,
923}
924
925impl DrawGroups {
926    /// The groups that `visit_groups` visits, in drawing order, of passes
927    /// whose stencil the tiles that `stencil_clear_tiles` gives for the
928    /// tiles they clip to clear ([`PaintParameters::stencil_clear_tiles`]).
929    /// Groups of one source clip to the same tiles, which are added once.
930    pub(crate) fn of<'a>(
931        visit_groups: impl FnOnce(&mut dyn FnMut(&'a Group)),
932        stencil_clear_tiles: impl FnOnce(&[UnwrappedTileID]) -> StencilClear,
933    ) -> DrawGroups {
934        let mut groups = DrawGroups::default();
935        let mut last: Option<&[UnwrappedTileID]> = None;
936        visit_groups(&mut |group| {
937            groups.count += 1;
938            if let Some(tiles) = group.stencil_tiles()
939                && last.is_none_or(|last| last != tiles)
940            {
941                groups.clip_tiles.extend(tiles.iter().copied());
942                last = Some(tiles);
943            }
944            groups.composited.extend(group.composited());
945        });
946        groups.stencil_clear = stencil_clear_tiles(&groups.clip_tiles);
947        groups.clip_tiles.extend_from_slice(&groups.stencil_clear);
948        if !groups.clip_tiles.is_sorted() {
949            groups.clip_tiles.sort_unstable();
950        }
951        groups.clip_tiles.dedup();
952        groups
953    }
954
955    /// The depth range of the passes' 3D draws, from 0, below the depths of
956    /// the groups' 2D draws.
957    #[must_use]
958    pub(crate) fn depth_range_size(&self) -> f32 {
959        depth_range_size(self.count)
960    }
961}
962
963/// The depth range of the 3D draws of passes of `groups` draw groups, from
964/// 0, below the depths of the groups' 2D draws.
965#[must_use]
966pub(crate) fn depth_range_size(groups: usize) -> f32 {
967    1.0 - ((groups + 2) * PaintParameters::NUM_SUBLAYERS as usize) as f32 * PaintParameters::DEPTH_EPSILON
968}
969
970/// The order the frame draws the layers' groups in, each at the depth of
971/// [`PaintParameters::current_layer`], which [`DrawOrder::step`] moves to
972/// the next group's.
973#[derive(Clone, Copy, Debug, PartialEq, Eq)]
974pub enum DrawOrder {
975    /// The layers' order, bottom to top, with the depth going down by one
976    /// after each group, to 0.
977    BottomUp,
978    /// The reverse order, top to bottom, with the depth going up by one
979    /// after each group.
980    TopDown,
981}
982
983impl DrawOrder {
984    /// Moves `parameters` to the depth of the group after the one it is at.
985    pub(crate) fn step(self, parameters: &mut PaintParameters<'_>) {
986        match self {
987            DrawOrder::BottomUp => parameters.current_layer = parameters.current_layer.saturating_sub(1),
988            DrawOrder::TopDown => parameters.current_layer += 1,
989        }
990    }
991}