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