ferravex_math/projection.rs
1//! Prepared, viewport-aware 3D projection and finite picking rays.
2//!
3//! Supply the actual world-to-clip matrix and its conventions explicitly. This
4//! module does not infer camera position, handedness, depth range, viewport, or
5//! finite/infinite far intent from matrix coefficients. It caches the existing
6//! [`Mat4::checked_inverse`]; point transforms reuse [`Mat4::try_project_point3`].
7//! Preparation and queries use fixed stack storage and no heap allocations.
8//! There is no clock, input, renderer, or physics ownership here.
9//!
10//! # Coordinates and clipping
11//!
12//! Screen positions and viewport dimensions share caller-selected units, normally
13//! host logical pixels. Apply framebuffer/DPR conversion at the host boundary.
14//! X increases right; [`ScreenYAxis`] defines screen Y. Viewport origin always
15//! means the numerical minimum corner. NDC X/Y run from -1 to +1. Screen edges
16//! map to NDC edges, with **no implicit half-pixel offset**. For an integer pixel
17//! index, supply `origin + (index + 0.5)` to sample its center. Both edges are
18//! inclusive; a host sharing adjacent rectangles must resolve edge ownership.
19//!
20//! Depth is returned/accepted as NDC Z, never a linear world distance or a
21//! remapped window-depth value. [`NdcDepth`] names physical near and far endpoint
22//! values, including reversed depth. All membership tests are exact inclusive
23//! comparisons on the computed values, without epsilon or clamping.
24//!
25//! Matrices must use positive homogeneous W in the supported clip volume (as
26//! Ferravex perspective and orthographic constructors do). Projection rejects
27//! negative W as [`ProjectionError::BehindCamera`] and zero W as a matrix error.
28//! This is a projective half-space test, **not** an inferred eye position: an
29//! orthographic matrix has constant W, so behind-eye points are identified only
30//! by their out-of-range depth. Projection permits outside XY/depth and reports
31//! membership flags, useful for HUD anchors. Unprojection/picking reject outside
32//! inputs. No operation promises accuracy for ill-conditioned matrices.
33//!
34//! # Runnable camera, HUD anchor, and picking recipe
35//!
36//! This headless first-party recipe uses the same RH GL depth convention as
37//! `ferravex-render::Camera3D`. Graphics cameras using `perspective_rh` instead
38//! need `NdcDepth::ZeroToOne`. A graphics `ClipDepth` adapter belongs in graphics,
39//! never as a dependency of this math module.
40//!
41//! ```rust
42//! use ferravex_math::{Mat4, Vec3, vec2, vec3};
43//! use ferravex_math::projection::{
44//! FarPlane, NdcDepth, PreparedProjector3D, ScreenYAxis, Viewport,
45//! };
46//!
47//! fn main() -> Result<(), Box<dyn std::error::Error>> {
48//! // A host has already reserved the header and selected this logical viewport.
49//! let viewport = Viewport { origin: vec2(20., 80.), size: vec2(800., 400.) };
50//! let view = Mat4::try_look_at_rh(vec3(0., 0., 5.), Vec3::ZERO, Vec3::Y)?;
51//! let lens = Mat4::try_perspective_rh_gl(1., 2., 0.5, 50.)?;
52//! let mut projector = PreparedProjector3D::try_new(
53//! lens * view, viewport, ScreenYAxis::Down,
54//! NdcDepth::NegativeOneToOne, FarPlane::Finite,
55//! )?;
56//! let anchor = projector.project(Vec3::ZERO)?;
57//! assert!(anchor.inside_viewport && anchor.inside_depth);
58//! assert!(anchor.screen.abs_diff_eq(vec2(420., 280.), 0.001));
59//! let restored = projector.unproject(anchor.screen, anchor.ndc_depth)?;
60//! assert!(restored.abs_diff_eq(Vec3::ZERO, 0.0001));
61//!
62//! // A logical pointer uses the same viewport as drawing; no DPR multiplication.
63//! let ray = projector.pick_ray(anchor.screen)?;
64//! assert!(ray.origin.abs_diff_eq(vec3(0., 0., 4.5), 0.0001));
65//! assert!(ray.direction.abs_diff_eq(Vec3::NEG_Z, 0.0001));
66//! // Intersect the z=0 authoring plane. A physics consumer can instead pass
67//! // origin/direction to its own query and cap distance at the far endpoint.
68//! let distance = -ray.origin.z / ray.direction.z;
69//! let hit = ray.origin + ray.direction * distance;
70//! assert!(hit.abs_diff_eq(Vec3::ZERO, 0.0001));
71//! assert!(ray.far_point.z < hit.z);
72//!
73//! // Resize/camera updates are transactional. Suspend rendering/input after
74//! // a zero-size error; the retained transform remains usable on restoration.
75//! let before = projector;
76//! let suspended = Viewport { size: vec2(0., 0.), ..viewport };
77//! assert!(projector.try_update(lens * view, suspended, ScreenYAxis::Down,
78//! NdcDepth::NegativeOneToOne, FarPlane::Finite).is_err());
79//! assert_eq!(projector, before);
80//! Ok(())
81//! }
82//! ```
83
84use crate::{Mat4, MatrixError, Vec2, Vec3, vec2, vec3};
85
86/// Numerical minimum and positive extent in the same units as screen queries.
87///
88/// Preparation requires each extent to be at least one logical unit. The maximum
89/// edge is `origin + size`, rounded to f32; mapping and membership both use those
90/// same rounded edges. Nonfinite, overflowing, or collapsed edges are rejected.
91/// See the module recipe for construction with an offset viewport.
92#[derive(Clone, Copy, Debug, PartialEq)]
93pub struct Viewport {
94 /// Minimum X/Y screen coordinate, independent of screen Y direction.
95 pub origin: Vec2,
96 /// Width/height, each at least one screen unit when prepared.
97 pub size: Vec2,
98}
99
100/// Direction in which numerical screen Y increases; NDC +Y is always up.
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102pub enum ScreenYAxis {
103 /// NDC +Y maps to the maximum screen Y edge.
104 Up,
105 /// NDC +Y maps to the minimum screen Y edge (usual logical pixel convention).
106 Down,
107}
108
109/// Explicit NDC Z endpoints, ordered by physical near-to-far, not numeric value.
110///
111/// ```
112/// use ferravex_math::projection::NdcDepth;
113/// assert_eq!(NdcDepth::ReverseZeroToOne.near(), 1.);
114/// assert_eq!(NdcDepth::ReverseZeroToOne.far(), 0.);
115/// ```
116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
117pub enum NdcDepth {
118 /// Near -1, far +1 (RH GL constructors and render Camera3D).
119 NegativeOneToOne,
120 /// Near 0, far +1 (RH/LH non-GL constructors and graphics Camera).
121 ZeroToOne,
122 /// Near +1, far -1; supply a matrix authored for reversed GL depth.
123 ReverseNegativeOneToOne,
124 /// Near +1, far 0; supply a matrix authored for reversed zero-to-one depth.
125 ReverseZeroToOne,
126}
127
128impl NdcDepth {
129 /// Physical near plane's NDC Z. See the enum example.
130 pub const fn near(self) -> f32 {
131 match self {
132 Self::NegativeOneToOne => -1.,
133 Self::ZeroToOne => 0.,
134 Self::ReverseNegativeOneToOne | Self::ReverseZeroToOne => 1.,
135 }
136 }
137
138 /// Physical far plane's NDC Z. See the enum example.
139 pub const fn far(self) -> f32 {
140 match self {
141 Self::NegativeOneToOne | Self::ZeroToOne => 1.,
142 Self::ReverseNegativeOneToOne => -1.,
143 Self::ReverseZeroToOne => 0.,
144 }
145 }
146
147 fn contains(self, z: f32) -> bool {
148 z >= self.near().min(self.far()) && z <= self.near().max(self.far())
149 }
150}
151
152/// Caller declaration of far-plane intent; it cannot be recovered reliably from
153/// rounded, composed matrix coefficients. Infinite far is explicitly unsupported.
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub enum FarPlane {
156 /// Caller authored a finite far plane; preparation also checks the clip volume.
157 Finite,
158 /// Always rejected, even if coefficient rounding happens to yield finite points.
159 Infinite,
160}
161
162/// Checked projection/preparation failure, with no fallback camera or point.
163///
164/// ```
165/// use ferravex_math::projection::ProjectionError;
166/// let error: &dyn std::error::Error = &ProjectionError::OutsideViewport;
167/// assert!(error.to_string().contains("viewport"));
168/// ```
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170#[non_exhaustive]
171pub enum ProjectionError {
172 /// Existing checked matrix diagnostic (including singular, nonfinite, zero W,
173 /// or an unrepresentable projected coordinate).
174 Matrix(MatrixError),
175 /// Nonfinite viewport, extent below one, or overflowing/collapsed f32 edges.
176 InvalidViewport,
177 /// The caller declared an infinite far plane, which this API does not support.
178 UnsupportedInfiniteFar,
179 /// A corner has nonpositive inverse W. The declared closed clip volume
180 /// touches/crosses infinity or lies outside the supported positive-W half-space.
181 InvalidClipVolume,
182 /// Projected point has negative homogeneous W.
183 BehindCamera,
184 /// Screen input contains NaN or infinity (checked before membership).
185 NonFiniteScreen,
186 /// NDC depth input is NaN or infinity (checked before membership).
187 NonFiniteDepth,
188 /// Screen input is outside the inclusive viewport.
189 OutsideViewport,
190 /// Finite NDC depth input is outside the inclusive declared depth interval.
191 OutsideDepth,
192 /// A screen output cannot round to finite f32.
193 ResultOutOfRange,
194 /// Rounded near/far world endpoints coincide; no direction can be normalized.
195 DegenerateRay,
196}
197
198impl std::fmt::Display for ProjectionError {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 match self {
201 Self::Matrix(error) => write!(f, "projection matrix operation failed: {error}"),
202 Self::InvalidViewport => f.write_str(
203 "viewport needs finite, distinct edges and extents of at least one screen unit",
204 ),
205 Self::UnsupportedInfiniteFar => f.write_str(
206 "infinite far projection is unsupported; supply an authored finite-far camera",
207 ),
208 Self::InvalidClipVolume => f.write_str(
209 "clip volume must have finite endpoints and positive inverse homogeneous W",
210 ),
211 Self::BehindCamera => f.write_str("point is behind the positive-W camera half-space"),
212 Self::NonFiniteScreen => f.write_str("screen position must be finite"),
213 Self::NonFiniteDepth => f.write_str("NDC depth must be finite"),
214 Self::OutsideViewport => {
215 f.write_str("screen position is outside the inclusive viewport")
216 }
217 Self::OutsideDepth => {
218 f.write_str("NDC depth is outside the declared near/far interval")
219 }
220 Self::ResultOutOfRange => f.write_str("screen result exceeds finite f32 range"),
221 Self::DegenerateRay => {
222 f.write_str("near and far endpoints coincide after f32 rounding")
223 }
224 }
225 }
226}
227
228impl std::error::Error for ProjectionError {
229 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
230 match self {
231 Self::Matrix(error) => Some(error),
232 _ => None,
233 }
234 }
235}
236
237impl From<MatrixError> for ProjectionError {
238 fn from(error: MatrixError) -> Self {
239 Self::Matrix(error)
240 }
241}
242
243/// A finite positive-W projection, including unclamped clip membership.
244/// See the module's HUD recipe. Membership is not occlusion testing.
245#[derive(Clone, Copy, Debug, PartialEq)]
246pub struct ProjectedPoint {
247 /// Absolute screen coordinates, possibly outside the viewport.
248 pub screen: Vec2,
249 /// Unmodified NDC Z, possibly outside the declared near/far interval.
250 pub ndc_depth: f32,
251 /// True when computed NDC X/Y are both within inclusive -1..=1.
252 pub inside_viewport: bool,
253 /// True when computed NDC Z is inside the declared inclusive interval.
254 pub inside_depth: bool,
255}
256
257/// Picking ray with explicit finite clipping endpoints. See the module recipe.
258#[derive(Clone, Copy, Debug, PartialEq)]
259pub struct PickingRay3D {
260 /// World point on the physical near plane, **not** an inferred camera eye.
261 pub origin: Vec3,
262 /// Unit world direction from near toward far (subject to f32 rounding).
263 /// `origin + direction * t` uses world-distance t >= 0.
264 pub direction: Vec3,
265 /// World point on the physical finite far plane. Consumers enforcing camera
266 /// clipping should limit their query to this endpoint; the ray has no implicit cap.
267 pub far_point: Vec3,
268}
269
270/// Validated world-to-clip transform and cached clip-to-world inverse.
271///
272/// Perspective and orthographic finite-far matrices are supported, including
273/// reversed depth and either handedness. Preparation checks all eight NDC box
274/// corners for positive inverse W and representable world coordinates. Because
275/// inverse W is affine, positive corner values exclude infinity throughout the
276/// closed box in the cached transform. This cannot certify original camera
277/// intent after matrix rounding: callers must declare [`FarPlane`] truthfully.
278///
279/// The inverse has f32 coefficients and the same conditioning/underflow limits
280/// as [`Mat4::checked_inverse`]. Degenerate rays after endpoint rounding remain
281/// query errors. No implicit matrix normalization changes the W-sign policy.
282/// See the complete module recipe for construction, queries and failed updates.
283#[derive(Clone, Copy, Debug, PartialEq)]
284pub struct PreparedProjector3D {
285 view_projection: Mat4,
286 inverse: Mat4,
287 viewport: Viewport,
288 end: Vec2,
289 y_axis: ScreenYAxis,
290 depth: NdcDepth,
291}
292
293impl PreparedProjector3D {
294 /// Prepares a finite-far camera. See the module recipe.
295 ///
296 /// Validation order: viewport, explicit far intent, checked inverse, then
297 /// clip-volume corners. No inverse is recomputed during point/ray queries.
298 pub fn try_new(
299 view_projection: Mat4,
300 viewport: Viewport,
301 y_axis: ScreenYAxis,
302 depth: NdcDepth,
303 far_plane: FarPlane,
304 ) -> Result<Self, ProjectionError> {
305 if !viewport.origin.is_finite()
306 || !viewport.size.is_finite()
307 || viewport.size.x < 1.
308 || viewport.size.y < 1.
309 {
310 return Err(ProjectionError::InvalidViewport);
311 }
312 let end = viewport.origin + viewport.size;
313 if !end.is_finite() || end.x <= viewport.origin.x || end.y <= viewport.origin.y {
314 return Err(ProjectionError::InvalidViewport);
315 }
316 if far_plane == FarPlane::Infinite {
317 return Err(ProjectionError::UnsupportedInfiniteFar);
318 }
319 let inverse = view_projection.checked_inverse()?;
320 for z in [depth.near(), depth.far()] {
321 for y in [-1., 1.] {
322 for x in [-1., 1.] {
323 let ndc = vec3(x, y, z);
324 if homogeneous_w(inverse, ndc) <= 0. {
325 return Err(ProjectionError::InvalidClipVolume);
326 }
327 inverse.try_project_point3(ndc)?;
328 }
329 }
330 }
331 Ok(Self {
332 view_projection,
333 inverse,
334 viewport,
335 end,
336 y_axis,
337 depth,
338 })
339 }
340
341 /// Replaces all prepared state only after successful validation. Any error
342 /// retains the prior camera, inverse and viewport; see the module recipe.
343 pub fn try_update(
344 &mut self,
345 view_projection: Mat4,
346 viewport: Viewport,
347 y_axis: ScreenYAxis,
348 depth: NdcDepth,
349 far_plane: FarPlane,
350 ) -> Result<(), ProjectionError> {
351 *self = Self::try_new(view_projection, viewport, y_axis, depth, far_plane)?;
352 Ok(())
353 }
354
355 /// Projects a world point without clipping XY/depth. Returns separate
356 /// membership flags; rejects nonfinite points, zero/negative W, and range
357 /// failures. Tiny positive W is allowed with no arbitrary epsilon.
358 /// Finite negative-W points return `BehindCamera` before perspective division;
359 /// nonfinite inputs and zero W retain their checked matrix diagnostics.
360 /// See the module HUD recipe.
361 pub fn project(&self, world: Vec3) -> Result<ProjectedPoint, ProjectionError> {
362 if world.is_finite() && homogeneous_w(self.view_projection, world) < 0. {
363 return Err(ProjectionError::BehindCamera);
364 }
365 let ndc = self.view_projection.try_project_point3(world)?;
366 let x = (f64::from(ndc.x) + 1.) * 0.5;
367 let y = match self.y_axis {
368 ScreenYAxis::Up => (f64::from(ndc.y) + 1.) * 0.5,
369 ScreenYAxis::Down => (1. - f64::from(ndc.y)) * 0.5,
370 };
371 let screen = vec2(
372 screen_f32(f64::from(self.viewport.origin.x) + x * self.span_x())?,
373 screen_f32(f64::from(self.viewport.origin.y) + y * self.span_y())?,
374 );
375 Ok(ProjectedPoint {
376 screen,
377 ndc_depth: ndc.z,
378 inside_viewport: ndc.x >= -1. && ndc.x <= 1. && ndc.y >= -1. && ndc.y <= 1.,
379 inside_depth: self.depth.contains(ndc.z),
380 })
381 }
382
383 /// Unprojects an inclusive viewport position and inclusive NDC depth through
384 /// the cached inverse. Rejects nonfinite inputs, then outside XY, then outside
385 /// depth. No extrapolation/clamping or window-depth conversion is performed.
386 /// See the module round-trip recipe.
387 pub fn unproject(&self, screen: Vec2, ndc_depth: f32) -> Result<Vec3, ProjectionError> {
388 if !screen.is_finite() {
389 return Err(ProjectionError::NonFiniteScreen);
390 }
391 if !ndc_depth.is_finite() {
392 return Err(ProjectionError::NonFiniteDepth);
393 }
394 if screen.x < self.viewport.origin.x
395 || screen.y < self.viewport.origin.y
396 || screen.x > self.end.x
397 || screen.y > self.end.y
398 {
399 return Err(ProjectionError::OutsideViewport);
400 }
401 if !self.depth.contains(ndc_depth) {
402 return Err(ProjectionError::OutsideDepth);
403 }
404 let x = 2. * (f64::from(screen.x) - f64::from(self.viewport.origin.x)) / self.span_x() - 1.;
405 let y = 2. * (f64::from(screen.y) - f64::from(self.viewport.origin.y)) / self.span_y() - 1.;
406 let y = if self.y_axis == ScreenYAxis::Down {
407 -y
408 } else {
409 y
410 };
411 Ok(self
412 .inverse
413 .try_project_point3(vec3(x as f32, y as f32, ndc_depth))?)
414 }
415
416 /// Near-plane-origin ray toward the physical finite far endpoint. Orthographic
417 /// rays are parallel with distinct origins; perspective rays diverge from
418 /// near-plane origins. Never guesses an eye or substitutes a finite far value.
419 /// Endpoint subtraction/normalization uses f64 so extreme finite endpoints
420 /// need not have a representable f32 difference. See the module picking recipe.
421 pub fn pick_ray(&self, screen: Vec2) -> Result<PickingRay3D, ProjectionError> {
422 let origin = self.unproject(screen, self.depth.near())?;
423 let far_point = self.unproject(screen, self.depth.far())?;
424 let delta = [
425 f64::from(far_point.x) - f64::from(origin.x),
426 f64::from(far_point.y) - f64::from(origin.y),
427 f64::from(far_point.z) - f64::from(origin.z),
428 ];
429 let length = delta.into_iter().map(|v| v * v).sum::<f64>().sqrt();
430 if length == 0. {
431 return Err(ProjectionError::DegenerateRay);
432 }
433 let direction = Vec3::from_array(delta.map(|v| (v / length) as f32));
434 Ok(PickingRay3D {
435 origin,
436 direction,
437 far_point,
438 })
439 }
440
441 fn span_x(&self) -> f64 {
442 f64::from(self.end.x) - f64::from(self.viewport.origin.x)
443 }
444
445 fn span_y(&self) -> f64 {
446 f64::from(self.end.y) - f64::from(self.viewport.origin.y)
447 }
448}
449
450fn homogeneous_w(matrix: Mat4, point: Vec3) -> f64 {
451 matrix
452 .row(3)
453 .to_array()
454 .into_iter()
455 .zip(point.extend(1.).to_array())
456 .map(|(a, b)| f64::from(a) * f64::from(b))
457 .sum()
458}
459
460fn screen_f32(value: f64) -> Result<f32, ProjectionError> {
461 let value = value as f32;
462 if value.is_finite() {
463 Ok(value)
464 } else {
465 Err(ProjectionError::ResultOutOfRange)
466 }
467}