Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
"""
Tests for `nearest_point_index` in `belfryscad.engine.renderer` — the pure
screen-space nearest-point picking helper shared by `SceneRenderer.
pick_nearest_point` and (once migrated) the data viewers' vertex-click
handlers. Pure math, no GL/Qt dependency. Also covers `nearest_segment_index`
(and its `_closest_point_on_segment_to_ray` building block), the analogous
line-segment picking helper behind `SceneRenderer.pick_nearest_segment` and
the Path/Region editors' right-click-on-a-line "Add Vertex" feature.
"""
import math
import numpy as np
import pytest
from pytest import approx
from belfryscad.engine.renderer import (
nearest_point_index, nearest_segment_index, _closest_point_on_segment_to_ray, Camera,
_axis_density, _tick_is_drawn, _axis_extent, _axis_spans,
)
class TestNearestPointIndex:
def test_exact_hit_at_center(self):
# identity mvp: clip == [x, y, z, 1], so w_clip == 1 always;
# (0, 0, 0) maps to the exact center of a w x h viewport.
mvp = np.eye(4)
points = np.array([[0.0, 0.0, 0.0]])
assert nearest_point_index(points, mvp, 50, 50, 100, 100) == 0
def test_picks_nearest_of_several(self):
mvp = np.eye(4)
points = np.array([[0.0, 0.0, 0.0], [0.1, 0.1, 0.0], [5.0, 5.0, 0.0]])
# (0.1, 0.1) is closer to screen center than (0, 0) after projection
# scaling; verify by construction rather than assuming index order.
idx = nearest_point_index(points, mvp, 55, 45, 100, 100)
assert idx == 1
def test_miss_beyond_threshold(self):
mvp = np.eye(4)
points = np.array([[100.0, 0.0, 0.0]])
assert nearest_point_index(points, mvp, 50, 50, 100, 100) == -1
def test_empty_points_returns_minus_one(self):
mvp = np.eye(4)
points = np.zeros((0, 3))
assert nearest_point_index(points, mvp, 50, 50, 100, 100) == -1
def test_degenerate_viewport_returns_minus_one(self):
mvp = np.eye(4)
points = np.array([[0.0, 0.0, 0.0]])
assert nearest_point_index(points, mvp, 50, 50, 0, 100) == -1
assert nearest_point_index(points, mvp, 50, 50, 100, 0) == -1
def test_point_behind_camera_excluded(self):
# Perspective-like mvp: w_clip = -z, so z > 0 is "behind" the camera.
mvp = np.eye(4)
mvp[3] = [0, 0, -1, 0]
points = np.array([
[0.0, 0.0, 5.0], # behind camera (w_clip = -5) — must be excluded
[0.0, 0.0, -5.0], # in front (w_clip = 5) — projects to screen center
])
idx = nearest_point_index(points, mvp, 50, 50, 100, 100)
assert idx == 1
def test_custom_threshold_respected(self):
mvp = np.eye(4)
points = np.array([[0.2, 0.0, 0.0]]) # a few px off center
# default threshold (12px) should hit; a very tight threshold should miss
assert nearest_point_index(points, mvp, 50, 50, 100, 100) != -1
assert nearest_point_index(points, mvp, 50, 50, 100, 100, threshold_px=0.5) == -1
class TestClosestPointOnSegmentToRay:
def test_perpendicular_ray_through_midpoint(self):
a, b = np.array([0.0, 0.0, 0.0]), np.array([10.0, 0.0, 0.0])
ray_o, ray_d = np.array([5.0, 0.0, 5.0]), np.array([0.0, 0.0, -1.0])
pt = _closest_point_on_segment_to_ray(a, b, ray_o, ray_d)
assert np.allclose(pt, [5.0, 0.0, 0.0], atol=1e-6)
def test_clamped_to_segment_endpoint(self):
# Ray passes the segment's line well beyond point b -- the closest
# point must clamp to b, not extrapolate past it.
a, b = np.array([0.0, 0.0, 0.0]), np.array([10.0, 0.0, 0.0])
ray_o, ray_d = np.array([25.0, 0.0, 5.0]), np.array([0.0, 0.0, -1.0])
pt = _closest_point_on_segment_to_ray(a, b, ray_o, ray_d)
assert np.allclose(pt, [10.0, 0.0, 0.0], atol=1e-6)
def test_clamped_to_segment_start(self):
a, b = np.array([0.0, 0.0, 0.0]), np.array([10.0, 0.0, 0.0])
ray_o, ray_d = np.array([-25.0, 0.0, 5.0]), np.array([0.0, 0.0, -1.0])
pt = _closest_point_on_segment_to_ray(a, b, ray_o, ray_d)
assert np.allclose(pt, [0.0, 0.0, 0.0], atol=1e-6)
class TestNearestSegmentIndex:
def test_picks_segment_under_cursor(self):
mvp = np.eye(4)
points = np.array([[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 10.0, 0.0], [0.0, 10.0, 0.0]])
segments = [(0, 1), (1, 2), (2, 3), (3, 0)]
ray_o, ray_d = np.array([5.0, 0.0, 5.0]), np.array([0.0, 0.0, -1.0])
# world (5,0,0) with identity mvp projects to screen (300, 50) in a 100x100 viewport
result = nearest_segment_index(points, segments, ray_o, ray_d, mvp, 300, 50, 100, 100)
assert result is not None
idx, pt = result
assert idx == 0
assert np.allclose(pt, [5.0, 0.0, 0.0], atol=1e-6)
def test_miss_beyond_threshold(self):
mvp = np.eye(4)
points = np.array([[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]])
segments = [(0, 1)]
ray_o, ray_d = np.array([5.0, 0.0, 5.0]), np.array([0.0, 0.0, -1.0])
assert nearest_segment_index(points, segments, ray_o, ray_d, mvp, 999, 999, 100, 100) is None
def test_empty_segments_returns_none(self):
mvp = np.eye(4)
points = np.array([[0.0, 0.0, 0.0]])
ray_o, ray_d = np.array([0.0, 0.0, 5.0]), np.array([0.0, 0.0, -1.0])
assert nearest_segment_index(points, [], ray_o, ray_d, mvp, 50, 50, 100, 100) is None
def test_degenerate_viewport_returns_none(self):
mvp = np.eye(4)
points = np.array([[0.0, 0.0, 0.0], [10.0, 0.0, 0.0]])
segments = [(0, 1)]
ray_o, ray_d = np.array([5.0, 0.0, 5.0]), np.array([0.0, 0.0, -1.0])
assert nearest_segment_index(points, segments, ray_o, ray_d, mvp, 50, 50, 0, 100) is None
class TestCameraViewMatrixContinuity:
"""Regression test: `_look_at`'s gimbal-lock fallback (used whenever the
forward vector is parallel to world-up, i.e. exactly elevation +-90)
hardcodes an arbitrary +X "right" vector, which doesn't match the
azimuth-dependent basis the camera continuously converges to just off
the pole. Landing exactly on elevation=90 (the old "Top" view preset)
made the very first orbit-drag frame snap to whatever that arbitrary
fallback implied — up to a 90-degree jump."""
def test_right_vector_is_continuous_approaching_the_pole(self):
cam = Camera()
cam.azimuth, cam.distance = 0, 50.0
cam.elevation = 89.9999
near_pole = cam.view_matrix()[0, :3]
cam.elevation = 89.0
after_drag = cam.view_matrix()[0, :3]
assert np.linalg.norm(near_pole - after_drag) < 0.02
def test_exact_pole_fallback_does_not_match_the_continuous_limit(self):
# Documents *why* the fix avoids landing on exactly elevation=90:
# the degenerate fallback used there disagrees with the value the
# continuous formula converges to from either side.
cam = Camera()
cam.azimuth, cam.distance = 0, 50.0
cam.elevation = 90.0
exact_pole = cam.view_matrix()[0, :3]
cam.elevation = 89.0
just_off_pole = cam.view_matrix()[0, :3]
assert np.linalg.norm(exact_pole - just_off_pole) > 1.0
def test_continuity_holds_at_other_azimuths_too(self):
cam = Camera()
cam.distance = 50.0
for az in (37.0, 120.0, 210.0, 295.0):
cam.azimuth = az
cam.elevation = 89.9999
near_pole = cam.view_matrix()[0, :3]
cam.elevation = 89.0
after_drag = cam.view_matrix()[0, :3]
assert np.linalg.norm(near_pole - after_drag) < 0.02, f"discontinuity at azimuth={az}"
class TestCameraRoll:
"""Camera.roll -- the third axis $vpr's Y component maps to (alongside
elevation/X and azimuth/Z), and the axis Camera.orbit_free's "Orbit"
drag mode (see TestCameraOrbitFree below) derives as part of its
result. Sign/magnitude verified by rendering the same scene+camera
through both BelfrySCAD's --camera CLI flag and real OpenSCAD.app's
identical --camera rot_y component and comparing the resulting images
pixel-for-pixel (not just reasoned about) -- see
project_orbit_rotation_mode memory."""
def test_roll_zero_matches_no_roll(self):
cam = Camera()
cam.azimuth, cam.elevation, cam.distance, cam.roll = 270, 0, 50.0, 0.0
m1 = cam.view_matrix()
cam.roll = 360.0 # equivalent angle
m2 = cam.view_matrix()
assert np.allclose(m1, m2, atol=1e-5)
def test_roll_does_not_move_the_eye(self):
cam = Camera()
cam.azimuth, cam.elevation, cam.distance = 270, 0, 50.0
cam.roll = 0.0
eye_before = cam.eye_position().copy()
cam.roll = 45.0
eye_after = cam.eye_position()
assert np.allclose(eye_before, eye_after)
def test_roll_90_rotates_right_and_up_as_expected(self):
# az=270, el=0 -> eye at (0,-distance,0), forward=+Y, so with no
# roll: right=(1,0,0), up=(0,0,1) (world-up, unrolled).
cam = Camera()
cam.azimuth, cam.elevation, cam.distance = 270, 0, 50.0
cam.roll = 0.0
m0 = cam.view_matrix()
assert np.allclose(m0[0, :3], [1, 0, 0], atol=1e-5)
assert np.allclose(m0[1, :3], [0, 0, 1], atol=1e-5)
# Rotating the up vector 90 deg around the +Y forward axis (right-
# hand rule) sends world-up (0,0,1) -> (1,0,0), and right rotates
# the same way: (1,0,0) -> (0,0,-1).
cam.roll = 90.0
m90 = cam.view_matrix()
assert np.allclose(m90[0, :3], [0, 0, -1], atol=1e-5)
assert np.allclose(m90[1, :3], [1, 0, 0], atol=1e-5)
def test_roll_180_flips_up(self):
cam = Camera()
cam.azimuth, cam.elevation, cam.distance = 270, 0, 50.0
cam.roll = 0.0
up0 = cam.view_matrix()[1, :3].copy()
cam.roll = 180.0
up180 = cam.view_matrix()[1, :3]
assert np.allclose(up0, -up180, atol=1e-5)
def test_stereo_view_matrices_respect_roll(self):
cam = Camera()
cam.azimuth, cam.elevation, cam.distance = 270, 0, 50.0
cam.stereo = True
cam.roll = 90.0
right_eye, left_eye = cam.stereo_view_matrices(800, 600)
# Both stereo eyes' up row should match the same rolled up vector
# the mono view_matrix() produces (not the un-rolled world-up).
mono_up = cam.view_matrix()[1, :3]
assert np.allclose(right_eye[1, :3], mono_up, atol=1e-4)
assert np.allclose(left_eye[1, :3], mono_up, atol=1e-4)
def test_anaglyph_eyes_give_the_right_depth_sign(self):
"""The anaglyph puts stereo_view_matrices()'s SECOND matrix behind
the red (left) lens. Swapped eyes turn depth inside out, and nothing
else would notice: a point behind the focus must sit further left in
the left eye's image, a point in front further right."""
cam = Camera()
cam.distance = 100.0
right_view, left_view = cam.stereo_view_matrices(1100, 700)
proj = cam.projection_matrix(1100 / 700)
fwd = cam.target - cam.eye_position()
fwd = fwd / np.linalg.norm(fwd)
def ndc_x(view, p):
v = proj @ view @ np.append(p, 1.0)
return v[0] / v[3]
far = cam.target + fwd * 40
near = cam.target - fwd * 40
assert ndc_x(left_view, far) < ndc_x(right_view, far)
assert ndc_x(left_view, near) > ndc_x(right_view, near)
class TestCameraOrbitFree:
"""Camera.orbit_free -- true trackball rotation for the "Orbit"
Shift+drag mode: rotates around the camera's OWN current up/right
axes each call (composing in the local frame), unlike Turntable
mode's azimuth/elevation drag, which is always relative to fixed
world-Z. No clamp -- the view can tumble through either pole
continuously (a discontinuity in the *derived azimuth number* when
crossing a pole is expected and fine; the actual 3D view must stay
continuous, which is what these tests check)."""
def test_horizontal_only_rotates_azimuth_keeps_roll_and_elevation(self):
# Hand-derived: az=270,el=0,roll=0,dist=50 -> eye=(0,-50,0). A pure
# 90 deg horizontal orbit rotates that offset around world-Z (true_up
# is already (0,0,1) here) to (50,0,0) -- eye on +X, i.e. az=0,
# el=0, roll=0, exactly a +90 deg azimuth shift with nothing else
# touched.
cam = Camera()
cam.azimuth, cam.elevation, cam.roll, cam.distance = 270, 0, 0, 50.0
cam.orbit_free(90, 0)
assert (cam.azimuth + 180) % 360 - 180 == approx(0.0, abs=1e-3)
assert cam.elevation == approx(0.0, abs=1e-4)
assert cam.roll == approx(0.0, abs=1e-4)
assert cam.distance == approx(50.0, abs=1e-4)
def test_distance_is_preserved(self):
cam = Camera()
cam.azimuth, cam.elevation, cam.roll, cam.distance = 37.0, 12.0, 5.0, 80.0
cam.orbit_free(23.0, -17.0)
assert cam.distance == approx(80.0, abs=1e-3)
def test_no_net_rotation_when_dx_dy_zero(self):
cam = Camera()
cam.azimuth, cam.elevation, cam.roll, cam.distance = 123.0, -20.0, 40.0, 30.0
cam.orbit_free(0, 0)
assert cam.azimuth % 360 == approx(123.0 % 360, abs=1e-3)
assert cam.elevation == approx(-20.0, abs=1e-3)
assert cam.roll % 360 == approx(40.0 % 360, abs=1e-3)
def test_composes_through_the_pole_without_a_jump_in_the_view(self):
cam = Camera()
cam.azimuth, cam.elevation, cam.roll, cam.distance = 0.0, 80.0, 0.0, 50.0
prev_eye = cam.eye_position().copy()
for _ in range(20):
cam.orbit_free(0, 2.0)
eye = cam.eye_position()
# Small step -> small change in eye position, no jump, and it
# stays on the sphere of the given radius around target
# throughout (this is the actual "no gimbal lock" guarantee --
# Turntable mode instead clamps elevation to avoid ever
# reaching this regime at all).
assert np.linalg.norm(eye - prev_eye) < 5.0
assert np.linalg.norm(eye - cam.target) == approx(50.0, abs=1e-2)
prev_eye = eye.copy()
def test_round_trip_set_from_eye_and_up_matches_forward_state(self):
cam = Camera()
cam.azimuth, cam.elevation, cam.roll, cam.distance = 142.0, 31.0, 17.0, 65.0
eye = cam.eye_position()
up = cam._rolled_up(cam.target - eye)
cam2 = Camera()
cam2.target = cam.target.copy()
cam2._set_from_eye_and_up(eye, up)
assert cam2.azimuth % 360 == approx(cam.azimuth % 360, abs=1e-3)
assert cam2.elevation == approx(cam.elevation, abs=1e-3)
assert cam2.roll % 360 == approx(cam.roll % 360, abs=1e-3)
assert cam2.distance == approx(cam.distance, abs=1e-3)
def _forward(cam: Camera) -> np.ndarray:
az, el = math.radians(cam.azimuth), math.radians(cam.elevation)
return -np.array([math.cos(el) * math.cos(az), math.cos(el) * math.sin(az), math.sin(el)],
dtype=np.float32)
def _hit_on_focal_plane(cam: Camera, ray_origin: np.ndarray, ray_dir: np.ndarray) -> np.ndarray:
"""Reproduces zoom_to_point's own ray/focal-plane intersection, for
assertions independent of its internal state changes."""
forward = _forward(cam)
t = float(np.dot(cam.target - ray_origin, forward)) / float(np.dot(ray_dir, forward))
return ray_origin + ray_dir * t
class TestCameraZoomToPoint:
"""Scroll-wheel zoom should keep the world point under the cursor fixed
on screen (dolly toward/away from that point) rather than always
dollying toward cam.target."""
def test_center_ray_hit_stays_on_target(self):
cam = Camera()
cam.azimuth, cam.elevation, cam.distance = 295.0, 35.0, 50.0
cam.target = np.array([1.0, 2.0, 3.0], dtype=np.float32)
ray_origin = cam.eye_position()
ray_dir = (cam.target - ray_origin)
ray_dir /= np.linalg.norm(ray_dir)
cam.zoom_to_point(ray_origin, ray_dir, 0.5)
assert cam.distance == approx(25.0)
assert cam.target == approx(np.array([1.0, 2.0, 3.0]), abs=1e-4)
def test_off_center_perspective_ray_hit_point_is_preserved(self):
# A ray from the eye, perturbed off dead-center (as a perspective
# camera_ray() for an off-center pixel would be) -- the point it
# hits on the focal plane must land in the same place before and
# after zooming, not drift toward cam.target.
cam = Camera()
cam.azimuth, cam.elevation, cam.distance = 295.0, 35.0, 50.0
cam.target = np.array([1.0, 2.0, 3.0], dtype=np.float32)
eye = cam.eye_position()
ray_dir = (cam.target - eye) + np.array([3.0, -2.0, 1.0], dtype=np.float32)
ray_dir /= np.linalg.norm(ray_dir)
before = _hit_on_focal_plane(cam, eye, ray_dir)
cam.zoom_to_point(eye, ray_dir, 0.5)
after = _hit_on_focal_plane(cam, eye, ray_dir)
assert after == approx(before, abs=1e-3)
def test_orthographic_style_parallel_ray_hit_point_is_preserved(self):
# Orthographic rays are parallel (same direction for every pixel)
# but originate from different points across the frustum, not a
# single eye. A version of this method that assumed a single
# eye_position() origin collapsed every such ray's hit point onto
# cam.target regardless of the ray's actual lateral offset -- this
# is the regression this test guards against.
cam = Camera()
cam.azimuth, cam.elevation, cam.distance = 295.0, 35.0, 50.0
cam.target = np.array([1.0, 2.0, 3.0], dtype=np.float32)
forward = _forward(cam)
# a "right"-ish vector, not parallel to forward
lateral = np.cross(forward, np.array([0.0, 0.0, 1.0], dtype=np.float32))
lateral /= np.linalg.norm(lateral)
ray_origin = cam.eye_position() + lateral * 7.0 # off to the side, like an ortho ray
ray_dir = forward.copy()
before = _hit_on_focal_plane(cam, ray_origin, ray_dir)
assert not np.allclose(before, cam.target, atol=1e-3) # sanity: genuinely off-target
cam.zoom_to_point(ray_origin, ray_dir, 0.5)
after = _hit_on_focal_plane(cam, ray_origin, ray_dir)
assert after == approx(before, abs=1e-3)
def test_zoom_out_factor_greater_than_one_also_preserves_hit(self):
cam = Camera()
cam.azimuth, cam.elevation, cam.distance = 295.0, 35.0, 50.0
cam.target = np.array([0.0, 0.0, 0.0], dtype=np.float32)
eye = cam.eye_position()
ray_dir = (cam.target - eye) + np.array([-2.0, 4.0, -1.0], dtype=np.float32)
ray_dir /= np.linalg.norm(ray_dir)
before = _hit_on_focal_plane(cam, eye, ray_dir)
cam.zoom_to_point(eye, ray_dir, 1.5)
after = _hit_on_focal_plane(cam, eye, ray_dir)
assert cam.distance == approx(75.0)
assert after == approx(before, abs=1e-3)
def test_respects_min_distance_clamp(self):
cam = Camera()
cam.distance = 0.15
cam.target = np.array([0.0, 0.0, 0.0], dtype=np.float32)
eye = cam.eye_position()
ray_dir = (cam.target - eye)
ray_dir /= np.linalg.norm(ray_dir)
cam.zoom_to_point(eye, ray_dir, 0.5, min_distance=0.1)
assert cam.distance == approx(0.1)
class TestAxisDensity:
"""Axis tick/label thinning: as an axis swings toward end-on (pointing
at/away from the camera), evenly-spaced-in-world ticks crowd into an
ever-smaller on-screen span. _axis_density should grow stride
(skip-N-between-each) smoothly before the existing hard cutoff (5
degrees from end-on) fully suppresses that axis -- see the screenshot
in the PR/commit this covers, where labels overlapped illegibly well
before the cutoff kicked in."""
def test_broadside_axes_are_full_density(self):
cam = Camera()
cam.azimuth, cam.elevation = 45.0, 45.0 # no axis anywhere near end-on
end_on, stride = _axis_density(cam)
assert end_on == [False, False, False]
assert stride == [1, 1, 1]
def test_stride_grows_as_axis_approaches_end_on(self):
cam = Camera()
cam.azimuth = 85.0 # keeps Y axis increasingly end-on as elevation -> 0
strides = []
for el in (60.0, 30.0, 10.0, 2.0):
cam.elevation = el
end_on, stride = _axis_density(cam)
assert not end_on[1], f"elevation={el} should not hit the hard cutoff yet"
strides.append(stride[1])
# non-decreasing as the axis gets closer to end-on
assert strides == sorted(strides)
assert strides[-1] > strides[0]
def test_stride_is_a_power_of_two(self):
cam = Camera()
cam.azimuth = 85.0
for el in (60.0, 30.0, 10.0, 6.0):
cam.elevation = el
_, stride = _axis_density(cam)
s = stride[1]
assert s & (s - 1) == 0, f"stride {s} at elevation={el} is not a power of two"
def test_hard_cutoff_still_applies_within_five_degrees(self):
cam = Camera()
cam.azimuth, cam.elevation = 0.0, 0.0 # X axis dead-on
end_on, _ = _axis_density(cam)
assert end_on == [True, False, False]
def test_other_axes_unaffected_by_one_axis_going_end_on(self):
cam = Camera()
cam.azimuth, cam.elevation = 0.0, 0.0
end_on, stride = _axis_density(cam)
assert end_on[1] is False and end_on[2] is False
assert stride[1] == 1 and stride[2] == 1
class TestAxisExtent:
"""_axis_extent feeds both the drawn axis-line length and the target
tick/label density (_nice_spacings' raw = L / 28). It must scale with
fov as well as distance, so a Shift+wheel FOV change (which changes how
much world is visible at a fixed distance, same visual effect as
zooming) keeps tick density visually consistent on screen -- see the
PR/commit this covers, where narrowing fov left ticks unchanged in
world-space while showing far fewer of them on screen."""
def test_matches_old_flat_formula_at_default_fov(self):
cam = Camera()
cam.distance = 40.0
assert cam.fov == Camera.DEFAULT_FOV
assert _axis_extent(cam) == approx(cam.distance * 2.5)
def test_narrower_fov_shrinks_extent(self):
cam = Camera()
cam.distance = 40.0
default = _axis_extent(cam)
cam.fov = Camera.DEFAULT_FOV / 2
assert _axis_extent(cam) < default
def test_wider_fov_grows_extent(self):
cam = Camera()
cam.distance = 40.0
default = _axis_extent(cam)
cam.fov = Camera.DEFAULT_FOV * 2
assert _axis_extent(cam) > default
def test_scales_linearly_with_distance_at_fixed_fov(self):
cam = Camera()
cam.fov = 60.0
cam.distance = 10.0
small = _axis_extent(cam)
cam.distance = 20.0
assert _axis_extent(cam) == approx(small * 2)
class TestTickIsDrawn:
"""Regression: thinning by stride used to exempt major ticks (always
shown, matching the pre-existing hard-cutoff behavior), but major_steps
and stride aren't related, so a kept major tick could land right next
to a kept minor tick while a stride-length gap opened up elsewhere --
visibly inconsistent spacing. Below the hard cutoff, stride must apply
uniformly to every tick so the drawn set is a strict arithmetic
subsequence (constant gap)."""
def test_drawn_ticks_form_a_constant_gap_sequence(self):
for major_steps, stride in [(5, 4), (5, 8), (10, 4), (4, 2), (3, 4), (7, 3)]:
drawn = [k for k in range(1, 60)
if _tick_is_drawn(k, major_steps, False, stride)]
gaps = {b - a for a, b in zip(drawn, drawn[1:])}
assert gaps == {stride}, f"major_steps={major_steps} stride={stride}: gaps={gaps}"
def test_stride_one_draws_every_tick(self):
drawn = [k for k in range(1, 10) if _tick_is_drawn(k, 5, False, 1)]
assert drawn == list(range(1, 10))
def test_hard_cutoff_only_draws_majors(self):
drawn_major = [k for k in range(1, 21) if _tick_is_drawn(k, 5, True, 4)]
assert drawn_major == [5, 10, 15, 20]
def test_hard_cutoff_ignores_stride(self):
# Majors always show at the hard cutoff regardless of stride.
for stride in (1, 2, 4, 8):
drawn = [k for k in range(1, 21) if _tick_is_drawn(k, 5, True, stride)]
assert drawn == [5, 10, 15, 20]
class TestCameraClipPlanes:
"""Regression: near/far used to be fixed constants (0.1, 10000), so
frame_bounds() auto-positioning the camera far enough away to fit a
large or elongated object (e.g. cylinder(h=3500, d=1000), which needs
distance~10438 to fit at the default fov=22.5) silently clipped
whichever end of the object was farther from the eye -- and varied
with zoom, since that changes distance."""
def test_small_scene_unaffected(self):
# Floors at the original constants, so typical/small scenes see no
# behavior change at all.
cam = Camera()
cam.distance = 50.0
near, far = cam.clip_planes()
assert near == approx(0.1)
assert far == approx(10000.0)
def test_far_grows_with_distance(self):
cam = Camera()
cam.distance = 10438.0
near, far = cam.clip_planes()
assert far > cam.distance
assert far == approx(cam.distance * 3.0)
def test_near_far_ratio_matches_original_constants(self):
# near must grow proportionally with far -- holding it fixed while
# far grows would only worsen depth-buffer precision for large
# scenes on top of the clipping bug.
cam = Camera()
cam.distance = 50000.0
near, far = cam.clip_planes()
assert far / near == approx(10000.0 / 0.1)
def test_reported_cylinder_case_fits_within_far(self):
# The exact repro: cylinder(h=3500, d=1000), auto-framed.
cam = Camera()
bb_min = np.array([-500.0, -500.0, 0.0])
bb_max = np.array([500.0, 500.0, 3500.0])
cam.frame_bounds(bb_min, bb_max)
near, far = cam.clip_planes()
eye = cam.eye_position()
view_dir = (cam.target - eye)
view_dir /= np.linalg.norm(view_dir)
for z in (0.0, 3500.0):
point = np.array([0.0, 0.0, z])
depth = float(np.dot(point - eye, view_dir))
assert near < depth < far, f"z={z} at depth={depth} falls outside [{near}, {far}]"
def test_frame_bounds_matches_the_reference_view_all():
"""`radius / sin(fov/2)`, the same formula as OpenSCAD's Camera::viewAll.
It was `radius / tan(fov/2) * 1.1`, which sits `1.1 * cos(fov/2)` — 7.9%
at the default 22.5 fov — further out, so every `--viewall` docs image
came out about 7% smaller than the published one.
"""
from belfryscad.engine.renderer import Camera
cam = Camera()
bb_min = np.array([-10.0, -20.0, -1.0])
bb_max = np.array([10.0, 20.0, 1.0])
cam.frame_bounds(bb_min, bb_max)
radius = float(np.linalg.norm(bb_max - bb_min) / 2)
assert cam.distance == approx(radius / math.sin(math.radians(cam.fov / 2)))
# The target is the bbox centre, which is what makes viewAll's
# centre-to-target term zero.
assert cam.target == approx(np.array([0.0, 0.0, 0.0]))
def test_frame_bounds_never_returns_a_degenerate_distance():
"""A single point has zero radius; the camera still needs somewhere to
stand."""
from belfryscad.engine.renderer import Camera
cam = Camera()
cam.frame_bounds(np.zeros(3), np.zeros(3))
assert cam.distance >= 1.0
class TestAxisSpans:
"""`_axis_spans` splits an axis half into short pieces so no single
primitive reaches far outside the frustum. Apple's Software Renderer --
what GitHub's macOS runners use, and what builds BOSL2's wiki images --
drops such a primitive whole, which left cube()'s second example with a
Y axis that had every tick mark and no line."""
def test_covers_the_whole_axis_without_gaps_or_overlap(self):
spans = _axis_spans(100.0, 10.0)
assert spans[0][0] == 0.0
assert spans[-1][1] == approx(100.0)
for (_, end), (start, _) in zip(spans, spans[1:]):
assert start == approx(end)
def test_no_span_exceeds_the_tick_spacing(self):
# The point of the split: every piece stays near the view, on the
# same footing as a tick mark.
for L, seg in ((100.0, 10.0), (429.81, 10.0), (7.5, 2.0)):
assert all(end - start <= seg + 1e-9 for start, end in _axis_spans(L, seg))
def test_a_final_short_span_is_kept_rather_than_rounded_away(self):
# L is a camera-derived float, so it rarely lands on a tick
# boundary; dropping the remainder would leave the axis visibly
# short of its own last tick.
assert _axis_spans(25.0, 10.0)[-1] == approx((20.0, 25.0))
def test_falls_back_to_one_span_without_a_usable_spacing(self):
# Exactly the old single-line behaviour, so a degenerate spacing
# cannot spin the while loop forever.
assert _axis_spans(100.0, 0.0) == [(0.0, 100.0)]
assert _axis_spans(100.0, -1.0) == [(0.0, 100.0)]
def test_a_degenerate_axis_draws_nothing(self):
assert _axis_spans(0.0, 10.0) == []
# --- #518: View All fits the projection, not the bounding sphere ----------
def _fits(cam, bb_min, bb_max, aspect):
"""Largest |NDC| any bbox corner reaches. <= 1 means fully on screen."""
import itertools
mvp = cam.projection_matrix(aspect) @ cam.view_matrix()
worst = 0.0
for c in itertools.product(*zip(bb_min, bb_max)):
v = mvp @ np.array([*c, 1.0], dtype=np.float32)
assert abs(v[3]) > 1e-9
worst = max(worst, abs(v[0] / v[3]), abs(v[1] / v[3]))
return worst
def test_framing_without_an_aspect_keeps_reference_parity():
"""--viewall and every docsgen image depend on this exact distance --
radius/sin(fov/2), measured against OpenSCAD. Passing no aspect must
still take that path untouched."""
from belfryscad.engine.renderer import Camera
lo, hi = np.array([-1.0, -1.0, -100.0]), np.array([1.0, 1.0, 100.0])
cam = Camera()
cam.frame_bounds(lo, hi)
expected = np.linalg.norm(hi - lo) / 2 / math.sin(math.radians(cam.fov / 2))
assert cam.distance == pytest.approx(expected)
def test_framing_with_an_aspect_fits_the_projection():
"""The reporter's case: a 2x2x200 column seen down Z is a 2x2 square,
and the sphere fit backs off far enough to swing the 200 axis through
the view. Fitting the projection should come in dramatically closer --
and still show all of it."""
from belfryscad.engine.renderer import Camera
lo, hi = np.array([-1.0, -1.0, -100.0]), np.array([1.0, 1.0, 100.0])
aspect = 700 / 560
sphere = Camera(); sphere.azimuth, sphere.elevation = 0.0, 90.0
sphere.frame_bounds(lo, hi)
fitted = Camera(); fitted.azimuth, fitted.elevation = 0.0, 90.0
fitted.frame_bounds(lo, hi, aspect)
assert fitted.distance < sphere.distance / 4
assert _fits(sphere, lo, hi, aspect) < 0.05 # a speck, which is the bug
# Fills the viewport bar FIT_MARGIN on each side.
assert _fits(fitted, lo, hi, aspect) == pytest.approx(
1.0 - 2 * Camera.FIT_MARGIN, abs=1e-3)
@pytest.mark.parametrize("az,el", [(295, 35), (0, 90), (0, 0), (45, 20), (0, -90), (137, -62)])
@pytest.mark.parametrize("ortho", [False, True])
@pytest.mark.parametrize("bb", [
([-1.0, -1.0, -100.0], [1.0, 1.0, 100.0]), # tall column
([-10.0, -10.0, -10.0], [10.0, 10.0, 10.0]), # compact
([-100.0, -100.0, -1.0], [100.0, 100.0, 1.0]), # flat plate
])
def test_the_projection_fit_never_clips(az, el, ortho, bb):
"""Tighter is only right if nothing falls off the edge. Every corner
must land inside the frustum, in both projections, at any orientation."""
from belfryscad.engine.renderer import Camera
lo, hi = np.array(bb[0]), np.array(bb[1])
aspect = 700 / 560
cam = Camera()
cam.azimuth, cam.elevation, cam.orthographic = az, el, ortho
cam.frame_bounds(lo, hi, aspect)
fill = _fits(cam, lo, hi, aspect)
assert fill <= 1.0 - 2 * Camera.FIT_MARGIN + 1e-3, "nothing may clip"
# And it is a FIT, not just a safe distance: the binding dimension
# should actually reach the margin rather than stopping short.
assert fill == pytest.approx(1.0 - 2 * Camera.FIT_MARGIN, abs=1e-3)
62c9a9e10This file is pinned to the selected release. Download the original to open it in your design tool.