Skip to main content

oa/ui/
viewport.rs

1//! `Viewport` — passive camera/target/view description for rendering.
2//!
3//! Donor: `oa/ui/viewport.h` and `oa/ui/viewport.cpp`.
4//!
5//! Architecture naming resolution:
6//! - `Viewport` (ui): passive camera + target + viewport rectangle (data)
7//! - `Viewer` (viewer): the windowed interactive application (controller)
8//!
9//! This is not a window or an interactive element. It declares what to
10//! render and where without owning swapchains or handling input.
11
12use crate::render::{Camera, Texture};
13use crate::{Error, Result};
14
15/// What kind of content the viewport describes.
16///
17/// Donor: `oa::ViewportMode`.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum ViewportMode {
20	/// 2D image/video with an orthographic camera.
21	#[default]
22	Image2D,
23	/// 3D scene with a perspective camera.
24	Scene3D,
25	/// Matrix-as-heatmap visualization.
26	Matrix,
27	/// Video with a timeline (2D + time control).
28	Video,
29	/// Live camera feed.
30	CameraStream,
31}
32
33/// Viewport rectangle and depth range.
34///
35/// Donor: `oa::ViewportDesc`.
36#[derive(Clone, Copy, Debug, PartialEq)]
37pub struct ViewportDesc {
38	pub x: i32,
39	pub y: i32,
40	pub width: i32,
41	pub height: i32,
42	pub min_depth: f32,
43	pub max_depth: f32,
44}
45
46impl Default for ViewportDesc {
47	fn default() -> Self {
48		Self {
49			x: 0,
50			y: 0,
51			width: 1280,
52			height: 720,
53			min_depth: 0.0,
54			max_depth: 1.0,
55		}
56	}
57}
58
59impl ViewportDesc {
60	/// Return whether the rectangle is positive and the depth range is a
61	/// finite ordered subset of `[0, 1]`.
62	#[must_use]
63	pub fn is_valid(&self) -> bool {
64		self.width > 0
65			&& self.height > 0
66			&& self.min_depth.is_finite()
67			&& self.max_depth.is_finite()
68			&& self.min_depth >= 0.0
69			&& self.min_depth <= self.max_depth
70			&& self.max_depth <= 1.0
71	}
72
73	/// Return `width / height`.
74	///
75	/// # Errors
76	///
77	/// Returns [`ErrorKind::InvalidArgument`] when the description is invalid.
78	///
79	/// [`ErrorKind::InvalidArgument`]: crate::ErrorKind::InvalidArgument
80	pub fn aspect_ratio(&self) -> Result<f32> {
81		if !self.is_valid() {
82			return Err(Error::invalid_argument(
83				"ViewportDesc aspect ratio requires a valid viewport",
84			));
85		}
86		Ok(self.width as f32 / self.height as f32)
87	}
88}
89
90/// Scissor rectangle for clipping.
91///
92/// Donor: `oa::ScissorDesc`.
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub struct ScissorDesc {
95	pub x: i32,
96	pub y: i32,
97	pub width: i32,
98	pub height: i32,
99}
100
101impl Default for ScissorDesc {
102	fn default() -> Self {
103		Self {
104			x: 0,
105			y: 0,
106			width: 1280,
107			height: 720,
108		}
109	}
110}
111
112impl ScissorDesc {
113	/// Return whether the rectangle is positive.
114	#[must_use]
115	pub const fn is_valid(&self) -> bool {
116		self.width > 0 && self.height > 0
117	}
118
119	/// Return whether `(x, y)` lies inside the rectangle.
120	#[must_use]
121	pub const fn contains(&self, x: i32, y: i32) -> bool {
122		self.is_valid()
123			&& x as i64 >= self.x as i64
124			&& (x as i64) < self.x as i64 + self.width as i64
125			&& y as i64 >= self.y as i64
126			&& (y as i64) < self.y as i64 + self.height as i64
127	}
128}
129
130/// Layer/filter flags for selective rendering.
131///
132/// Donor: `oa::RenderLayer`.
133#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
134pub struct RenderLayer(pub u32);
135
136impl RenderLayer {
137	pub const NONE: Self = Self(0);
138	pub const DEFAULT: Self = Self(1 << 0);
139	pub const UI: Self = Self(1 << 1);
140	pub const OVERLAY: Self = Self(1 << 2);
141	pub const BACKGROUND: Self = Self(1 << 3);
142	pub const DEBUG: Self = Self(1 << 4);
143	pub const ALL: Self = Self(0xFFFF_FFFF);
144
145	/// Return whether `other` shares any bit with this mask.
146	#[must_use]
147	pub const fn intersects(self, other: Self) -> bool {
148		self.0 & other.0 != 0
149	}
150}
151
152impl std::ops::BitOr for RenderLayer {
153	type Output = Self;
154	fn bitor(self, rhs: Self) -> Self {
155		Self(self.0 | rhs.0)
156	}
157}
158
159impl std::ops::BitOrAssign for RenderLayer {
160	fn bitor_assign(&mut self, rhs: Self) {
161		self.0 |= rhs.0;
162	}
163}
164
165impl std::ops::BitAnd for RenderLayer {
166	type Output = Self;
167	fn bitand(self, rhs: Self) -> Self {
168		Self(self.0 & rhs.0)
169	}
170}
171
172/// Passive view description for rendering.
173///
174/// Declares camera, target, viewport, scissor, layer mask, and clear values.
175/// `setup_image_2d`/`setup_image_aspect_fit` manufacture and retain an
176/// orthographic camera internally; an externally borrowed camera supplied
177/// later through [`Self::set_camera`] takes precedence again.
178///
179/// Donor: `oa::Viewport`.
180pub struct Viewport<'a> {
181	mode: ViewportMode,
182	camera: Option<&'a Camera>,
183	internal_camera: Option<Camera>,
184	target: Option<&'a Texture>,
185	viewport: ViewportDesc,
186	scissor: ScissorDesc,
187	use_scissor: bool,
188	layer_mask: RenderLayer,
189	clear_color: [f32; 4],
190	clear_depth: f32,
191}
192
193impl<'a> Default for Viewport<'a> {
194	fn default() -> Self {
195		Self::with_mode(ViewportMode::Image2D)
196	}
197}
198
199impl<'a> Viewport<'a> {
200	/// Create a viewport for `mode`.
201	#[must_use]
202	pub fn with_mode(mode: ViewportMode) -> Self {
203		Self {
204			mode,
205			camera: None,
206			internal_camera: None,
207			target: None,
208			viewport: ViewportDesc::default(),
209			scissor: ScissorDesc::default(),
210			use_scissor: false,
211			layer_mask: RenderLayer::DEFAULT,
212			clear_color: [0.01, 0.01, 0.01, 1.0],
213			clear_depth: 1.0,
214		}
215	}
216
217	/// Set the content mode.
218	pub fn set_mode(&mut self, mode: ViewportMode) {
219		self.mode = mode;
220	}
221
222	/// Return the content mode.
223	#[must_use]
224	pub const fn mode(&self) -> ViewportMode {
225		self.mode
226	}
227
228	/// Borrow an external camera, or `None` to clear one.
229	pub fn set_camera(&mut self, camera: Option<&'a Camera>) {
230		self.camera = camera;
231	}
232
233	/// Return the active camera — the borrowed external camera when present,
234	/// otherwise the internally manufactured one.
235	#[must_use]
236	pub fn camera(&self) -> Option<&Camera> {
237		self.camera.or(self.internal_camera.as_ref())
238	}
239
240	/// Borrow the render target, or `None` to clear it.
241	pub fn set_target(&mut self, target: Option<&'a Texture>) {
242		self.target = target;
243	}
244
245	/// Return the borrowed render target.
246	#[must_use]
247	pub const fn target(&self) -> Option<&'a Texture> {
248		self.target
249	}
250
251	/// Set the viewport rectangle and depth range.
252	///
253	/// # Errors
254	///
255	/// Returns an error for non-positive dimensions or a depth range outside
256	/// `[0, 1]`.
257	pub fn set_viewport(&mut self, viewport: ViewportDesc) -> Result<()> {
258		if !viewport.is_valid() {
259			return Err(Error::invalid_argument(
260				"Viewport::set_viewport requires positive dimensions and a finite [0,1] depth range",
261			));
262		}
263		self.viewport = viewport;
264		Ok(())
265	}
266
267	/// Return the configured viewport rectangle.
268	#[must_use]
269	pub const fn viewport(&self) -> ViewportDesc {
270		self.viewport
271	}
272
273	/// Enable scissor clipping with `scissor`.
274	///
275	/// # Errors
276	///
277	/// Returns an error for non-positive dimensions.
278	pub fn set_scissor(&mut self, scissor: ScissorDesc) -> Result<()> {
279		if !scissor.is_valid() {
280			return Err(Error::invalid_argument(
281				"Viewport::set_scissor requires positive dimensions",
282			));
283		}
284		self.scissor = scissor;
285		self.use_scissor = true;
286		Ok(())
287	}
288
289	/// Disable scissor clipping.
290	pub fn disable_scissor(&mut self) {
291		self.use_scissor = false;
292	}
293
294	/// Return whether scissor clipping is enabled.
295	#[must_use]
296	pub const fn is_scissor_enabled(&self) -> bool {
297		self.use_scissor
298	}
299
300	/// Return the configured scissor rectangle.
301	#[must_use]
302	pub const fn scissor(&self) -> ScissorDesc {
303		self.scissor
304	}
305
306	/// Set the layer visibility mask.
307	pub fn set_layer_mask(&mut self, mask: RenderLayer) {
308		self.layer_mask = mask;
309	}
310
311	/// Return the layer visibility mask.
312	#[must_use]
313	pub const fn layer_mask(&self) -> RenderLayer {
314		self.layer_mask
315	}
316
317	/// Return whether `layer` passes the visibility mask.
318	#[must_use]
319	pub const fn is_layer_visible(&self, layer: RenderLayer) -> bool {
320		self.layer_mask.intersects(layer)
321	}
322
323	/// Set the RGBA clear color.
324	///
325	/// # Errors
326	///
327	/// Returns an error for non-finite components.
328	pub fn set_clear_color(&mut self, color: [f32; 4]) -> Result<()> {
329		if !color.iter().all(|component| component.is_finite()) {
330			return Err(Error::invalid_argument(
331				"Viewport::set_clear_color requires finite components",
332			));
333		}
334		self.clear_color = color;
335		Ok(())
336	}
337
338	/// Return the RGBA clear color.
339	#[must_use]
340	pub const fn clear_color(&self) -> [f32; 4] {
341		self.clear_color
342	}
343
344	/// Set the clear depth.
345	///
346	/// # Errors
347	///
348	/// Returns an error for a non-finite value or one outside `[0, 1]`.
349	pub fn set_clear_depth(&mut self, depth: f32) -> Result<()> {
350		if !depth.is_finite() || !(0.0..=1.0).contains(&depth) {
351			return Err(Error::invalid_argument(
352				"Viewport::set_clear_depth requires a finite value in [0,1]",
353			));
354		}
355		self.clear_depth = depth;
356		Ok(())
357	}
358
359	/// Return the clear depth.
360	#[must_use]
361	pub const fn clear_depth(&self) -> f32 {
362		self.clear_depth
363	}
364
365	/// Return whether the viewport is complete and consistent: an active
366	/// camera, a borrowed target, a valid viewport rectangle, a valid
367	/// enabled scissor, and finite clear values.
368	#[must_use]
369	pub fn is_valid(&self) -> bool {
370		self.camera().is_some()
371			&& self.target.is_some()
372			&& self.viewport.is_valid()
373			&& (!self.use_scissor || self.scissor.is_valid())
374			&& self
375				.clear_color
376				.iter()
377				.all(|component| component.is_finite())
378			&& self.clear_depth.is_finite()
379			&& (0.0..=1.0).contains(&self.clear_depth)
380	}
381
382	/// Set up orthographic 2D image viewing over `target`.
383	///
384	/// Manufactures an internal orthographic camera matching the image
385	/// extent; a later [`Self::set_camera`] overrides it again.
386	///
387	/// # Errors
388	///
389	/// Returns an error for non-positive image dimensions or an invalid
390	/// viewport.
391	pub fn setup_image_2d(
392		&mut self,
393		image_width: f32,
394		image_height: f32,
395		target: &'a Texture,
396		viewport: ViewportDesc,
397	) -> Result<()> {
398		if !image_width.is_finite()
399			|| !image_height.is_finite()
400			|| image_width <= 0.0
401			|| image_height <= 0.0
402		{
403			return Err(Error::invalid_argument(
404				"Viewport::setup_image_2d requires finite positive image dimensions",
405			));
406		}
407		if !viewport.is_valid() {
408			return Err(Error::invalid_argument(
409				"Viewport::setup_image_2d requires a valid viewport",
410			));
411		}
412		self.internal_camera = Some(Camera::new_orthographic(
413			image_width,
414			image_height,
415			0.0,
416			1.0,
417		));
418		self.camera = None;
419		self.mode = ViewportMode::Image2D;
420		self.target = Some(target);
421		self.viewport = viewport;
422		self.scissor = ScissorDesc {
423			x: viewport.x,
424			y: viewport.y,
425			width: viewport.width,
426			height: viewport.height,
427		};
428		self.use_scissor = false;
429		Ok(())
430	}
431
432	/// Set up aspect-fitted image display: a centered letterboxed viewport
433	/// preserving the image aspect inside the window.
434	///
435	/// # Errors
436	///
437	/// Returns an error for non-positive dimensions, a window exceeding
438	/// signed pixel coordinates, or a result that cannot be represented as a
439	/// positive pixel rectangle.
440	pub fn setup_image_aspect_fit(
441		&mut self,
442		image_width: f32,
443		image_height: f32,
444		window_width: f32,
445		window_height: f32,
446		target: &'a Texture,
447	) -> Result<()> {
448		if !image_width.is_finite()
449			|| !image_height.is_finite()
450			|| !window_width.is_finite()
451			|| !window_height.is_finite()
452			|| image_width <= 0.0
453			|| image_height <= 0.0
454			|| window_width <= 0.0
455			|| window_height <= 0.0
456		{
457			return Err(Error::invalid_argument(
458				"Viewport::setup_image_aspect_fit requires finite positive image and window dimensions",
459			));
460		}
461		let max_pixel = f64::from(i32::MAX);
462		if f64::from(window_width) > max_pixel || f64::from(window_height) > max_pixel {
463			return Err(Error::out_of_range(
464				"Viewport::setup_image_aspect_fit window exceeds signed pixel coordinates",
465			));
466		}
467		let image_aspect = f64::from(image_width) / f64::from(image_height);
468		let window_aspect = f64::from(window_width) / f64::from(window_height);
469		let (display_width, display_height) = if image_aspect > window_aspect {
470			(
471				f64::from(window_width),
472				f64::from(window_width) / image_aspect,
473			)
474		} else {
475			(
476				f64::from(window_height) * image_aspect,
477				f64::from(window_height),
478			)
479		};
480		let offset_x = (f64::from(window_width) - display_width) * 0.5;
481		let offset_y = (f64::from(window_height) - display_height) * 0.5;
482		if !display_width.is_finite()
483			|| !display_height.is_finite()
484			|| !offset_x.is_finite()
485			|| !offset_y.is_finite()
486			|| display_width < 0.5
487			|| display_height < 0.5
488			|| display_width > max_pixel
489			|| display_height > max_pixel
490			|| offset_x < 0.0
491			|| offset_y < 0.0
492			|| offset_x > max_pixel
493			|| offset_y > max_pixel
494		{
495			return Err(Error::out_of_range(
496				"Viewport::setup_image_aspect_fit result cannot be represented as a positive pixel rectangle",
497			));
498		}
499		let viewport = ViewportDesc {
500			x: offset_x.round() as i32,
501			y: offset_y.round() as i32,
502			width: display_width.round() as i32,
503			height: display_height.round() as i32,
504			min_depth: 0.0,
505			max_depth: 1.0,
506		};
507		self.setup_image_2d(image_width, image_height, target, viewport)
508	}
509}