ridge-bake: near pixels bind r_max at the clip in every tile (no near-only special case); mutate.py kills only on an assertion raised by the fixtures' own code, the _view wrapper is gone
The runner prints the innermost traceback frame's file with each FAIL; a KILL is an AssertionError whose frame lies in the tests directory, so a numpy crash in the baker or an assert inside the library is CRASHED. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5117d67a53
commit
98e885cb3f
197 changed files with 37 additions and 1407 deletions
|
|
@ -35,7 +35,7 @@ Files are `Copernicus_DSM_COG_10_<N|S>dd_00_<E|W>ddd_00_DEM.tif`; the list below
|
|||
4. **Seams.** `coverage` counts the visible rows of the opaque view per log-distance bin and column. `seams` finds one seam per authored split per column by dynamic programming (seam carving, forward energy): it sits in a gap between depths, moving it costs 2 per bin plus the visible rows it sweeps (so it never hops across a ridge between two columns and splits it side by side), a seam inside visible terrain is cheap to cross-fade, the authored depth only breaks ties. Seam k stays 0.4 nat beyond seam k-1. The DP runs over the ring three times side by side and keeps the middle lap, so a seam is continuous across the wrap (column 6399 to 0) and a tile boundary is only a crop.
|
||||
5. **Cards.** `cards` runs per tile, on that tile's columns and the matching normals (it is column-independent: a tile is a crop of per-column results, so no seam appears at a tile boundary). It makes card i from the first visible hit at or beyond seam i-1 (layered depth: a farther card keeps the terrain a nearer ridge hides), alpha 1 minus a smoothstep over seam i in log-distance (the cross-fade), crest rows with fractional coverage, distance and normal interpolated between samples by angle, albedo from a small height and slope material, cropped to the rows where alpha is not zero. The rows of card i > 0 below the angle of its first sample (hit and first sample of the card) are its **wall**: the extruded face of the ridge the card starts at, which keeps that sample's distance, wears the ground material at its height with the face up, and is flagged `wall`. Card 0 also draws the **near march** (ruling `ridge-near-ground-outline`): the place's own DEM from `NEAR_START_M` = 1 m to the near clip `NEAR_CLIP_M` = 500 m (`near_march`: float64 bilinear samples every max(1 m, 0.02 d) up to 10 m, about 170 per column, low-passed with the place's own `prefilter_m`), joined to the far march by `join_near` on the whole ring before the tile cut, its angles capped per column at the angle of the clip sample so the near ground draws inside the silhouette of the terrain at the clip (a near hill above that edge is cut along it). Its rows are ordinary terrain with their own normal and the albedo of their own height and n_up, flagged `near` in memory; `cards` refuses a march that starts at the clip. The runtime reads them as ground at the clip distance (they decode at `log_d_min`) and lights them like any card pixel. The alpha-over composite of the cards equals the opaque view; `check_cover` refuses a tile that differs by more than 0.02.
|
||||
6. **Tiles.** The ring is absolute compass, column 0 = north, column c at azimuth (c + 0.5) / 6400 x 360; `places.json`'s `az_deg` / `look_at` is only the rest azimuth (`view.look_az_deg`). Tile t owns columns [200 t, 200 t + 200) (11.25 degrees) and its files hold [200 t - 2, 200 t + 202): two columns of real neighbour data each side (the client's ink pass and lighting read one texel each way; the client crops it), taken periodically by `ridge.ring_cols`. Per card and tile the file is cropped to the rows where that tile's 8-bit alpha is not zero (`top`, `h`); a card that holds nothing in a tile is `null` there (the client interpolates its distance from the neighbours); a card with no solid pixel in any tile is refused.
|
||||
7. **Distance and the offset range.** The bake holds no camera (ruling `ridge-camera-full-ring`). `pack` gives each card tile `distance_m` = exp(median ln d) over the tile's solid pixels that are neither wall nor near ground (its interior 200 columns); the client derives each card's slide from that and the viewer's offset r and heading. `camera.r_max_m` is the largest |r| (never above half the nearest terrain's distance) at which, for every tile, card and phi (24 steps of the camera's angle on the circle against its heading; the offset-only rotation mode moves phi round the whole circle), the least-squares line `a + s beta` fitted to the exact view angle `atan2(R sin beta - r sin phi, R cos beta - r cos phi)` over the widest viewport (`HFOV_MAX_DEG` = 72 / 1.1) errs by at most `FIT_PX_MAX` = 24 card px (the continuous error: the line by quadrature over the viewport, the worst error looked for on 513 points, so a handful of samples cannot undercount it); the distance d is that of the NEAREST solid (alpha >= 0.5, neither wall nor near ground) pixel the card draws in the tile's interior columns, which is where the slide errs most (the line is fitted for the tile's `distance_m`, the median, but the bound is held for the nearest terrain: a tile whose terrain spans 600 to 2000 m is bound at 600 m); a tile whose card 0 draws only near ground (under the clip) has no such pixel, but it is slid at its `distance_m` (the clip, 500 m), so it binds at 500 m; and the resident gate (below) must hold at r_max_m too. `camera.r_max_forward_m` is the same search at phi = 0 alone (same `FIT_PX_MAX`, the same half-distance cap, the same resident gate): the camera pushed forward along its heading, which is where the offset stays when the view direction turns with it (the modes 'still' and 'both'), so it is at least `r_max_m`; the client takes `r_max_m` for the offset-only mode and for a backward offset, `r_max_forward_m` for a forward one in the other modes (`view.ts` `offsetRange`). `FIT_PX_MAX` is provisional, tuned by eye (ruling `ridge-offset-range-fit`). A bake whose `r_max_m` is below `R_MAX_FLOOR_M` = 25 m is refused, naming the card and tile. `distance_m` and the nearest-terrain table exclude the near ground (a tile with nothing outside it gets `distance_m` = 500 m), so card 0's distances are never nearer than the near clip (`write_bake` refuses one that is), and `r_max_m` and `r_max_forward_m` hold for the nearest solid terrain each card draws in each tile, at or beyond 500 m, a near-only tile counts at 500 m: the ground nearer than that rides card 0's slide and is not measured beyond that.
|
||||
7. **Distance and the offset range.** The bake holds no camera (ruling `ridge-camera-full-ring`). `pack` gives each card tile `distance_m` = exp(median ln d) over the tile's solid pixels that are neither wall nor near ground (its interior 200 columns); the client derives each card's slide from that and the viewer's offset r and heading. `camera.r_max_m` is the largest |r| (never above half the nearest terrain's distance) at which, for every tile, card and phi (24 steps of the camera's angle on the circle against its heading; the offset-only rotation mode moves phi round the whole circle), the least-squares line `a + s beta` fitted to the exact view angle `atan2(R sin beta - r sin phi, R cos beta - r cos phi)` over the widest viewport (`HFOV_MAX_DEG` = 72 / 1.1) errs by at most `FIT_PX_MAX` = 24 card px (the continuous error: the line by quadrature over the viewport, the worst error looked for on 513 points, so a handful of samples cannot undercount it); the distance d is that of the NEAREST solid (alpha >= 0.5, neither wall nor near ground) pixel the card draws in the tile's interior columns, which is where the slide errs most (the line is fitted for the tile's `distance_m`, the median, but the bound is held for the nearest terrain: a tile whose terrain spans 600 to 2000 m is bound at 600 m); each tile's near pixels (under the clip) count as terrain at the clip, 500 m, alongside its solid pixels, whatever else the tile holds (they are drawn at the clip; a tile of near ground only is slid there too), so a tile with any near pixel binds at 500 m at the latest; and the resident gate (below) must hold at r_max_m too. `camera.r_max_forward_m` is the same search at phi = 0 alone (same `FIT_PX_MAX`, the same half-distance cap, the same resident gate): the camera pushed forward along its heading, which is where the offset stays when the view direction turns with it (the modes 'still' and 'both'), so it is at least `r_max_m`; the client takes `r_max_m` for the offset-only mode and for a backward offset, `r_max_forward_m` for a forward one in the other modes (`view.ts` `offsetRange`). `FIT_PX_MAX` is provisional, tuned by eye (ruling `ridge-offset-range-fit`). A bake whose `r_max_m` is below `R_MAX_FLOOR_M` = 25 m is refused, naming the card and tile. `distance_m` and the nearest-terrain table exclude the near ground (a tile with nothing outside it gets `distance_m` = 500 m), so card 0's distances are never nearer than the near clip (`write_bake` refuses one that is), and `r_max_m` and `r_max_forward_m` hold for the nearest solid terrain each card draws in each tile, at or beyond 500 m, a tile with near pixels counts them at 500 m: the ground nearer than that rides card 0's slide and is not measured beyond that.
|
||||
8. **Normals.** `normals` takes the along-ray slope and the across-ray slope at equal distance (neighbouring columns, same sample), both times the vertical exaggeration.
|
||||
|
||||
Files per card `i` and tile `t`: `card-<i>-t<tt>-colour.webp` (lossy RGB albedo, lossless straight alpha) and `card-<i>-t<tt>-geometry.webp` (lossless: R, G = (n + 1) / 2 for the normal's along and across components, B = log-distance normalised between `encoding.log_d_min` and `log_d_max`; wall pixels write R = G = 255, a code outside the unit disc that no real normal reaches), each 204 columns wide. The manifest lists the cards nearest first (`near_m`, `far_m`: the median seam depths over the ring) and `tiles[t][i]` = `{ top, h, distance_m, colour, geometry }` or `null`; the runtime paints the cards last to first. The `bake_id` is the sha256 of the files, tile-major, then card, colour then geometry.
|
||||
|
|
|
|||
|
|
@ -252,7 +252,7 @@ def bake_place(pid):
|
|||
|
||||
def pack(bake):
|
||||
"""The tiles of a bake as bytes plus their manifest facts. Per card tile: distance_m = exp(median ln d) over the solid (alpha >= 0.5) pixels that are neither wall nor near ground (under the clip) of the interior TILE_W columns (a tile with none falls back to its non-wall, then any, lit pixels, near ground never; a tile with nothing outside the near ground gets ridge.NEAR_CLIP_M: the near ground itself is not measured, but such a tile is slid at that distance and binds r_max there);
|
||||
a card with no rows in a tile is null there. Per card: the median seam depths over the ring. camera.r_max_m: solve_r_max over the NEAREST solid non-wall pixel of each card tile (not its median distance_m; a tile whose card 0 draws only near ground, under the clip, is slid at the clip distance and binds there) and every camera angle on its circle (the offset-only rotation mode), camera.r_max_forward_m: the same at phi = 0 alone (the modes where the offset turns with the view). Refuses a card empty in every tile (naming the splits) and a card with
|
||||
a card with no rows in a tile is null there. Per card: the median seam depths over the ring. camera.r_max_m: solve_r_max over the NEAREST solid non-wall pixel of each card tile (not its median distance_m; each tile's near pixels, under the clip, count as terrain at the clip alongside its solid pixels, whatever else the tile holds: they are drawn at the clip) and every camera angle on its circle (the offset-only rotation mode), camera.r_max_forward_m: the same at phi = 0 alone (the modes where the offset turns with the view). Refuses a card empty in every tile (naming the splits) and a card with
|
||||
no solid terrain apart from its wall in any tile. Returns dict(cards, tiles, camera, report) (report is printed, not written)."""
|
||||
import ridge
|
||||
sm = bake['seams']; sp = bake['splits_km']; k = len(sp) + 1; ppd = bake['view']['px_per_deg_h']; inner = slice(APRON, APRON + TILE_W); enc = bake['meta']['encoding']
|
||||
|
|
@ -265,7 +265,7 @@ def pack(bake):
|
|||
if c['alpha'].shape[0] == 0: row.append(None); drow.append(None); nrow.append(None); continue
|
||||
al, wl, ld, nr = c['alpha'][:, inner], c['wall'][:, inner], c['logd'][:, inner], c['near'][:, inner]; solid = (al >= 0.5) & ~wl & ~nr; any_solid[i] |= bool(solid.any())
|
||||
pool = next(((m, l) for m, l in ((solid, ld), ((al > 0) & ~wl & ~nr, ld), ((al > 0) & ~nr, ld), ((c['alpha'] > 0) & ~c['near'], c['logd'])) if m.any()), None)
|
||||
dm = float(np.exp(np.median(pool[1][pool[0]]))) if pool else ridge.NEAR_CLIP_M; nrow.append(float(np.exp(ld[solid].min())) if solid.any() else (ridge.NEAR_CLIP_M if pool is None else None)) # the nearest solid terrain the card draws in this tile; a tile with nothing but near ground is slid at the clip (its distance_m), so it binds there; None where it draws only wall or faint pixels
|
||||
dm = float(np.exp(np.median(pool[1][pool[0]]))) if pool else ridge.NEAR_CLIP_M; nrow.append(min((v for v in (float(np.exp(ld[solid].min())) if solid.any() else None, ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None) if v is not None), default=None)) # the nearest terrain the card draws in this tile: its solid pixels, and its near pixels as terrain at the clip (they are drawn at the clip whatever else the tile holds); None where it draws only wall or faint pixels
|
||||
row.append(dict(top=c['top'], colour=encode_colour(c['albedo'], c['alpha']), geometry=encode_geometry(c['n_r'], c['n_t'], c['logd'], enc, c['wall']), distance_m=dm)); drow.append(dm); brow.append(c['alpha'].shape[0])
|
||||
tiles.append(row); dist.append(drow); near.append(nrow); bands.append(brow)
|
||||
for i in range(k):
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
"""Mutation check: re-introduce a cause into a COPY of the baker, run the fixtures against it, and require that at least one fails.
|
||||
venv/bin/python tests/mutate.py [word ...] (runs the unmutated copy first and exits 2 if a fixture fails; prints one line per mutant whose name holds every word; exit 1 if a mutant survives or only crashes the run: a kill is an AssertionError in a fixture)"""
|
||||
venv/bin/python tests/mutate.py [word ...] (runs the unmutated copy first and exits 2 if a fixture fails; prints one line per mutant whose name holds every word; exit 1 if a mutant survives or only crashes the run: a kill is an AssertionError raised by the fixtures' own code)"""
|
||||
import os, shutil, subprocess, sys, tempfile
|
||||
HERE = os.path.dirname(os.path.abspath(__file__)); SRC = os.path.join(HERE, '..')
|
||||
MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
|
||||
|
|
@ -41,7 +41,9 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
|
|||
'pack: the apron fallback pool reads near pixels': ("((c['alpha'] > 0) & ~c['near'], c['logd'])", "(c['alpha'] > 0, c['logd'])"),
|
||||
'pack: a tile with nothing outside the near ground is not at the clip': ("if pool else ridge.NEAR_CLIP_M", "if pool else 0.0"),
|
||||
'r_max: the tile median binds, not the nearest terrain': ("r_max = solve_r_max(near, bands, ppd); r_fwd = solve_r_max(near, bands, ppd, phis=1)", "r_max = solve_r_max(dist, bands, ppd); r_fwd = solve_r_max(dist, bands, ppd, phis=1)"),
|
||||
'r_max: a tile of near ground only binds nothing': ("(ridge.NEAR_CLIP_M if pool is None else None))", "None)"),
|
||||
'r_max: near pixels do not bind at the clip': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "None"),
|
||||
'r_max: near pixels bind only in a tile with no other solid pixel': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() and not solid.any() else None"),
|
||||
'r_max: near pixels bind only where they outnumber the solid ones': ("ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).any() else None", "ridge.NEAR_CLIP_M if ((al >= 0.5) & nr).sum() > solid.sum() else None"),
|
||||
'r_max: the nearest pixel is the farthest solid one': ("nrow.append(float(np.exp(ld[solid].min()))", "nrow.append(float(np.exp(ld[solid].max()))"),
|
||||
'near clip: the writer compares the float32 distance strictly': ("if rmin < ridge.NEAR_CLIP_M * (1 - 1e-5): raise", "if rmin < ridge.NEAR_CLIP_M: raise"),
|
||||
'near clip: the march starts nearer than the clip': ("d = [NEAR_CLIP_M]", "d = [100.0]"),
|
||||
|
|
@ -91,7 +93,7 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
|
|||
}
|
||||
EQUIVALENT = {'fit: the error is looked for between four points': "the worst error of the best line is at the viewport's two ends for every distance and offset the bound is searched over (checked against a 20001-sample brute force in test_fit_px_is_the_continuous_error); the grid only guards a shape where it is not"} # mutant name -> one line on why it is behaviourally equivalent (reported, not run)
|
||||
def execute(edit):
|
||||
"""Run the fixtures on a COPY of the baker, with edit = (text, replacement) applied or None for the unmutated copy: (returncode or None if the text is gone, [(fixture, exception class)] of every FAIL line, last stderr line)."""
|
||||
"""Run the fixtures on a COPY of the baker, with edit = (text, replacement) applied or None for the unmutated copy: (returncode or None if the text is gone, [(fixture, exception class, directory of the innermost traceback frame)] of every FAIL line, last stderr line)."""
|
||||
d = tempfile.mkdtemp(); shutil.copytree(SRC, os.path.join(d, 'src'), ignore=shutil.ignore_patterns('tests', '__pycache__'))
|
||||
try:
|
||||
if edit:
|
||||
|
|
@ -100,19 +102,19 @@ def execute(edit):
|
|||
s = open(p).read(); open(p, 'w').write(s.replace(a, b))
|
||||
r = subprocess.run([sys.executable, os.path.join(HERE, 'test_ridge.py')], env=dict(os.environ, RIDGE_SRC=os.path.join(d, 'src')), capture_output=True, text=True)
|
||||
finally: shutil.rmtree(d)
|
||||
fails = [(l.split('|')[0][4:].strip(), (l.split('|', 1)[1].strip().split('(')[0] if '|' in l else '?')) for l in r.stdout.splitlines() if l.startswith('FAIL')]
|
||||
fails = [(f[0][4:].strip(), f[1].strip(), os.path.dirname(os.path.abspath(f[2].strip()))) for f in (l.split(' | ', 3) for l in r.stdout.splitlines() if l.startswith('FAIL')) if len(f) == 4]
|
||||
return r.returncode, fails, (r.stderr.strip().splitlines() or ['no output'])[-1][:200]
|
||||
def run(item):
|
||||
"""KILLED: at least one fixture failed on an ASSERTION (AssertionError). CRASHED: the run failed but no fixture failed an assertion (every FAIL is another exception, NameError and the like, or none printed, or the mutant text is gone), which proves nothing and fails the run. SURVIVED: every fixture passed."""
|
||||
name, (a, b) = item; rc, fails, err = execute((a, b)); asserts = [n for n, c in fails if c == 'AssertionError']
|
||||
"""KILLED: at least one fixture failed on an assertion the test code itself raised (an AssertionError whose innermost traceback frame lies in the tests directory). CRASHED: the run failed but no fixture did that (every FAIL is another exception, NameError or a numpy error and the like, or an assert inside the baker, or none printed, or the mutant text is gone), which proves nothing and fails the run. SURVIVED: every fixture passed."""
|
||||
name, (a, b) = item; rc, fails, err = execute((a, b)); asserts = [n for n, c, w in fails if c == 'AssertionError' and w == HERE]
|
||||
state = 'CRASHED ' if rc is None or (rc and not asserts) else 'KILLED ' if rc else 'SURVIVED '
|
||||
why = ', '.join(f'{n}[{c}]' for n, c in fails) if fails else err
|
||||
why = ', '.join(f'{n}[{c}{"" if w == HERE else " in " + os.path.basename(w)}]' for n, c, w in fails) if fails else err
|
||||
line = state + name + ' -> ' + why; print(line, file=sys.stderr, flush=True) # progress: a killed run keeps what finished
|
||||
return line, state != 'KILLED '
|
||||
def baseline():
|
||||
"""The unmutated copy must pass every fixture before any mutant means anything: a broken environment would kill them all."""
|
||||
rc, fails, err = execute(None)
|
||||
if rc or fails: print('BASELINE FAILED: the unmutated baker does not pass its fixtures: ' + (', '.join(f'{n}[{c}]' for n, c in fails) or err), file=sys.stderr, flush=True); sys.exit(2)
|
||||
if rc or fails: print('BASELINE FAILED: the unmutated baker does not pass its fixtures: ' + (', '.join(f'{n}[{c}]' for n, c, w in fails) or err), file=sys.stderr, flush=True); sys.exit(2)
|
||||
print('BASELINE ok: the unmutated copy passes every fixture', file=sys.stderr, flush=True)
|
||||
if __name__ == '__main__':
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
|
|
|||
|
|
@ -541,28 +541,26 @@ def test_the_near_clip_compare_does_not_depend_on_float32_rounding():
|
|||
for clip in (500.0, 520.0, 700.0):
|
||||
ridge.NEAR_CLIP_M = clip; b = _toy(dists=(clip, 15000.0, 50000.0), amp=0.0); pk = export.pack(b); assert pk['tiles'][0][0]['distance_m'] != 0
|
||||
try: dest = _write(d + f'/ok{clip:g}', b, pk)
|
||||
except ValueError as e: raise AssertionError(('a card 0 at the near clip was refused', clip, str(e)))
|
||||
except ValueError as e: assert 'near clip' not in str(e), ('a card 0 at the near clip was refused', clip, str(e)); raise
|
||||
assert dest.exists(), ('a card 0 at the near clip was refused', clip)
|
||||
b = _toy(dists=(698.9, 15000.0, 50000.0), amp=0.0); ridge.NEAR_CLIP_M = 700.0; _refuses(d + '/under', b, export.pack(b), 'a card 0 under the near clip was written')
|
||||
finally: ridge.NEAR_CLIP_M = saved; shutil.rmtree(d)
|
||||
def _view(sk):
|
||||
"""set_view of a skyline it must hold: a refusal is a failed assertion of the fixture, not a crash."""
|
||||
try: return ridge.set_view(sk)
|
||||
except ValueError as e: raise AssertionError(('set_view refused a skyline it must hold', str(e)))
|
||||
def test_set_view_keeps_the_ground_rows_under_the_horizon():
|
||||
"""A skyline +28 degrees high and +5 low is compressed below 1x so the horizon sits at row 450 or above (GROUND_ROWS_MIN rows under it); one +60 degrees high cannot hold them even at 0.5x and refuses naming sky_deg and the floor; a Vienna-like skyline
|
||||
(the 10x clamp) and one that fits its anchors above 1x are unchanged to 1e-9; a low skyline never binds the horizon."""
|
||||
assert ridge.GROUND_ROWS_MIN == 150 and ridge.E_MIN == 0.5 and ridge.NEAR_CLIP_M == 500.0, 'the authored constants are pinned'
|
||||
sk = np.full(W, 5.0); sk[100] = 28.0; v = _view(sk)
|
||||
assert v['horizon_row'] <= H - ridge.GROUND_ROWS_MIN + 1e-6 and v['exaggeration'] < 1 and v['binds'] == 'horizon' and abs(v['horizon_row'] - (H - ridge.GROUND_ROWS_MIN)) < 1e-6 and abs(v['px_per_deg'] - (H - 150 - 0.04 * H) / 28.0) < 1e-9, v
|
||||
sk = np.full(W, 5.0); sk[100] = 60.0
|
||||
try: ridge.set_view(sk)
|
||||
except ValueError as e: assert '60.00' in str(e) and '8.89' in str(e) and '0.5x' in str(e), str(e)
|
||||
except ValueError as e:
|
||||
if 'under the horizon' not in str(e): raise # not the refusal: a crash
|
||||
assert '60.00' in str(e) and '8.89' in str(e) and '0.5x' in str(e), str(e)
|
||||
else: assert False, 'a skyline that cannot hold the ground rows was accepted'
|
||||
sk = np.full(W, 1.7); sk[7] = 2.0; v = _view(sk); assert abs(v['px_per_deg'] - 10 * ridge.HPX_DEG) < 1e-9 and abs(v['horizon_row'] - (2.0 * 10 * ridge.HPX_DEG + 0.04 * H)) < 1e-9 and v['binds'] == 'ceiling', v
|
||||
sk = np.full(W, 1.0); sk[7] = 3.0; sk[9] = -1.0; v = _view(sk); assert abs(v['px_per_deg'] - 0.62 * H / 4.0) < 1e-9 and v['binds'] == 'skyline', v
|
||||
sk = np.full(W, -30.0); sk[7] = 12.0; v = _view(sk); assert abs(v['px_per_deg'] - 0.5 * ridge.HPX_DEG) < 1e-9 and v['binds'] == 'floor', v
|
||||
sk = np.full(W, -9.0); sk[7] = -2.0; v = _view(sk); assert v['horizon_row'] < 0.04 * H and v['binds'] != 'horizon', v
|
||||
sk = np.full(W, 5.0); sk[100] = 28.0; v = ridge.set_view(sk)
|
||||
assert v['horizon_row'] <= H - ridge.GROUND_ROWS_MIN + 1e-6 and v['exaggeration'] < 1 and v['binds'] == 'horizon' and abs(v['horizon_row'] - (H - ridge.GROUND_ROWS_MIN)) < 1e-6 and abs(v['px_per_deg'] - (H - 150 - 0.04 * H) / 28.0) < 1e-9, v
|
||||
sk = np.full(W, 1.7); sk[7] = 2.0; v = ridge.set_view(sk); assert abs(v['px_per_deg'] - 10 * ridge.HPX_DEG) < 1e-9 and abs(v['horizon_row'] - (2.0 * 10 * ridge.HPX_DEG + 0.04 * H)) < 1e-9 and v['binds'] == 'ceiling', v
|
||||
sk = np.full(W, 1.0); sk[7] = 3.0; sk[9] = -1.0; v = ridge.set_view(sk); assert abs(v['px_per_deg'] - 0.62 * H / 4.0) < 1e-9 and v['binds'] == 'skyline', v
|
||||
sk = np.full(W, -30.0); sk[7] = 12.0; v = ridge.set_view(sk); assert abs(v['px_per_deg'] - 0.5 * ridge.HPX_DEG) < 1e-9 and v['binds'] == 'floor', v
|
||||
sk = np.full(W, -9.0); sk[7] = -2.0; v = ridge.set_view(sk); assert v['horizon_row'] < 0.04 * H and v['binds'] != 'horizon', v
|
||||
def test_the_near_clip_and_the_ground_rows_are_refused_at_the_writer():
|
||||
"""The march starts at the authored near clip; write_bake refuses a bake whose card 0 stands nearer than it (nothing nearer is baked as terrain), and validate_manifest, which the writer and the committed bakes go through, refuses a plane with fewer than GROUND_ROWS_MIN rows under the horizon and accepts exactly that many."""
|
||||
assert D[0] == ridge.NEAR_CLIP_M == ridge.schedule(True)[0] and (np.diff(D) > 0).all(), 'the march does not start at the near clip'
|
||||
|
|
@ -608,19 +606,25 @@ def test_near_ground_has_the_material_and_relief_of_its_own_heights():
|
|||
else: assert np.abs(c['albedo'][sel, x] - ridge.albedo(np.full(int(sel.sum()), base[x]), up[sel, x])).max() < 1e-5, ('a near row has not the material of its own height', x)
|
||||
got[blk[x]] = c['albedo'][sel, x].mean(0)
|
||||
assert np.abs(got[0] - got[1]).max() > 0.05 and np.abs(got[1] - got[2]).max() > 0.05 and np.abs(got[0] - got[2]).max() > 0.05, ('the blocks do not differ where the ground does', got)
|
||||
def test_near_pixels_are_not_measured():
|
||||
"""pack of a bake with near rows (card 0, one tile: its lower third is near ground at 150 m) equals in every distance_m and in the camera pack of the same bake with those pixels cut out; a tile whose card 0 is near only gets distance_m == NEAR_CLIP_M and BINDS r_max at that distance (it is slid at 500 m) even where every other tile stands 3000 m away, and write_bake accepts it."""
|
||||
b = _toy(); base = export.pack(b); cs = [[dict(c) for c in tile] for tile in b['cards']]; c = cs[3][0]; n = c['alpha'].shape[0]; near = np.zeros_like(c['near']); near[n * 2 // 3:] = True
|
||||
def test_near_pixels_bind_at_the_clip_wherever_they_are():
|
||||
"""Near pixels are drawn at the clip, so each tile's near pixels count in the r_max fit as terrain at the clip alongside its solid pixels, and never in distance_m. Card 0, every other tile 3000 m away: (a) a tile whose lower third is near ground at 150 m keeps its distance_m but binds at 500 m, and without those pixels binds nothing;
|
||||
(b) a tile of near ground only has distance_m == NEAR_CLIP_M, binds exactly like terrain at 500 m, and write_bake accepts it; (c) a tile of near ground with a few stray solid pixels at 3000 m binds the same, whatever the stray count (no threshold)."""
|
||||
b = _toy(); base = export.pack(b); cs = [[dict(c) for c in tile] for tile in b['cards']]; c = cs[3][0]; n = c['alpha'].shape[0]; near = np.zeros_like(c['near']); near[n * 2 // 3:] = True; ppd = ridge.HPX_DEG
|
||||
dists = lambda pk: [[e and e['distance_m'] for e in row] for row in pk['tiles']]; at_clip = lambda src: dict(src, logd=np.full_like(src['logd'], math.log(ridge.NEAR_CLIP_M)))
|
||||
cs[3][0] = dict(c, near=near, logd=np.where(near, math.log(150.0), c['logd']).astype(np.float32)); a = export.pack(dict(b, cards=cs))
|
||||
cs[3][0] = dict(c, alpha=np.where(near, 0.0, c['alpha']).astype(np.float32)); cut = export.pack(dict(b, cards=cs)); dists = lambda pk: [[e and e['distance_m'] for e in row] for row in pk['tiles']]
|
||||
assert dists(a) == dists(cut) == dists(base) and a['camera'] == cut['camera'] == base['camera'], ('near pixels were measured', a['camera'], cut['camera'])
|
||||
cs[3][0] = dict(c, alpha=np.where(near, 0.0, c['alpha']).astype(np.float32)); cut = export.pack(dict(b, cards=cs)); cs[3][0] = at_clip(c); clip = export.pack(dict(b, cards=cs))
|
||||
assert dists(a) == dists(cut) == dists(base) and cut['camera'] == base['camera'], ('near pixels were measured in distance_m', dists(a)[3], dists(base)[3])
|
||||
assert a['camera'] == clip['camera'] and a['camera']['r_max_m'] < base['camera']['r_max_m'] - 5 and a['camera']['r_max_forward_m'] < base['camera']['r_max_forward_m'] - 5, ('near pixels in a tile of terrain do not bind at the clip', a['camera'], base['camera'])
|
||||
cs[3][0] = c; only = dict(cs[9][0]); cs[9][0] = dict(only, near=np.ones_like(only['near']), logd=np.full_like(only['logd'], math.log(300.0))); ob = dict(b, cards=cs); pk = export.pack(ob); d = tempfile.mkdtemp()
|
||||
try:
|
||||
assert pk['tiles'][9][0]['distance_m'] == ridge.NEAR_CLIP_M and pk['tiles'][8][0]['distance_m'] == base['tiles'][8][0]['distance_m'], ('a near-only tile', pk['tiles'][9][0]['distance_m'])
|
||||
r, rf = pk['camera']['r_max_m'], pk['camera']['r_max_forward_m']; ppd = ridge.HPX_DEG; assert r < base['camera']['r_max_m'] - 5 and rf < base['camera']['r_max_forward_m'] - 5, ('a near-only tile does not bind', pk['camera'], base['camera'])
|
||||
r, rf = pk['camera']['r_max_m'], pk['camera']['r_max_forward_m']; assert r < base['camera']['r_max_m'] - 5 and rf < base['camera']['r_max_forward_m'] - 5, ('a near-only tile does not bind', pk['camera'], base['camera'])
|
||||
assert export.fit_px(ridge.NEAR_CLIP_M, r, ppd) <= export.FIT_PX_MAX + 1e-6 and export.fit_px(ridge.NEAR_CLIP_M, rf, ppd, 1) <= export.FIT_PX_MAX + 1e-6 and export.fit_px(ridge.NEAR_CLIP_M, r + 0.5, ppd) > export.FIT_PX_MAX, ('the near-only tile is not bound at the clip distance it is slid at', r, rf)
|
||||
cs[9][0] = dict(only, logd=np.full_like(only['logd'], math.log(ridge.NEAR_CLIP_M))); assert export.pack(dict(b, cards=cs))['camera'] == pk['camera'], 'a near-only tile does not bind exactly like terrain at the clip'
|
||||
cs[9][0] = at_clip(only); assert export.pack(dict(b, cards=cs))['camera'] == pk['camera'], 'a near-only tile does not bind exactly like terrain at the clip'
|
||||
assert _write(d + '/ok', ob, pk).exists(), 'a bake with a near-only tile was refused'
|
||||
for stray in (1, 6, 40): # solid pixels at 3000 m among the near ground of a tile: it binds at the clip all the same
|
||||
st = np.zeros_like(only['near']); st[:1, 10:10 + stray] = True; cs[9][0] = dict(only, near=~st, logd=np.where(st, only['logd'], math.log(300.0)).astype(np.float32)); sp = export.pack(dict(b, cards=cs))
|
||||
assert sp['camera'] == pk['camera'], ('stray solid pixels unbound a tile of near ground', stray, sp['camera'], pk['camera'])
|
||||
finally: shutil.rmtree(d)
|
||||
def test_cards_refuses_a_march_without_the_near_ground():
|
||||
"""ridge.cards on a march whose first sample is the near clip (not joined to the near march) raises, naming join_near: card 0 can never extrude the clip sample again."""
|
||||
|
|
@ -679,5 +683,5 @@ if __name__ == '__main__':
|
|||
fails = 0
|
||||
for t in TESTS:
|
||||
try: t(); print("PASS", t.__name__)
|
||||
except Exception as e: fails += 1; print("FAIL", t.__name__, "|", repr(e)[:300])
|
||||
except Exception as e: fails += 1; print("FAIL", t.__name__, "|", type(e).__name__, "|", traceback.extract_tb(e.__traceback__)[-1].filename, "|", repr(e)[:300]) # name | class | file of the innermost frame | repr: mutate.py kills only on an AssertionError raised in this directory
|
||||
print("failures:", fails); sys.exit(1 if fails else 0)
|
||||
|
|
|
|||
Loading…
Reference in a new issue