SRC=os.environ.get('RIDGE_SRC')oros.path.join(os.path.dirname(os.path.abspath(__file__)),'..');sys.path.insert(0,SRC)# RIDGE_WORK and RIDGE_TILES must be set (tests/run.sh sets them)
importnumpyasnp,ridge
fromridgeimportW,TAPER,TAPER_MAX,taper_len
EYE=100.0;GROUND=50.0# ground below the eye: every ray climbs, so only the placed blocks make ridges
"""steepest step allowed inside a taper: smoothstep slope 1.5 x the end drop / taper_len(drop) (+ margin), the end drop taken as max((highest top within w columns) - lo, 0.4)"""
seg=S['top'][[(x+k)%Wforkinrange(-w,w+1)]];drop=max(seg.max()-S['lo'][x],0.4);return1.6*drop/float(taper_len(drop))+0.02# the taper always falls at least 0.4 deg (top - 0.4 when the valley is shallower)
"""Flat-topped plateau, az 100-140, 20-24 km, 900 m. Right answer: top = theta(900, 20 km) inside, nothing above it anywhere, outside the plateau the top only falls
assert(np.diff(seg)<=1e-9).all(),('taper is not monotone away from the plateau',side,np.diff(seg).max())
assertseg[-1]<seg[0]-0.3,'taper does not die away'
assertS['wt'][(x0+side*(n+3))%W]==0,'the layer is still drawn far outside the plateau'
j=np.abs(np.diff(top,append=top[0]));bad=[(x,round(float(j[x]),3))forxinactive_pairs(S)ifj[x]>jump_bound(S,x)];assertnotbad,('column jump above the bound',bad[:5])
drop=th-S['lo'][col_of(120)];width=int(((S['wt']>0)&(S['wt']<1))[col_of(140):col_of(140)+90].sum());assertdrop>1.5andwidth>=0.9*min(72,30*drop),('a tall end must fall over ~30 columns per degree of drop up to 72 (absolute, not the constant) (its drop is %.2f deg)'%drop,width)
"""Plateau az 100-140 whose height climbs 600 -> 1200 m with azimuth. Right answer: left of the left end nothing is higher than the left end's own top, right of the right end
nothingishigherthantherightend's top (the round-1 bug held the END value on both sides: a 0.9 deg step on the low side)."""
"""Two chains in one slot: L1 present on cols 0-99 (top 0.2), L2 present on cols 200-299 (top 2.0) but its HELD value elsewhere is 0.5 > 0.2. Right answer: on cols 0-99
assertlen(S)==1and(S[0]['wt'][0:100]==1).all()andnp.allclose(S[0]['top'][0:100],0.2),('absent chain won the slot union',S[0]['top'][:3],S[0]['wt'][:3])
"""Two plateaus side by side, 700 m (az 60-180) then 1300 m (180-300). Right answer: level theta_A left, theta_B right, one step at az 180 (col 3200)."""
"""Gaussian peak 1800 m at az 90, 30 km, sigma 1.5 km. Right answer: one maximum at az 90 +-0.2, monotone either side inside the chain, no secondary bump."""
"""Plateau az 350 -> 10 (across 0/360). Right answer: flat top, no step across the seam, one chain crossing it, and the result does not depend on where column 0 is."""
"""Real bake: no per-column step above the stated bound. In a chain (wt == 1) a step above 0.12 deg is allowed only if both columns carry the raw span peak that wins there (a real step of the DEM, e.g. a roof edge); in a taper the
"""Right answer: sun due north at 5 deg: the ray is 580 m at the wall, the wall is 1000 m => fully shadowed (1.0). Sun due north at 30 deg clears the wall (0.0). Sun due south: the wall is behind the sun (0.0).
"""Wall of 1000 m at lon 16.575-16.585 (5.5-6.2 km EAST of the sample point at lat 48.4, cos(lat) matters), flat 100 m elsewhere. Sun due east at 5 deg: shadowed (580 m ray vs 1000 m).
assertf(90.0,5.0)>0.99,('east wall does not shadow a low east sun',f(90.0,5.0))
assertf(270.0,5.0)<0.01,('east wall shadows a west sun',f(270.0,5.0))
assertf(90.0,6.0)>0.99andf(90.0,12.0)<0.01,('east-wall shadow edge is at the wrong elevation (wall is 5.5 km east of the point: the sun ray at 6 deg is 660 m there, at 12 deg 1.2 km)',f(90.0,6.0),f(90.0,12.0))
deftest_shadow_darkens_the_face_it_covers():
"""Whole pipeline on a synthetic ramp (slope 0.35, lit by the relief light): with the shadow march forced to 1 every face pixel is darker than with it forced to 0 (the shadow removes direct sun); forced 0 equals shadows off."""
off=ridge.relight(L,300.0,30.0,*pf,shadows=False);c=slice(col_of(105),col_of(135));rows=slice(0,ridge.H);Ly=max(L,key=lambdal:((l['m'][rows,c]>0.99)&(l['w'][rows,c]<0.05)).sum());m=(Ly['m'][rows,c]>0.99)&(Ly['w'][rows,c]<0.05)# body pixels (not the mist foot) of the layer that owns the plateau
assertm.any(),'no solid face pixels to compare'
assertdark[rows,c][m].mean()<lit[rows,c][m].mean()-0.02,('shadow does not darken the face',dark[rows,c][m].mean(),lit[rows,c][m].mean())
assertnp.abs(lit-off).max()<1e-4,'a zero shadow differs from shadows off'
# ---------------------------------------------------------------------------------------- shading fixtures (round 3): the face history -> per-pixel normal
"""(analytic n.L, baked n.L) at pixels of the cone layer: the analytic one marches the ray finely to the first sample whose running-max angle reaches the pixel's elevation and takes the cone's own normal there."""
"""Cone (apex 1800 m, base radius 6 km, 20 km away), sun from the west at 20 deg. Right answer: the shading of each pixel is the cone's own n.L at the point that pixel sees, so it changes down every
"""Planar ramp facing the viewer, az 60-120, rising 0.35 per metre of distance from 20 km to 24 km, then a drop. Right answer: every face pixel's front slope is 0.35 (19.3 deg) and its lateral tilt is 0,
assertlen(rows)>20andabs(np.median(sl)-0.35)<0.03andnp.percentile(np.abs(sl-0.35),90)<0.08,('front slope is not the plane\'s',np.median(sl),np.percentile(np.abs(sl-0.35),90))
assertnp.abs(la).max()<0.08,('lateral tilt on a plane',np.abs(la).max())
"""Two plateaus (700 m / 1300 m) meeting at az 180. Right answer: the face is level laterally (la ~ 0) away from the step, and strongly tilted at it (the height changes by 600 m between two neighbouring columns)."""
"""Flat ground with a 19 m x 40 m block 700 m away (a roof / tree in a DSM). Right answer: no layer: a peak needs PROM_M (25 m) of height over its valley, and the 4 km NEAR_CAP shoulder rule obeys the same
A,Hh=rays(terrain(bump(19.0)));r=ridge.sweep(D,A,Hh);assertnot[lforlinr['keep']ifl['dist']<4000],('a 19 m bump became a ridge',[(l['x0'],l['span'],round(l['dist']))forlinr['keep']])
A,Hh=rays(terrain(bump(60.0)));r=ridge.sweep(D,A,Hh);assert[lforlinr['keep']ifl['dist']<1000],'a 60 m block must be a ridge'
"""Right answer (cone): the iso-height lines drawn on a layer are at least CONTOUR_MIN_PX apart over three quarters of its face (round 2 picked the interval from the SHALLOWEST columns, so the steep centre
assertlen(sp)>20andnp.percentile(sp,25)>=8,('contour lines too dense',np.percentile(sp,25),len(sp))
deftest_no_layer_paints_a_wall_down_the_frame():
"""Right answer: a layer's alpha is 0 further below its own crest than its foot allows (<= 210 px): its column boundary leaves no vertical edge through the floor (round 2 painted the body to the bottom of the
forLyinL:below=np.arange(ridge.H)[:,None]-(ridge.TOP_DEG-Ly['ang'])[None,:]*ridge.PXDEG_V;assertLy['a'][below>215].max()==0,('layer painted below its foot',Ly['rank'])
end=[cforcinrange(W)if0<S['wt'][c]<0.12];assertend,'fixture has no taper end'
bad=[(c,int((Ly['a'][:,c]>0.1).sum()))forcinendif(Ly['a'][:,c]>0.1).sum()>0.85*max(Ly['ang'][c]-Ly['lo'][c],0)*ridge.PXDEG_V+4];assertnotbad,('a chain end hangs a curtain thicker than the ridge is tall',bad[:4])
"""Two plateaus in one distance slot (az 100-110 at 700 m, az 200-215 at 1100 m, both 20-24 km). Right answer: rotating the ring by 1600 columns changes nothing, in EVERY column of the slot including those where no chain is present
(round3firstpickedthefirstchaininlistorderthere;listorderdependsonwherecolumn0is,andthosevaluesfeedtheblursateverychainend:HalfDome's rotation test went from 0 to 97 px)."""
A,Hh=rays(terrain(block(100,110,20000,24000,700),block(200,215,20000,24000,1100)));r=ridge.sweep(D,A,Hh);R=2800;r2=ridge.sweep(D,np.roll(A,-R,axis=1),np.roll(Hh,-R,axis=1))# 2800 columns carries the az 200-215 block through column 0: the chains swap places in list order
forkin('top','lo','wt','pd','ph','vh','slope'):assertnp.abs(np.roll(S2[k],R)-S1[k]).max()<1e-9,('slot not rotation invariant',S1['slot'],k,np.abs(np.roll(S2[k],R)-S1[k]).max())
forkin('hd','hh'):assertnp.abs(np.roll(S2[k],R,axis=1)-S1[k]).max()<1e-6,('slot history not rotation invariant',S1['slot'],k)
"""Terrace (50 m, eye 100 m) ending at 10 km, a 0 m basin, a 60 m ridge at 30 km (az 80-100). Right answer: the ridge is a layer at 30 km: it stands 0.5 deg above its visible valley, which is 4 times the 25 m / 30 km bar of 0.048 deg.
(Round3's first cut compared raw heights, ridge 60 m vs the valley's0m...andlostridgeswhosevalleysampleisnearandhigh.)"""
hf=lambdadk,az:np.where(dk<10000,50.0,np.where(in_arc(az,80,100)&(dk>=30000)&(dk<30500),60.0,np.where(in_arc(az,80,100)&(dk>=50000)&(dk<55000),300.0,0.0)))# the 300 m wall at 50 km keeps the ridge from being committed as the ray's last peak
A,Hh=rays(hf);r=ridge.sweep(D,A,Hh);far=[lforlinr['keep']ifabs(l['dist']-30000)<1500];assertfarandfar[0]['span']>200,('the 30 km ridge is missing',[(l['x0'],l['span'],round(l['dist']))forlinr['keep']])
"""(a) a 0.5 deg wide, 60 m block at 1.7 km with nothing else near: the nearest layer must cover it (a hole would show the far ridge's body). (b) the same stub in front of a long near ridge (az 100-160, 150 m, 1.5 km):
A,Hh=rays(terrain(block(90,90.5,1700,1740,110)));r=ridge.sweep(D,A,Hh);assert[lforlinr['keep']ifl['dist']<2500],'lone foreground stub dropped: hole in the nearest layer'
A,Hh=rays(terrain(block(100,160,1500,1600,150),block(129,129.5,600,640,160)));r=ridge.sweep(D,A,Hh);assertnot[lforlinr['keep']ifl['dist']<1000],('a stub inside a near ridge became an arch',[(l['x0'],l['span'],round(l['dist']))forlinr['keep']])
"""Plane h = 50 + 0.3 (E - 20000) - 0.2 N over az 85-95, 20-24 km, then a drop. At az 90 the radial is +E and the tangent is -N, so n ~ (-0.3 r - la t, 1) with la = -(dh/dN) = +0.2. Right answer: front slope 0.3, lateral tilt 0.2, each within 0.04
"""Samples (angle, distance, height): (0, 100, 0) (2, 200, 10) (1, 300, 5) (1.5, 350, 8) (3, 400, 30). The third and fourth are hidden behind the second (the fourth RISES from the third, so only a running maximum drops it). Right answer: at elevation 2.5 the face is half way between the second and the fourth sample: distance 300, height 20
"""Block A (az 60-130, 15 km out, 700 m) and block B (az 110-180, 21 km out, 940 m): the same top angle, the same distance slot, so the slot owner switches where their tapers cross. Right answer: at every column where the owner's
assertnp.abs(la).max()<0.5,('tilt across an occlusion edge at column',x,np.abs(la).max())
# ---------------------------------------------------------------------------------------- relief light (round 3): n.L uses an authored light, colour / haze / shadows keep the real sun
def_gully(dk,az):
"""A ramp facing the viewer (0.35 slope, az 50-130, 20-24 km) cut by gullies that run down the slope: height +300 m sin(2 pi N / 3 km), so the lateral tilt swings between -0.63 and +0.63 across the face."""
"""Relight the gullied ramp seen from az 90 with spies on ndl_field (the L it shades with and the n.L it returns for the ramp's layer) and on cast_shadows (the sun it marches toward). Returns (image, Ls, n.L of the ramp layer, shadow suns, layer)."""
"""Gullied ramp seen from az 90, sun directly behind the viewer (az 270, 20 deg up). Lit head-on, a gully's two flanks shade alike (n.L std over the face 0.034 with the real sun as the shading light);
"""View centre az 90 (the viewer looks east). The relief light is the view centre +/- 45 deg on the side of the view axis the real sun is on. Sun at az 300 (north of the axis, the viewer's left) -> relief az 90-45 = 45;
sunataz240(south,theviewer's right) -> relief az 90+45 = 135. Elevation is 25..40 deg (an absolute range, not the constant) both times, whatever the sun'selevation."""
"""Same sun azimuth, elevation 10 deg vs 40 deg: the relief direction is identical, the picture is not (sun colour / haze / strength change), and at -10 deg (night) the face is darker than at 40."""
assertnp.abs(i1[rows,640]-i2[rows,640]).mean()>0.01,'colour does not follow the real sun';asserti3[rows,640].mean()<0.6*i2[rows,640].mean(),('night is not dark',i3[rows,640].mean(),i2[rows,640].mean())
"""Plateau az 100-140 (20-24 km) seen from az 120. Right answer: in the floor band (the frame's bottom 80 rows) no column differs from its neighbour by more than the grain (baseline 0.009, a painted wall 0.25): the compositor must use the layer's
lum=img@np.array([0.2126,0.7152,0.0722]);st=np.abs(np.diff(lum[ridge.H-80:],axis=1)).mean(0);assertst.max()<0.03,('wall: column-wise luminance step in the floor band',st.max(),int(np.argmax(st)))
"""A layer's alpha is 1 down to 60% of its foot length, then smoothsteps to 0 at the foot. Right answer on a plateau column: rows with alpha > 0.99 / rows with alpha > 0.001 = 0.6 (+-0.04), and it has the full 210 px foot at most
"""Two plateaus (700 / 1300 m) meeting at az 180: the raw lateral tilt is a spike at the step. Right answer: the baked tilt is blurred over a few columns: no column-to-column change above 0.5 (unblurred: 0.9), and the tilt is still > 0.2 at the step."""
"""Ramp (slope 1.0, az 110-130, 20-22 km) whose tapering ends carry coarser metres-per-pixel. Right answer: the contour spacing in the core is 9-10 px (interval from the chain's own face), not 13-14 (the taper columns pulled the percentile up). median <= 12 and p25 >= 8."""
"""spec_field against an independent evaluation: half vector H = normalise(L + V), V the unit vector back to the viewer (-r) in every column, n = (-sl r - la t + z)/|.|, GGX alpha 0.3. Two different lights, random faces: the field must match to 1e-9
"""fresnel(sl, nrm) = (1 - n.V)^3 with n.V = sl / |n|: 1 for a flat or back-leaning face (sl <= 0), falling monotonically to ~0 for a face that stands up at the viewer (sl = 5: 0.00001)."""
"""mosaic-/rays- cache files are keyed by a digest of their inputs. Right answer: identical inputs -> identical key (the preset id does not enter), a changed preset field (eye height, range, position), tile list or baker constant (refraction, detail noise) -> a different key."""
"""The affine haze split is exact for one group: the far plane (floor + slot 0) over one flat colour equals relight of slot 0 alone with that colour as sky and haze (grain off, no shadows) within 1/255 mean and 4/255 max.
"""Real Vienna bake at noon, three planes over a flat sky vs relight(flat=that sky): the stacking loss (a nearer group's haze veils the farther plane instead of the sky) measured 4.9/255 mean; the bound is 6, so a split
"""Planes carry straight (un-premultiplied) colour: the mid plane (slot 1, 16 km) and the near plane (slot 2, 5 km) each alone over a flat sky equal the opaque relight of that one slot over the same sky, on the rows
abovethehorizon(thefloorbelongstothefarplane).Theirbodiesaretranslucent(thehazeshareisalpha's deficit), so premultiplied colour would be darker by alpha and fail by tens of 1/255. u8() keeps colour and alpha apart."""
body=pl[name][:top,:,3]>0.3;assertbody.sum()>1000andpl[name][:top,:,3][body].mean()<0.97,(name,'the fixture has no translucent body to test')
d=np.abs(got-want)*255;assertd.mean()<0.5andd.max()<4.0,(name,'plane over a flat sky differs from its slot relight: colour is premultiplied or the haze split is wrong',d.mean(),d.max())
"""Two bakes of the same input give the same bake_id and bytes; the manifest validates against the schema, planes are the window wide (<= the cap), frame pairs fit the budget, plane paths exist relative to
manifest.json,lumamin<=maxin0..1perframe,theindexpointsatthedirandarebakereplacestheplace's old dir."""
committed=json.load(open(os.path.join(SRC,'ridge-bake.schema.json')));assertcommitted==json.loads(json.dumps(export.SCHEMA)),'ridge-bake.schema.json is stale (export.py --write-schema)'
"""bake_id = first 12 hex of sha256 over the plane bytes in key order, then far, mid, near: one changed byte in any plane changes it, swapping two planes changes it, and the value equals an independent hash."""
"""Any two ADJACENT frames above PAIR_BYTES_MAX are refused (a heavy frame next to a light one at the cap passes), as is a plane wider than the cap, and nothing is written."""
"""Two hand-built planes: a solid mid-grey (sRGB 128 -> linear 0.2158) and a solid white (1.0); a translucent black pixel (alpha 100) is not measured. Reads back to 1e-3."""
z=export.decode(export.encode(np.full((8,8,4),1.0,np.float32)));assertz.shape==(8,8,4)and(z[...,3]==255).all(),'an everywhere-opaque plane must read back as RGBA'