mln-rs-runtime 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! A render session's thread: its renderer, its frame demands, and the work
//! that the handle sends it.

mod frames;
mod init;
mod ops;

use std::cell::Cell;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak};

use mln_engine::exec::queue::Queue;
use mln_engine::{RendererEvent, RendererEvents, Update, UpdateReader};
use mln_style::error::Error;

use self::frames::{Behind, PendingDemand, StillDemand};
use self::init::Gfx;
#[cfg(target_family = "wasm")]
pub(crate) use self::init::prepare;
pub(crate) use self::init::{Init, TargetInit, build};
use super::frame::{FrameDisposition, FrameResult};
use super::local::LocalTarget;
use super::session::{RenderSessionState, SessionShared, WorkId};
use super::target::{BorrowedRing, Driver, SurfaceOverlay};
use crate::completion::Resolver;
use crate::log_target;
use crate::map::Published as MapPublished;
use crate::runtime::Outbox;

/// The work of the thread that runs a session, which owns the session's
/// worker once it is built.
pub(crate) type SessionQueue = Queue<Option<Worker>>;

/// Runs `task` on the session whose thread runs `queue`, after the work sent
/// before.
pub(crate) fn post(queue: &SessionQueue, task: impl FnOnce(&mut Worker, &mut Outbox) + Send + 'static) {
    queue.post(move |worker| run(worker, task));
}

/// Runs `task` on the session, then delivers what it sends to the host, with
/// the session unlocked: a driver call, which the delivery is part of. A
/// session that was abandoned lets go of its graphics objects first.
fn run(worker: &mut Option<Worker>, task: impl FnOnce(&mut Worker, &mut Outbox)) {
    let Some(worker) = worker.as_mut() else { return };
    let shared = Arc::clone(&worker.shared);
    let _call = shared.enter_call();
    let mut outbox = Outbox::default();
    {
        let _gate = shared.gate.lock();
        let ran = mln_engine::exec::panic::catch(|| {
            if !worker.torn_down && shared.state.lock().lifecycle == RenderSessionState::Abandoned {
                worker.tear_down(&mut outbox);
            }
            task(worker, &mut outbox);
        });
        if let Err(message) = ran {
            worker.fail_after_panic(&message, &mut outbox);
        }
    }
    shared.wait_for_senders();
    outbox.deliver();
}

/// Work for the session's thread.
pub(crate) type Task = Box<dyn FnOnce(&mut Worker, &mut Outbox) + Send>;

/// Tells the session's thread that a resize sent to the map has landed:
/// [`land`](Self::land) when the resize reaches the session, or on drop
/// when it never does.
pub(crate) struct ResizeLanding(Option<SessionQueue>);

impl ResizeLanding {
    pub(crate) fn new(queue: SessionQueue) -> Self {
        ResizeLanding(Some(queue))
    }

    pub(crate) fn land(mut self, worker: &mut Worker, outbox: &mut Outbox) {
        self.0 = None;
        worker.resize_landed(outbox);
    }
}

impl Drop for ResizeLanding {
    fn drop(&mut self) {
        if let Some(queue) = self.0.take() {
            post(&queue, Worker::resize_landed);
        }
    }
}

/// A render session on its thread.
pub(crate) struct Worker {
    shared: Arc<SessionShared>,
    /// `None` once the session failed to build it, or let go of it.
    gfx: Option<Gfx>,
    /// What the host draws over the frames presented to the next surface
    /// that the session makes ([`DriverWork::set_overlay`](super::DriverWork::set_overlay)).
    pub(crate) overlay: Option<SurfaceOverlay>,
    /// The scale factor that the renderer draws at.
    scale_factor: f64,
    reader: Option<UpdateReader>,
    /// The map's queue for the renderer's events.
    map_events: Option<RendererEvents>,
    /// The renderer's own queue, which the session reads before it passes
    /// the events on to the map.
    renderer_events: RendererEvents,
    update_scheduled: Arc<AtomicBool>,
    /// The sequence number of the map's last command that ran.
    map_applied: u64,
    /// The map's last frame sample.
    map_sampled: u64,
    /// What the map publishes, from the bind on: the last command that ran.
    map_published: Option<Arc<MapPublished>>,
    /// The demands in the order they came, each waiting until the map ran
    /// the commands sent before it.
    queue: VecDeque<PendingDemand>,
    /// The demands that wait for a newer update than the one they found.
    waiting: Vec<(PendingDemand, u64)>,
    /// The demands that wait for a borrowed ring to free a texture, ahead of
    /// the queue.
    parked: VecDeque<PendingDemand>,
    /// The token of the demand that the session is rendering, which a panic
    /// on the way ends with the others.
    rendering: Option<u64>,
    /// The textures of a borrowed ring.
    ring: Option<BorrowedRing>,
    /// The update generation and session generation of the last render.
    rendered_update: u64,
    rendered_generation: u64,
    /// The demand of the map's still image, while the image waits for a
    /// frame.
    still: Option<StillDemand>,
    /// The `still_image_request_id` of the last still image that the
    /// session rendered.
    still_rendered: u64,
    /// The `still_image_request_id` of the still image that a resource error
    /// on its way to the map fails. The session draws no frame for it.
    still_failing: Cell<u64>,
    /// Whether the target holds a frame since it attached or resized.
    has_frame: bool,
    /// The sources of the last render.
    sources: Option<Arc<mln_style::SourceList>>,
    torn_down: bool,
    /// Whether the map refused to bind the session, which then never gets
    /// an update to render.
    unbound: bool,
    /// Whether the session ended: its thread has no more work for it.
    pub(crate) finished: bool,
    /// Counts the resizes that landed, of those that the session sent.
    resizes_landed: u64,
    /// Counts the host's demands that reached the session.
    demands_received: u64,
    /// The work that waits for the work sent before it, in the order sent.
    behind: VecDeque<Behind>,
    /// The target that a teardown keeps while views name their sync
    /// objects, until the last view ends.
    viewed: Option<LocalTarget>,
}

impl Drop for Worker {
    fn drop(&mut self) {
        self.drop_gfx();
    }
}

fn target_lost() -> Error {
    Error::target_lost("the render session lost its renderer")
}

impl Worker {
    fn new(shared: Arc<SessionShared>, init: Init, overlay: Option<SurfaceOverlay>, outbox: &mut Outbox) -> Worker {
        let renderer_events = RendererEvents::new();
        let queue = shared.queue.clone();
        renderer_events.set_waker(Some(Arc::new(move || {
            post(&queue, |worker, _| {
                worker.forward_events();
            });
        })));
        // A session that a detach or abandon reached first needs no renderer.
        let attaching = shared.state.lock().lifecycle == RenderSessionState::Attaching;
        let scale_factor = init.scale_factor;
        let ring = match &init.target {
            TargetInit::Borrowed { ring, .. } => Some(ring.clone()),
            _ => None,
        };
        let built = attaching.then(|| Gfx::new(init, overlay, &renderer_events));
        let gfx = match built {
            Some(Ok(gfx)) => {
                let mut state = shared.state.lock();
                state.graphics_objects = Gfx::OBJECTS - 1;
                state.abandon_keeps_graphics = gfx.target.device().abandon_keeps_graphics();
                drop(state);
                Some(gfx)
            }
            Some(Err(error)) => {
                let attach = {
                    let mut state = shared.state.lock();
                    if state.lifecycle == RenderSessionState::Attaching {
                        state.lifecycle = RenderSessionState::Failed;
                    }
                    state.failure = Some(error.clone());
                    state.attach.take()
                };
                if let Some(attach) = attach {
                    outbox.resolve(attach, Err(error));
                }
                None
            }
            None => None,
        };
        Worker {
            shared,
            gfx,
            overlay: None,
            scale_factor,
            reader: None,
            map_events: None,
            renderer_events,
            update_scheduled: Arc::new(AtomicBool::new(false)),
            map_applied: 0,
            map_sampled: 0,
            map_published: None,
            queue: VecDeque::new(),
            waiting: Vec::new(),
            parked: VecDeque::new(),
            rendering: None,
            ring,
            rendered_update: 0,
            rendered_generation: 0,
            still: None,
            still_rendered: 0,
            still_failing: Cell::new(0),
            has_frame: false,
            sources: None,
            torn_down: false,
            unbound: false,
            finished: false,
            resizes_landed: 0,
            demands_received: 0,
            behind: VecDeque::new(),
            viewed: None,
        }
    }

    /// The completion of the work `id`, unless an abandon completed it.
    pub(crate) fn take_work<T: Send + 'static>(&self, id: WorkId) -> Option<Resolver<T>> {
        self.shared.take_work(id)
    }

    // MARK: - The map

    /// The map bound the session in its command `sequence`: from now on the
    /// session draws its updates and reports to it.
    pub(crate) fn bound(
        &mut self,
        sequence: u64,
        reader: UpdateReader,
        events: RendererEvents,
        published: Arc<MapPublished>,
        outbox: &mut Outbox,
    ) {
        if self.torn_down {
            return;
        }
        self.map_applied = self.map_applied.max(sequence);
        self.map_published = Some(published);
        let scheduled = Arc::clone(&self.update_scheduled);
        let queue = self.shared.queue.clone();
        // A caller-driven session's thread runs only when the host services
        // it, which the host may do only once it knows to draw, so the map's
        // thread tells it of the update.
        let redraw = (self.shared.driver == Driver::CallerThread).then(|| Arc::downgrade(&self.shared));
        reader.set_waker(Some(Arc::new(move || {
            if let Some(wake) = redraw.as_ref().and_then(Weak::upgrade).and_then(|shared| shared.take_redraw_wake()) {
                wake();
            }
            if !scheduled.swap(true, Ordering::SeqCst) {
                post(&queue, Worker::on_update);
            }
        })));
        self.reader = Some(reader);
        self.map_events = Some(events);
        let attach = {
            let mut state = self.shared.state.lock();
            if state.lifecycle == RenderSessionState::Attaching {
                state.lifecycle = RenderSessionState::Attached;
            }
            state.attach.take()
        };
        if let Some(attach) = attach {
            outbox.resolve(attach, Ok(()));
        }
        // A new session has the map's latest update to draw.
        if self.gfx.is_some() && self.latest().is_some() {
            self.wake_for_redraw(outbox);
        }
        // The demands that came while the session attached wait for the
        // attach to complete, which the outbox delivers once this task ends,
        // so they render in a task of their own.
        post(&self.shared.queue, Worker::pump);
    }

    /// The map couldn't bind the session.
    pub(crate) fn bind_failed(&mut self, error: Error, outbox: &mut Outbox) {
        let attach = {
            let mut state = self.shared.state.lock();
            if state.lifecycle == RenderSessionState::Attaching {
                state.lifecycle = RenderSessionState::Failed;
                state.failure = Some(error.clone());
            }
            state.attach.take()
        };
        self.unbound = true;
        self.drop_gfx();
        if let Some(attach) = attach {
            outbox.resolve(attach, Err(error));
        }
        self.end_demands(FrameDisposition::Failed, outbox);
        self.run_queued(outbox);
    }

    /// The map ran its command `sequence`, and published what it changed.
    pub(crate) fn map_applied(&mut self, sequence: u64, outbox: &mut Outbox) {
        self.map_applied = self.map_applied.max(sequence);
        self.pump(outbox);
    }

    /// The map took its frame sample `sample`, and published the update.
    pub(crate) fn map_sampled(&mut self, sample: u64, outbox: &mut Outbox) {
        self.map_sampled = self.map_sampled.max(sample);
        self.pump(outbox);
    }

    /// The map published an update.
    fn on_update(&mut self, outbox: &mut Outbox) {
        self.update_scheduled.store(false, Ordering::SeqCst);
        self.pump(outbox);
        // A demand that is already queued or parked answers this update once
        // its map work lands; waking for a redraw meanwhile would disarm
        // `redraw_armed` and make a frame pacer demand a duplicate frame.
        if self.gfx.is_some()
            && self.queue.is_empty()
            && self.parked.is_empty()
            && self.latest().is_some_and(|update| update.generation != self.rendered_update)
        {
            self.wake_for_redraw(outbox);
        }
    }

    /// Tells the host that the map has something new to draw, unless it was
    /// told since its last demand, or the session has no target.
    fn wake_for_redraw(&self, outbox: &mut Outbox) {
        if let Some(wake) = self.shared.take_redraw_wake() {
            outbox.push(move || wake());
        }
    }

    fn latest(&self) -> Option<Update> {
        self.reader.as_ref()?.latest()
    }

    fn latest_generation(&self) -> u64 {
        self.reader.as_ref().map_or(0, UpdateReader::generation)
    }

    /// Passes the renderer's events on to the map. The renderer asks for an
    /// update when something arrives for its tiles: it takes it in now, so
    /// that the work it starts runs before the next frame.
    fn forward_events(&mut self) {
        if let Some(renderer) = self.gfx.as_mut().and_then(|gfx| gfx.target.renderer_mut()) {
            renderer.receive_tiles();
        }
        let events = self.renderer_events.take();
        self.forward(events);
    }

    fn forward(&self, events: Vec<RendererEvent>) {
        // The map fails the still image that waits when it takes a resource
        // error, so a frame for that image drawn before the map says so would
        // show a failed image.
        if events.iter().any(|event| matches!(event, RendererEvent::ResourceError(_))) {
            self.still_failing.set(self.pending_still_image());
        }
        if let Some(map_events) = &self.map_events {
            for event in events {
                map_events.push(event);
            }
        }
    }

    // MARK: - Failure and lifecycle

    /// Fails the attached session when its device was lost, which it can't
    /// render on again. Returns whether it failed.
    fn fail_if_device_lost(&mut self, outbox: &mut Outbox) -> bool {
        let Some(error) = self.gfx.as_ref().and_then(|gfx| gfx.target.device().lost()) else { return false };
        tracing::error!(target: log_target::RENDER, error = %error.message, "The render session's device was lost");
        self.fail(error, outbox);
        true
    }

    /// Fails the attached session with `error`, ending the demands on their
    /// way, and lets go of its renderer and target.
    fn fail(&mut self, error: Error, outbox: &mut Outbox) {
        let failed = {
            let mut state = self.shared.state.lock();
            let attached = self.gfx.is_some() && state.lifecycle == RenderSessionState::Attached;
            if attached {
                state.lifecycle = RenderSessionState::Failed;
                state.failure = Some(error);
            }
            attached
        };
        if failed {
            self.end_demands(FrameDisposition::Failed, outbox);
            self.drop_gfx();
            self.run_queued(outbox);
        }
    }

    /// Fails the session after a panic in its work, a bug in the library:
    /// it lets go of its renderer and target, which the panic may have left
    /// half-changed, and ends the attach and the demands on their way. A
    /// detach or release still ends the session.
    fn fail_after_panic(&mut self, message: &str, outbox: &mut Outbox) {
        let error = Error::failed(format!("the render session stopped after a panic in the library: {message}"));
        tracing::error!(target: log_target::CRASH, error = message, "The render session stopped after a panic in the library");
        let attach = {
            let mut state = self.shared.state.lock();
            if matches!(state.lifecycle, RenderSessionState::Attaching | RenderSessionState::Attached) {
                state.lifecycle = RenderSessionState::Failed;
                state.failure = Some(error.clone());
            }
            state.attach.take()
        };
        if let Some(attach) = attach {
            outbox.resolve(attach, Err(error));
        }
        // These run on the state that the panic left, so they may panic too.
        let _ = mln_engine::exec::panic::catch(|| {
            if let Some(token) = self.rendering.take() {
                let result = FrameResult::unrendered(Some(token), FrameDisposition::Failed, self.latest_generation());
                self.publish(&result, outbox);
            }
            self.end_demands(FrameDisposition::Failed, outbox);
            self.drop_gfx();
            self.run_queued(outbox);
        });
    }

    /// Lets go of the map's updates and the graphics objects, and ends the
    /// demands on their way.
    pub(crate) fn tear_down(&mut self, outbox: &mut Outbox) {
        self.end_demands(FrameDisposition::TargetNotReady, outbox);
        self.torn_down = true;
        if let Some(reader) = self.reader.take() {
            reader.set_waker(None);
        }
        self.renderer_events.set_waker(None);
        self.forward_events();
        self.drop_gfx();
        self.map_events = None;
        self.sources = None;
        self.has_frame = false;
        let attach = self.shared.state.lock().attach.take();
        if let Some(attach) = attach {
            outbox.resolve(attach, Err(Error::target_lost("the render session ended before it attached")));
        }
    }

    /// Lets go of the renderer and its target: frees them, unless the
    /// session keeps them until the process exits. While a view is open on
    /// one of the ring's frames, the target and its backend stay until the
    /// last view ends.
    fn drop_gfx(&mut self) {
        let Some(mut gfx) = self.gfx.take() else { return };
        let (keep, viewed, abandoned) = {
            let mut state = self.shared.state.lock();
            state.graphics_objects = 0;
            let viewed = state.views != 0 && !state.keep_graphics;
            state.viewed_teardown |= viewed;
            (state.keep_graphics, viewed, state.lifecycle == RenderSessionState::Abandoned)
        };
        // The host's graphics objects may be gone, so the layers' work after
        // the GPU forgets what it made instead of destroying it.
        if (keep || abandoned)
            && let Some(renderer) = gfx.target.renderer_mut()
        {
            renderer.lose_context();
        }
        if keep {
            // The host's graphics objects behind them may be gone already.
            std::mem::forget(gfx);
        } else if viewed {
            gfx.target.tear_down_renderer();
            self.viewed = Some(gfx.target);
        }
    }

    /// The last view of the session's frames ended: lets go of the target
    /// that a teardown kept for it, and ends a session that waited for that.
    pub(crate) fn release_viewed(&mut self) {
        if self.viewed.take().is_some() && self.finished && self.shared.driver == Driver::CoreWorker {
            self.shared.queue.stop();
        }
    }

    /// Whether the session's thread is done with it: the session ended, and
    /// no view keeps its target.
    pub(crate) fn is_done(&self) -> bool {
        self.finished && self.viewed.is_none()
    }

    /// Lets go of the session on its thread, which runs no more of its work.
    pub(crate) fn close(mut self, outbox: &mut Outbox) {
        if !self.torn_down {
            self.tear_down(outbox);
        }
    }

    /// Detaches the session: it lets go of its graphics objects and its map,
    /// and ends, without waiting for the map's thread, which a host's
    /// completion may hold. The map unbinds the session before it binds
    /// another.
    pub(crate) fn detach(&mut self, outbox: &mut Outbox) {
        // A panic in the teardown, such as a custom layer's, still detaches
        // the session.
        if let Err(message) = mln_engine::exec::panic::catch(|| self.tear_down(outbox)) {
            self.fail_after_panic(&message, outbox);
        }
        let map = self.shared.state.lock().map.clone();
        if let Some(map) = map {
            map.unbind_session(self.shared.id);
        }
        self.finish(outbox);
    }

    /// Ends the session: it completes the detach and the releases, lets go
    /// of the map, and stops the session's thread.
    pub(crate) fn finish(&mut self, outbox: &mut Outbox) {
        let (waiters, map) = {
            let mut state = self.shared.state.lock();
            if state.lifecycle == RenderSessionState::Detaching {
                state.lifecycle = RenderSessionState::Detached;
            }
            (state.take_waiters(), state.map.take())
        };
        if let Some(map) = &map {
            map.release_session_claim(self.shared.id);
        }
        outbox.push(move || waiters.settle(&Ok(()), target_lost));
        outbox.push(move || drop(map));
        self.finished = true;
        // A target that views keep stops the queue once they end.
        if self.shared.driver == Driver::CoreWorker && self.viewed.is_none() {
            self.shared.queue.stop();
        }
    }
}