Add perspective projection and tests

This commit is contained in:
Amalia Sucipto committed 2026-10-29 11:11:19 +01:00
1 parent 4931d5e7dc
commit 72d00b4c01
2 files changed
+84 -4

No files matched your search

+38 -2
View File
@@ -1,5 +1,6 @@
from typing import TypeAlias
from math import cos, sin
from typing import TypeAlias
Number: TypeAlias = int | float
Matrix: TypeAlias = list[list[Number]]
@@ -192,6 +193,38 @@ def project_ortho(
return (x * scale, y * scale)
def project_perspective(
point: tuple[float, float, float],
focal_length: float = 1.0,
scale: float = 1.0,
camera_distance: float = 4.0,
) -> tuple[float, float]:
"""Project a 3D point onto a 2D plane using perspective.
Args:
point: The 3D point containing x, y, and z coordinates.
focal_length: Controls the strength of the perspective.
scale: Scaling factor for the projected coordinates.
camera_distance: Distance offset of the camera.
Returns:
The projected 2D coordinates.
Raises:
ValueError: If the projection denominator is zero.
"""
x, y, z = point
depth = z + camera_distance
if depth == 0:
raise ValueError("Projection depth must not be zero.")
projected_x = x * focal_length / depth * scale
projected_y = y * focal_length / depth * scale
return (projected_x, projected_y)
if __name__ == "__main__":
# Beispiel Multiplikation
@@ -215,4 +248,7 @@ if __name__ == "__main__":
expected = [[1, 4], [2, 5], [3, 6]]
assert transpose(matrix) == expected
print("Transponierung erfolgreich:", transpose(matrix))
print("Transponierung erfolgreich:", transpose(matrix))