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