mln_runtime/render/session/mod.rs
1//! The handle of a render session, and the state that its thread shares
2//! with the handle.
3
4mod acquired;
5mod attach;
6mod shared;
7
8use std::sync::Arc;
9use std::sync::atomic::Ordering;
10
11use mln_engine::camera::LogicalExtent;
12use mln_engine::exec::thread::Joined;
13use mln_engine::query::{RenderedQueryOptions, SourceQueryOptions};
14use mln_engine::tile::feature::Feature;
15use mln_style::bitmap::PremultipliedImage;
16use mln_style::error::Error;
17use mln_style::size::Size;
18
19pub use self::acquired::{AcquiredFrame, FrameView};
20pub(crate) use self::attach::attach;
21pub(crate) use self::shared::{Abandoner, Published, SessionId, SessionShared, WorkId};
22use self::shared::{Pacing, check_usable, released, with_unlocked_wakes};
23use super::driver::DriverWork;
24use super::frame::{FrameDemand, FrameResult};
25use super::query::RenderedQueryGeometry;
26use super::target::{BorrowedRing, Driver, ExportKind, GpuSync, SentSurface, Surface, SyncKind, SyncKinds};
27use super::worker::{self, Worker};
28use crate::completion::Completion;
29use crate::frame_pacer::FramePacer;
30use crate::map::Applied;
31use crate::runtime::Outbox;
32
33/// Where a render session is in its life.
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub enum RenderSessionState {
36 /// The session is starting: it builds its renderer and binds to its map.
37 Attaching,
38 Attached,
39 /// A detach or release is on its way.
40 Detaching,
41 /// The session let go of its map and its graphics objects.
42 Detached,
43 /// The session couldn't build its renderer, or failed while it rendered,
44 /// as when a panic in its work stopped it. Its snapshot says why.
45 Failed,
46 Abandoned,
47}
48
49/// The state of a render session at one moment.
50#[derive(Clone, Debug, PartialEq)]
51pub struct RenderSessionSnapshot {
52 pub state: RenderSessionState,
53 /// The target's logical size, and the map's pixel ratio.
54 pub extent: LogicalExtent,
55 /// Grows each time the target changes size or is replaced.
56 pub generation: u64,
57 /// Counts the frames that the session rendered.
58 pub frame_generation: u64,
59 /// Why the session failed.
60 pub failure: Option<Error>,
61 /// Whether the session is attached and has a target to render to. It is
62 /// false from a [`release_target`](RenderSession::release_target) until
63 /// a [`set_surface`](RenderSession::set_surface) gives it a new one.
64 pub has_target: bool,
65 /// How many of a borrowed ring's frames the host holds.
66 pub acquired_frames: u32,
67}
68
69/// What a render session can do.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
71pub struct RenderSessionCapabilities {
72 pub driver: Driver,
73 /// How many textures the session's texture ring has.
74 pub texture_ring_depth: u32,
75 /// Whether the host can take the frames it renders.
76 pub frame_acquisition: bool,
77 /// Whether [`RenderSession::read_texture`] can read its pixels.
78 pub readback: bool,
79 /// Whether it shows frames on a surface.
80 pub presentation: bool,
81 /// The kind of sync that a borrowed ring's frames carry.
82 pub producer_sync_kind: Option<SyncKind>,
83 /// The kinds of sync that [`AcquiredFrame::release`] takes.
84 pub consumer_sync_kinds: SyncKinds,
85 /// How an exported ring shares its images, for an exported ring.
86 pub export_kind: Option<ExportKind>,
87}
88
89/// Sizes in pixels a target of `size` logical pixels at `scale_factor`, by
90/// [`LogicalExtent::physical_size`].
91pub(crate) fn physical_size(size: Size, scale_factor: f64) -> Result<Size, Error> {
92 LogicalExtent::new(size, scale_factor)
93 .physical_size()
94 .ok_or_else(|| Error::invalid_argument(format!("{size:?} at scale factor {scale_factor} has no physical size")))
95}
96
97/// A render session: a renderer that draws a map into a target, on a thread
98/// of its own or on the host's.
99///
100/// The host demands frames, which finish with [`FrameResult`]s that
101/// [`drain_frame_results`](Self::drain_frame_results) takes. A demand shows
102/// the map's commands sent before it, except the changes that an open
103/// command group holds back. The session's work runs on its thread in the
104/// order it was sent, and reports through a [`Completion`]. `Clone` is
105/// another handle to the same session, and any thread may use one.
106///
107/// A session that attached with [`Driver::CallerThread`] runs its work only
108/// when the host services its [`DriverWork`], which
109/// [`take_driver_work`](Self::take_driver_work) hands out.
110///
111/// The session lives until [`detach`](Self::detach),
112/// [`release`](Self::release), [`dispose`](Self::dispose) or
113/// [`abandon`](Self::abandon), or until its last handle drops, and it holds
114/// its map until then. A call that sends work to a session that no longer
115/// takes it fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind), or
116/// with the failure of a session that failed.
117///
118/// Unless the session was released or disposed, the last drop of its
119/// handles, [`AcquiredFrame`]s and [`FrameView`]s waits for a core worker's
120/// thread to end, once the session has let go of its graphics objects and
121/// its map. A drop on a thread of the library, such as in a callback or a
122/// wake that the library runs, doesn't wait: it leaves the session's thread
123/// to end alone.
124#[derive(Clone)]
125pub struct RenderSession {
126 handle: Arc<SessionHandle>,
127}
128
129/// Disposes of the session when the last handle drops.
130struct SessionHandle {
131 shared: Arc<SessionShared>,
132 thread_end: ThreadEnd,
133}
134
135/// A core worker's thread, which the last of the host's handles, frames and
136/// views of the session to drop waits for. A caller-driven session has no
137/// thread, and in the browser the thread is the host's.
138type ThreadEnd = Option<Arc<Joined>>;
139
140impl Drop for SessionHandle {
141 /// Disposes of the session, which ends its thread once the frames and
142 /// views of it end too, then waits for the thread as `thread_end` drops,
143 /// unless they hold it.
144 fn drop(&mut self) {
145 let _ = self.shared.dispose(None);
146 }
147}
148
149impl std::fmt::Debug for RenderSession {
150 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151 f.debug_struct("RenderSession").field("id", &self.shared().id).finish()
152 }
153}
154
155impl PartialEq for RenderSession {
156 fn eq(&self, other: &RenderSession) -> bool {
157 Arc::ptr_eq(&self.handle, &other.handle)
158 }
159}
160
161impl Eq for RenderSession {}
162
163impl RenderSession {
164 fn shared(&self) -> &Arc<SessionShared> {
165 &self.handle.shared
166 }
167
168 /// Sends a command with `send`, such as [`barrier`](Self::barrier), and
169 /// calls `callback` once with its result, where the session delivers
170 /// it: on the session's thread, inside its driver call, even when the
171 /// command runs before `send` returns. A [`Completion::on_complete`]
172 /// after the command returned would run at once on this thread instead.
173 /// The callback doesn't run when `send` fails.
174 ///
175 /// Fails as `send` does.
176 pub fn send_then<T: Send + 'static>(
177 &self,
178 send: impl FnOnce(&RenderSession) -> Result<Completion<T>, Error>,
179 callback: impl FnOnce(Result<T, Error>) + Send + 'static,
180 ) -> Result<(), Error> {
181 // The wakes that the command runs wait for the lock's release, so a
182 // host's wake that services the session can't wait for it.
183 with_unlocked_wakes(|| {
184 let ready = {
185 let _sending = self.shared().hold_sending();
186 send(self)?.on_complete_unless_ready(callback)
187 };
188 // A result that came without the session's thread, such as a
189 // command dropped unrun, goes to the callback here.
190 if let Some((callback, result)) = ready {
191 callback(result);
192 }
193 Ok(())
194 })
195 }
196
197 /// Sends `task` to the session's thread, after the work sent before,
198 /// resizes included, and completes with its result. A session that lost
199 /// its graphics objects before the task runs completes it with
200 /// [`ErrorKind::TargetLost`](mln_style::error::ErrorKind).
201 pub(crate) fn operation<T: Send + 'static>(
202 &self,
203 task: impl FnOnce(&mut Worker, &mut Outbox) -> Result<T, Error> + Send + 'static,
204 ) -> Result<Completion<T>, Error> {
205 let shared = self.shared();
206 with_unlocked_wakes(|| {
207 let mut state = shared.state.lock();
208 check_usable(&state)?;
209 let (completion, resolver) = shared.completion();
210 let work = state.register(resolver);
211 let resizes = state.resizes_sent;
212 worker::post(&shared.queue, move |worker, outbox| {
213 let task: worker::Task = Box::new(move |worker, outbox| {
214 let Some(resolver) = worker.take_work(work) else { return };
215 let result = task(worker, outbox);
216 outbox.resolve(resolver, result);
217 });
218 worker.after_earlier_work(resizes, task, outbox);
219 });
220 drop(state);
221 Ok(completion)
222 })
223 }
224
225 /// Hands out the work of a [`Driver::CallerThread`] session, for the
226 /// calling thread to run: the session's graphics work runs only in its
227 /// [`service`](DriverWork::service), and on no other thread.
228 ///
229 /// Take it once, on the host's graphics thread, from the attach on: the
230 /// attach itself completes in a service. It stays available after a
231 /// release, which the host services to its end.
232 ///
233 /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
234 /// session on a core worker, and with
235 /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it was taken.
236 pub fn take_driver_work(&self) -> Result<DriverWork, Error> {
237 let shared = self.shared();
238 if shared.driver != Driver::CallerThread {
239 return Err(Error::unsupported("the render session runs on a core worker"));
240 }
241 if shared.driver_work_taken.swap(true, Ordering::SeqCst) {
242 return Err(Error::invalid_state("the render session's driver work was taken already"));
243 }
244 let _ = shared.thread.set(std::thread::current().id());
245 Ok(DriverWork::new(Arc::clone(shared)))
246 }
247
248 /// What the session can do. Fails with
249 /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it is released.
250 pub fn capabilities(&self) -> Result<RenderSessionCapabilities, Error> {
251 let state = self.shared().state.lock();
252 if state.released {
253 return Err(released());
254 }
255 Ok(self.shared().capabilities)
256 }
257
258 /// The session's state now. Fails with
259 /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once it is released.
260 pub fn snapshot(&self) -> Result<RenderSessionSnapshot, Error> {
261 let state = self.shared().state.lock();
262 if state.released {
263 return Err(released());
264 }
265 Ok(RenderSessionSnapshot {
266 state: state.lifecycle,
267 extent: LogicalExtent { size: state.size, scale_factor: state.scale_factor },
268 generation: state.generation,
269 frame_generation: state.frame_generation,
270 failure: state.failure.clone(),
271 has_target: state.lifecycle == RenderSessionState::Attached && state.has_target,
272 acquired_frames: state.acquired_frames,
273 })
274 }
275
276 /// Takes the newest frame that a borrowed ring rendered, if one waits:
277 /// the older frames that the host didn't acquire are dropped, and the
278 /// session may render into their textures again. While the host holds a
279 /// frame in every texture, demands wait for a release.
280 ///
281 /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
282 /// session without a ring, and as a call that sends work does once the
283 /// session no longer takes work.
284 pub fn acquire_frame(&self) -> Result<Option<AcquiredFrame>, Error> {
285 let shared = self.shared();
286 let mut state = shared.state.lock();
287 check_usable(&state)?;
288 if !shared.capabilities.frame_acquisition {
289 return Err(Error::unsupported("render session does not expose acquired texture frames"));
290 }
291 if state.pending_retargets != 0 {
292 return Ok(None);
293 }
294 let newest = state
295 .ring
296 .iter()
297 .enumerate()
298 .filter(|(_, slot)| !slot.acquired && slot.frame.is_some())
299 .max_by_key(|(_, slot)| slot.frame.as_ref().map_or(0, |frame| frame.result.frame_generation))
300 .map(|(index, _)| index);
301 let Some(index) = newest else { return Ok(None) };
302 for (other, slot) in state.ring.iter_mut().enumerate() {
303 if other != index && !slot.acquired {
304 slot.frame = None;
305 }
306 }
307 let slot = &mut state.ring[index];
308 let Some(frame) = slot.frame.take() else { return Ok(None) };
309 slot.acquired = true;
310 state.acquired_frames += 1;
311 Ok(Some(AcquiredFrame {
312 shared: Arc::clone(shared),
313 thread_end: self.handle.thread_end.clone(),
314 slot: index,
315 frame,
316 done: false,
317 }))
318 }
319
320 /// Gives a borrowed ring new textures, of `size` logical pixels: as many
321 /// as it has, of its format. The completion reports the map's change and
322 /// the sync after which the host may use the old textures that the new
323 /// ring doesn't have, as [`release_target`](Self::release_target) says.
324 ///
325 /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
326 /// session without a borrowed ring, with
327 /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for another number
328 /// of textures, and with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
329 /// while the host holds one of the ring's frames. Completes with
330 /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for textures of
331 /// another format or kind.
332 pub fn set_ring(&self, size: Size, ring: BorrowedRing) -> Result<Completion<(Applied, GpuSync)>, Error> {
333 let shared = Arc::clone(self.shared());
334 {
335 let mut state = shared.state.lock();
336 check_usable(&state)?;
337 if shared.capabilities.readback {
338 return Err(Error::unsupported("an offscreen session keeps its target"));
339 }
340 if !shared.capabilities.frame_acquisition {
341 return Err(Error::unsupported("a surface session takes no caller-owned texture"));
342 }
343 if shared.capabilities.export_kind.is_some() {
344 return Err(Error::unsupported("an exported ring resizes instead of taking new textures"));
345 }
346 if state.acquired_frames != 0 {
347 return Err(Error::invalid_state("cannot replace the render target while a texture frame is acquired"));
348 }
349 if ring.depth() != state.ring.len() {
350 return Err(Error::invalid_argument(
351 "texture_count must equal the ring depth the session attached with",
352 ));
353 }
354 state.pending_retargets += 1;
355 }
356 let guard = RetargetGuard(Arc::clone(&shared));
357 // The guard goes with the closure, whether the closure runs or the
358 // resize drops it.
359 self.resize_then(size, None, move |worker, size, scale_factor, applied, outbox| {
360 let _guard = guard;
361 Ok((applied, worker.set_ring(size, scale_factor, &ring, outbox)?))
362 })
363 }
364
365 /// Asks the session to render a frame, which shows the map commands sent
366 /// before the call, except the changes that an open command group holds
367 /// back, and the map's animations as they are at the call: demand each
368 /// frame at the display's pace. A demand sent while the session attaches
369 /// waits for it.
370 ///
371 /// Every demand finishes with one [`FrameResult`] that carries its token.
372 /// A demand that isn't [`DemandMode::Force`](super::DemandMode::Force)
373 /// replaces the demands with the same mode still on their way, which
374 /// finish as [`FrameDisposition::Superseded`](super::FrameDisposition).
375 /// While the session has no target, or a surface has no texture to
376 /// render into, a demand finishes as
377 /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
378 pub fn demand_frame(&self, demand: FrameDemand) -> Result<(), Error> {
379 let shared = self.shared();
380 with_unlocked_wakes(|| shared.demand_locked(&mut shared.state.lock(), demand))
381 }
382
383 /// Paces the session's frames with `pacer`, or with none, stops. At the
384 /// first refresh that the pacer allows after the map has something new to
385 /// draw, it demands a frame in
386 /// [`DemandMode::IfChanged`](super::DemandMode::IfChanged) with token 0,
387 /// unless a demand came first. One pacer can pace many sessions.
388 ///
389 /// Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a
390 /// session with a redraw wake.
391 pub fn set_frame_pacer(&self, pacer: Option<Arc<FramePacer>>) -> Result<(), Error> {
392 let shared = self.shared();
393 let request = {
394 let mut state = shared.state.lock();
395 check_usable(&state)?;
396 if shared.redraw_wake.is_some() {
397 return Err(Error::invalid_state("a render session with a redraw wake takes no frame pacer"));
398 }
399 let same = match (&state.pacing, &pacer) {
400 (Some(pacing), Some(pacer)) => Arc::ptr_eq(&pacing.pacer, pacer),
401 (None, None) => true,
402 _ => false,
403 };
404 if same {
405 return Ok(());
406 }
407 state.pacing = pacer.map(|pacer| Pacing::new(pacer, Arc::downgrade(shared)));
408 state.pacing.as_ref().filter(|_| !state.redraw_armed).map(Pacing::request)
409 };
410 if let Some(request) = request {
411 request();
412 }
413 Ok(())
414 }
415
416 /// Takes the frame results that wait, oldest first. Fails with
417 /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) once the session is
418 /// released.
419 pub fn drain_frame_results(&self) -> Result<Vec<FrameResult>, Error> {
420 let mut state = self.shared().state.lock();
421 if state.released {
422 return Err(released());
423 }
424 state.frame_woken = false;
425 Ok(std::mem::take(&mut state.results))
426 }
427
428 /// Resizes the target, and the map with it, to `extent`'s size in
429 /// logical pixels, and sets the map's scale factor to `extent`'s, such
430 /// as when a window moves to a display of another density. The map keeps
431 /// its tiles, and the renderer draws the next frame at the new scale
432 /// factor. A later demand shows the new extent, and one sent before
433 /// shows the old. An exported ring gets images of the new size, and the
434 /// frames that the host holds keep theirs until it gives them back.
435 ///
436 /// Fails first as a call that sends work does once the session no
437 /// longer takes work. Then fails with
438 /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a borrowed ring,
439 /// which [`set_ring`](Self::set_ring) resizes, and with
440 /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an empty size,
441 /// or a scale factor that isn't finite and positive.
442 pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
443 check_usable(&self.shared().state.lock())?;
444 let capabilities = self.shared().capabilities;
445 if capabilities.frame_acquisition && capabilities.export_kind.is_none() {
446 return Err(Error::unsupported("a borrowed ring is sized by its owner: give it new textures instead"));
447 }
448 let LogicalExtent { size, scale_factor } = extent;
449 if !scale_factor.is_finite() || scale_factor <= 0.0 {
450 return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
451 }
452 self.resize_then(size, Some(scale_factor), |worker, size, scale_factor, applied, outbox| {
453 worker.resize(size, scale_factor, outbox).map(|()| applied)
454 })
455 }
456
457 /// Sends a map command that resizes the map to `size`, at
458 /// `scale_factor` or the session's when that is `None`, then runs
459 /// `change` on the session's thread with the map's change, which resizes
460 /// or replaces the target, and completes with its result.
461 fn resize_then<T: Send + 'static>(
462 &self,
463 size: Size,
464 scale_factor: Option<f64>,
465 change: impl FnOnce(&mut Worker, Size, f64, Applied, &mut Outbox) -> Result<T, Error> + Send + 'static,
466 ) -> Result<Completion<T>, Error> {
467 if size.is_empty() {
468 return Err(Error::invalid_argument("the target's size must not be empty"));
469 }
470 let shared = self.shared();
471 with_unlocked_wakes(|| {
472 let mut state = shared.state.lock();
473 check_usable(&state)?;
474 let map = state.map.clone().ok_or_else(|| Error::invalid_state("the render session has no map"))?;
475 let scale_factor = scale_factor.unwrap_or(state.sent_scale_factor);
476 state.sent_scale_factor = scale_factor;
477 let (completion, resolver) = shared.completion();
478 let work = state.register(resolver);
479 // The work sent after waits for the resize to land, which it
480 // does even when the map drops it.
481 state.resizes_sent += 1;
482 let landing = worker::ResizeLanding::new(shared.queue.clone());
483 let sent =
484 map.resize_for_session(size, scale_factor, shared.queue.clone(), move |worker, result, outbox| {
485 if let Some(resolver) = worker.take_work::<T>(work) {
486 let result = result.and_then(|applied| change(worker, size, scale_factor, applied, outbox));
487 outbox.resolve(resolver, result);
488 }
489 landing.land(worker, outbox);
490 });
491 if let Err(error) = sent {
492 state.pending.remove(&work);
493 return Err(error);
494 }
495 drop(state);
496 Ok(completion)
497 })
498 }
499
500 /// Lets go of a surface session's surface, and keeps the rest of the
501 /// session, such as when the platform takes the window away. The demands
502 /// on their way, and later ones until
503 /// [`set_surface`](Self::set_surface) gives the session a surface again,
504 /// finish as [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
505 /// Once the release completes, the session no longer uses the surface or
506 /// the window it was made from. For a ring, it completes with a sync of
507 /// the session's producer kind, after which the host may use or destroy
508 /// the textures: the session's GPU work on them, and its waits for the
509 /// consumer syncs that they were given back with, end there. The session
510 /// keeps the objects that the sync names until its next release or
511 /// replacement of the target completes, or it ends. It keeps nothing of
512 /// the released textures: one that a later ring has again starts fresh,
513 /// even one that the host gave up.
514 ///
515 /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for an
516 /// offscreen session or an exported ring, whose targets are their own.
517 /// Completes with [`ErrorKind::Failed`](mln_style::error::ErrorKind) when a ring
518 /// can't submit its work on the textures, which it keeps then.
519 pub fn release_target(&self) -> Result<Completion<Option<GpuSync>>, Error> {
520 if self.shared().capabilities.export_kind.is_some() {
521 return Err(Error::unsupported("an exported ring keeps its images until the session ends"));
522 }
523 let shared = Arc::clone(self.shared());
524 let capabilities = shared.capabilities;
525 if !capabilities.presentation && !capabilities.frame_acquisition {
526 check_usable(&shared.state.lock())?;
527 return Err(Error::unsupported("an offscreen session keeps its target"));
528 }
529 let guard = {
530 let mut state = shared.state.lock();
531 check_usable(&state)?;
532 if state.acquired_frames != 0 {
533 return Err(Error::invalid_state("release every acquired frame before the target"));
534 }
535 // No frame is acquired until the release runs: its textures go
536 // with it.
537 capabilities.frame_acquisition.then(|| {
538 state.pending_retargets += 1;
539 RetargetGuard(Arc::clone(&shared))
540 })
541 };
542 self.operation(move |worker, outbox| {
543 let _guard = guard;
544 worker.release_target(outbox)
545 })
546 }
547
548 /// Gives a surface session a new surface of `size` logical pixels, after
549 /// [`release_target`](Self::release_target), or in place of the one it
550 /// has, and resizes the map to it. Once the completion reports success,
551 /// the session no longer uses the old surface. The session presents to
552 /// it on its device: a window becomes a surface of the device's backend,
553 /// and a `Surface::wgpu` must come from the instance of a WebGPU
554 /// device. Where the backend made for the old surface can't present to
555 /// the new one, as OpenGL ES's context can't to another window, the
556 /// session makes its backend and renderer again.
557 ///
558 /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an
559 /// empty size, with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for
560 /// an offscreen session, and with
561 /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a window that is
562 /// minimized or has no client area. Completes with
563 /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the session's
564 /// device can't present to the surface in the format that the session
565 /// renders in: attach a new session instead. Completes with
566 /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the window had no
567 /// area to present to by then. The session then keeps the surface it had,
568 /// at the new size.
569 pub fn set_surface(&self, size: Size, surface: Surface) -> Result<Completion<Applied>, Error> {
570 check_usable(&self.shared().state.lock())?;
571 let capabilities = self.shared().capabilities;
572 if capabilities.frame_acquisition {
573 return Err(Error::unsupported("a borrowed texture session takes no native surface"));
574 }
575 if !capabilities.presentation {
576 return Err(Error::unsupported("an offscreen session keeps its target"));
577 }
578 surface.check_area()?;
579 let surface = SentSurface::new(surface, self.shared().id);
580 self.resize_then(size, None, move |worker, size, scale_factor, applied, outbox| {
581 worker.set_surface(size, scale_factor, surface.receive()?, outbox).map(|()| applied)
582 })
583 }
584
585 /// Ends the frame demands on their way, including those that wait for a
586 /// map update and the demand of a still image, which finish as
587 /// [`FrameDisposition::NoUpdate`](super::FrameDisposition), and completes
588 /// once the work sent before it has run. A still image that still waits
589 /// gets a new demand once the barrier ran.
590 pub fn barrier(&self) -> Result<Completion<()>, Error> {
591 self.operation(|worker, outbox| {
592 worker.barrier(outbox);
593 Ok(())
594 })
595 }
596
597 /// Frees memory that the renderer can rebuild, such as caches.
598 pub fn reduce_memory_use(&self) -> Result<Completion<()>, Error> {
599 self.operation(|worker, _| worker.reduce_memory_use())
600 }
601
602 /// Clears what the renderer holds, such as loaded tiles, so that the
603 /// next frame loads and draws the map again.
604 pub fn clear_data(&self) -> Result<Completion<()>, Error> {
605 self.operation(Worker::clear_data)
606 }
607
608 /// Logs the renderer's sources and tiles.
609 pub fn dump_debug_logs(&self) -> Result<Completion<()>, Error> {
610 self.operation(|worker, _| worker.dump_debug_logs())
611 }
612
613 /// The pixels of the last frame that an offscreen session rendered:
614 /// premultiplied RGBA, in rows from top to bottom, at the target's size
615 /// in pixels.
616 ///
617 /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
618 /// surface session. Completes with
619 /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) when the session
620 /// hasn't rendered a frame since it attached or resized.
621 pub fn read_texture(&self) -> Result<Completion<PremultipliedImage>, Error> {
622 check_usable(&self.shared().state.lock())?;
623 if !self.shared().capabilities.readback {
624 return Err(Error::unsupported("a surface session can't read its frames back"));
625 }
626 self.operation(|worker, _| worker.read_texture())
627 }
628
629 /// The features that the session drew in an area of the screen, in its
630 /// last frame. A feature that several layers draw appears once for each.
631 /// The topmost layer's features come first, and the bottom layer's last.
632 /// A box covers only its part inside the target, so one past every edge
633 /// covers the whole target.
634 ///
635 /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
636 /// point that isn't finite or a line string without points.
637 pub fn query_rendered_features(
638 &self,
639 geometry: RenderedQueryGeometry,
640 options: RenderedQueryOptions,
641 ) -> Result<Completion<Vec<Feature>>, Error> {
642 geometry.points()?;
643 self.operation(move |worker, _| match geometry.within(worker.size()).map(|geometry| geometry.points()) {
644 Some(points) => worker.renderer()?.query_rendered_features(&points?, &options),
645 None => Ok(Vec::new()),
646 })
647 }
648
649 /// The features of the source `source_id` in the tiles that it loaded
650 /// for the current view. A source loads tiles only while a visible layer
651 /// uses it.
652 ///
653 /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for an
654 /// empty `source_id`.
655 pub fn query_source_features(
656 &self,
657 source_id: impl Into<String>,
658 options: SourceQueryOptions,
659 ) -> Result<Completion<Vec<Feature>>, Error> {
660 let source_id = source_id_of(source_id)?;
661 self.operation(move |worker, _| worker.renderer()?.query_source_features(&source_id, &options))
662 }
663
664 /// The clusters and points that a cluster of a clustered GeoJSON source
665 /// splits into at the next zoom level. `cluster_id` is a cluster
666 /// feature's `cluster_id` property.
667 ///
668 /// The query reads the source as the session's most recent render
669 /// attempt had it. A cluster ID belongs to one version of the source's
670 /// data, so query the features again after the data changes.
671 ///
672 /// Completes with [`ErrorKind::NotFound`](mln_style::error::ErrorKind) when that
673 /// render had no source `source_id`, or the source has no cluster
674 /// `cluster_id`, and with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind)
675 /// when the source isn't a clustered GeoJSON source.
676 pub fn cluster_children(
677 &self,
678 source_id: impl Into<String>,
679 cluster_id: u32,
680 ) -> Result<Completion<Vec<mln_style::feature::Feature<f64>>>, Error> {
681 let source_id = source_id_of(source_id)?;
682 self.operation(move |worker, _| worker.cluster(&source_id, cluster_id, |_, children| Ok(children)))
683 }
684
685 /// The points in a cluster of a clustered GeoJSON source: it skips the
686 /// first `offset`, then holds up to `limit`. It fails as
687 /// [`cluster_children`](Self::cluster_children) does.
688 pub fn cluster_leaves(
689 &self,
690 source_id: impl Into<String>,
691 cluster_id: u32,
692 limit: u32,
693 offset: u32,
694 ) -> Result<Completion<Vec<mln_style::feature::Feature<f64>>>, Error> {
695 let source_id = source_id_of(source_id)?;
696 self.operation(move |worker, _| {
697 worker.cluster(&source_id, cluster_id, |index, _| index.leaves(cluster_id, limit, offset))
698 })
699 }
700
701 /// The zoom level at which a cluster of a clustered GeoJSON source splits
702 /// into two or more clusters or points. It fails as
703 /// [`cluster_children`](Self::cluster_children) does.
704 pub fn cluster_expansion_zoom(
705 &self,
706 source_id: impl Into<String>,
707 cluster_id: u32,
708 ) -> Result<Completion<u8>, Error> {
709 let source_id = source_id_of(source_id)?;
710 self.operation(move |worker, _| {
711 worker.cluster(&source_id, cluster_id, |index, _| index.cluster_expansion_zoom(cluster_id))
712 })
713 }
714
715 /// Detaches the session from its map and frees its graphics objects. The
716 /// demands on their way finish as
717 /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once
718 /// the detach completes, another session can attach to the map.
719 pub fn detach(&self) -> Result<Completion<()>, Error> {
720 let shared = self.shared();
721 with_unlocked_wakes(|| {
722 let mut state = shared.state.lock();
723 if !matches!(state.lifecycle, RenderSessionState::Failed) {
724 check_usable(&state)?;
725 } else if state.released {
726 return Err(released());
727 }
728 if state.acquired_frames != 0 {
729 return Err(Error::invalid_state("release every acquired frame before the session detaches"));
730 }
731 let (completion, resolver) = shared.completion();
732 state.detach_waiters.push(resolver);
733 shared.start_detach(&mut state);
734 Ok(completion)
735 })
736 }
737
738 /// Stops the session at once, without its pending graphics work: that
739 /// work completes with [`ErrorKind::TargetLost`](mln_style::error::ErrorKind)
740 /// before this returns, and the demands on their way finish as
741 /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once it
742 /// returns, the session renders no more, and another session can attach
743 /// to the map. Release the session afterward.
744 ///
745 /// Returns how many graphics objects the session keeps until the
746 /// process exits. A caller-driven session abandoned on the thread that
747 /// services it lets go of them there, at its next service or when its
748 /// [`DriverWork`] drops, and keeps none. Abandoned on another thread, it
749 /// keeps them, since only that thread may free them, and logs a warning.
750 ///
751 /// It waits for a core worker's driver call on another thread, such as a
752 /// frame that it renders. Fails with
753 /// [`ErrorKind::Busy`](mln_style::error::ErrorKind) inside a driver call on the
754 /// session's own thread, such as from a completion that the session
755 /// delivers, and while a caller-driven session's service runs on another
756 /// thread. Fails with [`ErrorKind::InvalidState`](mln_style::error::ErrorKind)
757 /// once the session is detached, abandoned or released.
758 pub fn abandon(&self) -> Result<u32, Error> {
759 self.shared().abandon(Abandoner::Host)
760 }
761
762 /// Abandons the session as [`abandon`](Self::abandon) does, but makes no
763 /// graphics call: the session keeps its graphics objects until the
764 /// process exits. Returns how many it keeps, such as its renderer and
765 /// the backend it draws with.
766 ///
767 /// This is for a host whose shutdown may already have destroyed the
768 /// graphics objects behind the session.
769 pub fn abandon_keeping_graphics(&self) -> Result<u32, Error> {
770 with_unlocked_wakes(|| self.shared().abandon_locked(Abandoner::Host, true))
771 }
772
773 /// Releases the session, detaching it first when it is attached. The
774 /// completion reports when the session has let go of its map and its
775 /// graphics objects, and nothing waits for its thread to end after
776 /// that. Every call on the session fails with
777 /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) after.
778 ///
779 /// A caller-driven session detaches at the host's next service, so keep
780 /// servicing it until the release completes. One that isn't attached,
781 /// such as while it attaches or after it failed, is abandoned instead,
782 /// and so is one whose map is released before that service.
783 pub fn release(&self) -> Result<Completion<()>, Error> {
784 {
785 let state = self.shared().state.lock();
786 let live = matches!(state.lifecycle, RenderSessionState::Attaching | RenderSessionState::Attached);
787 if live && !state.released && state.acquired_frames != 0 {
788 return Err(Error::invalid_state("release every acquired frame before the session is released"));
789 }
790 }
791 let (completion, resolver) = self.shared().completion();
792 self.shared().dispose(Some(resolver))?;
793 self.detach_thread();
794 Ok(completion)
795 }
796
797 /// Releases the session in any state, without waiting, and nothing waits
798 /// for its thread to end. Dropping the last handle does the same, then
799 /// waits for the thread.
800 pub fn dispose(&self) -> Result<(), Error> {
801 self.shared().dispose(None)?;
802 self.detach_thread();
803 Ok(())
804 }
805
806 /// Releases the session in any state, without waiting and without a
807 /// graphics call past the one in progress. A session that hasn't ended
808 /// is abandoned, keeping its graphics objects until the process exits,
809 /// as [`abandon_keeping_graphics`](Self::abandon_keeping_graphics) does.
810 /// Nothing waits for its thread to end.
811 pub fn dispose_keeping_graphics(&self) -> Result<(), Error> {
812 self.shared().dispose_keeping_graphics()?;
813 self.detach_thread();
814 Ok(())
815 }
816
817 /// Leaves a core worker's thread to end alone, for a release or
818 /// disposal, which don't wait for it.
819 fn detach_thread(&self) {
820 if let Some(thread) = &self.handle.thread_end {
821 thread.detach();
822 }
823 }
824}
825
826/// Counts a host's frame demand until the session evaluates or ends it, or
827/// drops it unrun.
828pub(crate) struct DemandGuard(Arc<SessionShared>);
829
830impl Drop for DemandGuard {
831 fn drop(&mut self) {
832 let mut state = self.0.state.lock();
833 state.pending_demands = state.pending_demands.saturating_sub(1);
834 }
835}
836
837/// Counts a ring replacement or release on its way until it runs, or never
838/// will.
839struct RetargetGuard(Arc<SessionShared>);
840
841impl Drop for RetargetGuard {
842 fn drop(&mut self) {
843 let mut state = self.0.state.lock();
844 state.pending_retargets = state.pending_retargets.saturating_sub(1);
845 }
846}
847
848fn source_id_of(source_id: impl Into<String>) -> Result<String, Error> {
849 let source_id = source_id.into();
850 if source_id.is_empty() {
851 return Err(Error::invalid_argument("the source ID must not be empty"));
852 }
853 Ok(source_id)
854}
855
856// Handles cross threads; the renderer never leaves its own.
857const _: () = {
858 const fn assert_send_sync<T: Send + Sync>() {}
859 assert_send_sync::<RenderSession>();
860};