1use std::{error::Error, fmt};
2
3use crate::{LogicalScreenPosition, LogicalViewport, WorldLength};
4
5#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Vec3 {
11 x: f32,
12 y: f32,
13 z: f32,
14}
15
16impl Vec3 {
17 pub const ZERO: Self = Self::new_unchecked(0.0, 0.0, 0.0);
19 pub const X: Self = Self::new_unchecked(1.0, 0.0, 0.0);
21 pub const Y: Self = Self::new_unchecked(0.0, 1.0, 0.0);
23 pub const Z: Self = Self::new_unchecked(0.0, 0.0, 1.0);
25
26 pub fn new(x: f32, y: f32, z: f32) -> Result<Self, Pseudo3dError> {
28 if x.is_finite() && y.is_finite() && z.is_finite() {
29 Ok(Self::new_unchecked(x, y, z))
30 } else {
31 Err(Pseudo3dError::NonFiniteVector { x, y, z })
32 }
33 }
34
35 pub(crate) const fn new_unchecked(x: f32, y: f32, z: f32) -> Self {
36 Self { x, y, z }
37 }
38
39 fn from_f64(x: f64, y: f64, z: f64) -> Result<Self, Pseudo3dError> {
40 if x.is_finite()
41 && y.is_finite()
42 && z.is_finite()
43 && x.abs() <= f32::MAX as f64
44 && y.abs() <= f32::MAX as f64
45 && z.abs() <= f32::MAX as f64
46 {
47 Ok(Self::new_unchecked(x as f32, y as f32, z as f32))
48 } else {
49 Err(Pseudo3dError::ArithmeticOverflow)
50 }
51 }
52
53 pub const fn x(self) -> f32 {
55 self.x
56 }
57
58 pub const fn y(self) -> f32 {
60 self.y
61 }
62
63 pub const fn z(self) -> f32 {
65 self.z
66 }
67
68 pub fn checked_add(self, other: Self) -> Result<Self, Pseudo3dError> {
70 Self::from_f64(
71 self.x as f64 + other.x as f64,
72 self.y as f64 + other.y as f64,
73 self.z as f64 + other.z as f64,
74 )
75 }
76
77 pub fn checked_sub(self, other: Self) -> Result<Self, Pseudo3dError> {
79 Self::from_f64(
80 self.x as f64 - other.x as f64,
81 self.y as f64 - other.y as f64,
82 self.z as f64 - other.z as f64,
83 )
84 }
85
86 pub fn checked_scale(self, scale: f32) -> Result<Self, Pseudo3dError> {
88 if !scale.is_finite() {
89 return Err(Pseudo3dError::NonFiniteScalar { value: scale });
90 }
91 Self::from_f64(
92 self.x as f64 * scale as f64,
93 self.y as f64 * scale as f64,
94 self.z as f64 * scale as f64,
95 )
96 }
97
98 pub fn checked_dot(self, other: Self) -> Result<f32, Pseudo3dError> {
100 f64_to_f32(
101 self.x as f64 * other.x as f64
102 + self.y as f64 * other.y as f64
103 + self.z as f64 * other.z as f64,
104 )
105 }
106
107 pub fn checked_cross(self, other: Self) -> Result<Self, Pseudo3dError> {
109 Self::from_f64(
110 self.y as f64 * other.z as f64 - self.z as f64 * other.y as f64,
111 self.z as f64 * other.x as f64 - self.x as f64 * other.z as f64,
112 self.x as f64 * other.y as f64 - self.y as f64 * other.x as f64,
113 )
114 }
115
116 pub fn normalized(self) -> Result<Self, Pseudo3dError> {
118 let length = length_f64(self);
119 if length == 0.0 {
120 return Err(Pseudo3dError::ZeroLengthVector);
121 }
122 Self::from_f64(
123 self.x as f64 / length,
124 self.y as f64 / length,
125 self.z as f64 / length,
126 )
127 }
128}
129
130#[derive(Debug, Clone, Copy, PartialEq)]
132pub struct Rotation3d {
133 x: f32,
134 y: f32,
135 z: f32,
136 w: f32,
137}
138
139impl Rotation3d {
140 pub const IDENTITY: Self = Self {
142 x: 0.0,
143 y: 0.0,
144 z: 0.0,
145 w: 1.0,
146 };
147
148 pub fn from_axis_angle(axis: Vec3, radians: f32) -> Result<Self, Pseudo3dError> {
150 if !radians.is_finite() {
151 return Err(Pseudo3dError::NonFiniteAngle { radians });
152 }
153 let axis = axis.normalized()?;
154 let (sine, cosine) = (radians as f64 * 0.5).sin_cos();
155 Self::normalized_from_f64(
156 axis.x as f64 * sine,
157 axis.y as f64 * sine,
158 axis.z as f64 * sine,
159 cosine,
160 )
161 }
162
163 pub fn from_euler_xyz(x: f32, y: f32, z: f32) -> Result<Self, Pseudo3dError> {
165 let x_rotation = Self::from_axis_angle(Vec3::X, x)?;
166 let y_rotation = Self::from_axis_angle(Vec3::Y, y)?;
167 let z_rotation = Self::from_axis_angle(Vec3::Z, z)?;
168 x_rotation.then(y_rotation)?.then(z_rotation)
169 }
170
171 pub fn then(self, next: Self) -> Result<Self, Pseudo3dError> {
173 let left = next;
174 let right = self;
175 Self::normalized_from_f64(
176 left.w as f64 * right.x as f64
177 + left.x as f64 * right.w as f64
178 + left.y as f64 * right.z as f64
179 - left.z as f64 * right.y as f64,
180 left.w as f64 * right.y as f64 - left.x as f64 * right.z as f64
181 + left.y as f64 * right.w as f64
182 + left.z as f64 * right.x as f64,
183 left.w as f64 * right.z as f64 + left.x as f64 * right.y as f64
184 - left.y as f64 * right.x as f64
185 + left.z as f64 * right.w as f64,
186 left.w as f64 * right.w as f64
187 - left.x as f64 * right.x as f64
188 - left.y as f64 * right.y as f64
189 - left.z as f64 * right.z as f64,
190 )
191 }
192
193 pub fn rotate(self, vector: Vec3) -> Result<Vec3, Pseudo3dError> {
195 let qx = self.x as f64;
196 let qy = self.y as f64;
197 let qz = self.z as f64;
198 let qw = self.w as f64;
199 let vx = vector.x as f64;
200 let vy = vector.y as f64;
201 let vz = vector.z as f64;
202
203 let tx = 2.0 * (qy * vz - qz * vy);
204 let ty = 2.0 * (qz * vx - qx * vz);
205 let tz = 2.0 * (qx * vy - qy * vx);
206 Vec3::from_f64(
207 vx + qw * tx + (qy * tz - qz * ty),
208 vy + qw * ty + (qz * tx - qx * tz),
209 vz + qw * tz + (qx * ty - qy * tx),
210 )
211 }
212
213 fn normalized_from_f64(x: f64, y: f64, z: f64, w: f64) -> Result<Self, Pseudo3dError> {
214 let length = (x * x + y * y + z * z + w * w).sqrt();
215 if !length.is_finite() || length == 0.0 {
216 return Err(Pseudo3dError::ArithmeticOverflow);
217 }
218 let x = f64_to_f32(x / length)?;
219 let y = f64_to_f32(y / length)?;
220 let z = f64_to_f32(z / length)?;
221 let w = f64_to_f32(w / length)?;
222 Ok(Self { x, y, z, w })
223 }
224}
225
226#[derive(Debug, Clone, Copy, PartialEq)]
228pub struct Transform3d {
229 translation: Vec3,
230 rotation: Rotation3d,
231 scale: Vec3,
232}
233
234impl Transform3d {
235 pub const IDENTITY: Self = Self {
237 translation: Vec3::ZERO,
238 rotation: Rotation3d::IDENTITY,
239 scale: Vec3::new_unchecked(1.0, 1.0, 1.0),
240 };
241
242 pub fn new(
244 translation: Vec3,
245 rotation: Rotation3d,
246 scale: Vec3,
247 ) -> Result<Self, Pseudo3dError> {
248 if scale.x <= 0.0 || scale.y <= 0.0 || scale.z <= 0.0 {
249 return Err(Pseudo3dError::InvalidScale { scale });
250 }
251 Ok(Self {
252 translation,
253 rotation,
254 scale,
255 })
256 }
257
258 pub fn from_rotation_scale(rotation: Rotation3d, scale: f32) -> Result<Self, Pseudo3dError> {
260 let scale = Vec3::new(scale, scale, scale)?;
261 Self::new(Vec3::ZERO, rotation, scale)
262 }
263
264 pub const fn translation(self) -> Vec3 {
266 self.translation
267 }
268
269 pub const fn rotation(self) -> Rotation3d {
271 self.rotation
272 }
273
274 pub const fn scale(self) -> Vec3 {
276 self.scale
277 }
278
279 pub fn transform_point(self, point: Vec3) -> Result<Vec3, Pseudo3dError> {
281 let scaled = Vec3::from_f64(
282 point.x as f64 * self.scale.x as f64,
283 point.y as f64 * self.scale.y as f64,
284 point.z as f64 * self.scale.z as f64,
285 )?;
286 self.rotation.rotate(scaled)?.checked_add(self.translation)
287 }
288
289 #[cfg(feature = "wgpu")]
290 pub(crate) fn model_rows(self) -> Result<[[f32; 4]; 3], Pseudo3dError> {
291 let x = self.rotation.x as f64;
292 let y = self.rotation.y as f64;
293 let z = self.rotation.z as f64;
294 let w = self.rotation.w as f64;
295 let scale_x = self.scale.x as f64;
296 let scale_y = self.scale.y as f64;
297 let scale_z = self.scale.z as f64;
298 let rows = [
299 [
300 (1.0 - 2.0 * (y * y + z * z)) * scale_x,
301 (2.0 * (x * y - z * w)) * scale_y,
302 (2.0 * (x * z + y * w)) * scale_z,
303 self.translation.x as f64,
304 ],
305 [
306 (2.0 * (x * y + z * w)) * scale_x,
307 (1.0 - 2.0 * (x * x + z * z)) * scale_y,
308 (2.0 * (y * z - x * w)) * scale_z,
309 self.translation.y as f64,
310 ],
311 [
312 (2.0 * (x * z - y * w)) * scale_x,
313 (2.0 * (y * z + x * w)) * scale_y,
314 (1.0 - 2.0 * (x * x + y * y)) * scale_z,
315 self.translation.z as f64,
316 ],
317 ];
318 Ok([
319 f64_row_to_f32(rows[0])?,
320 f64_row_to_f32(rows[1])?,
321 f64_row_to_f32(rows[2])?,
322 ])
323 }
324}
325
326#[derive(Debug, Clone, Copy, PartialEq)]
328pub struct Projection3d {
329 kind: Projection3dKind,
330}
331
332#[derive(Debug, Clone, Copy, PartialEq)]
333enum Projection3dKind {
334 Perspective {
335 vertical_fov_radians: f32,
336 aspect_ratio: f32,
337 near: WorldLength,
338 far: WorldLength,
339 },
340 Orthographic {
341 vertical_span: WorldLength,
342 aspect_ratio: f32,
343 near: WorldLength,
344 far: WorldLength,
345 },
346}
347
348impl Projection3d {
349 pub fn perspective(
354 vertical_fov_radians: f32,
355 aspect_ratio: f32,
356 near: WorldLength,
357 far: WorldLength,
358 ) -> Result<Self, Pseudo3dError> {
359 if !valid_projection_range(aspect_ratio, near.get(), far.get())
360 || !vertical_fov_radians.is_finite()
361 || vertical_fov_radians <= 0.0
362 || vertical_fov_radians >= std::f32::consts::PI
363 || !(vertical_fov_radians as f64 * 0.5).tan().is_finite()
364 {
365 return Err(Pseudo3dError::InvalidProjection);
366 }
367 Ok(Self {
368 kind: Projection3dKind::Perspective {
369 vertical_fov_radians,
370 aspect_ratio,
371 near,
372 far,
373 },
374 })
375 }
376
377 pub fn orthographic(
379 vertical_span: WorldLength,
380 aspect_ratio: f32,
381 near: WorldLength,
382 far: WorldLength,
383 ) -> Result<Self, Pseudo3dError> {
384 if !valid_projection_range(aspect_ratio, near.get(), far.get()) {
385 return Err(Pseudo3dError::InvalidProjection);
386 }
387 Ok(Self {
388 kind: Projection3dKind::Orthographic {
389 vertical_span,
390 aspect_ratio,
391 near,
392 far,
393 },
394 })
395 }
396
397 pub const fn aspect_ratio(self) -> f32 {
399 match self.kind {
400 Projection3dKind::Perspective { aspect_ratio, .. }
401 | Projection3dKind::Orthographic { aspect_ratio, .. } => aspect_ratio,
402 }
403 }
404
405 pub const fn near(self) -> WorldLength {
407 match self.kind {
408 Projection3dKind::Perspective { near, .. }
409 | Projection3dKind::Orthographic { near, .. } => near,
410 }
411 }
412
413 pub const fn far(self) -> WorldLength {
415 match self.kind {
416 Projection3dKind::Perspective { far, .. }
417 | Projection3dKind::Orthographic { far, .. } => far,
418 }
419 }
420
421 pub const fn is_perspective(self) -> bool {
423 matches!(self.kind, Projection3dKind::Perspective { .. })
424 }
425}
426
427#[derive(Debug, Clone, Copy, PartialEq)]
429pub struct Camera3d {
430 position: Vec3,
431 right: Vec3,
432 up: Vec3,
433 forward: Vec3,
434 projection: Projection3d,
435}
436
437impl Camera3d {
438 pub fn look_at(
442 position: Vec3,
443 target: Vec3,
444 up_hint: Vec3,
445 projection: Projection3d,
446 ) -> Result<Self, Pseudo3dError> {
447 let forward = target.checked_sub(position)?.normalized()?;
448 let right = cross_f64(forward, up_hint)
449 .and_then(normalize_f64)
450 .ok_or(Pseudo3dError::InvalidCameraBasis)?;
451 let up = cross_f64(right, forward)
452 .and_then(normalize_f64)
453 .ok_or(Pseudo3dError::InvalidCameraBasis)?;
454 Ok(Self {
455 position,
456 right,
457 up,
458 forward,
459 projection,
460 })
461 }
462
463 pub const fn position(self) -> Vec3 {
465 self.position
466 }
467
468 #[cfg(feature = "wgpu")]
469 pub(crate) const fn forward(self) -> Vec3 {
470 self.forward
471 }
472
473 pub const fn projection(self) -> Projection3d {
475 self.projection
476 }
477
478 pub fn project_world(
489 self,
490 point: Vec3,
491 viewport: LogicalViewport,
492 ) -> Result<ProjectedPoint3d, Pseudo3dError> {
493 let relative = subtract_f64(point, self.position);
494 let view_x = dot_f64_tuple(relative, self.right);
495 let view_y = dot_f64_tuple(relative, self.up);
496 let view_depth = dot_f64_tuple(relative, self.forward);
497 if !view_depth.is_finite() || view_depth <= 0.0 {
498 return Err(Pseudo3dError::PointBehindCamera);
499 }
500
501 let (ndc_x, ndc_y, normalized_depth, near, far) = match self.projection.kind {
502 Projection3dKind::Perspective {
503 vertical_fov_radians,
504 aspect_ratio,
505 near,
506 far,
507 } => {
508 let near_value = near.get();
509 let far_value = far.get();
510 let half_height = view_depth * (vertical_fov_radians as f64 * 0.5).tan();
511 (
512 view_x / (half_height * aspect_ratio as f64),
513 view_y / half_height,
514 far_value as f64 / (far_value as f64 - near_value as f64)
515 - (far_value as f64 * near_value as f64)
516 / ((far_value as f64 - near_value as f64) * view_depth),
517 near,
518 far,
519 )
520 }
521 Projection3dKind::Orthographic {
522 vertical_span,
523 aspect_ratio,
524 near,
525 far,
526 } => {
527 let near_value = near.get();
528 let far_value = far.get();
529 let normalized_depth =
530 (view_depth - near_value as f64) / (far_value as f64 - near_value as f64);
531 (
532 view_x / (vertical_span.get() as f64 * aspect_ratio as f64 * 0.5),
533 view_y / (vertical_span.get() as f64 * 0.5),
534 normalized_depth,
535 near,
536 far,
537 )
538 }
539 };
540
541 let screen_x = (ndc_x * 0.5 + 0.5) * viewport.width() as f64;
542 let screen_y = (0.5 - ndc_y * 0.5) * viewport.height() as f64;
543 let screen_x = f64_to_f32(screen_x)?;
544 let screen_y = f64_to_f32(screen_y)?;
545 let view_depth_f32 = f64_to_f32(view_depth)?;
546 let normalized_depth_f32 = f64_to_f32(normalized_depth)?;
547 let inside_view = view_depth >= near.get() as f64
548 && view_depth <= far.get() as f64
549 && (-1.0..=1.0).contains(&ndc_x)
550 && (-1.0..=1.0).contains(&ndc_y);
551 Ok(ProjectedPoint3d {
552 logical_position: LogicalScreenPosition::new(screen_x, screen_y),
553 view_depth: view_depth_f32,
554 normalized_depth: normalized_depth_f32,
555 inside_view,
556 })
557 }
558
559 #[cfg(any(feature = "wgpu", test))]
560 pub(crate) fn world_to_clip_rows(self) -> Result<[[f32; 4]; 4], Pseudo3dError> {
561 let right_offset = -dot_f64(self.position, self.right);
562 let up_offset = -dot_f64(self.position, self.up);
563 let depth_offset = -dot_f64(self.position, self.forward);
564 let rows = match self.projection.kind {
565 Projection3dKind::Perspective {
566 vertical_fov_radians,
567 aspect_ratio,
568 near,
569 far,
570 } => {
571 let near = near.get() as f64;
572 let far = far.get() as f64;
573 let vertical_scale = (vertical_fov_radians as f64 * 0.5).tan();
574 let horizontal_scale = vertical_scale * aspect_ratio as f64;
575 let depth_scale = far / (far - near);
576 let depth_translation = -(far * near) / (far - near);
577 [
578 camera_row(self.right, right_offset, 1.0 / horizontal_scale),
579 camera_row(self.up, up_offset, 1.0 / vertical_scale),
580 camera_row(
581 self.forward,
582 depth_offset + depth_translation / depth_scale,
583 depth_scale,
584 ),
585 [
586 self.forward.x as f64,
587 self.forward.y as f64,
588 self.forward.z as f64,
589 depth_offset,
590 ],
591 ]
592 }
593 Projection3dKind::Orthographic {
594 vertical_span,
595 aspect_ratio,
596 near,
597 far,
598 } => {
599 let near = near.get() as f64;
600 let far = far.get() as f64;
601 let vertical_span = vertical_span.get() as f64;
602 let depth_extent = far - near;
603 [
604 camera_row(
605 self.right,
606 right_offset,
607 2.0 / (vertical_span * aspect_ratio as f64),
608 ),
609 camera_row(self.up, up_offset, 2.0 / vertical_span),
610 camera_row(self.forward, depth_offset - near, 1.0 / depth_extent),
611 [0.0, 0.0, 0.0, 1.0],
612 ]
613 }
614 };
615 Ok([
616 f64_row_to_f32(rows[0])?,
617 f64_row_to_f32(rows[1])?,
618 f64_row_to_f32(rows[2])?,
619 f64_row_to_f32(rows[3])?,
620 ])
621 }
622}
623
624#[derive(Debug, Clone, Copy, PartialEq)]
626pub struct ProjectedPoint3d {
627 logical_position: LogicalScreenPosition,
628 view_depth: f32,
629 normalized_depth: f32,
630 inside_view: bool,
631}
632
633impl ProjectedPoint3d {
634 pub const fn logical_position(self) -> LogicalScreenPosition {
636 self.logical_position
637 }
638
639 pub const fn view_depth(self) -> f32 {
641 self.view_depth
642 }
643
644 pub const fn normalized_depth(self) -> f32 {
650 self.normalized_depth
651 }
652
653 pub const fn inside_view(self) -> bool {
655 self.inside_view
656 }
657}
658
659#[derive(Debug, Clone, Copy, PartialEq)]
661pub enum Pseudo3dError {
662 NonFiniteVector {
664 x: f32,
666 y: f32,
668 z: f32,
670 },
671 NonFiniteScalar {
673 value: f32,
675 },
676 NonFiniteAngle {
678 radians: f32,
680 },
681 ZeroLengthVector,
683 InvalidScale {
685 scale: Vec3,
687 },
688 InvalidProjection,
690 InvalidCameraBasis,
692 PointBehindCamera,
694 ArithmeticOverflow,
696}
697
698impl fmt::Display for Pseudo3dError {
699 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
700 match self {
701 Self::NonFiniteVector { x, y, z } => {
702 write!(formatter, "3D vector must be finite, got ({x}, {y}, {z})")
703 }
704 Self::NonFiniteScalar { value } => {
705 write!(formatter, "3D scalar must be finite, got {value}")
706 }
707 Self::NonFiniteAngle { radians } => {
708 write!(formatter, "3D rotation angle must be finite, got {radians}")
709 }
710 Self::ZeroLengthVector => write!(formatter, "3D direction must have non-zero length"),
711 Self::InvalidScale { scale } => {
712 write!(formatter, "3D model scale must be positive, got {scale:?}")
713 }
714 Self::InvalidProjection => write!(formatter, "3D projection parameters are invalid"),
715 Self::InvalidCameraBasis => write!(formatter, "3D camera basis is degenerate"),
716 Self::PointBehindCamera => write!(formatter, "3D point is behind the camera"),
717 Self::ArithmeticOverflow => write!(formatter, "3D arithmetic overflowed f32 output"),
718 }
719 }
720}
721
722impl Error for Pseudo3dError {}
723
724fn valid_projection_range(aspect_ratio: f32, near: f32, far: f32) -> bool {
725 aspect_ratio.is_finite()
726 && aspect_ratio > 0.0
727 && near.is_finite()
728 && near > 0.0
729 && far.is_finite()
730 && far > near
731 && (far as f64 - near as f64) <= f32::MAX as f64
732}
733
734fn f64_to_f32(value: f64) -> Result<f32, Pseudo3dError> {
735 if value.is_finite() && value.abs() <= f32::MAX as f64 {
736 Ok(value as f32)
737 } else {
738 Err(Pseudo3dError::ArithmeticOverflow)
739 }
740}
741
742fn length_f64(vector: Vec3) -> f64 {
743 let x = vector.x as f64;
744 let y = vector.y as f64;
745 let z = vector.z as f64;
746 (x * x + y * y + z * z).sqrt()
747}
748
749fn subtract_f64(left: Vec3, right: Vec3) -> (f64, f64, f64) {
750 (
751 left.x as f64 - right.x as f64,
752 left.y as f64 - right.y as f64,
753 left.z as f64 - right.z as f64,
754 )
755}
756
757fn dot_f64_tuple(left: (f64, f64, f64), right: Vec3) -> f64 {
758 left.0 * right.x as f64 + left.1 * right.y as f64 + left.2 * right.z as f64
759}
760
761#[cfg(any(feature = "wgpu", test))]
762fn dot_f64(left: Vec3, right: Vec3) -> f64 {
763 left.x as f64 * right.x as f64 + left.y as f64 * right.y as f64 + left.z as f64 * right.z as f64
764}
765
766#[cfg(any(feature = "wgpu", test))]
767fn camera_row(axis: Vec3, offset: f64, scale: f64) -> [f64; 4] {
768 [
769 axis.x as f64 * scale,
770 axis.y as f64 * scale,
771 axis.z as f64 * scale,
772 offset * scale,
773 ]
774}
775
776#[cfg(any(feature = "wgpu", test))]
777fn f64_row_to_f32(row: [f64; 4]) -> Result<[f32; 4], Pseudo3dError> {
778 Ok([
779 f64_to_f32(row[0])?,
780 f64_to_f32(row[1])?,
781 f64_to_f32(row[2])?,
782 f64_to_f32(row[3])?,
783 ])
784}
785
786fn cross_f64(left: Vec3, right: Vec3) -> Option<(f64, f64, f64)> {
787 let result = (
788 left.y as f64 * right.z as f64 - left.z as f64 * right.y as f64,
789 left.z as f64 * right.x as f64 - left.x as f64 * right.z as f64,
790 left.x as f64 * right.y as f64 - left.y as f64 * right.x as f64,
791 );
792 result.0.is_finite().then_some(result)
793}
794
795fn normalize_f64(vector: (f64, f64, f64)) -> Option<Vec3> {
796 let length = (vector.0 * vector.0 + vector.1 * vector.1 + vector.2 * vector.2).sqrt();
797 if !length.is_finite() || length == 0.0 {
798 return None;
799 }
800 Vec3::from_f64(vector.0 / length, vector.1 / length, vector.2 / length).ok()
801}
802
803#[cfg(test)]
804mod tests {
805 use super::{Camera3d, Projection3d, Pseudo3dError, Rotation3d, Transform3d, Vec3};
806 use crate::{LogicalViewport, WorldLength};
807
808 fn vector(x: f32, y: f32, z: f32) -> Vec3 {
809 Vec3::new(x, y, z).unwrap()
810 }
811
812 fn world(value: f32) -> WorldLength {
813 WorldLength::new(value).unwrap()
814 }
815
816 fn close(actual: f32, expected: f32) {
817 assert!((actual - expected).abs() < 0.0001, "{actual} != {expected}");
818 }
819
820 #[test]
821 fn vector_normalization_preserves_extreme_finite_direction() {
822 let normalized = vector(f32::MAX, -f32::MAX, f32::MAX).normalized().unwrap();
823 let expected = 1.0 / 3.0_f32.sqrt();
824 close(normalized.x(), expected);
825 close(normalized.y(), -expected);
826 close(normalized.z(), expected);
827 assert_eq!(
828 Vec3::ZERO.normalized(),
829 Err(Pseudo3dError::ZeroLengthVector)
830 );
831 }
832
833 #[test]
834 fn rotation_composition_uses_documented_application_order() {
835 let quarter_turn = std::f32::consts::FRAC_PI_2;
836 let rotation = Rotation3d::from_euler_xyz(quarter_turn, quarter_turn, 0.0).unwrap();
837 let rotated = rotation.rotate(Vec3::Y).unwrap();
838 close(rotated.x(), 1.0);
839 close(rotated.y(), 0.0);
840 close(rotated.z(), 0.0);
841 }
842
843 #[test]
844 fn transform_rejects_invalid_scale_and_keeps_point_finite() {
845 let rotation = Rotation3d::from_axis_angle(Vec3::Z, std::f32::consts::FRAC_PI_2).unwrap();
846 assert!(matches!(
847 Transform3d::new(Vec3::ZERO, rotation, vector(1.0, 0.0, 1.0)),
848 Err(Pseudo3dError::InvalidScale { .. })
849 ));
850 let transform =
851 Transform3d::new(vector(3.0, 4.0, 5.0), rotation, vector(2.0, 2.0, 2.0)).unwrap();
852 let point = transform.transform_point(Vec3::X).unwrap();
853 close(point.x(), 3.0);
854 close(point.y(), 6.0);
855 close(point.z(), 5.0);
856 }
857
858 #[test]
859 fn perspective_camera_projects_center_and_reports_clip_membership() {
860 let viewport = LogicalViewport::new(800.0, 600.0).unwrap();
861 let projection = Projection3d::perspective(
862 std::f32::consts::FRAC_PI_2,
863 800.0 / 600.0,
864 world(0.1),
865 world(100.0),
866 )
867 .unwrap();
868 let camera =
869 Camera3d::look_at(vector(0.0, 0.0, 5.0), Vec3::ZERO, Vec3::Y, projection).unwrap();
870 let projected = camera.project_world(Vec3::ZERO, viewport).unwrap();
871 close(projected.logical_position().to_vec2().x(), 400.0);
872 close(projected.logical_position().to_vec2().y(), 300.0);
873 close(projected.view_depth(), 5.0);
874 assert!(projected.inside_view());
875
876 let outside = camera
877 .project_world(vector(50.0, 0.0, 0.0), viewport)
878 .unwrap();
879 assert!(!outside.inside_view());
880 assert_eq!(
881 camera.project_world(vector(0.0, 0.0, 6.0), viewport),
882 Err(Pseudo3dError::PointBehindCamera)
883 );
884 }
885
886 #[test]
887 fn perspective_camera_reports_unrepresentable_outside_projection() {
888 let camera = Camera3d::look_at(
889 Vec3::ZERO,
890 vector(0.0, 0.0, -1.0),
891 Vec3::Y,
892 Projection3d::perspective(std::f32::consts::FRAC_PI_2, 1.0, world(0.1), world(10.0))
893 .unwrap(),
894 )
895 .unwrap();
896 assert_eq!(
897 camera.project_world(
898 vector(f32::MAX, 0.0, -f32::MIN_POSITIVE),
899 LogicalViewport::new(100.0, 100.0).unwrap(),
900 ),
901 Err(Pseudo3dError::ArithmeticOverflow)
902 );
903 }
904
905 #[test]
906 fn orthographic_camera_preserves_size_across_depth() {
907 let viewport = LogicalViewport::new(800.0, 600.0).unwrap();
908 let projection =
909 Projection3d::orthographic(world(6.0), 800.0 / 600.0, world(0.1), world(100.0))
910 .unwrap();
911 let camera =
912 Camera3d::look_at(vector(0.0, 0.0, 5.0), Vec3::ZERO, Vec3::Y, projection).unwrap();
913 let near = camera
914 .project_world(vector(1.0, 0.0, 0.0), viewport)
915 .unwrap();
916 let far = camera
917 .project_world(vector(1.0, 0.0, -20.0), viewport)
918 .unwrap();
919 close(
920 near.logical_position().to_vec2().x(),
921 far.logical_position().to_vec2().x(),
922 );
923 assert!(near.normalized_depth() < far.normalized_depth());
924 }
925
926 #[test]
927 fn camera_and_projection_reject_degenerate_configuration() {
928 assert_eq!(
929 Projection3d::perspective(0.0, 1.0, world(0.1), world(10.0)),
930 Err(Pseudo3dError::InvalidProjection)
931 );
932 let projection = Projection3d::perspective(1.0, 1.0, world(0.1), world(10.0)).unwrap();
933 assert_eq!(
934 Camera3d::look_at(Vec3::ZERO, Vec3::ZERO, Vec3::Y, projection),
935 Err(Pseudo3dError::ZeroLengthVector)
936 );
937 assert_eq!(
938 Camera3d::look_at(vector(0.0, 0.0, 5.0), Vec3::ZERO, Vec3::Z, projection),
939 Err(Pseudo3dError::InvalidCameraBasis)
940 );
941 }
942
943 #[test]
944 fn gpu_clip_rows_match_public_camera_projection() {
945 let viewport = LogicalViewport::new(800.0, 600.0).unwrap();
946 for projection in [
947 Projection3d::perspective(1.1, 800.0 / 600.0, world(0.1), world(50.0)).unwrap(),
948 Projection3d::orthographic(world(7.0), 800.0 / 600.0, world(0.1), world(50.0)).unwrap(),
949 ] {
950 let camera = Camera3d::look_at(
951 vector(3.0, 2.0, 6.0),
952 vector(0.0, 0.5, 0.0),
953 Vec3::Y,
954 projection,
955 )
956 .unwrap();
957 let point = vector(0.5, 0.25, -1.0);
958 let projected = camera.project_world(point, viewport).unwrap();
959 let rows = camera.world_to_clip_rows().unwrap();
960 let homogeneous = [point.x(), point.y(), point.z(), 1.0];
961 let clip = rows.map(|row| {
962 row[0] * homogeneous[0] + row[1] * homogeneous[1] + row[2] * homogeneous[2] + row[3]
963 });
964 let ndc_x = clip[0] / clip[3];
965 let ndc_y = clip[1] / clip[3];
966 let screen_x = (ndc_x * 0.5 + 0.5) * viewport.width();
967 let screen_y = (0.5 - ndc_y * 0.5) * viewport.height();
968 close(screen_x, projected.logical_position().to_vec2().x());
969 close(screen_y, projected.logical_position().to_vec2().y());
970 close(clip[2] / clip[3], projected.normalized_depth());
971 }
972 }
973}