Skip to main content

oa/runtime/
presenter.rs

1//! SDL3-backed Vulkan presentation session.
2
3use crate::{Engine, Result, Texture};
4
5use super::{PresentationCapabilities, PresentationSurface, SdlWindow};
6
7/// Engine-borrowing presentation session.
8///
9/// Construction creates and owns the SDL3 Vulkan surface, then records whether
10/// the Engine's retained graphics queue can present to that exact surface.
11/// Swapchain acquire/present is intentionally the next lifecycle phase rather
12/// than a fabricated method on this real surface session.
13pub struct Presenter<'window> {
14	swapchain: Option<super::PresentationSwapchain>,
15	surface: Option<PresentationSurface<'window>>,
16	pending_drawable_extent: Option<[u32; 2]>,
17}
18
19impl<'window> Presenter<'window> {
20	pub(crate) fn validate_ui_engine(&self, engine: &super::EngineHandle) -> Result<()> {
21		self.surface().validate_ui_engine(engine)
22	}
23
24	/// Create a presentation session for one SDL3 window.
25	///
26	/// The Engine must have been built using `EngineRequirements::presentation()`
27	/// and `window.required_instance_extensions()`.
28	pub fn new(engine: &Engine, window: &'window SdlWindow) -> Result<Self> {
29		Ok(Self {
30			swapchain: None,
31			surface: Some(engine.new_presentation_surface(window)?),
32			pending_drawable_extent: None,
33		})
34	}
35
36	/// Whether the active swapchain negotiated premultiplied client-frame alpha.
37	pub fn has_transparent_composition(&self) -> bool {
38		self
39			.swapchain
40			.as_ref()
41			.is_some_and(super::PresentationSwapchain::is_transparent)
42	}
43
44	/// Return whether the Engine retained a graphics-capable queue.
45	///
46	/// A surface can exist without this capability; swapchain allocation will
47	/// require a graphics queue that can also present to this exact surface.
48	pub fn has_graphics(&self) -> bool {
49		self.surface().has_graphics()
50	}
51
52	/// Return whether the selected device enabled `VK_KHR_swapchain`.
53	pub fn supports_swapchain(&self) -> bool {
54		self.surface().supports_swapchain()
55	}
56
57	/// Return whether any queue family can present to this surface.
58	///
59	/// True when the graphics queue can present directly (same-family path) or
60	/// when a distinct present-capable family was found during surface creation.
61	pub fn has_present(&self) -> bool {
62		self.surface().present_queue_family().is_some()
63	}
64
65	/// Query the exact surface capabilities before swapchain allocation.
66	pub fn capabilities(&self) -> Result<PresentationCapabilities> {
67		self.surface().capabilities()
68	}
69
70	/// Select the currently valid drawable extent for a future swapchain.
71	pub fn swapchain_extent(&self, window: &SdlWindow) -> Result<Option<[u32; 2]>> {
72		self.surface().swapchain_extent(window.drawable_extent())
73	}
74
75	/// Validate whether a swapchain can be allocated at the current drawable size.
76	///
77	/// `false` is the normal minimized-window state; unsupported WSI capability
78	/// remains an error rather than being hidden behind a fallback.
79	pub fn can_create_swapchain(&self, window: &SdlWindow) -> Result<bool> {
80		if !self.has_graphics() || !self.has_present() || !self.supports_swapchain() {
81			return Ok(false);
82		}
83		Ok(
84			self
85				.surface()
86				.swapchain_config(window.drawable_extent())?
87				.is_some(),
88		)
89	}
90
91	/// Allocate the negotiated swapchain for the current drawable extent.
92	pub fn init_swapchain(&mut self, window: &SdlWindow) -> Result<bool> {
93		self.close_swapchain()?;
94		let extent = self
95			.pending_drawable_extent
96			.take()
97			.unwrap_or_else(|| window.drawable_extent());
98		self.swapchain = self.surface().create_swapchain(extent)?;
99		Ok(self.swapchain.is_some())
100	}
101
102	/// Wait for submitted WSI work before retiring or replacing swapchain resources.
103	pub fn wait_presentation_idle(&mut self) -> Result<()> {
104		if let Some(swapchain) = &mut self.swapchain {
105			swapchain.wait_idle()?;
106		}
107		Ok(())
108	}
109
110	/// Explicitly retire the current swapchain after its submitted WSI work completes.
111	pub fn close_swapchain(&mut self) -> Result<()> {
112		self.wait_presentation_idle()?;
113		self.swapchain = None;
114		Ok(())
115	}
116
117	/// Retire the old swapchain and allocate one for the current drawable extent.
118	pub fn recreate_swapchain(&mut self, window: &SdlWindow) -> Result<bool> {
119		self.close_swapchain()?;
120		self.init_swapchain(window)
121	}
122
123	/// Record SDL's pixel-size change for explicit swapchain retirement/recreation.
124	///
125	/// The caller must recreate only after all presentation work using the old
126	/// images has completed; this notification itself never submits or waits.
127	pub fn notify_pixel_size_changed(&mut self, width: u32, height: u32) {
128		self.pending_drawable_extent = Some([width, height]);
129	}
130
131	pub fn needs_swapchain_recreate(&self) -> bool {
132		self.pending_drawable_extent.is_some()
133	}
134
135	pub fn has_swapchain(&self) -> bool {
136		self
137			.swapchain
138			.as_ref()
139			.is_some_and(super::PresentationSwapchain::is_valid)
140	}
141
142	/// Return the number of owned swapchain image views.
143	pub fn swapchain_image_count(&self) -> usize {
144		self
145			.swapchain
146			.as_ref()
147			.map_or(0, super::PresentationSwapchain::image_count)
148	}
149
150	/// Number of independent WSI frame slots owned by this Presenter.
151	pub fn frames_in_flight(&self) -> usize {
152		self
153			.swapchain
154			.as_ref()
155			.map_or(0, super::PresentationSwapchain::frames_in_flight)
156	}
157
158	/// Acquire, transition, submit, and present one empty WSI frame.
159	/// Returns `true` when the surface became suboptimal and should be recreated.
160	pub fn present_empty_frame(&mut self) -> Result<bool> {
161		self.present_clear_frame(crate::Color::default())
162	}
163
164	/// Acquire, clear with a linear RGBA color, submit, and present one WSI frame.
165	pub fn present_clear_frame(&mut self, color: crate::Color) -> Result<bool> {
166		if !color
167			.to_array()
168			.iter()
169			.all(|value| value.is_finite() && (0.0..=1.0).contains(value))
170		{
171			return Err(crate::Error::invalid_argument(
172				"Presenter clear color must be finite RGBA values in [0, 1]",
173			));
174		}
175		self
176			.swapchain
177			.as_mut()
178			.ok_or_else(|| crate::Error::invalid_argument("Presenter has no initialized swapchain"))?
179			.present_clear(color.to_array())
180	}
181
182	/// Scale and present one native image-backed Texture.
183	pub fn present_texture(&mut self, texture: &Texture) -> Result<bool> {
184		let swapchain = self
185			.swapchain
186			.as_mut()
187			.ok_or_else(|| crate::Error::invalid_argument("Presenter has no initialized swapchain"))?;
188		if let Some(native) = texture.native() {
189			return swapchain.present_texture(native);
190		}
191		if let Some((image, _view, width, height, retention)) = texture.render_target_image() {
192			return swapchain.present_render_target(image, [width, height], retention);
193		}
194		Err(crate::Error::failed_precondition(
195			"Presenter::present_texture requires a buffer-backed or render-target-backed Texture",
196		))
197	}
198
199	/// Compose the UI layer and present it directly to the swapchain.
200	///
201	/// `record` draws the UI raster pass into `compose_image` as a color
202	/// attachment.  The swapchain blit and present run in the same submission
203	/// — no host readback, no extra queue round-trip.
204	pub fn present_compose(
205		&mut self,
206		compose_image: vk::Image,
207		compose_width: u32,
208		compose_height: u32,
209		record: impl FnOnce(&vk::Device, vk::CommandBuffer) -> crate::Result<()>,
210	) -> crate::Result<bool> {
211		self.present_compose_retained(compose_image, compose_width, compose_height, None, record)
212	}
213
214	/// Attach exact UI resource ownership to the submitted presentation frame.
215	pub(crate) fn present_compose_retained(
216		&mut self,
217		compose_image: vk::Image,
218		compose_width: u32,
219		compose_height: u32,
220		retention: Option<std::rc::Rc<dyn std::any::Any>>,
221		record: impl FnOnce(&vk::Device, vk::CommandBuffer) -> crate::Result<()>,
222	) -> crate::Result<bool> {
223		self
224			.swapchain
225			.as_mut()
226			.ok_or_else(|| crate::Error::invalid_argument("Presenter has no initialized swapchain"))?
227			.present_compose(
228				compose_image,
229				compose_width,
230				compose_height,
231				retention,
232				record,
233			)
234	}
235
236	/// Return the current swapchain image extent, or `None` when none is allocated.
237	pub fn swapchain_extent_px(&self) -> Option<[u32; 2]> {
238		self.swapchain.as_ref().map(|sc| sc.extent_px())
239	}
240
241	fn surface(&self) -> &PresentationSurface<'window> {
242		self.surface.as_ref().expect("Presenter surface is live")
243	}
244}
245
246impl Drop for Presenter<'_> {
247	fn drop(&mut self) {
248		if self
249			.swapchain
250			.as_ref()
251			.is_some_and(super::PresentationSwapchain::has_submitted_frames)
252		{
253			// Drop cannot wait for the presentation engine. Retain the complete WSI
254			// ownership graph rather than destroying a swapchain, semaphores, or its
255			// surface while presentation may still reference them. `close_swapchain`
256			// is the normal explicit, failure-bearing retirement boundary.
257			if let Some(swapchain) = self.swapchain.take() {
258				std::mem::forget(swapchain);
259			}
260			if let Some(surface) = self.surface.take() {
261				std::mem::forget(surface);
262			}
263			return;
264		}
265		// Explicit field order: destroy an unused/explicitly-idle swapchain before
266		// destroying the surface it was created from.
267		self.swapchain = None;
268		self.surface = None;
269	}
270}