Ridge legibility closeout: eased near foot, notch check, post-notch rebake, night scrim #167

Open
void wants to merge 3 commits from nibu/ridge-legibility into dev
40 changed files with 215 additions and 43 deletions

View file

@ -2,6 +2,6 @@
"schema": 1,
"default": "vienna",
"places": {
"vienna": "vienna-12e733dc9f09"
"vienna": "vienna-f25b2314a20c"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

View file

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

View file

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 51 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

View file

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

View file

@ -1,7 +1,7 @@
{
"schema": 1,
"baker_version": 1,
"bake_id": "12e733dc9f09",
"bake_id": "f25b2314a20c",
"place": {
"id": "vienna",
"name": "Vienna, looking SW to Rax/Schneeberg",
@ -34,7 +34,7 @@
"planes": {
"far": {
"file": "dawn-far.webp",
"bytes": 76030,
"bytes": 75202,
"w": 1280,
"h": 600
},
@ -46,15 +46,15 @@
},
"near": {
"file": "dawn-near.webp",
"bytes": 113422,
"bytes": 114340,
"w": 1280,
"h": 600
}
},
"bytes": 243378,
"bytes": 243468,
"luma": {
"min": 0.02173927318967578,
"max": 0.2161143719823614
"max": 0.2143920269061395
}
},
{
@ -67,7 +67,7 @@
"planes": {
"far": {
"file": "morning-far.webp",
"bytes": 77330,
"bytes": 76528,
"w": 1280,
"h": 600
},
@ -79,12 +79,12 @@
},
"near": {
"file": "morning-near.webp",
"bytes": 120478,
"bytes": 121380,
"w": 1280,
"h": 600
}
},
"bytes": 255884,
"bytes": 255984,
"luma": {
"min": 0.023307705502610833,
"max": 0.5966843818121018
@ -100,7 +100,7 @@
"planes": {
"far": {
"file": "noon-far.webp",
"bytes": 78634,
"bytes": 77662,
"w": 1280,
"h": 600
},
@ -112,15 +112,15 @@
},
"near": {
"file": "noon-near.webp",
"bytes": 123036,
"bytes": 123968,
"w": 1280,
"h": 600
}
},
"bytes": 260354,
"bytes": 260314,
"luma": {
"min": 0.028024916825206435,
"max": 0.7110067687110413
"max": 0.7120793110425
}
},
{
@ -133,7 +133,7 @@
"planes": {
"far": {
"file": "golden-far.webp",
"bytes": 76038,
"bytes": 75080,
"w": 1280,
"h": 600
},
@ -145,14 +145,14 @@
},
"near": {
"file": "golden-near.webp",
"bytes": 114944,
"bytes": 115796,
"w": 1280,
"h": 600
}
},
"bytes": 245668,
"bytes": 245562,
"luma": {
"min": 0.02139437660612246,
"min": 0.020826947830069446,
"max": 0.2869579287555448
}
},
@ -166,7 +166,7 @@
"planes": {
"far": {
"file": "dusk-far.webp",
"bytes": 75552,
"bytes": 74788,
"w": 1280,
"h": 600
},
@ -178,15 +178,15 @@
},
"near": {
"file": "dusk-near.webp",
"bytes": 112176,
"bytes": 113136,
"w": 1280,
"h": 600
}
},
"bytes": 239904,
"bytes": 240100,
"luma": {
"min": 0.018028911802351475,
"max": 0.18804654725014905
"max": 0.187384301855065
}
},
{
@ -199,7 +199,7 @@
"planes": {
"far": {
"file": "night-far.webp",
"bytes": 74732,
"bytes": 73982,
"w": 1280,
"h": 600
},
@ -211,12 +211,12 @@
},
"near": {
"file": "night-near.webp",
"bytes": 110780,
"bytes": 111634,
"w": 1280,
"h": 600
}
},
"bytes": 235704,
"bytes": 235808,
"luma": {
"min": 0.012974147057371975,
"max": 0.14255636176898956

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

View file

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 57 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

View file

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

View file

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 57 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

View file

@ -26,6 +26,9 @@ WEBP_QUALITY = 80
LUMA_SKY = 0.5 # the flat mid-grey sky the planes are composited over for the luma probe
LUMA_COVER = 0.5 # composite coverage (1 - prod(1 - alpha)) at or above which a pixel is measured
NEAR_CREST_ALPHA = 64 # alpha (0..255) at which a near-plane pixel counts as the ridge's body: the crest of a column is its first such row
NEAR_BODY_ALPHA = 40 # alpha at which a near-plane pixel still counts as body when finding where a column's body ends
NEAR_END_DROP_PX = 40 # how far the row where the body ends may fall short of the deepest end within NEAR_END_WINDOW columns: a notch where the near plane dissolves early over a few columns (Vienna had 60 at x 1252-1280; natural terrain 22)
NEAR_END_WINDOW = 8
NEAR_HOLE_ALPHA = 24 # alpha below which a pixel under the crest is a hole (the sky would show through the ground in front of the eye)
SHEET_SKY = (0.80, 0.86, 0.94) # the flat sky of the contact sheet
ATTRIBUTION = dict(
@ -102,12 +105,15 @@ def luma_range(decoded):
return float(y.min()), float(y.max())
def check_near_cover(near, horizon_row):
"""Refuse a near plane (RGBA uint8) that does not cover the ground in front of the eye: every column must have a crest (an alpha >= NEAR_CREST_ALPHA row), and from the crest down to the horizon row no pixel may be a hole (alpha < NEAR_HOLE_ALPHA).
"""Refuse a near plane (RGBA uint8) that does not cover the ground in front of the eye: every column must have a crest (an alpha >= NEAR_CREST_ALPHA row), and from the crest down to the horizon row no pixel may be a hole (alpha < NEAR_HOLE_ALPHA), and the row where the body ends may not fall more than NEAR_END_DROP_PX short of the deepest end within NEAR_END_WINDOW columns.
A transparent column, or a wedge of holes under a crest, shows the sky through the foreground; the farther planes may leave columns empty (a place with no ridge at that distance), the nearest may not."""
a = near[..., 3]; h, w = a.shape; crest = np.argmax(a >= NEAR_CREST_ALPHA, axis=0); none = ~(a >= NEAR_CREST_ALPHA).any(0)
if none.any(): raise ValueError(f'near plane: {int(none.sum())} fully transparent columns, first at x={int(np.argmax(none))}')
rows = np.arange(h)[:, None]; hole = (a < NEAR_HOLE_ALPHA) & (rows >= crest[None, :]) & (rows < int(horizon_row))
if hole.any(): x = int(np.argmax(hole.any(0))); raise ValueError(f'near plane: {int(hole.any(0).sum())} columns have a hole between the crest and the horizon, first at x={x} row {int(np.argmax(hole[:, x]))}')
body = a >= NEAR_BODY_ALPHA; end = h - 1 - np.argmax(body[::-1], axis=0) # the body's last row, per column: the dissolve below the horizon has no edge of its own
deepest = np.lib.stride_tricks.sliding_window_view(np.pad(end, NEAR_END_WINDOW, mode='edge'), 2 * NEAR_END_WINDOW + 1).max(-1); notch = deepest - end
if (notch > NEAR_END_DROP_PX).any(): x = int(np.argmax(notch > NEAR_END_DROP_PX)); raise ValueError(f'near plane: the body ends {int(notch[x])} px short of its neighbours in column {x} (row {int(end[x])}), a notch over {NEAR_END_DROP_PX} px')
def check_budget(frame_bytes, plane_w, plane_h):
"""Refuse a bake the runtime could not hold: any two adjacent frames (night with dawn too) above PAIR_BYTES_MAX, or the planes of a frame pair decoding above DECODE_BYTES_MAX."""

View file

@ -305,6 +305,17 @@ def face_field(hd, hh, ang, lo, pd, ph, vd, vh):
b_ = np.maximum(2 * COLW * Dp, 1.0); la = np.where(np.abs(a_) > 3 * b_, 0.0, np.clip((c_ - a_ * sl) / b_, -1.5, 1.5)) # neighbours at very different distances are an occlusion edge, not a surface: no tilt
return Z.astype(np.float32), Dp, blurw(sl, 2.0).astype(np.float32), blurw(la, 2.0).astype(np.float32), f
NEAR_FOOT_MARGIN_PX = 48
def slide_max(a, m):
"""A max filter of half-width m along the last axis; the ends repeat their edge value."""
pad = np.pad(a, [(0, 0)] * (a.ndim - 1) + [(m, m)], mode='edge')
return np.lib.stride_tricks.sliding_window_view(pad, 2 * m + 1, axis=-1).max(-1)
def near_foot(foot, ang):
"""The nearest layer's foot (px): at least reaching the horizon (the body stays opaque to it, the fade starting at FADE_AT of the foot), and the widest foot within NEAR_FOOT_MARGIN_PX eased, so a jump in the valley under the layer (where the winning chain changes) does not dissolve the body early over a few columns (Vienna x 1252-1280, 55 px)."""
foot = np.maximum(foot, np.clip(ang * PXDEG_V, 0, None) / FADE_AT)
return np.maximum(blurw(slide_max(foot, NEAR_FOOT_MARGIN_PX), NEAR_FOOT_MARGIN_PX / 2.0), foot)
def bake_layer(S, rank, far, near=False):
b = S['slot']; base = RAMP[b]; reg = int(round((rank - 2) * 1.5)); R_ = lambda v: np.roll(v, reg, axis=-1); px = 1.0 / PXDEG_V
s_ref = P.get('s_ref_deg', 8.0)
@ -316,7 +327,7 @@ def bake_layer(S, rank, far, near=False):
m = np.clip(toppx / 1.6 + 0.5, 0, 1) * np.clip(blurw((wt > 0).astype(float), 1.0) * 1.5, 0, 1)[None, :] # a layer is drawn only where a chain exists (or tapers)
rise_px = np.clip((ang - blurw(lo, 12.0)) * PXDEG_V, 1, None) # foot length from a smoothed valley: no per-column curtains
foot = np.clip(0.85 * rise_px, 28 * np.clip(wt, 0, 1), 210).clip(1) # a tapering end carries no 28 px curtain: the body shrinks with the chain's weight, so a chain end leaves no stub
if near: foot = np.maximum(foot, np.clip(ang * PXDEG_V, 0, None) / FADE_AT) # the nearest layer is the ground in front of the eye: its body stays opaque down to the horizon, whatever the strip's own valley says; it dissolves only below that (above the horizon a dissolved body shows the sky under a crest, and the valley angle jumps where the winning chain changes, so the sky showed as a wedge with a hard edge)
if near: foot = near_foot(foot, ang) # the nearest layer is the ground in front of the eye: its body stays opaque down to the horizon, whatever the strip's own valley says; it dissolves only below that (above the horizon a dissolved body shows the sky under a crest, and the valley angle jumps where the winning chain changes, so the sky showed as a wedge with a hard edge)
depthpx = np.clip(toppx / foot[None], 0, 1)
fade = np.clip((depthpx - FADE_AT) / (1 - FADE_AT), 0, 1); fade = fade * fade * (3 - 2 * fade); alpha = (m * (1 - fade)).astype(np.float32) # the body dissolves at its foot: what is behind (other layers, floor, sky) shows, so a column boundary leaves no wall down the frame
w = (depthpx ** 0.8 * 0.92).astype(np.float32) # weight of the foot colour (floor/haze mix, decided at relight)

View file

@ -79,7 +79,7 @@ M = {
'knock-out has a hard edge (no easing)': ('ridge.py', 'return np.clip(blurw(np.lib.stride_tricks.sliding_window_view(pad, 2 * m + 1, axis=1).max(-1), m / 2.0)[:, m:-m], 0, 1)', 'return np.clip(np.lib.stride_tricks.sliding_window_view(pad, 2 * m + 1, axis=1).max(-1)[:, m:-m], 0, 1)'),
'knock-out margin of one column': ('ridge.py', 'OCCLUDE_MARGIN_PX = 48 ', 'OCCLUDE_MARGIN_PX = 1 '),
'knock-out hides the nearer plane from the farther one, not the reverse': ('ridge.py', 'nearer = names[i + 1:]; left', 'nearer = names[:i]; left'),
'near foot floor removed: the near body dissolves above the horizon': ('ridge.py', 'if near: foot = np.maximum(foot,', 'if False: foot = np.maximum(foot,'),
'near foot floor removed: the near body dissolves above the horizon': ('ridge.py', 'foot = np.maximum(foot, np.clip(ang * PXDEG_V', 'foot = np.maximum(foot * 0, np.clip(ang * PXDEG_V * 0'),
'near foot floor starts the fade at the foot, not at the horizon': ('ridge.py', 'np.clip(ang * PXDEG_V, 0, None) / FADE_AT)', 'np.clip(ang * PXDEG_V, 0, None) / 1.0)'),
'near flag passed to every layer': ('ridge.py', 'near=rank == len(slots) - 1)', 'near=True)'),
'near flag passed to no layer': ('ridge.py', 'near=rank == len(slots) - 1)', 'near=False)'),
@ -88,6 +88,12 @@ M = {
'near cover checked on the mid plane': ('export.py', "check_near_cover(dec[k][-1], view['horizon_row'])", "check_near_cover(dec[k][1], view['horizon_row'])"),
'near cover checked on noon only': ('export.py', "for k in KEYS: check_near_cover(", "for k in ('noon',): check_near_cover("),
'near cover hole threshold of zero': ('export.py', 'NEAR_HOLE_ALPHA = 24 ', 'NEAR_HOLE_ALPHA = 0 '),
'near foot step not eased (the widest foot in the margin dropped)': ('ridge.py', 'return np.maximum(blurw(slide_max(foot, NEAR_FOOT_MARGIN_PX), NEAR_FOOT_MARGIN_PX / 2.0), foot)', 'return foot'),
'near foot widest-in-margin without the easing': ('ridge.py', 'blurw(slide_max(foot, NEAR_FOOT_MARGIN_PX), NEAR_FOOT_MARGIN_PX / 2.0)', 'slide_max(foot, NEAR_FOOT_MARGIN_PX)'),
'near foot margin of one column': ('ridge.py', 'NEAR_FOOT_MARGIN_PX = 48', 'NEAR_FOOT_MARGIN_PX = 1'),
'near cover allows any notch in where the body ends': ('export.py', 'NEAR_END_DROP_PX = 40 ', 'NEAR_END_DROP_PX = 600 '),
'near cover looks at no neighbour (window of zero)': ('export.py', 'NEAR_END_WINDOW = 8', 'NEAR_END_WINDOW = 0'),
'near cover measures the body end at alpha above any pixel': ('export.py', 'NEAR_BODY_ALPHA = 40 ', 'NEAR_BODY_ALPHA = 256 '),
'near cover looks below the horizon too': ('export.py', '& (rows < int(horizon_row))', '& (rows < h)'),
'near cover crest threshold above any alpha': ('export.py', 'NEAR_CREST_ALPHA = 64 ', 'NEAR_CREST_ALPHA = 256 '),
'near cover lets a transparent column through': ('export.py', 'if none.any(): raise ValueError', 'if False: raise ValueError'),

View file

@ -453,6 +453,18 @@ def test_near_plane_must_cover_every_column_and_leave_no_hole_under_its_crest():
except ValueError as e: assert why in str(e), (why, str(e))
else: assert False, ('a near plane with a ' + why + ' was accepted')
export.check_near_cover(ok, 30.0)
def test_near_foot_reaches_the_horizon_and_a_step_in_it_is_eased_not_cut():
"""The nearest layer's foot is at least the horizon distance over FADE_AT, and the widest foot within NEAR_FOOT_MARGIN_PX wins, eased: a 210 px foot beside a 100 px one (the valley jumping where the winning chain changes) leaves no column with a short foot within the margin of the long one, and no step over a few px per column; check_near_cover refuses a body that ends early over a few columns."""
ang = np.full(400, 3.0); foot = np.full(400, 210.0); foot[300:] = 100.0
f = ridge.near_foot(foot, ang)
assert (f >= np.maximum(foot, 3.0 * ridge.PXDEG_V / ridge.FADE_AT) - 1e-6).all() and (f[300:300 + ridge.NEAR_FOOT_MARGIN_PX // 2] > 190).all(), (f[300], f[330])
assert np.abs(np.diff(f)).max() < 8.0, np.abs(np.diff(f)).max()
assert ridge.near_foot(np.full(400, 1.0), np.full(400, 5.0)).min() >= 5.0 * ridge.PXDEG_V / ridge.FADE_AT - 1e-6
ok = np.zeros((60, 40, 4), np.uint8); ok[10:, :, 3] = 200; export.check_near_cover(ok, 30.0)
early = ok.copy(); early[15:, 30:, 3] = 0
try: export.check_near_cover(early, 12.0)
except ValueError as e: assert 'notch' in str(e), str(e)
else: assert False, 'a near plane whose body ends early in a few columns was accepted'
def test_write_bake_refuses_a_near_plane_with_a_wedge_and_lets_the_other_planes_have_empty_columns():
"""The refusal is at the writer, on the decoded near plane of every frame; the far and mid planes may have transparent columns (a place with no ridge at that distance in part of the window)."""
d = tempfile.mkdtemp()

View file

@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createRidgeScene } from './Ridge';
import { createRidgeScene, SCRIM_ALPHA, scrimBackground, scrimStops } from './Ridge';
import { valueNoise, hash2 } from './noise';
import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe';
import type { SkyColours } from './skyColour';
@ -140,11 +140,17 @@ const draws: string[] = [];
const images: unknown[][] = [];
/** Every RGBA grid the host canvas was painted from (the small canvas's putImageData). */
const painted: Uint8ClampedArray[] = [];
/** Every fillRect whose fill was a linear gradient: its stops, and how many images had been drawn before it (paint order). */
const fills: { stops: [number, string][]; imagesBefore: number }[] = [];
function ctx() {
const c: any = {
createLinearGradient: () => ({ addColorStop: vi.fn() }),
createLinearGradient: () => {
const stops: [number, string][] = [];
return { stops, addColorStop: (o: number, col: string) => stops.push([o, col]) };
},
fillRect() {
draws.push('sky');
if (c.fillGradient?.stops) fills.push({ stops: c.fillGradient.stops, imagesBefore: images.length });
},
save() {},
restore() {},
@ -182,7 +188,9 @@ function ctx() {
},
globalAlpha: 1,
globalCompositeOperation: 'source-over',
set fillStyle(_v: unknown) {},
set fillStyle(v: any) {
c.fillGradient = v;
},
};
return c;
}
@ -197,6 +205,7 @@ beforeEach(() => {
draws.length = 0;
images.length = 0;
painted.length = 0;
fills.length = 0;
search = '';
motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() };
doc = Object.assign(new EventTarget(), {
@ -387,7 +396,7 @@ describe('the starfield in the scene', () => {
expect(count('star')).toBe(N);
expect(count('sky')).toBe(1);
expect(parent.children[1].anims).toHaveLength(0); // the overlay, above the sky
expect(parent.children).toHaveLength(2);
expect(parent.children).toHaveLength(3); // canvas, overlay, scrim
const before = baked();
runFrames(16.7, 300); // 5 s at 60 fps; the overlay repaints at 20 fps
expect(baked()).toBe(before);
@ -413,7 +422,7 @@ describe('the starfield in the scene', () => {
const { parent, canvas } = host();
createRidgeScene({ canvas, tier: 'still', sky: night });
expect(count('star')).toBe(N);
expect(parent.children).toEqual([canvas]);
expect(parent.children).toEqual([canvas]); // the scrim is in the canvas
expect(rafQueue).toHaveLength(0);
});
@ -467,7 +476,7 @@ describe('the starfield in the scene', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: night })!;
runFrames(100, 100);
expect(parent.children).toEqual([canvas]);
expect(parent.children).toEqual([canvas]); // the scrim moves into the canvas
expect(count('star')).toBe(N);
expect(rafQueue).toHaveLength(0);
s.dispose();
@ -554,12 +563,13 @@ describe('the ridge planes in the scene', () => {
const rigOf = (parent: any) =>
parent.children.find((c: any) => c.children.some((g: any) => g.anims.length));
it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position', () => {
it('stacks twinkle canvas, scrim, rig, rain in that order, with no z-index and no fixed position', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: NOON })!;
const kinds = parent.children.map((c: any) => c.tag);
expect(kinds).toEqual(['canvas', 'canvas', 'div', 'div', 'div']);
expect(parent.children[2].children).toHaveLength(3);
expect(kinds).toEqual(['canvas', 'canvas', 'div', 'div', 'div', 'div']);
expect(parent.children[2].style.background).toBe(scrimBackground(night, true));
expect(parent.children[3].children).toHaveLength(3); // the rig is above the scrim: planes are never dimmed by it
parent.children.forEach((c: any) => {
expect(c.style.zIndex).toBeUndefined();
expect(c.style.position).not.toBe('fixed');
@ -568,6 +578,60 @@ describe('the ridge planes in the scene', () => {
expect(parent.children).toEqual([canvas]);
});
it("the scrim never takes a tap or a row's size, and is flat and heavier when the planes are missing", () => {
const withPlanes = host();
createRidgeScene({ canvas: withPlanes.canvas, tier: 'full', sky: night, backdrop: NOON });
const flat = host();
createRidgeScene({ canvas: flat.canvas, tier: 'full', sky: night });
const scrimOf = (p: any) => p.parent.children.find((c: any) => c.style.background);
[scrimOf(withPlanes), scrimOf(flat)].forEach((s: any) => {
expect(s.style.pointerEvents).toBe('none');
expect(s.style.position).toBe('absolute');
});
expect(scrimOf(withPlanes).style.background).toContain('0)'); // fades to nothing toward the ridge
expect(scrimOf(flat).style.background).toBe(scrimBackground(night, false));
expect(scrimOf(flat).style.background).not.toContain(', rgba(96,150,220,0)');
expect(scrimOf(flat).style.background).toContain(String(SCRIM_ALPHA.flat));
expect(SCRIM_ALPHA.flat).toBeGreaterThan(SCRIM_ALPHA.planes);
});
it('the settled still paints the scrim into the canvas under the planes, once: gradient with planes, flat without', () => {
for (const [backdrop, hasPlanes] of [
[NOON, true],
[undefined, false],
] as const) {
fills.length = 0;
images.length = 0;
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'still', sky: night, backdrop })!;
expect(parent.children).toEqual([canvas]); // nothing over the canvas dims the planes
const scrims = fills.filter(
(f) => JSON.stringify(f.stops) === JSON.stringify(scrimStops(night, hasPlanes))
);
expect(scrims).toHaveLength(1);
const planeImages = images.filter((a) =>
hasPlanes ? Object.values(NOON.a).includes(a[0] as HTMLImageElement) : false
);
expect(planeImages).toHaveLength(hasPlanes ? 3 : 0);
if (hasPlanes) expect(scrims[0].imagesBefore).toBe(images.indexOf(planeImages[0])); // the scrim, then the planes
s.dispose();
}
});
it('the DOM scrim and the still scrim are one gradient', () => {
for (const hasPlanes of [true, false]) {
const css = scrimBackground(night, hasPlanes);
scrimStops(night, hasPlanes).forEach(([, c]) => expect(css).toContain(c));
}
expect(scrimBackground(night, true)).toContain(' 55%, ');
});
it('a day sky has no scrim', () => {
const { parent, canvas } = host();
createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON });
expect(parent.children.some((c: any) => c.style.background)).toBe(false);
});
it('is three groups, far to near, each placed by windowFor and drifting by its depth of driftPx', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!;

View file

@ -5,7 +5,14 @@ import { skyColours, SkyColours, Srgb } from './skyColour';
import { paintSky as paintPhysicalSky } from './physicalSky';
import { windowFor } from './view';
import { crossfade } from './frameChoice';
import { activeAt, drawStars, drawTwinkle as paintTwinkle, makeStars, Star } from './stars';
import {
activeAt,
drawStars,
drawTwinkle as paintTwinkle,
isNight,
makeStars,
Star,
} from './stars';
import { drawRainTile, RAIN_TILES } from './rain';
import type { Backdrop, Planes } from './Backdrop';
import { PLANE_NAMES } from './manifest';
@ -23,6 +30,31 @@ export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
backdrop?: Backdrop;
};
/** The fill behind nav, header and room-list rows: the sky's top colour over the stars, under the planes. With planes it fades out toward the ridge; without them (they failed to load, or none was given) it is flat and heavier, so rows stay legible over the sky alone. Never changes layout: it is one pointer-transparent layer. */
export const SCRIM_ALPHA = { planes: 0.35, flat: 0.55 } as const;
/** The scrim's gradient, top to bottom, as [offset 0..1, colour]: the one spelling the DOM layer (`scrimBackground`) and the still's canvas fill both read. */
export const scrimStops = (sky: SkyColours, hasPlanes: boolean): [number, string][] => {
const [r, g, b] = sky.top;
const a = hasPlanes ? SCRIM_ALPHA.planes : SCRIM_ALPHA.flat;
const stops: [number, number][] = hasPlanes
? [
[0, 1],
[0.55, 1],
[0.85, 0],
]
: [
[0, 1],
[1, 1],
];
return stops.map(([o, k]) => [o, `rgba(${r},${g},${b},${a * k})`]);
};
export const scrimBackground = (sky: SkyColours, hasPlanes: boolean): string => {
const s = scrimStops(sky, hasPlanes);
return hasPlanes
? `linear-gradient(to bottom, ${s.map(([o, c]) => `${c} ${Math.round(o * 100)}%`).join(', ')})`
: `linear-gradient(${s[0][1]}, ${s[1][1]})`;
};
const css = (c: Srgb): string => `rgb(${c[0]},${c[1]},${c[2]})`;
function context2d(c: HTMLCanvasElement): CanvasRenderingContext2D | null {
return c.getContext('2d');
@ -97,6 +129,8 @@ const clock = (): number => (typeof performance !== 'undefined' ? performance.no
interface Built {
/** The twinkling stars' own canvas, over the sky; absent in a day sky and in 'still'. */
twinkle?: HTMLCanvasElement;
/** The legibility fill, over the stars and under the planes. */
scrim?: HTMLElement;
/** The ridge planes' rig, over the twinkle canvas and under the rain; absent in 'still' (the planes are drawn into the host canvas). */
rig?: { el: HTMLElement; anims: (Animation | undefined)[] };
/** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */
@ -144,6 +178,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
const teardown = () => {
built?.twinkle?.remove();
built?.scrim?.remove();
built?.rig?.anims.forEach((a) => a?.cancel());
built?.rig?.el.remove();
built?.rain?.anims.forEach((a) => a?.cancel());
@ -311,6 +346,35 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
});
};
/** The legibility fill, appended over whatever the parent holds so far. Over a dark sky only: a light one is not the stars' problem, and a dark fill would hurt dark text. */
const makeScrim = (): HTMLElement | undefined => {
if (!isNight(sky)) return undefined;
const scrim = document.createElement('div');
scrim.setAttribute('aria-hidden', 'true');
Object.assign(scrim.style, {
position: 'absolute',
left: '0',
top: '0',
width: '100%',
height: '100%',
pointerEvents: 'none',
background: scrimBackground(sky, !!opts.backdrop),
});
parent.appendChild(scrim);
return scrim;
};
/** The still's scrim, painted into the host canvas over the sky and stars and under the planes: the rig's order, in one image. */
const paintScrim = (hasPlanes: boolean) => {
if (!isNight(sky)) return;
const ctx = context2d(canvas);
if (!ctx) return;
const g = ctx.createLinearGradient(0, 0, 0, canvas.height);
scrimStops(sky, hasPlanes).forEach(([o, c]) => g.addColorStop(o, c));
ctx.fillStyle = g;
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
/** Paint the sky, the stars and the rain. Returns false when a 2D context is missing or there is no area yet. */
const build = (): boolean => {
teardown();
@ -341,8 +405,9 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
});
parent.appendChild(twinkle);
}
const scrim = makeScrim();
field = stars;
built = { twinkle };
built = { twinkle, scrim };
if (opts.backdrop && !still) built.rig = startRig(opts.backdrop, w, h);
if (tier !== 'still' && sky.physical && sky.physical.weather.rain > 0)
built.rain = startRain(sky.physical.weather.rain, sky.horizon, w, h, scale);
@ -397,6 +462,8 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
teardown();
cancelAnimationFrame(raf);
raf = 0;
// One order in every path: sky and stars, then the scrim, then the planes (the rig sits above the DOM scrim the same way).
paintScrim(!!opts.backdrop);
if (opts.backdrop) paintPlanes(opts.backdrop);
report(true);
};

View file

@ -15,6 +15,8 @@ import {
slotPeriod,
starCount,
twinkleGain,
STAR_BAND,
STAR_MAX_ALPHA,
} from './stars';
const DAY = {
@ -69,7 +71,8 @@ describe('star placement', () => {
it('fades with the sky: every star sits where the sky is dark, alpha within bounds', () => {
for (const s of makeStars(NIGHT, 390, 844)) {
expect(skyLuma(NIGHT, s.y)).toBeLessThan(NIGHT_LUMA);
expect(s.alpha).toBeLessThanOrEqual(0.9);
expect(s.alpha).toBeLessThanOrEqual(STAR_MAX_ALPHA);
expect(s.y).toBeLessThanOrEqual(STAR_BAND);
expect(s.alpha).toBeGreaterThanOrEqual(0.05);
}
});

View file

@ -17,6 +17,9 @@ export const NIGHT_LUMA = 110;
/** The sky gradient runs from the top (0) through mid (0.5) to the horizon glow (0.78 and below). */
export const SKY_STOPS = { mid: 0.5, horizon: 0.78 };
export const MAX_STARS = 400;
/** Stars live in the top of the sky only (a share of its height) and never brighter than this base alpha, so they stay quiet behind nav and header glyphs (ruling void-legibility-constraints). */
export const STAR_BAND = 0.6;
export const STAR_MAX_ALPHA = 0.6;
/** Twinkling stars at any instant (fewer only if the field has fewer stars). */
export const SLOTS = 32;
export const TWINKLE_PERIOD = { min: 2, max: 7 } as const;
@ -30,7 +33,7 @@ export interface Star {
y: number;
/** Radius in CSS px. */
r: number;
/** Base alpha 0..0.9 (brightness times how dark the sky is there). */
/** Base alpha 0..STAR_MAX_ALPHA (brightness times how dark the sky is there). */
alpha: number;
/** CSS colour, white tinted blue or warm. */
fill: string;
@ -85,7 +88,7 @@ export const starCount = (cssW: number, cssH: number): number =>
/**
* Seeded placement. Each candidate draws all its random numbers whether it is kept or not, so a
* given seed and sky always give the same field and the prefix does not shift with the count.
* Heights are squeezed toward the zenith (y = 0.78 u^1.7) and alpha falls with the sky's luma, so
* Heights are squeezed toward the zenith (y = STAR_BAND u^1.7) and alpha falls with the sky's luma, so
* the stars thin out and fade into the horizon glow. None for a day sky.
*/
export function makeStars(sky: SkyColours, cssW: number, cssH: number): Star[] {
@ -95,13 +98,13 @@ export function makeStars(sky: SkyColours, cssW: number, cssH: number): Star[] {
// Every candidate draws all its numbers, kept or not, so the prefix is stable.
const candidates = Array.from({ length: MAX_STARS }, () => ({
x: rnd(),
y: SKY_STOPS.horizon * rnd() ** 1.7,
y: STAR_BAND * rnd() ** 1.7,
r: 0.35 + 1.0 * rnd() ** 4,
bright: 0.35 + 0.65 * rnd() ** 1.5,
tint: rnd(),
})).slice(0, n);
return candidates.flatMap(({ x, y, r, bright, tint }) => {
const alpha = Math.min(0.9, bright * Math.max(0, 1 - skyLuma(sky, y) / NIGHT_LUMA));
const alpha = Math.min(STAR_MAX_ALPHA, bright * Math.max(0, 1 - skyLuma(sky, y) / NIGHT_LUMA));
if (alpha < 0.05) return [];
// White, pulled toward blue or toward warm by the tint draw.
const to: Srgb = tint < 0.5 ? [165, 195, 255] : [255, 222, 185];