Skip to main content

mln_engine/render/
renderer.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use mln_gfx::gpu::{ColorAttachment, DepthStencilAttachment, Gpu, LoadOp, TargetFormats};
5use mln_gfx::rendering_stats::{RenderingStats, TerrainStats};
6use mln_gfx::shaders::bindings::PAINT_PARAMS_ID;
7use mln_gfx::{FrameImage, Handoff, Rgba, ScissorRect};
8use mln_style::color::Color;
9use mln_style::error::Error;
10use mln_style::time::Instant;
11
12use crate::camera::FrameProjection;
13use crate::draw::context::Context;
14use crate::draw::draws::{DrawGroups, DrawOrder};
15use crate::exec::event_queue::Waker;
16use crate::exec::pool::Pool;
17use crate::render::clip_masks::ClipMasks;
18use crate::render::events::{RenderMode, RendererEvent, RendererEvents};
19use crate::render::frame::Frame;
20use crate::render::frame_projection;
21use crate::render::layer_composite::LayerComposite;
22use crate::render::orchestrator::RenderOrchestrator;
23use crate::render::paint_parameters::{OpenPass, PaintParameters};
24use crate::render::pass::RenderPass;
25use crate::render::update_parameters::UpdateParameters;
26use crate::text::GlyphCache;
27use crate::text::local_fonts::LocalGlyphs;
28use crate::worker::worker_codec::RemoteWorkers;
29use crate::{Registry, log_target};
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32enum RenderState {
33    Never,
34    Partial,
35    Fully,
36}
37
38/// What the last frame that [`Renderer::render`] drew spent on
39/// each of its steps, on the CPU, from its [update](Renderer::update) on.
40/// They follow each other, and together take nearly all of `update` and
41/// `render`.
42#[derive(Clone, Copy, Debug, Default, PartialEq)]
43pub struct RenderTimings {
44    /// The update up to symbol placement: the style's changes, the layers'
45    /// values, the sources' tiles and the layers' choice of them.
46    pub(crate) sources: Duration,
47    /// The rest of the update: placing symbols across tiles and updating
48    /// their buckets.
49    pub(crate) symbols: Duration,
50    /// Making the layers' draws from the tiles, with their uniforms.
51    pub(crate) layers: Duration,
52    /// Making the shaders when there are none, and uploading buffers and
53    /// textures.
54    pub(crate) upload: Duration,
55    /// Encoding the render passes and submitting them.
56    pub(crate) draw: Duration,
57}
58
59/// Draws a map's updates into the frames of one backend's [`Gpu`]: it keeps
60/// the map's sources, tiles and layers between frames, and the GPU objects
61/// they draw with.
62///
63/// The renderer holds no `Gpu`. Each call that makes, draws or frees its GPU
64/// objects takes the one it was made for, which its host lends it, as it
65/// does to the target that the renderer draws into. A frame runs in the
66/// host, with one `Gpu` lent to all of it:
67///
68/// ```ignore
69/// let frame = renderer.update(gpu, &update)?;
70/// let image = target.begin_frame(gpu)?;
71/// let drawn = renderer.render(gpu, &image, frame);
72/// let handoff = target.end_frame(gpu);
73/// renderer.finish_frame(gpu, drawn, handoff);
74/// ```
75///
76/// [`tear_down`](Self::tear_down) frees the renderer's GPU objects. A
77/// renderer dropped without it leaves them to the `Gpu`, which frees them
78/// when it drops, and runs the work after the GPU that its layers queued as
79/// lost ([`GpuEnd::Lost`](crate::draw::GpuEnd::Lost)).
80pub struct Renderer {
81    orchestrator: RenderOrchestrator,
82    encoder: Encoder,
83    /// Where the renderer reports its events, once the host gives it one.
84    events: Option<RendererEvents>,
85}
86
87/// A frame that [`Renderer::update`] brought the renderer's state to, for
88/// [`Renderer::render`] to draw.
89#[must_use = "an updated frame is drawn"]
90pub struct UpdatedFrame {
91    frame: Frame,
92    parameters: Arc<UpdateParameters>,
93    updated: Instant,
94}
95
96/// A frame that [`Renderer::render`] drew, for
97/// [`Renderer::finish_frame`] once the target handed it off.
98#[must_use = "a drawn frame is finished once its target handed it off"]
99pub struct DrawnFrame {
100    /// Why the frame failed on the GPU, if it did.
101    error: Option<Error>,
102    mode: RenderMode,
103    needs_repaint: bool,
104    /// When the frame's placement wants the next frame, if it does.
105    repaint_at: Option<Instant>,
106    placement_changed: bool,
107    /// The `still_image_request_id` of a still image's frame, or 0.
108    still_image_request_id: u64,
109    /// The `update_id` of the update the frame drew.
110    update_id: u64,
111    started: Instant,
112    symbols_started: Instant,
113    updated: Instant,
114    layers_uploaded: Instant,
115    start_rendering: Instant,
116}
117
118/// What the renderer keeps for its frames' encodes: its GPU state, the
119/// shaders, the passes' masks and composite, and what the last frame drew.
120struct Encoder {
121    /// What the renderer keeps over the backend's `Gpu`, which the
122    /// tear-down destroys after what the other fields hold.
123    context: Context,
124    pixel_ratio: f32,
125    /// Kept across frames; dropped in the tear-down.
126    clip_masks: ClipMasks,
127    /// What layers drawn as a whole draw into and composite with, between
128    /// frames.
129    layer_composite: LayerComposite,
130    /// Whether the context's shaders and pipelines are of an earlier pixel
131    /// ratio, which the next update's render layers no
132    /// longer draw with.
133    shaders_replaced: bool,
134    render_state: RenderState,
135    /// Where the last frame drew the map.
136    frame_projection: Option<FrameProjection>,
137    timings: RenderTimings,
138}
139
140impl DrawnFrame {
141    /// Why the frame failed on the GPU, if it did. Its image then lacks what
142    /// failed, or holds nothing.
143    #[must_use]
144    pub fn error(&self) -> Option<&Error> {
145        self.error.as_ref()
146    }
147}
148
149impl Renderer {
150    /// A renderer with a glyph cache of its own, as
151    /// [`with_glyph_cache`](Self::with_glyph_cache) makes.
152    #[cfg(test)]
153    pub(crate) fn new(
154        gpu: &dyn Gpu,
155        pixel_ratio: f32,
156        local_glyphs: LocalGlyphs,
157        registry: Arc<Registry>,
158        waker: Waker,
159        pool: &Pool,
160    ) -> Self {
161        Self::with_glyph_cache(gpu, pixel_ratio, local_glyphs, Arc::default(), registry, waker, pool)
162    }
163
164    /// A renderer that uses `glyph_cache`, which draws the layer and
165    /// source types of `registry`, runs its background work on `pool` and
166    /// draws `local_glyphs`. Its chooser of the device's
167    /// fonts runs there too, one choice at a time, never on the thread that
168    /// calls the renderer.
169    ///
170    /// `waker` runs, on any thread, when something the renderer waits for
171    /// arrives, such as a tile's data or a font engine that got ready: the
172    /// host asks the renderer's map for an update for it, as by pushing
173    /// [`RendererEvent::Invalidate`] to the queue the renderer reports to
174    /// ([`set_event_queue`](Self::set_event_queue)). It must not call the
175    /// renderer.
176    ///
177    /// The renderer draws with `gpu` and only with it: every later call
178    /// that takes a `Gpu` takes this one.
179    ///
180    /// The map that the renderer draws must have a registry filled by the
181    /// same calls as `registry`: a layer whose type `registry` lacks isn't
182    /// drawn. Renderers given the same `GlyphCache` share the glyphs they
183    /// parse from glyph PBFs.
184    pub fn with_glyph_cache(
185        gpu: &dyn Gpu,
186        pixel_ratio: f32,
187        local_glyphs: LocalGlyphs,
188        glyph_cache: Arc<GlyphCache>,
189        registry: Arc<Registry>,
190        waker: Waker,
191        pool: &Pool,
192    ) -> Self {
193        let engine = crate::text::font_face_engine::default_engine();
194        Self::with_fonts(gpu, pixel_ratio, local_glyphs, glyph_cache, engine, registry, waker, pool)
195    }
196
197    /// A renderer that uses `glyph_cache`, loads the font files of a style's
198    /// font faces with `font_face_engine` instead of
199    /// `font_face_engine::default_engine()`.
200    #[expect(clippy::too_many_arguments, reason = "each argument is a part of the renderer that its host picks")]
201    pub fn with_fonts(
202        gpu: &dyn Gpu,
203        pixel_ratio: f32,
204        local_glyphs: LocalGlyphs,
205        glyph_cache: Arc<GlyphCache>,
206        font_face_engine: Arc<dyn crate::text::font_face_engine::FontFaceEngine>,
207        registry: Arc<Registry>,
208        waker: Waker,
209        pool: &Pool,
210    ) -> Self {
211        Renderer {
212            orchestrator: RenderOrchestrator::new(
213                true,
214                local_glyphs,
215                glyph_cache,
216                font_face_engine,
217                registry,
218                waker,
219                pool,
220            ),
221            encoder: Encoder {
222                context: Context::new(*gpu.caps(), pixel_ratio),
223                pixel_ratio,
224                clip_masks: ClipMasks::default(),
225                layer_composite: LayerComposite::default(),
226                shaders_replaced: false,
227                render_state: RenderState::Never,
228                frame_projection: None,
229                timings: RenderTimings::default(),
230            },
231            events: None,
232        }
233    }
234
235    /// Draws at `pixel_ratio` device pixels per logical pixel from the next
236    /// frame on, which should be the map's (`Map::set_pixel_ratio`). The
237    /// renderer makes its shaders and draws again, frees the ones they
238    /// replace, and keeps its tiles. The host sizes the backend's
239    /// framebuffer for the new ratio.
240    pub fn set_pixel_ratio(&mut self, pixel_ratio: f32) {
241        if pixel_ratio == self.encoder.pixel_ratio {
242            return;
243        }
244        // The shaders build the pixel ratio in on some backends, so a new
245        // ratio takes new shaders, and new draws that use them.
246        self.replace_shaders(pixel_ratio);
247    }
248
249    /// Compiles the shaders at `pixel_ratio` from the next update on. The render layers' draws go with
250    /// that update, which makes the layers again, and the old shaders after
251    /// it.
252    fn replace_shaders(&mut self, pixel_ratio: f32) {
253        let encoder = &mut self.encoder;
254        encoder.pixel_ratio = pixel_ratio;
255        encoder.context.set_program_parameters(pixel_ratio);
256        encoder.clip_masks = ClipMasks::default();
257        encoder.layer_composite = LayerComposite::default();
258        encoder.shaders_replaced = true;
259        self.orchestrator.release_shaders();
260    }
261
262    /// Runs the tiles' jobs, and the raster tiles' workers, in
263    /// `workers` (by default on the renderer's pool). Set it before the
264    /// first render so that every tile uses it.
265    pub fn set_tile_workers(&mut self, workers: RemoteWorkers) {
266        self.orchestrator.set_tile_workers(workers);
267    }
268
269    /// Takes in what arrived for the tiles since the last frame (their data,
270    /// their jobs' replies, glyphs) and starts the jobs it makes ready. Each
271    /// frame does this first; a host that draws frames on a clock calls it
272    /// as soon as the renderer asks for an update, so that the tiles' work
273    /// doesn't wait for the next frame to start.
274    pub fn receive_tiles(&mut self) {
275        self.orchestrator.receive_tiles();
276        report(&mut self.orchestrator, self.events.as_ref());
277    }
278
279    /// Sets the queue the renderer pushes its events to: the map's, which
280    /// the map's frontend passes on.
281    pub fn set_event_queue(&mut self, events: Option<RendererEvents>) {
282        self.events = events;
283    }
284
285    /// Brings the renderer's state to `update_parameters`: its style,
286    /// sources, tiles, layers and placement. Returns the frame to draw,
287    /// which the host [renders](Self::render) into a frame of its target,
288    /// or `None` when there is nothing to draw: a still image that hasn't
289    /// loaded yet. The work after the GPU that layers queued
290    /// ([`AfterGpu`](crate::draw::AfterGpu)) runs once `gpu` finished.
291    pub fn update(&mut self, gpu: &mut dyn Gpu, update_parameters: &Arc<UpdateParameters>) -> Option<UpdatedFrame> {
292        let orchestrator = &mut self.orchestrator;
293        // Whether terrain draws depends on whether the backend has its shader.
294        orchestrator.terrain().make_shader(gpu, &mut self.encoder.context, update_parameters);
295        let frame = orchestrator.update(update_parameters);
296        report(orchestrator, self.events.as_ref());
297        let encoder = &mut self.encoder;
298        encoder.context.after_gpu().finish(gpu);
299        if std::mem::take(&mut encoder.shaders_replaced) {
300            encoder.context.release_shaders();
301        }
302        let frame = frame?;
303        Some(UpdatedFrame { frame, parameters: Arc::clone(update_parameters), updated: Instant::now() })
304    }
305
306    /// Draws `frame`, which the last [`update`](Self::update) returned, into
307    /// `image`, textures of `gpu` that the host's target began a frame with,
308    /// and submits the frame's passes. Returns the frame, which the host
309    /// ends on its target, whether or not it failed ([`DrawnFrame::error`]),
310    /// and then [finishes](Self::finish_frame).
311    pub fn render(&mut self, gpu: &mut dyn Gpu, image: &FrameImage, frame: UpdatedFrame) -> DrawnFrame {
312        self.encoder.encode(gpu, &mut self.orchestrator, self.events.as_ref(), image, frame)
313    }
314
315    /// Ends `frame`, which [`render`](Self::render) drew, once the host's
316    /// target handed it off as `handoff`: destroys what the frame replaced
317    /// and reports the frame with its rendering stats, and with its error
318    /// if it failed.
319    pub fn finish_frame(&mut self, gpu: &mut dyn Gpu, frame: DrawnFrame, handoff: Handoff) {
320        self.encoder.finish(gpu, self.events.as_ref(), frame, handoff);
321    }
322
323    /// The terrain of the frames it draws.
324    #[cfg(test)]
325    pub(crate) fn terrain(&mut self) -> &crate::render::terrain::RenderTerrain {
326        self.orchestrator.terrain()
327    }
328
329    /// Drops `value` on the renderer's workers instead of this
330    /// thread, for data that would take a frame long to free, such as the
331    /// sources of an earlier update. The renderer's drop waits for it.
332    pub fn drop_on_workers<T: Send + 'static>(&self, value: T) {
333        self.orchestrator.drop_on_workers(value);
334    }
335
336    /// Where the last frame that [`render`](Self::render) drew put the map,
337    /// or `None` before the first.
338    #[must_use]
339    pub fn frame_projection(&self) -> Option<FrameProjection> {
340        self.encoder.frame_projection
341    }
342
343    /// The features drawn in `geometry`, a point or a polygon in screen
344    /// coordinates. `Err` for a malformed tile.
345    pub fn query_rendered_features(
346        &mut self,
347        geometry: &[crate::geo::ScreenCoordinate],
348        options: &crate::query::RenderedQueryOptions,
349    ) -> Result<Vec<crate::tile::feature::Feature>, Error> {
350        let features = self.orchestrator.query_rendered_features(geometry, options);
351        report(&mut self.orchestrator, self.events.as_ref());
352        features
353    }
354
355    pub fn query_rendered_features_at_point(
356        &mut self,
357        point: &crate::geo::ScreenCoordinate,
358        options: &crate::query::RenderedQueryOptions,
359    ) -> Result<Vec<crate::tile::feature::Feature>, Error> {
360        self.query_rendered_features(&[*point], options)
361    }
362
363    pub fn query_rendered_features_in_box(
364        &mut self,
365        min: &crate::geo::ScreenCoordinate,
366        max: &crate::geo::ScreenCoordinate,
367        options: &crate::query::RenderedQueryOptions,
368    ) -> Result<Vec<crate::tile::feature::Feature>, Error> {
369        use crate::geo::ScreenCoordinate;
370        self.query_rendered_features(
371            &[*min, ScreenCoordinate::new(max.x, min.y), *max, ScreenCoordinate::new(min.x, max.y), *min],
372            options,
373        )
374    }
375
376    pub fn query_source_features(
377        &mut self,
378        source_id: &str,
379        options: &crate::query::SourceQueryOptions,
380    ) -> Result<Vec<crate::tile::feature::Feature>, Error> {
381        let features = self.orchestrator.query_source_features(source_id, options);
382        report(&mut self.orchestrator, self.events.as_ref());
383        features
384    }
385
386    /// Queries a feature extension: for a GeoJSON source with `cluster` on,
387    /// the "supercluster" extension's "children", "leaves" or
388    /// "expansion-zoom" of a cluster feature (one with a `cluster_id`
389    /// property). Anything else is a null value. `Err` for a cluster ID the
390    /// source doesn't have.
391    pub fn query_feature_extensions(
392        &self,
393        source_id: &str,
394        feature: &crate::tile::feature::Feature,
395        extension: &str,
396        extension_field: &str,
397        args: Option<&mln_style::feature::PropertyMap>,
398    ) -> Result<crate::query::FeatureExtensionValue, Error> {
399        self.orchestrator.query_feature_extensions(source_id, feature, extension, extension_field, args)
400    }
401
402    /// The data of the symbols the last placement placed, when
403    /// [`collect_placed_symbol_data`](Self::collect_placed_symbol_data)
404    /// turned their collection on.
405    #[must_use]
406    pub fn placed_symbols_data(&self) -> Vec<crate::placement::PlacedSymbolData> {
407        self.orchestrator.placed_symbols_data()
408    }
409
410    /// Logs every render source's tiles and the image manager's state.
411    pub fn dump_debug_logs(&self) {
412        self.orchestrator.dump_debug_logs();
413    }
414
415    /// Merges `state` into a feature's state.
416    ///
417    /// An update whose feature state for the source differs from the last
418    /// update's replaces the source's state with the update's, undoing what
419    /// this and [`remove_feature_state`](Self::remove_feature_state) did. A
420    /// renderer that a map drives takes its state from the map's
421    /// `set_feature_state`.
422    pub fn set_feature_state(
423        &mut self,
424        source_id: &str,
425        source_layer_id: Option<&str>,
426        feature_id: &str,
427        state: &mln_style::feature::FeatureState,
428    ) {
429        self.orchestrator.set_feature_state(source_id, source_layer_id, feature_id, state);
430    }
431
432    /// The state of a feature.
433    #[must_use]
434    pub fn feature_state(
435        &self,
436        source_id: &str,
437        source_layer_id: Option<&str>,
438        feature_id: &str,
439    ) -> mln_style::feature::FeatureState {
440        self.orchestrator.feature_state(source_id, source_layer_id, feature_id)
441    }
442
443    /// Removes a key of a feature's state, a feature's whole state, or a
444    /// source layer's. An update replaces the source's state as it does for
445    /// [`set_feature_state`](Self::set_feature_state).
446    pub fn remove_feature_state(
447        &mut self,
448        source_id: &str,
449        source_layer_id: Option<&str>,
450        feature_id: Option<&str>,
451        state_key: Option<&str>,
452    ) {
453        self.orchestrator.remove_feature_state(source_id, source_layer_id, feature_id, state_key);
454    }
455
456    pub fn collect_placed_symbol_data(&mut self, enable: bool) {
457        self.orchestrator.collect_placed_symbol_data(enable);
458    }
459
460    pub fn set_tile_cache_enabled(&mut self, enable: bool) {
461        self.orchestrator.set_tile_cache_enabled(enable);
462    }
463
464    /// Whether the renderer keeps tiles that left the view, to show them
465    /// again without loading them.
466    #[must_use]
467    pub fn tile_cache_enabled(&self) -> bool {
468        self.orchestrator.tile_cache_enabled()
469    }
470
471    /// Drops every layer, and runs the work after the GPU as lost
472    /// ([`GpuEnd::Lost`](crate::draw::GpuEnd::Lost)). Call it only before
473    /// the renderer goes, when its device or target went first: the
474    /// renderer's other GPU objects stay those of the lost device.
475    pub fn lose_context(&mut self) {
476        self.orchestrator.leave_layers();
477        self.encoder.context.after_gpu().lose();
478    }
479
480    /// Lets go of what the orchestrator caches, destroys what it and the
481    /// renderer released, and waits for `gpu`, so that its work finishes
482    /// before the app goes to the background.
483    pub fn reduce_memory_use(&mut self, gpu: &mut dyn Gpu) {
484        self.orchestrator.reduce_memory_use();
485        self.encoder.context.destroy_released(gpu);
486        if let Err(error) = gpu.flush(true) {
487            log::error!(target: log_target::RENDER, "Waiting for the GPU failed: {error}");
488        }
489        report(&mut self.orchestrator, self.events.as_ref());
490    }
491
492    /// The rendering stats, which count the renderer's resources until it
493    /// destroys them: a buffer or texture counts until the end of the frame
494    /// that follows its release, or until
495    /// [`reduce_memory_use`](Self::reduce_memory_use).
496    #[must_use]
497    pub fn rendering_stats(&self) -> RenderingStats {
498        self.encoder.context.stats()
499    }
500
501    /// Lets go of the map's data: its sources, tiles and layers, which the
502    /// next update loads again. The work after the GPU runs once `gpu`
503    /// finished.
504    pub fn clear_data(&mut self, gpu: &mut dyn Gpu) {
505        self.orchestrator.clear_data();
506        self.encoder.context.after_gpu().finish(gpu);
507        report(&mut self.orchestrator, self.events.as_ref());
508    }
509
510    /// Destroys the renderer's GPU objects on `gpu`, and runs the work after
511    /// the GPU once `gpu` finished. Returns its rendering stats as it leaves
512    /// them, with all its resources released.
513    pub fn tear_down(self, gpu: &mut dyn Gpu) -> RenderingStats {
514        let Renderer { mut orchestrator, mut encoder, .. } = self;
515        // The layers' GPU objects go to the context's queue, and their work
516        // after the GPU to its queue.
517        orchestrator.leave_layers();
518        drop(orchestrator);
519        encoder.clip_masks = ClipMasks::default();
520        encoder.layer_composite = LayerComposite::default();
521        encoder.context.tear_down(gpu);
522        encoder.context.after_gpu().finish(gpu);
523        encoder.context.stats()
524    }
525}
526
527impl Encoder {
528    /// The second phase of a frame: builds and refreshes the GPU objects of
529    /// the layers' draws of `frame` on `gpu`, draws them into `image` and
530    /// submits them. It reads the style, the sources, the tiles each layer
531    /// draws and the placement as the update left them, and changes only
532    /// what draws them on the GPU: the atlases' textures, the tiles'
533    /// buckets, which it uploads and binds to the atlases' textures, the
534    /// layers' drawing and the renderer's GPU state.
535    ///
536    /// It uploads the atlases and the tiles' buckets; then the draw update
537    /// makes the layers' draws of the frame, the draw upload uploads what
538    /// they bind, and the draw section encodes the passes and submits them.
539    fn encode(
540        &mut self,
541        gpu: &mut dyn Gpu,
542        orchestrator: &mut RenderOrchestrator,
543        events: Option<&RendererEvents>,
544        image: &FrameImage,
545        frame: UpdatedFrame,
546    ) -> DrawnFrame {
547        let UpdatedFrame { frame, parameters: update_parameters, updated } = frame;
548        let start = Instant::now();
549        {
550            let stats = self.context.rendering_stats();
551            stats.num_draw_calls = 0;
552            stats.terrain = TerrainStats::default();
553            stats.num_frames += 1;
554        }
555
556        if self.render_state == RenderState::Never {
557            emit(events, RendererEvent::RenderMapStarted);
558        }
559        emit(events, RendererEvent::RenderFrameStarted);
560
561        let state = &frame.transform.view;
562        let renderable_size = image.size;
563        let frustum_offset = state.frustum_offset();
564        let pixel_ratio = f64::from(self.pixel_ratio);
565        let scissor_rect = ScissorRect {
566            x: (frustum_offset.left * pixel_ratio) as i32,
567            y: (frustum_offset.top * pixel_ratio) as i32,
568            width: renderable_size
569                .width
570                .wrapping_sub(((frustum_offset.left + frustum_offset.right) * pixel_ratio) as u32),
571            height: renderable_size
572                .height
573                .wrapping_sub(((frustum_offset.top + frustum_offset.bottom) * pixel_ratio) as u32),
574        };
575
576        let composites_with_frame_depth =
577            image.depth_stencil.is_some_and(|texture| gpu.attaches_with_any_color(texture));
578        let mut parameters = PaintParameters::new(
579            &mut self.context,
580            &mut self.clip_masks,
581            &mut self.layer_composite,
582            composites_with_frame_depth,
583            &frame,
584            self.pixel_ratio,
585            renderable_size,
586            scissor_rect,
587        );
588
589        // - UPLOAD --------------------------------------------------------
590        // The tiles' atlas first, whose textures the tiles bind, then the
591        // tiles' buckets.
592        orchestrator.upload_atlas(gpu, parameters.context);
593        orchestrator.upload_sources(parameters.context);
594
595        // - DRAW UPDATE ---------------------------------------------------
596        // The layers' draws of the frame.
597        let uploaded = Instant::now();
598        orchestrator.update_layer_draws(gpu, &update_parameters, &mut parameters, &frame);
599        let layers_updated = Instant::now();
600
601        // What the frame's update and draw update replaced goes before the
602        // uploads make what replaces it.
603        parameters.context.destroy_released(gpu);
604
605        // - DRAW UPLOAD ---------------------------------------------------
606        orchestrator.upload_draws(gpu, parameters.context);
607        let draw_groups = DrawGroups::of(
608            |visit| orchestrator.visit_draw_groups(visit),
609            |tiles| parameters.stencil_clear_tiles(tiles),
610        );
611        parameters.stencil_clear.clone_from(&draw_groups.stencil_clear);
612        parameters.opaque_pass_cutoff = orchestrator.opaque_pass_cutoff();
613        let (proj_state, transform) = (parameters.view, parameters.transform_params);
614        parameters.clip_masks.update(gpu, parameters.context, proj_state.is_globe(), &draw_groups.clip_tiles, |tile| {
615            (transform.projection_data_for_tile(tile, false)).ubo()
616        });
617        orchestrator.terrain().upload_drapes(gpu, &mut parameters);
618        parameters.layer_composite.update(
619            gpu,
620            parameters.context,
621            image.size,
622            image.targets.color,
623            &draw_groups.composited,
624        );
625        let global_paint_params_ubo = parameters.global_paint_params();
626        parameters.context.write_global_uniform_buffer(gpu, PAINT_PARAMS_ID, &global_paint_params_ubo);
627        // What the uploads replaced goes before the passes make what
628        // replaces it, such as a draw's geometry.
629        parameters.context.destroy_released(gpu);
630        let layers_uploaded = Instant::now();
631
632        // - DRAW ----------------------------------------------------------
633        // The 3D layers draw into depth from 0 to the passes' depth range
634        // size, which the draw groups' count sets, and the layers that the
635        // frame lends its commands draw with the projection that the frame's
636        // result reports.
637        let depth_range_size = draw_groups.depth_range_size();
638        let clip_depth = parameters.context.caps().clip_depth;
639        let frame_projection = frame_projection::compute(&frame.transform, depth_range_size, clip_depth, frame.terrain);
640        parameters.lent_projection = Some(frame_projection);
641        draw(orchestrator, gpu, &mut parameters, &frame, image, draw_groups.count, depth_range_size);
642        orchestrator.terrain().count(parameters.context);
643        let start_rendering = Instant::now();
644        let submitted = parameters.end_pass(gpu).and_then(|()| gpu.flush(false));
645        if let Err(error) = &submitted {
646            parameters.context.fail(format!("Submitting the frame failed: {error}"));
647        }
648        // A target that a frame that failed drew may hold nothing.
649        parameters.context.end_targets(submitted.is_ok());
650        let error = parameters.context.device().take_failure().map(Error::native);
651        drop(parameters);
652        // A drape of a frame that failed may lack what failed: every drape
653        // draws again in the next frame.
654        if error.is_some() {
655            orchestrator.terrain().redraw_drapes();
656        }
657
658        self.timings.layers = layers_updated - uploaded;
659        self.timings.upload = (uploaded - start) + (layers_uploaded - layers_updated);
660        self.frame_projection = Some(frame_projection);
661        DrawnFrame {
662            mode: if frame.loaded { RenderMode::Full } else { RenderMode::Partial },
663            error,
664            needs_repaint: frame.needs_repaint,
665            repaint_at: frame.repaint_at,
666            placement_changed: frame.placement_changed,
667            still_image_request_id: if update_parameters.still_image_request {
668                update_parameters.still_image_request_id
669            } else {
670                0
671            },
672            update_id: update_parameters.update_id,
673            started: frame.started,
674            symbols_started: frame.symbols_started,
675            updated,
676            layers_uploaded,
677            start_rendering,
678        }
679    }
680
681    /// The end of a frame that [`encode`](Self::encode) drew, once its
682    /// target handed it off as `handoff`: destroys what the uploads and the
683    /// passes replaced, and reports the frame with the rendering stats.
684    fn finish(&mut self, gpu: &mut dyn Gpu, events: Option<&RendererEvents>, frame: DrawnFrame, handoff: Handoff) {
685        let DrawnFrame {
686            error,
687            mode,
688            needs_repaint,
689            repaint_at,
690            placement_changed,
691            still_image_request_id,
692            update_id,
693            started,
694            symbols_started,
695            updated,
696            layers_uploaded,
697            start_rendering,
698        } = frame;
699        let submitted = Instant::now();
700        let context = &mut self.context;
701        {
702            let stats = context.rendering_stats();
703            // The frame read back counts as a framebuffer, as an offscreen
704            // texture does.
705            stats.num_frame_buffers = i32::from(handoff == Handoff::ReadBack);
706            stats.rendering_time = (submitted - start_rendering).as_secs_f64();
707        }
708        // What the uploads and the passes replaced.
709        context.destroy_released(gpu);
710        {
711            let stats = context.rendering_stats();
712            stats.encoding_time = started.elapsed().as_secs_f64() - stats.rendering_time;
713        }
714        let stats = Arc::new(context.stats());
715
716        self.timings.sources = symbols_started - started;
717        self.timings.symbols = updated - symbols_started;
718        self.timings.draw = submitted - layers_uploaded;
719
720        emit(
721            events,
722            RendererEvent::RenderFrameFinished {
723                mode,
724                needs_repaint,
725                repaint_at,
726                placement_changed,
727                still_image_request_id,
728                update_id,
729                stats,
730                error: error.map(Box::new),
731            },
732        );
733
734        if mode == RenderMode::Partial {
735            self.render_state = RenderState::Partial;
736        } else if self.render_state != RenderState::Fully {
737            self.render_state = RenderState::Fully;
738            emit(events, RendererEvent::RenderMapFinished);
739        }
740    }
741}
742
743/// The draw section of a frame's encode: encodes the passes of `frame` into
744/// `image` through `gpu`, which holds the frame's work until it is
745/// submitted, each pass drawing the `num_draw_groups` draw groups at depths
746/// below `depth_range_size`.
747fn draw(
748    orchestrator: &mut RenderOrchestrator,
749    gpu: &mut dyn Gpu,
750    parameters: &mut PaintParameters<'_>,
751    frame: &Frame,
752    image: &FrameImage,
753    num_draw_groups: usize,
754    depth_range_size: f32,
755) {
756    // The ground's depth, which the layers that stand on terrain hide
757    // behind, in a pass of its own.
758    parameters.pass = RenderPass::Translucent;
759    parameters.depth_range_size = depth_range_size;
760    orchestrator.terrain().render_ground(gpu, parameters);
761
762    // The layers' targets and the shared targets, which the passes sample,
763    // and what the layers do with the frame's commands before its passes;
764    // then the terrain's drapes, each after its layers' targets.
765    orchestrator.before_passes(gpu, parameters);
766    orchestrator.terrain().render_drapes(gpu, parameters);
767
768    // The frame's pass, cleared to the backdrop, which shows where there are
769    // no tiles.
770    let Color { r, g, b, a, .. } = frame.background_color;
771    let color = Rgba::new(r, g, b, a);
772    let pass = OpenPass {
773        label: "main buffer",
774        color: Some(ColorAttachment {
775            texture: parameters.layer_composite.frame_texture().unwrap_or(image.color),
776            load: LoadOp::Clear(color),
777        }),
778        depth_stencil: image.depth_stencil.map(|texture| DepthStencilAttachment {
779            texture,
780            depth: LoadOp::Clear(1.0),
781            stencil: LoadOp::Clear(0),
782        }),
783        size: image.size,
784        targets: image.targets,
785    };
786    if let Err(error) = parameters.begin_pass(gpu, pass) {
787        parameters.context.fail(format!("Beginning the frame's pass failed: {error}"));
788    }
789
790    // The sky.
791    if let Some(sky) = orchestrator.sky() {
792        parameters.pass = RenderPass::Translucent;
793        parameters.depth_range_size = depth_range_size;
794        parameters.current_layer = num_draw_groups as u32 + 1;
795        sky.render(gpu, parameters);
796    }
797
798    // The opaque pass: front to back with the depth buffer, except on the
799    // globe, where 2D layers carry no depth and are painted bottom to top.
800    parameters.pass = RenderPass::Opaque;
801    parameters.depth_range_size = depth_range_size;
802    if frame.transform.view.is_globe() {
803        parameters.current_layer = (num_draw_groups as u32).wrapping_sub(1);
804        orchestrator.render_draw_groups(gpu, parameters, DrawOrder::BottomUp);
805    } else {
806        parameters.current_layer = 0;
807        orchestrator.render_draw_groups(gpu, parameters, DrawOrder::TopDown);
808    }
809
810    // The translucent pass. The planet goes into the depth buffer first, so
811    // 3D geometry behind the horizon stays hidden. Over terrain, each stack
812    // of draped layers draws its surface where its first layer draws, and
813    // the surface's depth goes first where a 3D layer draws before that.
814    parameters.pass = RenderPass::Translucent;
815    parameters.depth_range_size = depth_range_size;
816    orchestrator.globe_depth().render(gpu, parameters);
817    orchestrator.terrain().render_depth(gpu, parameters);
818    parameters.current_layer = (num_draw_groups as u32).wrapping_sub(1);
819    orchestrator.render_draw_groups(gpu, parameters, DrawOrder::BottomUp);
820
821    // The atmosphere.
822    if let Some(atmosphere) = orchestrator.atmosphere() {
823        parameters.pass = RenderPass::Translucent;
824        parameters.depth_range_size = depth_range_size;
825        parameters.current_layer = num_draw_groups as u32 + 1;
826        atmosphere.render(gpu, parameters);
827    }
828
829    // The frame, where it drew into the layer composite's texture, copied
830    // into the target.
831    let present = OpenPass {
832        label: "main buffer",
833        color: Some(ColorAttachment { texture: image.color, load: LoadOp::Clear(Rgba::new(0.0, 0.0, 0.0, 0.0)) }),
834        depth_stencil: None,
835        size: image.size,
836        targets: TargetFormats { color: image.targets.color, depth_stencil: None },
837    };
838    if let Err(error) = parameters.present_frame(gpu, present) {
839        parameters.context.fail(format!("Copying the frame into its target failed: {error}"));
840    }
841}
842
843/// Pushes what `orchestrator` reported since the last call to `events`, the
844/// renderer's event queue, or drops it when there is no queue.
845fn report(orchestrator: &mut RenderOrchestrator, events: Option<&RendererEvents>) {
846    for event in orchestrator.take_events() {
847        emit(events, event);
848    }
849}
850
851/// Pushes `event` to `events`, the renderer's event queue, if it has one.
852fn emit(events: Option<&RendererEvents>, event: RendererEvent) {
853    if let Some(events) = events {
854        events.push(event);
855    }
856}