zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
(() => {
if (matchMedia('(forced-colors: active)').matches || (navigator.connection && navigator.connection.saveData)) return;
const KEY = 'zds.garden', MAX_AGE = 36e5;
const probe = document.createElement('div');
probe.style.cssText = 'position:fixed;top:0;height:100vh;height:100lvh;width:0;visibility:hidden;pointer-events:none';
document.documentElement.append(probe);
const sceneHeight = () => probe.offsetHeight;
const sceneSize = (width, height) => width + 'x' + height;
const fresh = at => Date.now() - at < MAX_AGE;
const start = () => (function () {
const root = document.documentElement;
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)');
// CC0 textures from OpenGameArt, served by zds (src/internal/web/textures.zig) and cached.
const TEX = n => '/web/texture?name=' + n;
const TEXTURES = { grass: TEX('grass'), grass2: TEX('grass2'), sand: TEX('sand'), bark: TEX('bark'), dirt: TEX('dirt') };
// =====================================================================
// Renderer (WebGL2)
// Top-down orthographic garden. Every solid object is an ellipsoid in a
// float data texture, grouped under bounding spheres. Per frame:
// 1. water - heightfield simulation, ping-pong RGBA16F
// 2. caustics - grid mesh refracted toward the pond floor (Wallace)
// 3. scene - terrain, sheets, objects, water; ray-traced reflection
// and refraction, analytic AO, area-light soft shadows,
// terrain self-shadowing, cloud shadows, mist, grading
// A 2D canvas above adds pollen by day and fireflies by night.
// =====================================================================
const PAGE_SEL = '.card,.hero,.pulse,.grid>section';
const form = document.querySelector(PAGE_SEL);
if (!form) return;
// The scene is as tall as the screen gets (lvh), so a phone's address bar coming and going changes nothing.
let LVH = sceneHeight(), LVW = innerWidth;
const canvas = document.createElement('canvas'); canvas.id = 'garden-scene'; canvas.setAttribute('aria-hidden', 'true');
const gl = canvas.getContext('webgl2', { antialias: false, alpha: false });
if (!gl) return;
let hasSim = !!gl.getExtension('EXT_color_buffer_float');
const MAXN = 8, MAXP = 6, MAXG = 96, MAXI = 96, MAXPR = 900, TEXW = 256;
const PBASE = 2 * MAXG;
const TILE = 96, MAXTILES = 400, TSLOTS = 8; // 8 texels = 32 slots per tile
const TBASE = PBASE + 3 * MAXPR;
const TEXH = Math.ceil((TBASE + MAXTILES * TSLOTS) / TEXW);
const POND_GLSL = `
uniform vec4 u_pond[${MAXP}];
uniform int u_np;
uniform float u_pk;
float smin(float a, float b, float k){ float h = clamp(0.5 + 0.5*(b-a)/k, 0.0, 1.0); return mix(b, a, h) - k*h*(1.0-h); }
float sdPond(vec2 p){
float d = 1e5;
for (int i = 0; i < ${MAXP}; i++) { if (i >= u_np) break; d = smin(d, length(p - u_pond[i].xy) - u_pond[i].z, u_pk); }
return d;
}
float pondMask(float sd, float dpr){ return 1.0 - smoothstep(-6.0*dpr, 0.0, sd); }
float pondDepth(float sd, float dpr){ return pondMask(sd, dpr) * (5.0 + 34.0 * smoothstep(0.0, 46.0*dpr, -sd)) * dpr; }
`;
const AIR_VERT = `#version 300 es
in vec2 a_pos; in vec4 a_sz; in vec4 a_col;
uniform vec2 u_res; uniform float u_dpr; uniform vec4 u_cam;
out vec4 v_c; out float v_soft;
void main(){
vec2 d = (a_pos * u_dpr - u_cam.xy) * u_cam.w;
float c = cos(u_cam.z), s = sin(u_cam.z);
vec2 sp = vec2(c * d.x + s * d.y, -s * d.x + c * d.y) + u_res * 0.5;
gl_Position = vec4(sp.x / u_res.x * 2.0 - 1.0, 1.0 - sp.y / u_res.y * 2.0, 0.0, 1.0);
gl_PointSize = max(1.0, a_sz.x * 2.0 * u_dpr * u_cam.w);
v_c = vec4(a_col.rgb, a_sz.y); v_soft = a_sz.z;
}`;
const AIR_FRAG = `#version 300 es
precision mediump float;
in vec4 v_c; in float v_soft;
out vec4 o;
void main(){
float d = length(gl_PointCoord * 2.0 - 1.0);
if (d > 1.0) discard;
// fireflies: a bright core in a wide soft halo; pollen: a small soft-edged disc
float a = v_soft > 0.5 ? 0.9 * (1.0 - smoothstep(0.0, 0.35, d)) + 0.35 * (1.0 - smoothstep(0.35, 1.0, d)) : 1.0 - smoothstep(0.6, 1.0, d);
o = vec4(mix(v_c.rgb, v_c.rgb * vec3(0.84, 0.92, 0.64), v_soft * smoothstep(0.0, 0.5, d)), v_c.a * a);
}`;
const QUAD_VERT = `attribute vec2 a; void main(){ gl_Position = vec4(a, 0.0, 1.0); }`;
const SIM_FRAG = `
precision highp float;
uniform sampler2D u_prev; uniform vec2 u_texel; uniform vec2 u_res; uniform float u_dpr;
${POND_GLSL}
void main(){
vec2 uv = gl_FragCoord.xy * u_texel;
vec4 info = texture2D(u_prev, uv);
vec2 px = vec2(uv.x * u_res.x, (1.0 - uv.y) * u_res.y);
float mask = pondMask(sdPond(px), u_dpr);
vec2 dx = vec2(u_texel.x, 0.0), dy = vec2(0.0, u_texel.y);
float avg = (texture2D(u_prev, uv - dx).r + texture2D(u_prev, uv + dx).r + texture2D(u_prev, uv - dy).r + texture2D(u_prev, uv + dy).r) * 0.25;
info.g += (avg - info.r) * 1.1;
info.g *= 0.985;
info.r += info.g;
info.r *= mask; info.g *= mask;
gl_FragColor = vec4(info.r, info.g, mask, 1.0);
}`;
const DROP_FRAG = `
precision highp float;
uniform sampler2D u_prev; uniform vec2 u_texel; uniform vec2 u_res;
uniform vec2 u_center; uniform float u_radius; uniform float u_strength;
void main(){
vec2 uv = gl_FragCoord.xy * u_texel;
vec4 info = texture2D(u_prev, uv);
vec2 px = vec2(uv.x * u_res.x, (1.0 - uv.y) * u_res.y);
float drop = max(0.0, 1.0 - length(px - u_center) / u_radius);
drop = 0.5 - cos(drop * 3.14159265) * 0.5;
info.r += drop * u_strength * info.b;
gl_FragColor = info;
}`;
const CAU_VERT = `#version 300 es
precision highp float;
in vec2 a_uv;
uniform sampler2D u_sim; uniform vec2 u_texel; uniform vec2 u_res; uniform float u_dpr;
uniform vec3 u_light; uniform float u_hAmp;
${POND_GLSL}
out vec3 v_old; out vec3 v_new; out float v_in;
void main(){
vec4 info = texture(u_sim, a_uv);
vec2 p = vec2(a_uv.x * u_res.x, (1.0 - a_uv.y) * u_res.y);
float h = info.r * u_hAmp;
float sx = u_texel.x * u_res.x, sy = u_texel.y * u_res.y;
float hx = (texture(u_sim, a_uv + vec2(u_texel.x, 0.0)).r - texture(u_sim, a_uv - vec2(u_texel.x, 0.0)).r) * u_hAmp / (2.0 * sx);
float hy = (texture(u_sim, a_uv + vec2(0.0, u_texel.y)).r - texture(u_sim, a_uv - vec2(0.0, u_texel.y)).r) * u_hAmp / (2.0 * sy);
vec3 n = normalize(vec3(-hx, hy, 1.0));
vec3 dir = normalize(vec3(p, h) - u_light);
vec3 rf = refract(dir, n, 1.0 / 1.333);
float zf = -pondDepth(sdPond(p), u_dpr);
float t = (zf - h) / min(rf.z, -0.05);
vec2 q = p + rf.xy * t;
v_old = vec3(p, 0.0); v_new = vec3(q, 0.0); v_in = info.b;
vec2 clip = vec2(q.x / u_res.x, 1.0 - q.y / u_res.y) * 2.0 - 1.0;
gl_Position = vec4(clip, 0.0, 1.0);
}`;
const CAU_FRAG = `#version 300 es
precision highp float;
in vec3 v_old; in vec3 v_new; in float v_in;
out vec4 o;
void main(){
if (v_in < 0.5) discard;
float oldA = length(dFdx(v_old)) * length(dFdy(v_old));
float newA = length(dFdx(v_new)) * length(dFdy(v_new));
o = vec4(oldA / max(newA, 1e-5) * 0.2, 0.0, 0.0, 1.0);
}`;
const SCENE_VERT = `#version 300 es
in vec2 a; void main(){ gl_Position = vec4(a, 0.0, 1.0); }`;
const sceneFrag = mode => `#version 300 es
#define MODE ${mode}
precision highp float;
precision highp int;
precision highp sampler2D;
#define N ${MAXN}
#define MAXG ${MAXG}
#define MAXI ${MAXI}
#define PBASE ${PBASE}
#define TBASE ${TBASE}
uniform vec2 u_res;
uniform float u_tile; uniform int u_tilesX;
uniform float u_dpr;
uniform float u_time;
uniform vec3 u_light;
uniform float u_lr;
uniform sampler2D u_prims; uniform int u_ng;
uniform vec3 u_ground; uniform vec3 u_ground2;
uniform float u_dark;
uniform sampler2D u_sim; uniform sampler2D u_caust; uniform vec2 u_texel; uniform float u_hAmp; uniform float u_hasSim;
uniform sampler2D u_tGrass; uniform sampler2D u_tGrass2; uniform sampler2D u_tSand; uniform sampler2D u_tDirt; uniform sampler2D u_tBark;
uniform sampler2D u_decal;
uniform vec4 u_cam; // focus.xy (device px), heading, zoom
uniform int u_ng0; // first moving group: everything before it is baked
#define MAXD 24
uniform vec4 u_dyn[MAXD]; uniform int u_nd; // the moving groups' bounds
uniform sampler2D u_atmo, u_soft;
uniform vec4 u_fox, u_fox2; // fox: xy, heading, size; gait cycle, tail wag, height, stride
uniform sampler2D u_b0, u_b1, u_b2, u_b3; uniform float u_sway;
${POND_GLSL}
#if MODE == 1
layout(location = 0) out vec4 o0;
layout(location = 1) out vec4 o1;
layout(location = 2) out vec4 o2;
layout(location = 3) out vec4 o3;
#else
out vec4 fragColor;
#endif
vec4 fetchT(int i){ return texelFetch(u_prims, ivec2(i & 255, i >> 8), 0); }
int g_tile = 0; int g_tcount = 0;
float tileSlot(int k){ vec4 v = fetchT(TBASE + g_tile * 8 + (k >> 2)); int c = k & 3; return c == 0 ? v.x : c == 1 ? v.y : c == 2 ? v.z : v.w; }
void setTile(vec2 p){ g_tile = int(clamp(p.x / u_tile, 0.0, 1e4)) + int(clamp(p.y / u_tile, 0.0, 1e4)) * u_tilesX; g_tcount = int(tileSlot(0)); }
mat2 rot(float a){ float c = cos(a), s = sin(a); return mat2(c, s, -s, c); }
float sdBox(vec2 p, vec2 b, float r){
vec2 q = abs(p) - b + r;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
}
float hash(vec2 p){
vec3 p3 = fract(vec3(p.xyx) * 0.1031);
p3 += dot(p3, p3.yzx + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
float vnoise(vec2 p){
vec2 i = floor(p), f = fract(p); f = f*f*(3.0-2.0*f);
return mix(mix(hash(i), hash(i+vec2(1,0)), f.x), mix(hash(i+vec2(0,1)), hash(i+vec2(1,1)), f.x), f.y);
}
float fbm(vec2 p){ float v = 0.0, a = 0.5; for (int i = 0; i < 3; i++) { v += a*vnoise(p); p = p*2.1 + 5.7; a *= 0.5; } return v; }
float lum(vec3 c){ return dot(c, vec3(0.299, 0.587, 0.114)); }
vec2 uvOf(vec2 px){ return vec2(px.x / u_res.x, 1.0 - px.y / u_res.y); }
vec3 enc(vec3 c){ return sqrt(clamp(c * 0.5, 0.0, 1.0)); }
vec3 dec(vec3 e){ return e * e * 2.0; }
float encH(float h){ return clamp((h / u_dpr + 64.0) / 320.0, 0.0, 1.0); }
float decH(float e){ return (e * 320.0 - 64.0) * u_dpr; }
// Tiled texture with a second rotated layer to hide repetition.
vec3 tiled(sampler2D s, vec2 p, float tile){
vec2 q = p / tile;
vec3 a = texture(s, q).rgb;
vec3 b = texture(s, rot(0.9) * q * 0.71 + vec2(0.31, 0.77)).rgb;
float m = smoothstep(0.3, 0.7, vnoise(p * 0.004 / u_dpr + 2.0));
return mix(a, b, m);
}
vec3 texBump(sampler2D s, vec2 p, float tile, float st){
vec2 q = p / tile;
float e = 1.2 * u_dpr / tile;
float l0 = lum(texture(s, q).rgb);
float lx = lum(texture(s, q + vec2(e, 0.0)).rgb);
float ly = lum(texture(s, q + vec2(0.0, e)).rgb);
return vec3(-(lx - l0) * st, -(ly - l0) * st, 0.0);
}
// Rolling ground: broad hills, mid bumps. Flattens under the form and
// slopes to zero at the ponds.
float terrainRaw(vec2 p){
vec2 q = p * (0.0021 / u_dpr);
float h = fbm(q) - 0.5;
h += 0.35 * (vnoise(q * 3.1 + 7.0) - 0.5);
h += 0.22 * (fbm(q * 4.0 + 13.0) - 0.5);
return h * 110.0 * u_dpr;
}
float terrain(vec2 p){
float flat_ = 1.0;
float wet = smoothstep(0.0, 70.0 * u_dpr, sdPond(p));
return terrainRaw(p) * flat_ * wet;
}
// Hills shading hills: march toward the light along the heightfield.
float terrainShadow(vec2 p, float hz){
vec3 ld = normalize(u_light - vec3(p, hz));
float lxy = max(length(ld.xy), 1e-3);
float occ = 0.0, s = 12.0 * u_dpr;
for (int i = 0; i < 4; i++) {
vec2 q = p + ld.xy / lxy * s;
float rz = hz + ld.z / lxy * s;
float tz = terrain(q);
occ = max(occ, (tz - rz) / (5.0 * u_dpr + s * 0.12));
s *= 2.1;
}
return 1.0 - 0.6 * clamp(occ, 0.0, 1.0);
}
// Overpassing clouds: two drifting noise fields warp a third, so the
// shadows change shape as they cross rather than sliding rigidly.
float clouds(vec2 p){
vec2 q = p * (0.0009 / u_dpr) + vec2(u_time * 0.018, u_time * 0.007);
vec2 w = vec2(fbm(q * 1.7 + u_time * 0.035), fbm(q * 1.7 + vec2(4.2, 1.3) - u_time * 0.028));
float c = fbm(q + (w - 0.5) * 0.9);
return 1.0 - 0.6 * smoothstep(0.50, 0.70, c);
}
float g_cloud = 1.0;
vec3 g_normal;
float g_ao;
vec3 lightCol(){ return mix(vec3(1.0, 0.96, 0.88), vec3(0.62, 0.72, 1.0), u_dark); }
vec3 ambientCol(){ return mix(vec3(0.50, 0.53, 0.57), vec3(0.16, 0.18, 0.27), u_dark); }
vec3 sky(vec3 d){
vec3 day = mix(vec3(0.74, 0.80, 0.86), vec3(0.42, 0.60, 0.86), clamp(d.z, 0.0, 1.0));
vec3 night = mix(vec3(0.10, 0.12, 0.18), vec3(0.03, 0.04, 0.08), clamp(d.z, 0.0, 1.0));
return mix(day, night, u_dark);
}
void rayEll(vec3 ro, vec3 rd, vec4 A, vec4 B, out float dd, out float tc, out float thit){
vec3 inv = 1.0 / vec3(A.w, B.x, B.y);
mat2 R = rot(-B.z);
vec3 lo = vec3(R * (ro.xy - A.xy), ro.z - A.z) * inv;
vec3 ld = vec3(R * rd.xy, rd.z) * inv;
float a = dot(ld, ld), b = dot(lo, ld), c = dot(lo, lo);
tc = -b / a;
dd = sqrt(max(c - b*b/a, 0.0));
float disc = b*b - a*(c - 1.0);
thit = disc < 0.0 ? -1.0 : (-b - sqrt(disc)) / a;
}
vec3 ellNormal(vec3 hp, vec4 A, vec4 B){
vec3 l = vec3(rot(-B.z) * (hp.xy - A.xy), hp.z - A.z);
vec3 nl = normalize(l / vec3(A.w*A.w, B.x*B.x, B.y*B.y));
return normalize(vec3(rot(B.z) * nl.xy, nl.z));
}
float shadeGroup(vec3 P, vec3 ld, float distL, int g){
vec4 rg = fetchT(2*g + 1);
int start = int(rg.x), cnt = int(rg.y);
float s = 1.0;
for (int i = 0; i < MAXI; i++) {
if (i >= cnt) break;
int pi = PBASE + 3 * (start + i);
vec4 A = fetchT(pi), B = fetchT(pi + 1);
float dd, tc, th;
rayEll(P, ld, A, B, dd, tc, th);
if (tc <= 1.0) continue;
float rm = (A.w + B.x + B.y) / 3.0;
float penW = u_lr * tc / max(distL - tc, 1.0);
float cover = clamp((rm / max(penW, 1e-3)) * (rm / max(penW, 1e-3)), 0.0, 1.0);
bool bird = B.w > 4.04 && B.w < 4.1;
float pen = (penW + 0.6 * u_dpr) / rm * (bird ? 2.4 : 1.0);
float dark = B.w > 4.5 ? 0.45 : bird ? 0.7 : 0.08;
float sh = mix(dark, 1.0, smoothstep(1.0 - pen, 1.0 + pen, dd));
s *= 1.0 - (1.0 - sh) * cover;
}
return s;
}
// Fraction of the area light visible from P. An occluder only blocks
// the share of the light disc it covers, so small high things (birds)
// throw faint wide shade and low broad things throw dark crisp shade.
float visibility(vec3 P){
vec3 L = u_light;
vec3 ld = normalize(L - P);
float distL = length(L - P);
float s = 1.0;
for (int k = 1; k < 32; k++) {
if (k > g_tcount) break;
int g = int(tileSlot(k));
vec4 bd = fetchT(2*g);
vec3 oc = bd.xyz - P;
float t = dot(oc, ld);
float inside = step(dot(oc, oc), bd.w * bd.w);
if (t <= 0.0 && inside < 0.5) continue;
float m = bd.w + u_lr * 3.0 + 4.0 * u_dpr;
if (dot(oc, oc) - t*t > m*m && inside < 0.5) continue;
s *= shadeGroup(P, ld, distL, g);
if (s < 0.02) break;
}
return s;
}
// Shade from the moving groups (critters), which are not in the tiles.
float dynVis(vec3 P){
vec3 ld = normalize(u_light - P);
float distL = length(u_light - P), s = 1.0;
for (int i = 0; i < MAXD; i++) {
if (i >= u_nd) break;
int g = u_ng0 + i;
vec4 bd = u_dyn[i];
vec3 oc = bd.xyz - P;
float t = dot(oc, ld);
if (t <= 0.0) continue;
float m = bd.w + u_lr * 3.0 + 4.0 * u_dpr;
if (dot(oc, oc) - t*t > m*m) continue;
s *= shadeGroup(P, ld, distL, g);
}
return s;
}
// Analytic ambient occlusion (Quilez sphere term), faded with distance
// so there is no cutoff ring.
float occlusion(vec3 P, vec3 n){
float ao = 1.0;
for (int k = 1; k < 32; k++) {
if (k > g_tcount) break;
int g = int(tileSlot(k));
vec4 bd = fetchT(2*g);
vec4 rg = fetchT(2*g + 1);
vec3 dg = bd.xyz - P;
float reach = bd.w + 5.0 * rg.z;
if (dot(dg, dg) > reach * reach) continue;
int start = int(rg.x), cnt = int(rg.y);
for (int i = 0; i < MAXI; i++) {
if (i >= cnt) break;
int pi = PBASE + 3 * (start + i);
vec4 A = fetchT(pi), B = fetchT(pi + 1);
if (B.w > 4.5) continue;
float r = (A.w + B.x + B.y) / 3.0;
vec3 di = A.xyz - P;
float l = length(di);
if (l > r * 5.0 || l < 1e-3) continue;
float nl = dot(n, di / l);
float h = l / r, h2 = h*h;
float k2 = 1.0 - h2*nl*nl;
float res = max(0.0, nl) / h2;
if (k2 > 0.0) { res = clamp(0.5*(nl*h + 1.0)/h2, 0.0, 1.0); res = sqrt(res*res*res); }
ao *= 1.0 - res * 0.9 * smoothstep(5.0 * r, 3.0 * r, l);
}
}
return ao;
}
vec3 illuminate(vec3 P, vec3 n, vec3 base, float sheen, float vis, float ao){
vec3 toLight = u_light - P;
vec3 ld = normalize(toLight);
float atten = 1.0 / (1.0 + dot(toLight, toLight) * 0.35e-7 / (u_dpr * u_dpr));
float diff = max(dot(n, ld), 0.0) * mix(0.82, 1.1, u_dark);
float spec = pow(max(reflect(-ld, n).z, 0.0), 30.0) * sheen;
return base * ambientCol() * ao + lightCol() * (base * diff + spec) * (atten * vis);
}
vec3 lit(vec3 P, vec3 n, vec3 base, float sheen, float direct, float ao){
#if MODE == 1
g_normal = n; g_ao = ao;
return base;
#else
float vis = visibility(P) * direct * g_cloud;
#if MODE == 2
vis *= dynVis(P);
#endif
return illuminate(P, n, base, sheen, vis, ao);
#endif
}
vec3 unpackNormal(vec2 enc){
vec2 n = enc * 2.0 - 1.0;
return vec3(n, sqrt(max(0.0, 1.0 - dot(n, n))));
}
vec3 traceRay(vec3 ro, vec3 rd, float maxT, int mode, vec3 fallback, out float hitT){
float best = maxT; vec3 col = fallback; hitT = -1.0;
#if MODE == 2
int g0 = u_ng0;
#else
int g0 = 0;
#endif
for (int i = 0; i < MAXG; i++) {
int g = g0 + i;
if (g >= u_ng) break;
vec4 bd = fetchT(2*g);
vec3 oc = bd.xyz - ro;
float t = dot(oc, rd);
float inside = step(dot(oc, oc), bd.w * bd.w);
if (t <= 0.0 && inside < 0.5) continue;
if (dot(oc, oc) - t*t > bd.w * bd.w && inside < 0.5) continue;
vec4 rg = fetchT(2*g + 1);
int start = int(rg.x), cnt = int(rg.y);
for (int i = 0; i < MAXI; i++) {
if (i >= cnt) break;
int pi = PBASE + 3 * (start + i);
vec4 A = fetchT(pi), B = fetchT(pi + 1);
bool fish = B.w > 4.5;
if ((mode == 0 && fish) || (mode == 1 && !fish)) continue;
float dd, tc, th;
rayEll(ro, rd, A, B, dd, tc, th);
if (th < 1.0 || th > best) continue;
best = th; hitT = th;
vec3 hp = ro + rd * th;
vec3 n = ellNormal(hp, A, B);
vec3 ld = normalize(u_light - hp);
float diff = max(dot(n, ld), 0.0);
vec4 C = fetchT(pi + 2);
col = C.rgb * (ambientCol() + lightCol() * diff * 0.9);
}
}
return col;
}
// Light focused by the surface, as a moving pattern, so the floor shows caustics even in still water.
float caustic(vec2 p){
p *= 0.07 / u_dpr;
float w = 1.0;
for (int k = 0; k < 2; k++) {
float sc = k == 0 ? 1.0 : 1.37;
vec2 q = p * sc + vec2(0.11, -0.07) * u_time * (k == 0 ? 1.0 : -1.3), i = floor(q), f = fract(q);
float d1 = 8.0, d2 = 8.0;
for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) {
vec2 o = vec2(x, y), h = 0.5 + 0.4 * sin(u_time * 0.6 + 6.283 * vec2(hash(i + o), hash(i + o + 17.3)));
float d = length(o + h - f);
if (d < d1) { d2 = d1; d1 = d; } else if (d < d2) d2 = d;
}
w = min(w, d2 - d1);
}
return 1.0 + 0.55 * (1.0 - smoothstep(0.0, 0.08, w));
}
vec3 pondFloor(vec2 q, float zf, float caus){
vec3 Pf = vec3(q, zf);
float e = 1.5 * u_dpr;
float dzx = (-pondDepth(sdPond(q + vec2(e, 0.0)), u_dpr) + pondDepth(sdPond(q - vec2(e, 0.0)), u_dpr)) / (2.0 * e);
float dzy = (-pondDepth(sdPond(q + vec2(0.0, e)), u_dpr) + pondDepth(sdPond(q - vec2(0.0, e)), u_dpr)) / (2.0 * e);
float deep = clamp(-zf / (36.0 * u_dpr), 0.0, 1.0);
vec3 sandT = tiled(u_tSand, q, 190.0 * u_dpr);
vec3 dirtT = tiled(u_tDirt, q, 120.0 * u_dpr);
vec3 floorBase = mix(mix(sandT * vec3(0.62, 0.56, 0.46), dirtT * 0.7, 0.4), dirtT * vec3(0.5, 0.45, 0.38), deep);
vec3 nf = normalize(vec3(-dzx, -dzy, 1.0) + texBump(u_tSand, q, 190.0 * u_dpr, 4.0));
return lit(Pf, nf, floorBase, 0.02, caus, occlusion(Pf, nf));
}
vec3 shadeWater(vec2 px, vec2 uv, float sdP){
vec3 up = vec3(0.0, 0.0, 1.0);
vec3 col;
// ================= WATER =================
vec4 info = texture(u_sim, uv);
float sx = u_texel.x * u_res.x, sy = u_texel.y * u_res.y;
float h = info.r * u_hAmp;
float hx = (texture(u_sim, uv + vec2(u_texel.x, 0.0)).r - texture(u_sim, uv - vec2(u_texel.x, 0.0)).r) * u_hAmp / (2.0 * sx);
float hy = (texture(u_sim, uv + vec2(0.0, u_texel.y)).r - texture(u_sim, uv - vec2(0.0, u_texel.y)).r) * u_hAmp / (2.0 * sy);
if (u_hasSim < 0.5) {
hx = 0.02 * sin(px.x * 0.05 / u_dpr + u_time * 1.3);
hy = 0.02 * cos(px.y * 0.045 / u_dpr - u_time * 1.1);
}
vec3 nw = normalize(vec3(-hx, hy, 1.0));
vec3 view = vec3(0.0, 0.0, -1.0);
vec3 Ps = vec3(px, h);
vec3 T = refract(view, nw, 1.0 / 1.333);
vec2 q = px;
float zf = -pondDepth(sdP, u_dpr);
for (int it = 0; it < 3; it++) {
float t = (zf - h) / min(T.z, -0.05);
q = px + T.xy * t;
zf = -pondDepth(sdPond(q), u_dpr);
}
vec3 Pf = vec3(q, zf);
float caus = u_hasSim > 0.5 ? mix(1.0, clamp(texture(u_caust, uvOf(q)).r * 5.2, 0.0, 2.2), 0.85 * (1.0 - smoothstep(-14.0 * u_dpr, 0.0, sdPond(q)))) : 1.0;
#if MODE == 2
caus *= mix(1.0, caustic(q), smoothstep(-90.0 * u_dpr, -6.0 * u_dpr, sdPond(q)));
vec2 fq = uvOf(q);
vec3 floorCol = illuminate(Pf, unpackNormal(texture(u_b2, fq).xy), dec(texture(u_b0, fq).rgb),
0.02, texture(u_atmo, fq).z * caus * g_cloud * dynVis(Pf), texture(u_b3, fq).y);
#else
vec3 floorCol = pondFloor(q, zf, caus);
#endif
vec3 absorb = mix(vec3(0.009, 0.0042, 0.0026), vec3(0.016, 0.009, 0.0055), u_dark) / u_dpr;
float path = length(Pf - Ps) + (-zf);
vec3 refr = floorCol * exp(-absorb * path);
float fishT;
vec3 fishCol = traceRay(Ps, T, length(Pf - Ps), 1, vec3(-1.0), fishT);
if (fishT > 0.0) {
vec3 fp = Ps + T * fishT;
float fpath = fishT + max(-fp.z, 0.0);
refr = fishCol * exp(-absorb * fpath);
path = fpath;
}
refr = mix(refr, vec3(0.2, 0.42, 0.44) * ambientCol() * 2.2, 1.0 - exp(-path * 0.002 / u_dpr));
vec3 R = reflect(view, nw);
#if MODE == 2
vec2 reflectedAt = px + R.xy / max(R.z, 0.2) * 40.0 * u_dpr;
vec2 ruv = uvOf(reflectedAt);
vec4 rc = texture(u_b1, ruv);
vec3 reflected = illuminate(vec3(reflectedAt, decH(rc.a)), unpackNormal(texture(u_b2, ruv).zw), dec(rc.rgb),
0.03, texture(u_atmo, ruv).z * g_cloud, texture(u_b3, ruv).z);
vec3 refl = mix(sky(R), reflected * 0.8, texture(u_b0, ruv).a);
#else
float rt;
vec3 refl = traceRay(Ps, R, 1e6, 0, sky(R), rt);
#endif
float F = 0.02 + 0.98 * pow(1.0 - max(dot(-view, nw), 0.0), 5.0);
col = mix(refr, refl, F);
vec3 ld = normalize(u_light - Ps);
vec3 hv = normalize(ld - view);
#if MODE == 2
col += lightCol() * pow(max(dot(nw, hv), 0.0), 900.0) * 0.9 * texture(u_atmo, uv).z * dynVis(Ps) * g_cloud;
col *= 1.0 - 0.35 * texture(u_b3, uv).w;
#else
col += lightCol() * pow(max(dot(nw, hv), 0.0), 900.0) * 0.9 * visibility(Ps) * g_cloud;
col *= 1.0 - 0.35 * (1.0 - occlusion(Ps, up));
#endif
return col;
}
vec3 shadeGround(vec2 px, float sdP, float hz0){
vec3 up = vec3(0.0, 0.0, 1.0);
vec3 col;
// ================= TERRAIN =================
float e = 2.0 * u_dpr;
float hz = hz0;
float gx = (terrain(px + vec2(e, 0.0)) - hz) / e;
float gy = (terrain(px + vec2(0.0, e)) - hz) / e;
vec3 tn = normalize(vec3(-gx, -gy, 1.0));
float slope = length(vec2(gx, gy));
float hgt = clamp(hz / (45.0 * u_dpr), -1.0, 1.0);
float moisture = smoothstep(0.3, -0.7, hgt) * 0.8 + 0.2 * vnoise(px * 0.006 / u_dpr + 9.0);
vec3 tint = u_ground2 / vec3(0.525, 0.643, 0.388);
vec3 g1 = tiled(u_tGrass, px, 380.0 * u_dpr);
vec3 g2 = tiled(u_tGrass2, px, 300.0 * u_dpr);
vec3 g = mix(g1, g2 * 0.9, clamp(moisture, 0.0, 1.0)) * tint;
g = mix(g, vec3(lum(g)), 0.3) * 0.78;
g = mix(g, g * vec3(1.12, 1.02, 0.62), smoothstep(0.2, 0.9, hgt) * 0.7);
g = mix(g, g * vec3(0.72, 0.84, 0.78), smoothstep(-0.25, -0.9, hgt) * 0.6);
float bare = smoothstep(1.13, 1.24, vnoise(px * 0.004 / u_dpr + 3.0) + 0.5 * vnoise(px * 0.015 / u_dpr));
float earth = clamp(smoothstep(0.8, 1.2, slope) + bare, 0.0, 1.0);
vec3 dirt = tiled(u_tDirt, px, 140.0 * u_dpr) * vec3(0.9, 0.82, 0.7) * (0.85 + 0.3 * vnoise(px * 0.05 / u_dpr));
g = mix(g, dirt, earth);
vec3 bn = mix(texBump(u_tGrass, px, 380.0 * u_dpr, 5.0), texBump(u_tDirt, px, 140.0 * u_dpr, 2.5), earth);
vec3 n = normalize(tn + bn);
float bank = 1.0 - smoothstep(0.0, 12.0 * u_dpr, sdP);
vec3 sand = mix(tiled(u_tSand, px, 190.0 * u_dpr) * vec3(0.55, 0.5, 0.42), dirt * 0.8, 0.5);
g = mix(g, sand, bank * 0.8);
n = normalize(mix(n, tn + texBump(u_tSand, px, 190.0 * u_dpr, 3.0), bank));
vec3 Pg = vec3(px, hz);
float ao = occlusion(Pg, n) * (1.0 - 0.15 * bank);
col = lit(Pg, n, g, 0.02, terrainShadow(px, hz), ao);
return col;
}
// The highest ellipsoid under a pixel, over the groups it is tested against.
float topZ, topCov, trx, try_;
vec4 tA, tB, tC, tG; vec2 tl;
void hitGroup(vec2 px, int g){
vec4 bd = fetchT(2*g);
vec2 dg = px - bd.xy;
if (dot(dg, dg) > (bd.w + 2.0) * (bd.w + 2.0)) return;
vec4 rg = fetchT(2*g + 1);
int start = int(rg.x), cnt = int(rg.y);
for (int i = 0; i < MAXI; i++) {
if (i >= cnt) break;
int pi = PBASE + 3 * (start + i);
vec4 A = fetchT(pi), B = fetchT(pi + 1);
if (B.w > 4.5) continue;
vec2 l = rot(-B.z) * (px - A.xy);
float rx = A.w, ry = B.x;
if (B.w < 1.5) {
vec2 dir = normalize(l + 1e-4);
float wob = vnoise(dir * 3.0 + A.xy * 0.05) + 0.5 * vnoise(dir * 7.0 + A.z * 0.1);
rx *= 0.93 + 0.1 * (wob - 0.75); ry *= 0.93 + 0.1 * (wob - 0.75);
}
float e = l.x*l.x/(rx*rx) + l.y*l.y/(ry*ry);
if (e < 1.0) {
float zz = A.z + B.y * sqrt(1.0 - e);
if (zz > topZ) {
topZ = zz; tA = A; tB = B; tC = fetchT(pi + 2); tl = l; trx = rx; try_ = ry; tG = bd;
topCov = clamp((1.0 - sqrt(e)) * min(rx, ry) / (0.9 * u_dpr), 0.0, 1.0);
}
}
}
}
float rcone(vec2 p, vec2 a, vec2 b, float ra, float rb){ vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0); return length(pa - ba * h) - mix(ra, rb, h); }
// The fox as one silhouette in its own frame (x forward), blended with smooth minimums.
float g_fr;
float foxSd(vec2 q){
float rump = rcone(q, vec2(-9.0, 0.0), vec2(1.0, 0.0), 4.8, 3.8);
float chest = rcone(q, vec2(1.0, 0.0), vec2(8.5, 0.0), 3.8, 5.1);
float b = smin(rump, chest, 1.6);
b = smin(b, rcone(q, vec2(13.7, 0.0), vec2(23.0, 0.0), 4.7, 1.0), 1.6);
vec2 ear = vec2(q.x, abs(q.y));
b = smin(b, rcone(ear, vec2(14.1, 2.5), vec2(12.9, 6.8), 2.5, 0.25), 0.7);
vec2 t1 = vec2(-18.0, sin(u_fox2.y) * 5.0), t2 = vec2(-31.0, sin(u_fox2.y) * 11.0);
b = smin(b, min(rcone(q, vec2(-10.0, 0.0), t1, 2.1, 3.9), rcone(q, t1, t2, 3.9, 1.3)), 1.5);
float legs = 1e5, paws = 1e5;
for (int i = 0; i < 4; i++) {
bool front = i < 2;
float side = i % 2 == 0 ? 1.0 : -1.0;
float phase = fract(u_fox2.x + (front ? 0.0 : 0.75) + (side < 0.0 ? 0.5 : 0.0));
float swing = clamp((phase - 0.58) / 0.42, 0.0, 1.0);
// At full stride the stance covers 14 CSS pixels, the distance traveled in 58% of a cycle.
float reach = phase < 0.58 ? 1.0 - 2.0 * phase / 0.58 : 2.0 * smoothstep(0.0, 1.0, swing) - 1.0;
float lift = sin(3.14159 * swing) * u_fox2.w;
float hip = front ? 7.3 : -7.9;
vec2 paw = vec2(hip + (front ? 1.0 : -0.8) + 5.0 * reach * u_fox2.w, side * (6.6 - 1.5 * lift));
legs = min(legs, rcone(q, vec2(hip, side * 3.25), paw, 1.6, 1.0 - lift * 0.2));
paws = min(paws, length(q - paw));
}
b = smin(b, legs, 0.9);
g_fr = length(ear - vec2(13.1, 5.25)) < 0.9 ? 3.0
: (paws < 1.45 && legs < b + 0.4) || length(q - vec2(22.9, 0.0)) < 1.2
|| length(ear - vec2(19.35, 1.9)) < 0.65 ? 2.0
: (q.x > 17.3 && q.x < 21.8 && abs(q.y) > 1.05) || length(q - t2) < 4.4 ? 1.0 : 0.0;
return b;
}
vec2 foxQ(vec2 px){ vec2 d = (px - u_fox.xy) / u_fox.w; float c = cos(u_fox.z), s = sin(u_fox.z); return vec2(c * d.x + s * d.y, c * d.y - s * d.x); }
vec4 foxShade(vec2 px){
vec2 q = foxQ(px);
if (u_fox.w <= 0.0 || dot(q, q) > 1700.0) return vec4(0.0);
float d = foxSd(q), reg = g_fr;
float cov = clamp(0.5 - d * u_fox.w / u_dpr, 0.0, 1.0);
if (cov <= 0.0) return vec4(0.0);
float dx = foxSd(q + vec2(0.5, 0.0)) - d, dy = foxSd(q + vec2(0.0, 0.5)) - d;
float c = cos(u_fox.z), s = sin(u_fox.z), hgt = clamp(-d / 4.5, 0.0, 1.0);
vec3 n = normalize(vec3(-vec2(c * dx - s * dy, s * dx + c * dy) * 2.0 * (1.0 - hgt) * 0.75, 0.6 + hgt));
vec3 base = (reg > 2.5 ? vec3(0.62, 0.29, 0.15) : reg > 1.5 ? vec3(0.2, 0.12, 0.08)
: reg > 0.5 ? vec3(0.95, 0.93, 0.88) : vec3(0.96, 0.47, 0.13)) * (0.92 + 0.12 * vnoise(q * 1.7));
return vec4(lit(vec3(px, u_fox2.z + hgt * 5.0 * u_fox.w), n, base, 0.04, 1.0, 1.0), cov);
}
float foxShadow(vec2 px){
vec2 q = foxQ(px - (u_fox.xy - u_light.xy) * u_fox2.z / max(u_light.z - u_fox2.z, 1.0));
if (u_fox.w <= 0.0 || dot(q, q) > 1700.0) return 1.0;
return 1.0 - 0.36 * (1.0 - smoothstep(-3.0, 5.0, foxSd(q)));
}
vec3 shadeTop(vec2 px){
vec3 P = vec3(px, topZ);
vec3 nl = normalize(vec3(tl.x / (trx*trx), tl.y / (try_*try_), (topZ - tA.z) / (tB.y*tB.y)));
vec3 n = normalize(vec3(rot(tB.z) * nl.xy, nl.z));
vec3 base = tC.rgb;
float rad = sqrt(tl.x*tl.x/(trx*trx) + tl.y*tl.y/(try_*try_));
float sheen = 0.03;
float kind = tB.w;
if (kind < 1.5) {
vec3 lt = tiled(u_tGrass, px + tC.w * 31.0, 105.0 * u_dpr);
base *= 0.7 + 0.9 * lum(lt);
base *= 0.94 + 0.06 * (1.0 - rad*rad);
n = normalize(mix(n, normalize(vec3((px - tG.xy) / tG.w, 0.8)), 0.68));
n = normalize(n + texBump(u_tGrass, px + tC.w * 31.0, 105.0 * u_dpr, 3.2) + texBump(u_tGrass, px, 42.0 * u_dpr, 1.4));
} else if (kind < 2.5) {
float ang = atan(tl.y, tl.x);
float petals = 0.5 + 0.5 * cos(ang * 5.0 + tC.w);
float sep = (1.0 - smoothstep(0.0, 0.22, petals)) * step(0.32, rad);
base *= 1.0 - 0.28 * sep;
base *= 1.0 + 0.12 * (1.0 - rad);
vec3 centre = mix(vec3(0.95, 0.78, 0.30), vec3(0.55, 0.50, 0.28), u_dark);
base = mix(base, centre, smoothstep(0.34, 0.20, rad));
sheen = 0.08;
} else if (kind < 3.5) {
vec3 bk = texture(u_tBark, vec2(tl.x * 0.012, tl.y * 0.03) / u_dpr + tC.w).rgb;
base *= 0.45 + 1.4 * lum(bk);
sheen = 0.01;
} else if (kind > 4.1) {
vec2 rq = px * (0.22 / u_dpr) + tC.w;
float f0 = vnoise(rq), fx = vnoise(rq + vec2(0.35, 0.0)), fy = vnoise(rq + vec2(0.0, 0.35));
n = normalize(n + vec3(f0 - fx, f0 - fy, 0.0) * 2.2);
base *= 0.72 + 0.5 * vnoise(px * (0.09 / u_dpr) + tC.w * 3.0);
base = mix(base, vec3(0.52, 0.58, 0.34), smoothstep(0.62, 0.82, vnoise(px * (0.07 / u_dpr) - tC.w)) * 0.55);
sheen = 0.04;
} else {
base *= 0.92 + 0.16 * vnoise(px * 0.5 / u_dpr + tC.w);
sheen = 0.05;
}
return lit(P, n, base, sheen, 1.0, occlusion(P, n));
}
// Low mist in the hollows, a blue-lifted grade and the vignette.
float mistAt(vec2 px){
vec2 mq = px * (0.0022 / u_dpr) + vec2(u_time * 0.045, u_time * 0.018);
vec2 mw = vec2(fbm(mq * 1.3 + u_time * 0.05), fbm(mq * 1.3 + 3.0 - u_time * 0.04));
return smoothstep(0.46, 0.82, fbm(mq + (mw - 0.5) * 0.8));
}
vec3 finish(vec3 col, vec2 px, vec2 spx, float hz0, float objZ, float mist0){
float mist = mist0 * (0.7 + 0.3 * smoothstep(20.0 * u_dpr, -40.0 * u_dpr, hz0));
float mistAmt = mist * mix(0.18, 0.34, u_dark);
mistAmt *= 1.0 - smoothstep(0.0, 120.0 * u_dpr, objZ);
vec3 mistCol = mix(vec3(0.80, 0.87, 0.90), vec3(0.15, 0.19, 0.30), u_dark);
col = mix(col, mistCol, mistAmt);
float L = lum(col);
col = mix(col, col * col * (3.0 - 2.0 * col), 0.22);
col = mix(vec3(L), col, 1.08);
col += mix(vec3(0.0), vec3(0.02, 0.03, 0.06), u_dark) * (1.0 - L);
vec2 vuv = spx / u_res;
col *= 0.84 + 0.16 * smoothstep(1.25, 0.35, distance(vuv, vec2(0.5)));
return col;
}
// The bake stores colours as sqrt(c / 2) so values up to 2 and dark night tones both survive 8 bits.
void main(){
vec2 spx = vec2(gl_FragCoord.x, u_res.y - gl_FragCoord.y);
topZ = -1e9; topCov = 0.0; trx = 1.0; try_ = 1.0;
tA = vec4(0.0); tB = vec4(1.0); tC = vec4(0.0); tl = vec2(0.0);
float edge = 6.0 * u_dpr;
#if MODE == 1
// Bake light-independent materials, normals, heights and ambient occlusion.
vec2 px = spx;
setTile(px);
float hz0 = terrain(px);
float sdP = sdPond(px);
float wao = 0.0;
vec3 ground;
if (sdP > -edge) ground = shadeGround(px, sdP, hz0);
else {
ground = pondFloor(px, -pondDepth(sdP, u_dpr), 1.0);
wao = 1.0 - occlusion(vec3(px, 0.0), vec3(0.0, 0.0, 1.0));
}
vec2 gn = g_normal.xy;
float ga = g_ao;
for (int k = 1; k < 32; k++) { if (k > g_tcount) break; hitGroup(px, int(tileSlot(k))); }
vec3 obj = vec3(0.0);
g_normal = vec3(0.0, 0.0, 1.0); g_ao = 1.0;
if (topCov > 0.0) obj = shadeTop(px);
o0 = vec4(enc(ground), topCov);
o1 = vec4(enc(obj), encH(topCov > 0.0 ? topZ : hz0));
// Ground and object normals face up, so each needs only XY.
o2 = vec4(gn, g_normal.xy) * 0.5 + 0.5;
// Ground height, ground and object ambient occlusion, water-surface occlusion.
o3 = vec4(encH(hz0), ga, g_ao, wao);
#elif MODE == 2
// Composite: the bake, plus what moves (water, clouds, sway, critters, mist).
vec2 px = spx;
vec2 uv = vec2(px.x / u_res.x, 1.0 - px.y / u_res.y);
setTile(px);
vec4 b3 = texture(u_b3, uv);
float hz0 = decH(b3.x);
// Canopies sway: the object layer is read a little upwind, more for taller things.
float ph = vnoise(px * (0.006 / u_dpr)) * 6.283;
vec2 sw = vec2(sin(u_time * 0.8 + ph) * 2.2, cos(u_time * 0.63 + ph * 1.3) * 1.5) * u_dpr * u_sway * clamp((decH(texture(u_b1, uv).a) - hz0) / (150.0 * u_dpr), 0.0, 1.0);
vec2 suv = uvOf(px - sw);
vec4 s0 = texture(u_b0, suv), s1 = texture(u_b1, suv);
vec4 atm = texture(u_atmo, uv);
g_cloud = atm.x;
float sdP = sdPond(px);
vec3 ground = vec3(px, hz0);
vec3 col = illuminate(ground, unpackNormal(texture(u_b2, uv).xy), dec(texture(u_b0, uv).rgb),
0.02, atm.z * g_cloud * dynVis(ground), b3.y);
col *= 1.0 - 0.45 * texture(u_decal, px / u_res).a;
if (sdP < edge) {
vec3 w = shadeWater(px, uv, sdP);
col = sdP < -edge ? w : mix(w, col, smoothstep(-edge * 0.5, edge * 0.5, sdP));
col = mix(col, col * 1.2 + 0.035, exp(-abs(sdP + u_dpr) / (1.6 * u_dpr)) * 0.45);
}
float oz = decH(s1.a);
col *= foxShadow(px);
if (s0.a > 0.0) {
vec3 P = vec3(px, oz);
vec3 obj = illuminate(P, unpackNormal(texture(u_b2, suv).zw), dec(s1.rgb),
0.04, visibility(P) * g_cloud * dynVis(P), texture(u_b3, suv).z);
col = mix(col, obj, s0.a);
}
// The soft look: the bake's blurred copy, a little everywhere and more toward the top and bottom, and its highlights bloomed.
vec3 soft = illuminate(ground, vec3(0.0, 0.0, 1.0), dec(texture(u_soft, uv).rgb),
0.0, atm.z * g_cloud, mix(b3.y, 1.0, 0.5));
if (sdP > edge) col = mix(col, soft, 0.18 + 0.42 * smoothstep(0.22, 0.5, abs(spx.y / u_res.y - 0.5)));
col += max(soft - 0.62, 0.0) * 0.45;
vec4 fx = s0.a > 0.5 && oz > u_fox2.z + 12.0 * u_dpr ? vec4(0.0) : foxShade(px);
col = mix(col, fx.rgb, fx.a);
float objZ = max(oz, 0.0) * s0.a;
for (int i = 0; i < MAXD; i++) { if (i >= u_nd) break; vec2 dg = px - u_dyn[i].xy; if (dot(dg, dg) < (u_dyn[i].w + 2.0) * (u_dyn[i].w + 2.0)) hitGroup(px, u_ng0 + i); }
if (topZ > -1e8) { col = mix(col, shadeTop(px), topCov); objZ = max(objZ, max(topZ, 0.0) * topCov); }
fragColor = vec4(finish(col, px, spx, hz0, objZ, atm.y), 1.0);
#elif MODE == 4
// Blur of the finished bake (ground with plants on it) at a quarter of its resolution.
vec2 px = vec2(gl_FragCoord.x, u_res.y / 4.0 - gl_FragCoord.y) * 4.0;
vec3 acc = vec3(0.0); float wsum = 0.0;
for (int i = -3; i <= 3; i++) for (int j = -3; j <= 3; j++) {
vec2 o = vec2(float(i), float(j)) * 3.0 * u_dpr;
float w = exp(-float(i * i + j * j) * 0.18);
vec2 q = uvOf(px + o);
vec4 a = texture(u_b0, q);
acc += mix(dec(a.rgb), dec(texture(u_b1, q).rgb), a.a) * w; wsum += w;
}
fragColor = vec4(enc(acc / wsum), 1.0);
#elif MODE == 3
// Clouds, mist and ground shadows, at an eighth of the scene resolution.
vec2 grid = ceil(u_res / 8.0);
vec2 uv = gl_FragCoord.xy / grid;
vec2 px = vec2(uv.x, 1.0 - uv.y) * u_res;
setTile(px);
float sdP = sdPond(px);
float hz = sdP < -edge ? -pondDepth(sdP, u_dpr) : decH(texture(u_b3, uv).x);
float shade = visibility(vec3(px, hz));
if (sdP >= -edge) shade *= terrainShadow(px, hz);
fragColor = vec4(clouds(px), mistAt(px), shade, 1.0);
#else
// Live: the whole scene traced every frame, used while the camera follows an animal.
vec2 px = u_cam.xy + rot(u_cam.z) * ((spx - u_res * 0.5) / u_cam.w);
vec2 uv = vec2(px.x / u_res.x, 1.0 - px.y / u_res.y);
setTile(px);
float hz0 = terrain(px);
g_cloud = clouds(px);
float sdP = sdPond(px);
vec3 col;
if (sdP < -edge) col = shadeWater(px, uv, sdP);
else {
col = shadeGround(px, sdP, hz0) * (1.0 - 0.45 * texture(u_decal, px / u_res).a);
if (sdP < edge) col = mix(shadeWater(px, uv, sdP), col, smoothstep(-edge, edge, sdP));
}
col *= foxShadow(px);
for (int k = 1; k < 32; k++) { if (k > g_tcount) break; hitGroup(px, int(tileSlot(k))); }
float objZ = 0.0;
if (topZ > -1e8) { col = mix(col, shadeTop(px), topCov); objZ = max(topZ, 0.0) * topCov; }
vec4 fx = topZ > u_fox2.z + 12.0 * u_dpr ? vec4(0.0) : foxShade(px);
col = mix(col, fx.rgb, fx.a);
fragColor = vec4(finish(col, px, spx, hz0, objZ, mistAt(px)), 1.0);
#endif
}`;
// ---------- GL helpers ----------
// Programs compile in the background where the browser can (the poster shows
// meanwhile): nothing asks for their status until they report done.
const pcx = gl.getExtension('KHR_parallel_shader_compile');
const progs = [];
function program(vs, fs, attrs) {
const p = gl.createProgram(), sh = [];
for (const [type, src] of [[gl.VERTEX_SHADER, vs], [gl.FRAGMENT_SHADER, fs]]) {
const x = gl.createShader(type);
gl.shaderSource(x, src); gl.compileShader(x); gl.attachShader(p, x); sh.push(x);
}
const a = {};
attrs.forEach((name, i) => { gl.bindAttribLocation(p, i, name); a[name] = i; });
gl.linkProgram(p);
const o = { p, u: {}, a, ok: null, sh };
progs.push(o);
return o;
}
function settle(o) {
if (o.ok !== null) return true;
if (pcx && !gl.getProgramParameter(o.p, pcx.COMPLETION_STATUS_KHR)) return false;
o.ok = !!gl.getProgramParameter(o.p, gl.LINK_STATUS);
if (!o.ok) { console.error(o.sh.map(x => gl.getShaderInfoLog(x)).join('') + gl.getProgramInfoLog(o.p)); return true; }
const n = gl.getProgramParameter(o.p, gl.ACTIVE_UNIFORMS);
for (let i = 0; i < n; i++) { const info = gl.getActiveUniform(o.p, i); o.u[info.name.replace(/\[0\]$/, '')] = gl.getUniformLocation(o.p, info.name); }
return true;
}
const quadBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, quadBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 3,-1, -1,3]), gl.STATIC_DRAW);
function drawQuad(prog) {
gl.bindBuffer(gl.ARRAY_BUFFER, quadBuf);
gl.enableVertexAttribArray(prog.a.a);
gl.vertexAttribPointer(prog.a.a, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
const scene = program(SCENE_VERT, sceneFrag(0), ['a']);
// The still garden is baked and composited each frame; the live program runs only while riding.
const bakeP = program(SCENE_VERT, sceneFrag(1), ['a']), compP = program(SCENE_VERT, sceneFrag(2), ['a']), atmoP = program(SCENE_VERT, sceneFrag(3), ['a']), softP = program(SCENE_VERT, sceneFrag(4), ['a']);
const airP = program(AIR_VERT, AIR_FRAG, ['a_pos', 'a_sz', 'a_col']);
let baking = false;
const dynData = new Float32Array(24 * 4);
let nd = 0;
let sim = null, drop = null, cau = null;
if (hasSim) {
sim = program(QUAD_VERT, SIM_FRAG, ['a']);
drop = program(QUAD_VERT, DROP_FRAG, ['a']);
cau = program(CAU_VERT, CAU_FRAG, ['a_uv']);
}
// ---------- Image textures ----------
let texReady = 0;
function imageTexture(src, avg) {
const t = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(avg));
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
const img = new Image();
img.onload = () => {
gl.bindTexture(gl.TEXTURE_2D, t);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
texReady++; rebake = true;
};
img.onerror = () => texReady++;
img.src = src;
return t;
}
const tex = {
grass: imageTexture(TEXTURES.grass, [110, 160, 70, 255]),
grass2: imageTexture(TEXTURES.grass2, [100, 150, 60, 255]),
sand: imageTexture(TEXTURES.sand, [210, 180, 140, 255]),
dirt: imageTexture(TEXTURES.dirt, [150, 130, 105, 255]),
bark: imageTexture(TEXTURES.bark, [90, 60, 40, 255]),
};
// ---------- Object data texture ----------
const objData = new Float32Array(TEXW * TEXH * 4);
const objTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, objTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, TEXW, TEXH, 0, gl.RGBA, gl.FLOAT, objData);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
let np = 0, ng = 0, dpr = 1, ngS = 0, npS = 0;
function beginFrameObjects() { np = 0; ng = 0; }
function prim(x, y, z, rx, ry, rz, th, kind, col, seed) {
if (np >= MAXPR) return;
const o = (PBASE + 3 * np) * 4;
objData[o] = x * dpr; objData[o+1] = y * dpr; objData[o+2] = z * dpr; objData[o+3] = Math.max(rx, 0.3) * dpr;
objData[o+4] = Math.max(ry, 0.3) * dpr; objData[o+5] = Math.max(rz, 0.3) * dpr; objData[o+6] = th; objData[o+7] = kind;
objData[o+8] = col[0]; objData[o+9] = col[1]; objData[o+10] = col[2]; objData[o+11] = seed;
np++;
}
function group(fn) {
if (ng >= MAXG) return;
const start = np;
fn();
const cnt = Math.min(np - start, MAXI);
np = start + cnt;
if (cnt <= 0) return;
let cx = 0, cy = 0, cz = 0, rmax = 0;
for (let i = 0; i < cnt; i++) { const o = (PBASE + 3 * (start + i)) * 4; cx += objData[o]; cy += objData[o+1]; cz += objData[o+2]; }
cx /= cnt; cy /= cnt; cz /= cnt;
let R = 0;
for (let i = 0; i < cnt; i++) {
const o = (PBASE + 3 * (start + i)) * 4;
const r = Math.max(objData[o+3], objData[o+4], objData[o+5]);
rmax = Math.max(rmax, (objData[o+3] + objData[o+4] + objData[o+5]) / 3);
R = Math.max(R, Math.hypot(objData[o] - cx, objData[o+1] - cy, objData[o+2] - cz) + r);
}
const go = (2 * ng) * 4;
objData[go] = cx; objData[go+1] = cy; objData[go+2] = cz; objData[go+3] = R + 1;
objData[go+4] = start; objData[go+5] = cnt; objData[go+6] = rmax; objData[go+7] = 0;
ng++;
}
let tilesX = 1, tilesY = 1;
function buildTiles() {
tilesX = Math.max(1, Math.ceil(W / (TILE * dpr))); tilesY = Math.max(1, Math.ceil(H / (TILE * dpr)));
if (tilesX * tilesY > MAXTILES) { tilesX = Math.min(tilesX, 25); tilesY = Math.min(tilesY, Math.floor(MAXTILES / tilesX)); }
const tpx = TILE * dpr;
const base = TBASE * 4;
for (let t = 0; t < tilesX * tilesY; t++) objData[base + t * TSLOTS * 4] = 0;
const Lx = light.x * dpr, Ly = light.y * dpr, Lz = light.z * dpr;
for (let g = 0; g < ng; g++) {
const go = (2 * g) * 4;
const cx = objData[go], cy = objData[go+1], cz = objData[go+2], R = objData[go+3], rmax = objData[go+6];
// reach: its own radius, plus how far its shadow can be thrown, plus AO range
const top = cz + R;
const dx = objMode === 2 ? Math.max(Math.abs(cx), Math.abs(W - cx)) : cx - Lx;
const dy = objMode === 2 ? Math.max(Math.abs(cy), Math.abs(H - cy)) : cy - Ly;
const shadow = top * Math.hypot(dx, dy) / Math.max(60, Lz - top);
const reach = R + Math.max(shadow + 22 * dpr * 3, 5 * rmax) + 4 * dpr;
const x0 = Math.max(0, Math.floor((cx - reach) / tpx)), x1 = Math.min(tilesX - 1, Math.floor((cx + reach) / tpx));
const y0 = Math.max(0, Math.floor((cy - reach) / tpx)), y1 = Math.min(tilesY - 1, Math.floor((cy + reach) / tpx));
for (let ty = y0; ty <= y1; ty++) for (let tx = x0; tx <= x1; tx++) {
const to = base + (ty * tilesX + tx) * TSLOTS * 4;
const n = objData[to];
if (n >= TSLOTS * 4 - 1) continue;
objData[to + n + 1] = g;
objData[to] = n + 1;
}
}
}
function uploadObjects() {
buildTiles();
gl.bindTexture(gl.TEXTURE_2D, objTex);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, TEXW, TEXH, gl.RGBA, gl.FLOAT, objData);
}
// ---------- Bake ----------
// One material cache, rebuilt when the scene changes. Light and shadows are evaluated every frame.
let material, atmo, soft, rebake = true, objMode = 0, ready = false;
function rgbaTarget(w, h) {
const t = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return t;
}
function frameTarget(w, h, count) {
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
const buffers = Array.from({ length: count }, (_, i) => gl.COLOR_ATTACHMENT0 + i);
const tx = buffers.map(slot => {
const t = rgbaTarget(w, h);
gl.framebufferTexture2D(gl.FRAMEBUFFER, slot, gl.TEXTURE_2D, t, 0);
return t;
});
gl.drawBuffers(buffers);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
return { fb, tx, w, h };
}
function makeSceneTargets() {
for (const target of [material, atmo, soft]) {
if (!target) continue;
gl.deleteFramebuffer(target.fb);
target.tx.forEach(t => gl.deleteTexture(t));
}
material = baking ? frameTarget(W, H, 4) : null;
atmo = baking ? frameTarget(Math.ceil(W / 8), Math.ceil(H / 8), 1) : null;
soft = baking ? frameTarget(Math.ceil(W / 4), Math.ceil(H / 4), 1) : null;
rebake = true;
}
function renderTarget(target, prog, t) {
gl.bindFramebuffer(gl.FRAMEBUFFER, target.fb);
gl.viewport(0, 0, target.w, target.h);
sceneUniforms(prog, t);
drawQuad(prog);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
// ---------- Render targets ----------
let W = 1, H = 1, simW = 1, simH = 1;
const simTex = [null, null], simFB = [null, null];
let cauTex = null, cauFB = null, cur = 0, mesh = null;
const blankTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, blankTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0,0,0,255]));
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
function makeTarget(w, h) {
const t = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, t, 0);
const ok = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
return ok ? { t, fb } : null;
}
function buildMesh(gw, gh) {
const verts = new Float32Array((gw + 1) * (gh + 1) * 2);
let vi = 0;
for (let y = 0; y <= gh; y++) for (let x = 0; x <= gw; x++) { verts[vi++] = x / gw; verts[vi++] = y / gh; }
const idx = new Uint32Array(gw * gh * 6);
let ii = 0;
for (let y = 0; y < gh; y++) for (let x = 0; x < gw; x++) {
const a = y * (gw + 1) + x, b = a + 1, c = a + gw + 1, d = c + 1;
idx[ii++] = a; idx[ii++] = c; idx[ii++] = b; idx[ii++] = b; idx[ii++] = c; idx[ii++] = d;
}
const vb = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vb); gl.bufferData(gl.ARRAY_BUFFER, verts, gl.STATIC_DRAW);
const ib = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idx, gl.STATIC_DRAW);
return { vb, ib, count: idx.length };
}
document.body.prepend(canvas);
const AIRN = 256, airData = new Float32Array(AIRN * 10), airBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, airBuf);
gl.bufferData(gl.ARRAY_BUFFER, airData.byteLength, gl.DYNAMIC_DRAW);
// The internal resolution is picked once per tab, from a short benchmark
// under the poster, and never changes while the page runs: resizing the
// canvas reallocates it, which is a hitch of its own. The water simulation
// keeps its own resolution so ripples never restart.
const DPR2 = Math.min(window.devicePixelRatio || 1, 2), TIERS = [1, 0.75, 0.5], TIER_KEY = 'zds.garden.tier';
let tier = -1;
try { const v = sessionStorage.getItem(TIER_KEY); if (v !== null && TIERS[+v]) tier = +v; } catch (e) {}
const top = () => Math.min(DPR2, Math.sqrt(2.2e6 / (innerWidth * LVH)));
let scale = top() * TIERS[Math.max(0, tier)];
function applyScale() {
dpr = scale;
W = Math.floor(innerWidth * dpr); H = Math.floor(LVH * dpr);
canvas.width = W; canvas.height = H;
if (ready) makeSceneTargets();
}
function resize() {
applyScale();
if (hasSim) {
simW = Math.max(64, Math.floor(innerWidth / 2)); simH = Math.max(64, Math.floor(LVH / 2));
for (let i = 0; i < 2; i++) {
if (simTex[i]) { gl.deleteTexture(simTex[i]); gl.deleteFramebuffer(simFB[i]); }
const t = makeTarget(simW, simH);
if (!t) { hasSim = false; break; }
simTex[i] = t.t; simFB[i] = t.fb;
}
if (hasSim) {
if (cauTex) { gl.deleteTexture(cauTex); gl.deleteFramebuffer(cauFB); }
const c = makeTarget(simW, simH);
if (!c) hasSim = false; else { cauTex = c.t; cauFB = c.fb; }
}
if (hasSim && !mesh) mesh = buildMesh(200, 130);
}
plantGarden();
spawnAir();
}
// ---------- Theme tokens ----------
function hex(v) {
v = v.trim();
const m = v.match(/rgba?\(([^)]+)\)/);
if (m) { const p = m[1].split(',').map(parseFloat); return [p[0] / 255, p[1] / 255, p[2] / 255]; }
v = v.replace('#', '');
if (v.length === 3) v = v.split('').map(c => c + c).join('');
const n = parseInt(v, 16);
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}
// Cards stay real DOM with a CSS shadow; the scene only keeps critters off them.
for (const el of document.querySelectorAll(PAGE_SEL)) el.classList.add('g-sheet');
let sheets = [...document.querySelectorAll('.g-sheet')];
// Card rects in document coordinates, measured on resize only, never per frame.
let cardRects = [];
const measureCards = () => { cardRects = sheets.map(el => { const r = el.getBoundingClientRect(); return [r.left + scrollX, r.top + scrollY, r.right + scrollX, r.bottom + scrollY]; }); };
measureCards();
new ResizeObserver(measureCards).observe(document.body);
// A page that swaps its content in place (swap.js) brings new cards to mark and measure.
document.addEventListener('zds:swap', () => { for (const el of document.querySelectorAll(PAGE_SEL)) el.classList.add('g-sheet'); sheets = [...document.querySelectorAll('.g-sheet')]; measureCards(); });
let colors = {}, isDark = 0;
function readTokens() {
rebake = true;
const cs = getComputedStyle(root);
colors = { ground: hex(cs.getPropertyValue('--ground')), ground2: hex(cs.getPropertyValue('--ground2')) };
isDark = parseFloat(cs.getPropertyValue('--is-dark')) || 0;
document.body.classList.toggle('g-night', isDark > 0.5);
refreshRide();
}
readTokens();
new MutationObserver(readTokens).observe(root, { attributes: true, attributeFilter: ['data-theme'] });
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', readTokens);
// ---------- Garden ----------
const POND_K = 44;
let ponds = [], trees = [], bushes = [], clumps = [], flowers = [], rocks = [];
function rng(seed) { return () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; }; }
function hsl(h, s, l) {
const k = n => (n + h / 30) % 12;
const a = s * Math.min(l, 1 - l);
const f = n => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
return [f(0), f(8), f(4)];
}
function sminJS(a, b, k) { const h = Math.max(0, Math.min(1, 0.5 + 0.5 * (b - a) / k)); return b + (a - b) * h - k * h * (1 - h); }
function sdPondJS(x, y) { let d = 1e5; for (const c of ponds) d = sminJS(d, Math.hypot(x - c.x, y - c.y) - c.r, POND_K); return d; }
function smoothstep(a, b, x) { const t = Math.max(0, Math.min(1, (x - a) / (b - a))); return t * t * (3 - 2 * t); }
function pondDepthJS(x, y) { const sd = sdPondJS(x, y); const mask = 1 - smoothstep(-6, 0, sd); return mask * (5 + 34 * smoothstep(0, 46, -sd)); }
const offCards = (x, y, m) => { const ox = scrollX, oy = scrollY; return !cardRects.some(r => x + ox > r[0] - m && x + ox < r[2] + m && y + oy > r[1] - m && y + oy < r[3] + m); };
// Same noise as the shader, so objects sit on the ground it draws.
function fract(v) { return v - Math.floor(v); }
function hashJS(x, y) {
let p0 = fract(x * 0.1031), p1 = fract(y * 0.1031), p2 = fract(x * 0.1031);
const d = p0 * (p1 + 33.33) + p1 * (p2 + 33.33) + p2 * (p0 + 33.33);
p0 += d; p1 += d; p2 += d;
return fract((p0 + p1) * p2);
}
function vnoiseJS(x, y) {
const ix = Math.floor(x), iy = Math.floor(y);
let fx = x - ix, fy = y - iy;
fx = fx * fx * (3 - 2 * fx); fy = fy * fy * (3 - 2 * fy);
const a = hashJS(ix, iy), b = hashJS(ix + 1, iy), c = hashJS(ix, iy + 1), d = hashJS(ix + 1, iy + 1);
const top = a + (b - a) * fx, bot = c + (d - c) * fx;
return top + (bot - top) * fy;
}
function fbmJS(x, y) { let v = 0, a = 0.5; for (let i = 0; i < 3; i++) { v += a * vnoiseJS(x, y); x = x * 2.1 + 5.7; y = y * 2.1 + 5.7; a *= 0.5; } return v; }
function terrainJS(x, y) {
const qx = x * 0.0021, qy = y * 0.0021;
let h = fbmJS(qx, qy) - 0.5;
h += 0.35 * (vnoiseJS(qx * 3.1 + 7, qy * 3.1 + 7) - 0.5);
h += 0.22 * (fbmJS(qx * 4 + 13, qy * 4 + 13) - 0.5);
const wet = smoothstep(0, 70, sdPondJS(x, y));
return h * 110 * wet;
}
// Tree after the Codrops "Fractals to Forests" recipe: a trunk splits
// recursively into thinner branches with gnarl and an upward growth
// force; the crown is a dense dome of leaf clusters so, from above, it
// reads as a mass of foliage with branches showing only in the gaps.
function growTree(R, x, y) {
const H = 105 + R() * 50;
const spread = 68 + R() * 50;
const hue = 86 + R() * 42;
const sat = 0.36 + R() * 0.12;
const wood = [0.40 + R() * 0.08, 0.28 + R() * 0.05, 0.17];
const parts = [];
parts.push({ x: 0, y: 0, z: H * 0.3, rx: 8, ry: 8, rz: H * 0.3, th: 0, kind: 3, col: wood, seed: R() * 40 });
const branch = (ox, oy, oz, dx, dy, dz, len, thick, level) => {
const g = 0.25 / Math.max(thick, 1);
dx += (R() - 0.5) * g; dy += (R() - 0.5) * g; dz += 0.12 / Math.max(thick, 1);
const l = Math.hypot(dx, dy, dz); dx /= l; dy /= l; dz /= l;
const ex = ox + dx * len, ey = oy + dy * len, ez = oz + dz * len;
const lxy = Math.hypot(ex - ox, ey - oy);
parts.push({ x: (ox + ex) / 2, y: (oy + ey) / 2, z: (oz + ez) / 2, rx: Math.max(lxy / 2, thick), ry: thick, rz: thick, th: Math.atan2(ey - oy, ex - ox), kind: 3, col: wood, seed: R() * 40 });
if (level >= 2) return;
const n = level === 0 ? 2 + (R() < 0.6 ? 1 : 0) : 2;
const baseA = Math.atan2(dy, dx);
for (let i = 0; i < n; i++) {
const a = baseA + (i - (n - 1) / 2) * (0.7 + R() * 0.4) + (R() - 0.5) * 0.3;
const up = 0.3 + R() * 0.35 - level * 0.1;
const ll = Math.hypot(Math.cos(a), Math.sin(a), up);
branch(ex, ey, ez, Math.cos(a) / ll, Math.sin(a) / ll, up / ll, len * (0.64 + R() * 0.12), thick * 0.62, level + 1);
}
};
const n0 = 3 + (R() < 0.5 ? 1 : 0);
for (let i = 0; i < n0; i++) {
const a = (i / n0) * 6.283 + R() * 0.8;
const up = 0.55 + R() * 0.25;
const ll = Math.hypot(Math.cos(a), Math.sin(a), up);
branch(0, 0, H * 0.6, Math.cos(a) / ll, Math.sin(a) / ll, up / ll, spread * 0.5, 5, 0);
}
const crown = 38;
for (let i = 0; i < crown; i++) {
const rr = spread * Math.sqrt(R()) * (0.9 + 0.2 * R());
const a = R() * 6.283;
const domeH = 0.42 * spread * Math.sqrt(Math.max(0, 1 - (rr / spread) * (rr / spread)));
const z = H + domeH - R() * 14;
const r = (17 + R() * 10) * (0.75 + 0.45 * (1 - rr / spread));
const lt = 0.22 + 0.16 * Math.max(0, Math.min(1, domeH / (0.42 * spread))) + R() * 0.05;
parts.push({ x: Math.cos(a) * rr, y: Math.sin(a) * rr, z, rx: r, ry: r * (0.85 + R() * 0.3), rz: r * 0.7, th: R() * 6.28, kind: 0, col: hsl(hue + R() * 14 - 7, sat, lt), seed: R() * 40 });
}
return { x, y, H, spread, phase: R() * 6.28, parts: parts.slice(0, MAXI) };
}
function plantGarden(keep) {
rebake = true;
const R = rng(4171);
const vw = innerWidth, vh = LVH;
ponds = [];
const room = 1e5;
const nPonds = room > 300 ? 2 : room > 180 ? 1 : 0;
for (let p = 0; p < nPonds; p++) {
const r0 = Math.min(120, room * 0.32);
for (let tries = 0; tries < 60; tries++) {
const x = R() * vw, y = R() * vh;
if (Math.hypot(x - innerWidth * 0.32, y - LVH * 0.12) < r0 * 2.2) continue;
if (ponds.some(c => Math.hypot(c.x - x, c.y - y) < r0 * 3.2)) continue;
ponds.push({ x, y, r: r0 * (0.75 + R() * 0.25), main: true });
for (let s = 0; s < 2; s++) {
const a = R() * 6.283, d = r0 * (0.55 + R() * 0.35);
ponds.push({ x: x + Math.cos(a) * d, y: y + Math.sin(a) * d, r: r0 * (0.45 + R() * 0.35), main: false });
}
break;
}
}
ponds = ponds.slice(0, MAXP);
const clear = (x, y, r, wet) => sdPondJS(x, y) > wet;
const place = (r, tries, wet) => {
for (let i = 0; i < tries; i++) {
const x = -r * 0.3 + R() * (vw + r * 0.6), y = -r * 0.3 + R() * (vh + r * 0.6);
if (clear(x, y, r, wet)) return [x, y];
}
return null;
};
trees = [];
const nTrees = Math.max(2, Math.min(7, Math.round(vw * vh / 200000)));
for (let t = 0; t < nTrees; t++) {
const p = place(95, 40, -20); if (!p) continue;
if (trees.some(o => Math.hypot(o.x - p[0], o.y - p[1]) < 130)) continue;
const tr = growTree(R, p[0], p[1]); tr.tz = terrainJS(p[0], p[1]); trees.push(tr);
}
bushes = [];
for (let b = 0; b < 7; b++) {
const r = 20 + R() * 22;
const p = place(r, 30, r * 0.6); if (!p) continue;
const hue = 100 + R() * 30;
bushes.push({ x: p[0], y: p[1], r, tz: terrainJS(p[0], p[1]), phase: R() * 6.28, lobes: [0, 1, 2, 3, 4].map(() => ({ dx: (R() - 0.5) * r * 1.1, dy: (R() - 0.5) * r * 1.1, r: r * (0.45 + R() * 0.3), col: hsl(hue + R() * 10, 0.36, 0.22 + R() * 0.1), seed: R() * 40 })) });
}
rocks = [];
for (let k = 0; k < 12; k++) {
const r = 4 + R() * 9;
const p = place(r, 20, 12); if (!p) continue;
const g = 0.5 + R() * 0.2;
rocks.push({ x: p[0], y: p[1], rx: r, ry: r * (0.6 + R() * 0.4), rz: r * (0.45 + R() * 0.3), th: R() * 6.28, col: [g, g * 0.97, g * 0.9], seed: R() * 40 });
}
clumps = []; flowers = [];
const palette = [[345, 0.62, 0.72], [22, 0.85, 0.66], [48, 0.85, 0.72], [270, 0.45, 0.74], [0, 0, 0.94], [335, 0.55, 0.60]];
for (let c = 0; c < 10; c++) {
const p = place(24, 20, 14); if (!p) continue;
const n = 3 + Math.floor(R() * 4);
const cl = { x: p[0], y: p[1], items: [] };
const pc = palette[Math.floor(R() * palette.length)];
for (let i = 0; i < n; i++) {
const fx = p[0] + (R() - 0.5) * 44, fy = p[1] + (R() - 0.5) * 44;
const f = { x: fx, y: fy, z: 24 + R() * 22, tz: terrainJS(fx, fy), r: 6 + R() * 7, col: hsl(pc[0] + R() * 20 - 10, pc[1], pc[2]), seed: R() * 6.28, phase: R() * 6.28 };
cl.items.push(f); flowers.push(f);
}
clumps.push(cl);
}
const kept = keep && packFauna();
spawnFauna(R);
if (kept) unpackFauna(kept);
}
// Wildlife as plain data, so it can ride along to the next page.
const packFauna = () => JSON.stringify(fauna, (k, v) => k === 'home' ? ponds.indexOf(v) : k === 'gz' || k === 'hop' ? undefined : v);
function unpackFauna(s) {
const o = JSON.parse(s);
if (!o || !Array.isArray(o.fish)) return;
for (const f of o.fish) f.home = ponds[f.home];
if (o.fish.some(f => !f.home)) o.fish = fauna.fish;
Object.assign(fauna, o);
}
// ---------- Wildlife (a few, unhurried) ----------
const fauna = { butterflies: [], birds: [], foxes: [], fish: [] };
const inView = (x, y, m) => x > -m && x < innerWidth + m && y > -m && y < LVH + m;
function randomClear(R, tries) {
for (let i = 0; i < tries; i++) {
const x = 30 + R() * (innerWidth - 60), y = 30 + R() * (LVH - 60);
if (sdPondJS(x, y) > 28) return [x, y];
}
return null;
}
function spawnFauna(R) {
fauna.butterflies = [];
const bcols = [[0.95, 0.52, 0.12], [0.36, 0.52, 0.95], [0.96, 0.92, 0.62], [0.92, 0.35, 0.45]];
for (let i = 0; i < 4 && flowers.length; i++) {
const f = flowers[Math.floor(R() * flowers.length)];
fauna.butterflies.push({ x: f.x, y: f.y, z: 42, tx: f.x, ty: f.y, phase: R() * 6.28, col: bcols[i % bcols.length], wait: R() * 3, ang: R() * 6.28 });
}
fauna.birds = [];
for (let i = 0; i < 2; i++) fauna.birds.push(newBird(R, true));
fauna.foxes = [];
const p = randomClear(R, 60) || [innerWidth * 0.1, LVH * 0.9];
fauna.foxes.push({ x: p[0], y: p[1], h: R() * 6.28, tx: p[0], ty: p[1], pause: 1, phase: R() * 6.28 });
fauna.fish = [];
const mains = ponds.filter(p => p.main);
const fcols = [[0.95, 0.48, 0.12], [0.93, 0.86, 0.78], [0.95, 0.62, 0.20]];
for (let i = 0; i < mains.length * 2; i++) {
const pd = mains[i % mains.length];
const a = R() * 6.28, d = R() * pd.r * 0.5;
fauna.fish.push({ x: pd.x + Math.cos(a) * d, y: pd.y + Math.sin(a) * d, h: R() * 6.28, home: pd, col: fcols[i % fcols.length], phase: R() * 6.28, speed: 16 + R() * 10 });
}
}
function newBird(R, anywhere) {
const side = Math.floor(R() * 4);
const m = 160;
let x, y;
if (anywhere) { x = R() * innerWidth; y = R() * LVH; }
else if (side === 0) { x = -m; y = R() * LVH; }
else if (side === 1) { x = innerWidth + m; y = R() * LVH; }
else if (side === 2) { x = R() * innerWidth; y = -m; }
else { x = R() * innerWidth; y = LVH + m; }
const h = Math.atan2(LVH / 2 - y + (R() - 0.5) * LVH * 0.8, innerWidth / 2 - x + (R() - 0.5) * innerWidth * 0.8);
return { x, y, h, z: 250 + R() * 90, speed: 42 + R() * 24, phase: R() * 6.28, col: [0.22, 0.19, 0.17] };
}
const frng = rng(99);
function settleFox(f, dt) {
const ground = terrainJS(f.x, f.y);
if (f.gz === undefined) f.gz = ground;
if (f.hop) {
f.hop.p = Math.min(1, f.hop.p + dt / f.hop.dur);
const p = f.hop.p;
f.gz = f.hop.from + (f.hop.to - f.hop.from) * p + Math.sin(p * Math.PI) * f.hop.height;
if (p >= 1) { f.gz = f.hop.to; f.hop = null; }
} else if (Math.abs(ground - f.gz) > 3.5) {
f.hop = { from: f.gz, to: ground, p: 0, dur: 0.38, height: 18 + Math.max(0, ground - f.gz) * 0.6 };
} else {
f.gz += (ground - f.gz) * Math.min(1, dt * 12);
}
}
// A clicked bird drops out of the sky, lands flat, lies stunned for a bit,
// picks itself up, stands looking about, then takes off again.
function knockBird(x, y) {
let best = null, bd_ = 34;
for (const bd of fauna.birds) {
if (bd.state && bd.state !== 'fly') continue;
const d = Math.hypot(bd.x - x, bd.y - y);
if (d < bd_) { bd_ = d; best = bd; }
}
if (!best) return false;
best.state = 'fall'; best.vz = 0; best.h0 = best.h; best.spin = (frng() < 0.5 ? -1 : 1) * (5 + frng() * 4);
return true;
}
function groundedBird(bd, dt, t) {
const g = terrainJS(bd.x, bd.y);
if (bd.state === 'fall') {
bd.vz += 1500 * dt;
bd.z -= bd.vz * dt;
bd.h += bd.spin * dt;
bd.x += Math.cos(bd.h0) * bd.speed * 0.3 * dt;
bd.y += Math.sin(bd.h0) * bd.speed * 0.3 * dt;
if (bd.z <= g + 1.2) {
bd.z = g + 1.2; bd.state = 'flat'; bd.timer = 1.8 + frng() * 1.6; bd.squash = 1;
if (sdPondJS(bd.x, bd.y) < 0) splash({ x: bd.x, y: bd.y, r: 24, s: 0.45 });
else for (let k = 0; k < 7; k++) puffs.push({ x: bd.x, y: bd.y, a: frng() * 6.28, sp: 30 + frng() * 50, r: 3 + frng() * 4, life: 0.7 + frng() * 0.5, age: 0 });
}
} else if (bd.state === 'flat') {
bd.timer -= dt;
if (bd.timer <= 0) { bd.state = 'up'; bd.timer = 0.7; }
} else if (bd.state === 'up') {
bd.timer -= dt; bd.squash = Math.max(0, bd.timer / 0.7);
if (bd.timer <= 0) { bd.state = 'stand'; bd.squash = 0; bd.timer = 2.5 + frng() * 3.5; bd.look = 0; bd.nextLook = 0.4; }
} else if (bd.state === 'stand') {
bd.timer -= dt; bd.nextLook -= dt;
if (bd.nextLook <= 0) { bd.look = (frng() - 0.5) * 1.4; bd.nextLook = 0.4 + frng() * 1.3; }
const pd = ptr.active ? Math.hypot(ptr.x - bd.x, ptr.y - bd.y) : 1e9;
if (bd.timer <= 0 || pd < 70) {
bd.state = 'takeoff'; bd.vz = 0; bd.look = 0;
bd.h = pd < 70 ? Math.atan2(bd.y - ptr.y, bd.x - ptr.x) : frng() * 6.28;
bd.cruise = 250 + frng() * 90;
}
} else if (bd.state === 'takeoff') {
bd.vz = Math.min(230, bd.vz + 320 * dt);
bd.z += bd.vz * dt;
const sp = bd.speed * Math.min(1, (bd.z - g) / 140);
bd.x += Math.cos(bd.h) * sp * dt;
bd.y += Math.sin(bd.h) * sp * dt;
if (bd.z >= bd.cruise) { bd.z = bd.cruise; bd.state = 'fly'; }
}
}
const puffs = [];
// Nothing leaves the garden: inside the margin a gentle turn back toward the
// middle, and a hard stop at the very edge.
function keepInScene(a, dt, margin) {
const m = margin, W_ = innerWidth, H_ = LVH;
if (a.x < m || a.x > W_ - m || a.y < m || a.y > H_ - m) {
const want = Math.atan2(H_ / 2 - a.y, W_ / 2 - a.x);
const near = Math.max(
Math.max(0, (m - a.x) / m), Math.max(0, (a.x - (W_ - m)) / m),
Math.max(0, (m - a.y) / m), Math.max(0, (a.y - (H_ - m)) / m));
a.h += ((want - a.h + Math.PI * 3) % (Math.PI * 2) - Math.PI) * Math.min(1, dt * (1.2 + 5 * near));
}
a.x = Math.max(8, Math.min(W_ - 8, a.x));
a.y = Math.max(8, Math.min(H_ - 8, a.y));
}
function updateFauna(dt, t) {
if (reduceMotion.matches) return;
for (const pf of puffs) { pf.age += dt; pf.x += Math.cos(pf.a) * pf.sp * dt * (1 - pf.age / pf.life); pf.y += Math.sin(pf.a) * pf.sp * dt * (1 - pf.age / pf.life); }
for (let i = puffs.length - 1; i >= 0; i--) if (puffs[i].age >= puffs[i].life) puffs.splice(i, 1);
const night = isDark > 0.5;
for (const b of fauna.butterflies) {
// Night: the butterflies are moths, and the cursor light draws them in.
// They orbit it in nervous, jittery loops until it goes away.
if (night && ptr.active) {
const rx = light.x - b.x, ry = light.y - b.y, pd = Math.hypot(rx, ry);
const inward = Math.atan2(ry, rx);
const ring = 26 + (b.phase % 1) * 30;
const want = pd > ring + 40 ? inward : inward + (b.phase > 3.14 ? 1 : -1) * Math.PI / 2 + (pd < ring ? Math.PI * 0.6 : 0);
b.ang += ((want - b.ang + Math.PI * 3) % (Math.PI * 2) - Math.PI) * Math.min(1, dt * 7);
const sp = 70 + Math.min(90, pd * 0.3);
b.x += Math.cos(b.ang) * sp * dt + Math.sin(t * 13 + b.phase) * 60 * dt;
b.y += Math.sin(b.ang) * sp * dt + Math.cos(t * 11 + b.phase) * 60 * dt;
b.x = Math.max(-20, Math.min(innerWidth + 20, b.x)); b.y = Math.max(-20, Math.min(LVH + 20, b.y));
b.z = terrainJS(b.x, b.y) + 58 + Math.sin(t * 7 + b.phase) * 10;
b.flee = 0; b.wait = 0;
continue;
}
// Startled: a cursor that comes close sends the butterfly darting away,
// fast at first, easing off with distance, then it settles on a new flower.
const pd = ptr.active ? Math.hypot(ptr.x - b.x, ptr.y - b.y) : 1e9;
if (pd < 110) b.flee = 1;
if (b.flee) {
const away = Math.atan2(b.y - ptr.y, b.x - ptr.x);
b.ang += ((away - b.ang + Math.PI * 3) % (Math.PI * 2) - Math.PI) * Math.min(1, dt * 9);
const sp = 90 + 160 * Math.max(0, 1 - pd / 260);
b.x += Math.cos(b.ang) * sp * dt + Math.sin(t * 9 + b.phase) * 30 * dt;
b.y += Math.sin(b.ang) * sp * dt + Math.cos(t * 8 + b.phase) * 30 * dt;
b.x = Math.max(-20, Math.min(innerWidth + 20, b.x)); b.y = Math.max(-20, Math.min(LVH + 20, b.y));
b.z = terrainJS(b.x, b.y) + 70 + Math.sin(t * 6 + b.phase) * 8;
if (pd > 280 || !ptr.active) {
b.flee = 0;
let best = null, bd = 1e9;
for (const f of flowers) { const dd = Math.hypot(f.x - b.x, f.y - b.y) + (Math.hypot(f.x - ptr.x, f.y - ptr.y) < 200 ? 1e5 : 0); if (dd < bd) { bd = dd; best = f; } }
if (best) { b.tx = best.x; b.ty = best.y; }
b.wait = 0;
}
continue;
}
if (b.wait > 0) b.wait -= dt;
const dx = b.tx - b.x, dy = b.ty - b.y, d = Math.hypot(dx, dy);
if (d < 6) {
if (b.wait <= 0 && flowers.length) {
const f = flowers[Math.floor(frng() * flowers.length)];
b.tx = f.x; b.ty = f.y; b.wait = 3 + frng() * 5;
}
} else {
const sp = 40;
b.ang += ((Math.atan2(dy, dx) - b.ang + Math.PI * 3) % (Math.PI * 2) - Math.PI) * Math.min(1, dt * 4);
b.x += Math.cos(b.ang) * sp * dt + Math.sin(t * 5 + b.phase) * 14 * dt;
b.y += Math.sin(b.ang) * sp * dt + Math.cos(t * 4.3 + b.phase) * 14 * dt;
}
b.z = terrainJS(b.x, b.y) + (d < 6 ? 30 : 46) + Math.sin(t * 2.2 + b.phase) * 5;
}
fauna.birds.forEach((bd, i) => {
if (bd.state && bd.state !== 'fly') { groundedBird(bd, dt, t); return; }
// Curious: birds wheel around the cursor while it is on the page, each on
// its own radius and direction. The bird you are riding ignores it, so the
// view is not dragged around by your own pointer.
if (ptr.active && cam.subject !== bd) {
const rx = ptr.x - bd.x, ry = ptr.y - bd.y, pd = Math.hypot(rx, ry);
const ring = 110 + (i % 2) * 60, dir = i % 2 ? 1 : -1;
const inward = Math.atan2(ry, rx);
const tangent = inward + dir * Math.PI / 2;
const k = Math.max(0, Math.min(1, (pd - ring) / 220)); // far: head in; near: circle
const want = pd < ring * 0.7 ? inward + Math.PI : tangent + (inward - tangent) * k;
bd.h += ((want - bd.h + Math.PI * 3) % (Math.PI * 2) - Math.PI) * Math.min(1, dt * 2.2);
bd.x += Math.cos(bd.h) * (bd.speed + 30) * dt;
bd.y += Math.sin(bd.h) * (bd.speed + 30) * dt;
} else {
bd.x += Math.cos(bd.h) * bd.speed * dt;
bd.y += Math.sin(bd.h) * bd.speed * dt;
bd.h += Math.sin(t * 0.4 + bd.phase) * 0.12 * dt;
}
keepInScene(bd, dt, 90);
});
for (const f of fauna.foxes) {
// The fox notices a cursor that comes close and trots after it,
// stopping just short; it loses interest once the cursor is far away.
const pd = ptr.active ? Math.hypot(ptr.x - f.x, ptr.y - f.y) : 1e9;
if (!f.chase && pd < 170) { f.chase = true; f.pause = 0.25; }
if (f.chase && (pd > 320 || !ptr.active)) { f.chase = false; f.pause = 1.5; }
settleFox(f, dt);
if (f.pause > 0) { f.pause -= dt; continue; }
if (f.chase && pd < 26) continue;
const dx = (f.chase ? ptr.x : f.tx) - f.x, dy = (f.chase ? ptr.y : f.ty) - f.y;
if (!f.chase && Math.hypot(dx, dy) < 8) {
const p = randomClear(frng, 40);
if (p) { f.tx = p[0]; f.ty = p[1]; }
f.pause = 2 + frng() * 5;
continue;
}
const want = Math.atan2(dy, dx);
f.h += ((want - f.h + Math.PI * 3) % (Math.PI * 2) - Math.PI) * Math.min(1, dt * (f.chase ? 6 : 3));
const distance = (f.chase ? Math.min(95, 40 + pd * 0.35) : 34) * dt;
const nx = f.x + Math.cos(f.h) * distance, ny = f.y + Math.sin(f.h) * distance;
if (sdPondJS(nx, ny) > (f.chase ? 18 : 22) && (f.chase || offCards(nx, ny, 30) || !offCards(f.x, f.y, 30))) {
f.x = nx; f.y = ny;
f.walked = (f.walked || 0) + distance;
if (f.walked > 13) { f.walked = 0; dropPrint(f, t); }
} else if (!f.chase) {
f.pause = 0.5;
const p = randomClear(frng, 40);
if (p) { f.tx = p[0]; f.ty = p[1]; }
}
if (!f.chase) {
f.x = Math.max(14, Math.min(innerWidth - 14, f.x));
f.y = Math.max(14, Math.min(LVH - 14, f.y));
}
}
for (const fs of fauna.fish) {
// Spooked by a splash: dart away from it, then calm down over a second or two.
let sp = fs.speed;
if (fs.scare > 0) {
fs.scare -= dt;
const away = Math.atan2(fs.y - fs.sy, fs.x - fs.sx);
fs.h += ((away - fs.h + Math.PI * 3) % (Math.PI * 2) - Math.PI) * Math.min(1, dt * 10);
sp = fs.speed + 150 * Math.min(1, fs.scare / 1.4);
} else {
fs.h += (frng() - 0.5) * 1.2 * dt;
}
const ax = fs.x + Math.cos(fs.h) * 26, ay = fs.y + Math.sin(fs.h) * 26;
if (sdPondJS(ax, ay) > -16) {
const want = Math.atan2(fs.home.y - fs.y, fs.home.x - fs.x);
fs.h += ((want - fs.h + Math.PI * 3) % (Math.PI * 2) - Math.PI) * Math.min(1, dt * (fs.scare > 0 ? 8 : 4));
}
const nx = fs.x + Math.cos(fs.h) * sp * dt, ny = fs.y + Math.sin(fs.h) * sp * dt;
if (sdPondJS(nx, ny) < -8) { fs.x = nx; fs.y = ny; }
}
}
function addStill(t, still) {
for (const tr of trees) {
const sway = still ? 0 : Math.sin(t * 0.8 + tr.phase) * 2.2;
const swy = still ? 0 : Math.cos(t * 0.63 + tr.phase * 1.3) * 1.5;
const tz = tr.tz;
group(() => {
for (const p of tr.parts) {
const k = p.z / tr.H;
prim(tr.x + p.x + sway * k, tr.y + p.y + swy * k, tz + p.z, p.rx, p.ry, p.rz, p.th, p.kind, p.col, p.seed);
}
});
}
for (const b of bushes) {
group(() => {
for (const l of b.lobes) prim(b.x + l.dx, b.y + l.dy, b.tz + 9 + l.r * 0.45, l.r, l.r, l.r * 0.7, 0, 1, l.col, l.seed);
});
}
for (const c of clumps) {
group(() => {
for (const f of c.items) {
const sw = still ? 0 : Math.sin(t * 1.1 + f.phase) * 1.2;
prim(f.x + sw, f.y, f.tz + f.z, f.r, f.r, f.r * 0.5, 0, 2, f.col, f.seed);
}
});
}
for (const rk of rocks) {
group(() => prim(rk.x, rk.y, terrainJS(rk.x, rk.y) + rk.rz * 0.35, rk.rx, rk.ry, rk.rz, rk.th, 4.2, rk.col, rk.seed));
}
}
function addMoving(t, still) {
const moth = isDark > 0.5;
for (const b of fauna.butterflies) {
const px_ = Math.cos(b.ang + Math.PI / 2), py_ = Math.sin(b.ang + Math.PI / 2);
if (moth) {
// Moths: dusty, pale, fat-bodied, wings held wide and flat, a quick shallow flutter.
const flap = still ? 0.85 : 0.55 + 0.45 * Math.abs(Math.cos(t * 17 + b.phase));
const mc = [0.62, 0.56, 0.44], mb = [0.42, 0.36, 0.28];
const off = 2.4 + 4.6 * flap;
group(() => {
prim(b.x, b.y, b.z, 4.6, 1.9, 1.7, b.ang, 4, mb, 1);
prim(b.x + Math.cos(b.ang) * 4.2 + px_ * 1.6, b.y + Math.sin(b.ang) * 4.2 + py_ * 1.6, b.z + 1.2, 2.6, 0.5, 0.4, b.ang + 0.5, 4, mb, 17);
prim(b.x + Math.cos(b.ang) * 4.2 - px_ * 1.6, b.y + Math.sin(b.ang) * 4.2 - py_ * 1.6, b.z + 1.2, 2.6, 0.5, 0.4, b.ang - 0.5, 4, mb, 18);
prim(b.x + px_ * off - Math.cos(b.ang) * 1.2, b.y + py_ * off - Math.sin(b.ang) * 1.2, b.z + 1.2, 6.4, 5.4 * flap, 0.6, b.ang - 0.25, 4, mc, 2);
prim(b.x - px_ * off - Math.cos(b.ang) * 1.2, b.y - py_ * off - Math.sin(b.ang) * 1.2, b.z + 1.2, 6.4, 5.4 * flap, 0.6, b.ang + 0.25, 4, mc, 3);
});
continue;
}
const o = still ? 0.8 : 0.35 + 0.65 * Math.abs(Math.cos(t * 11 + b.phase));
const fx = Math.cos(b.ang), fy = Math.sin(b.ang), dk = b.col.map(c => c * 0.8);
group(() => {
prim(b.x, b.y, b.z, 4.8, 1.1, 1.1, b.ang, 4, [0.12, 0.1, 0.08], 1);
for (const sd of [1, -1]) {
prim(b.x + px_ * sd * (1.8 + 8.2 * o) + fx * 2.6, b.y + py_ * sd * (1.8 + 8.2 * o) + fy * 2.6, b.z + 1.5, 6.6, 9.4 * o, 0.7, b.ang + sd * 0.3, 4, b.col, 2);
prim(b.x + px_ * sd * (1.4 + 6.2 * o) - fx * 4.2, b.y + py_ * sd * (1.4 + 6.2 * o) - fy * 4.2, b.z + 1.3, 5.2, 7 * o, 0.7, b.ang - sd * 0.45, 4, dk, 3);
}
});
}
for (const bd of fauna.birds) {
const st = bd.state || 'fly';
const px_ = Math.cos(bd.h + Math.PI / 2), py_ = Math.sin(bd.h + Math.PI / 2);
const cx = Math.cos(bd.h), cy = Math.sin(bd.h);
if (st === 'flat' || st === 'up' || st === 'stand') {
// s = 1: pancaked on the ground, wings splayed. s = 0: standing, wings folded.
const s = st === 'stand' ? 0 : bd.squash;
const g = bd.z - 1.2;
const hz = bd.look || 0;
const twitch = st === 'stand' && !still ? Math.sin(t * 9 + bd.phase) * 0.15 : 0;
group(() => {
prim(bd.x, bd.y, g + 1.0 + 5.0 * (1 - s), 8 + 4 * s, 3.4 + 2.2 * s, 1.0 + 3.0 * (1 - s), bd.h, 4, bd.col, 4);
prim(bd.x + cx * (7.5 + 4.5 * s), bd.y + cy * (7.5 + 4.5 * s), g + 0.9 + 7.0 * (1 - s) + twitch, 2.8 + 0.6 * s, 2.6, 0.8 + 2.0 * (1 - s), bd.h + hz, 4, bd.col, 5);
const wo = 2.6 + 7 * s, wl = 1.4 + 11 * s;
prim(bd.x + px_ * wo + cx * 1.5 * s, bd.y + py_ * wo + cy * 1.5 * s, g + 0.7 + 2.6 * (1 - s), 5, wl, 0.6 + 0.8 * (1 - s), bd.h + 0.35 * s, 4, bd.col, 6);
prim(bd.x - px_ * wo + cx * 1.5 * s, bd.y - py_ * wo + cy * 1.5 * s, g + 0.7 + 2.6 * (1 - s), 5, wl, 0.6 + 0.8 * (1 - s), bd.h - 0.35 * s, 4, bd.col, 7);
if (s < 0.5) {
prim(bd.x + px_ * 1.6, bd.y + py_ * 1.6, g + 1.2, 0.5, 0.5, 1.4, bd.h, 4, [0.55, 0.42, 0.2], 19);
prim(bd.x - px_ * 1.6, bd.y - py_ * 1.6, g + 1.2, 0.5, 0.5, 1.4, bd.h, 4, [0.55, 0.42, 0.2], 20);
}
});
continue;
}
const ph = t * (st === 'takeoff' ? 9 : 5) + bd.phase;
const sp = still ? 0.95 : st === 'fall' ? 0.45 : 0.72 + 0.28 * Math.abs(Math.cos(ph));
const lift = still ? 0 : Math.sin(ph) * 3;
const dh = ((bd.h - (bd.ph ?? bd.h)) + Math.PI * 3) % (Math.PI * 2) - Math.PI;
bd.ph = bd.h;
bd.bank = (bd.bank || 0) + (Math.max(-0.6, Math.min(0.6, dh * 25)) - (bd.bank || 0)) * 0.08;
group(() => {
prim(bd.x, bd.y, bd.z, 8, 3, 2.8, bd.h, 4.05, bd.col, 4);
prim(bd.x + cx * 8.5, bd.y + cy * 8.5, bd.z + 0.8, 3.2, 2.7, 2.5, bd.h, 4.05, bd.col, 5);
prim(bd.x + cx * 12, bd.y + cy * 12, bd.z + 0.4, 2.2, 0.9, 0.8, bd.h, 4, [0.3, 0.27, 0.22], 18);
prim(bd.x - cx * 9.5, bd.y - cy * 9.5, bd.z, 4.6, 3.6, 0.6, bd.h, 4.05, bd.col, 21);
for (const sd of [1, -1]) {
const z = bd.z + 1.5 + lift + sd * bd.bank * 7;
const w = (k, back) => [bd.x + px_ * sd * k * sp - cx * back, bd.y + py_ * sd * k * sp - cy * back];
let [x, y] = w(9.5, 1.4); prim(x, y, z + lift * 0.4, 4.6, 10 * sp, 0.7, bd.h - sd * 0.12, 4.05, bd.col, 6);
[x, y] = w(8.5, -0.6); prim(x, y, z + lift * 0.4 + 0.4, 2.2, 8 * sp, 0.5, bd.h - sd * 0.12, 4.05, bd.col.map(c => c * 1.6 + 0.06), 23);
[x, y] = w(20, 4.6); prim(x, y, z + lift, 2.4, 5 * sp, 0.5, bd.h - sd * 0.55, 4.05, bd.col.map(c => c * 0.65), 7);
}
});
}
for (const fs of fauna.fish) {
const z = -pondDepthJS(fs.x, fs.y) * 0.55;
const wag = still ? 0 : Math.sin(t * (fs.scare > 0 ? 16 : 6) + fs.phase) * 0.5;
const ta = fs.h + Math.PI + wag;
group(() => {
prim(fs.x, fs.y, z, 9, 3.2, 2.6, fs.h, 5, fs.col, 15);
prim(fs.x + Math.cos(ta) * 11, fs.y + Math.sin(ta) * 11, z, 4, 2.6, 1.2, ta, 5, fs.col, 16);
});
}
}
function updateFoxPose(fox, distance, dt, t) {
const traveled = fox.hop ? 0 : distance;
fox.gait = ((fox.gait ?? 0) + traveled / 24) % 1;
const stride = fox.stride ?? 0;
const targetStride = traveled > 0 ? 1 : 0;
fox.stride = reduceMotion.matches ? 0 : stride + (targetStride - stride) * (1 - Math.exp(-dt * 18));
fox.wag = reduceMotion.matches ? 0 : Math.sin(t * 3 + fox.phase) * 0.35;
fox.z = 11 + (fox.gz ?? terrainJS(fox.x, fox.y)) + Math.cos(fox.gait * 4 * Math.PI) * 0.55 * fox.stride;
}
function buildObjects(t) {
beginFrameObjects();
addStill(t, reduceMotion.matches);
addMoving(t, reduceMotion.matches);
uploadObjects();
}
// The baked garden: plants and rocks at rest, and the tiles that index them.
function buildStill() {
beginFrameObjects();
addStill(0, true);
ngS = ng; npS = np;
uploadObjects();
}
// Each frame only the critters change: they go after the still things, and
// only their rows of the object texture are sent.
function buildMoving(t) {
ng = ngS; np = npS;
addMoving(t, reduceMotion.matches);
gl.bindTexture(gl.TEXTURE_2D, objTex);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, TEXW, 1, gl.RGBA, gl.FLOAT, objData, 0);
const r0 = (PBASE + 3 * npS) >> 8, r1 = (PBASE + 3 * Math.max(np, npS + 1) - 1) >> 8;
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, r0, TEXW, r1 - r0 + 1, gl.RGBA, gl.FLOAT, objData, r0 * TEXW * 4);
nd = Math.min(ng - ngS, 24);
dynData.set(objData.subarray(2 * ngS * 4, 2 * ngS * 4 + nd * 8).filter((_, i) => i % 8 < 4));
}
// ---------- Footprints: a ground decal layer the fox writes into ----------
const prints = [];
const decal = document.createElement('canvas');
const dctx = decal.getContext('2d');
const decalTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, decalTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0,0,0,0]));
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
const PRINT_LIFE = 28;
function dropPrint(f, t) {
prints.push({ x: f.x, y: f.y, h: f.h, side: f.step = !f.step, born: t });
if (prints.length > 160) prints.shift();
}
function paintPrints(t) {
const sc = 0.5;
const w = Math.max(1, Math.floor(innerWidth * sc)), hh = Math.max(1, Math.floor(LVH * sc));
if (decal.width !== w || decal.height !== hh) { decal.width = w; decal.height = hh; }
dctx.setTransform(sc, 0, 0, sc, 0, 0);
dctx.clearRect(0, 0, innerWidth, LVH);
while (prints.length && t - prints[0].born > PRINT_LIFE) prints.shift();
for (const p of prints) {
const age = (t - p.born) / PRINT_LIFE;
const a = 0.9 * (1 - age * age);
dctx.save();
dctx.translate(p.x, p.y); dctx.rotate(p.h);
const side = p.side ? 4.5 : -4.5;
dctx.fillStyle = `rgba(20,14,8,${a})`;
dctx.beginPath(); dctx.ellipse(-1.5, side, 3.2, 2.4, 0, 0, 6.283); dctx.fill();
for (let k = -1.5; k <= 1.5; k++) { dctx.beginPath(); dctx.ellipse(3.2 - Math.abs(k) * 0.5, side + k * 1.9, 1.15, 1.35, 0, 0, 6.283); dctx.fill(); }
dctx.restore();
}
gl.bindTexture(gl.TEXTURE_2D, decalTex);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, decal);
}
// ---------- Air: pollen by day, fireflies by night ----------
let motes = [];
function spawnAir() {
motes = [];
const n = Math.round(innerWidth * LVH / 22000);
for (let i = 0; i < n; i++) motes.push({ x: Math.random() * innerWidth, y: Math.random() * LVH, s: 0.8 + Math.random() * 1.6, p: Math.random() * 6.28, v: 0.4 + Math.random() * 0.8 });
}
function drawAir(t, dt) {
let n = 0;
const put = (x, y, r, a, cr, cg, cb, soft) => { if (n >= AIRN) return; const o = n++ * 10, d = airData; d[o] = x; d[o + 1] = y; d[o + 2] = r; d[o + 3] = a; d[o + 4] = soft; d[o + 6] = cr; d[o + 7] = cg; d[o + 8] = cb; };
const night = isDark > 0.5;
for (const pf of puffs) {
const k = pf.age / pf.life;
put(pf.x, pf.y, pf.r * (0.6 + k), 0.55 * (1 - k), night ? 0.47 : 0.84, night ? 0.43 : 0.76, night ? 0.35 : 0.59, 0);
}
for (const m of motes) {
if (!reduceMotion.matches) {
m.x += (Math.sin(t * 0.3 + m.p) * 6 + 4) * m.v * dt;
m.y += (Math.cos(t * 0.25 + m.p * 1.7) * 5 - 2) * m.v * dt;
if (m.x < -10) m.x = innerWidth + 10; if (m.x > innerWidth + 10) m.x = -10;
if (m.y < -10) m.y = LVH + 10; if (m.y > LVH + 10) m.y = -10;
}
if (night) {
const pulse = 0.35 + 0.65 * Math.max(0, Math.sin(t * 1.3 + m.p * 3));
if (pulse >= 0.4) put(m.x, m.y, 6 + m.s * 4, pulse, 0.9, 1, 0.5, 1);
} else put(m.x, m.y, m.s, 0.18 + 0.22 * (0.5 + 0.5 * Math.sin(t * 0.9 + m.p)), 1, 0.96, 0.78, 0);
}
if (!n || !airP.ok) return;
gl.useProgram(airP.p);
gl.uniform2f(airP.u.u_res, W, H);
gl.uniform1f(airP.u.u_dpr, dpr);
gl.uniform4f(airP.u.u_cam, cam.x * dpr, cam.y * dpr, cam.ang, cam.zoom);
gl.bindBuffer(gl.ARRAY_BUFFER, airBuf);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, airData, 0, n * 10);
[[0, 2, 0], [1, 4, 8], [2, 4, 24]].forEach(([i, k, off]) => { gl.enableVertexAttribArray(i); gl.vertexAttribPointer(i, k, gl.FLOAT, false, 40, off); });
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, night ? gl.ONE : gl.ONE_MINUS_SRC_ALPHA);
gl.drawArrays(gl.POINTS, 0, n);
gl.disable(gl.BLEND);
gl.disableVertexAttribArray(1); gl.disableVertexAttribArray(2);
}
addEventListener('resize', () => { const h = sceneHeight(); if (innerWidth === LVW && h === LVH) return; LVW = innerWidth; LVH = h; scale = top() * TIERS[Math.max(0, tier)]; resize(); }, { passive: true });
resize();
// ---------- Follow camera ----------
// The scene is drawn straight down, so riding with an animal means keeping it
// centred, turning the world so its heading points up, and moving in close.
const cam = { x: innerWidth / 2, y: LVH / 2, ang: 0, zoom: 1, mode: null, subject: null, k: 0 };
function camDesired() {
const s0 = cam.subject;
if (!s0) return null;
// Birds and the fox steer by h; a moth by ang.
const h = s0.h !== undefined ? s0.h : (s0.ang || 0);
const zoom = cam.kind === 'moth' ? 3.6 : cam.kind === 'fox' ? 3.0 : 2.3;
const back = 0.13 * LVH / zoom;
return { x: s0.x + Math.cos(h) * back, y: s0.y + Math.sin(h) * back, ang: h + Math.PI / 2, zoom };
}
function stepCam(dt) {
const d = camDesired();
const lerp = 1 - Math.pow(0.0025, Math.min(dt, 0.05));
if (d) {
cam.k = Math.min(1, cam.k + dt * 1.5);
cam.x += (d.x - cam.x) * lerp;
cam.y += (d.y - cam.y) * lerp;
// The view turns with the animal, but never faster than the eye can
// follow, so a tight turn banks the world instead of spinning it.
const da = (d.ang - cam.ang + Math.PI * 3) % (Math.PI * 2) - Math.PI;
const maxTurn = 0.9 * Math.min(dt, 0.05);
cam.ang += Math.max(-maxTurn, Math.min(maxTurn, da * lerp * 0.5));
cam.zoom += (d.zoom - cam.zoom) * lerp * 0.6;
} else if (cam.k > 0) {
cam.k = Math.max(0, cam.k - dt * 1.5);
cam.x += (innerWidth / 2 - cam.x) * lerp;
cam.y += (LVH / 2 - cam.y) * lerp;
cam.ang += (((0 - cam.ang + Math.PI * 3) % (Math.PI * 2) - Math.PI)) * lerp * 0.7;
cam.zoom += (1 - cam.zoom) * lerp * 0.6;
if (Math.abs(cam.zoom - 1) < 0.004 && Math.abs(cam.ang) < 0.01) { cam.zoom = 1; cam.ang = 0; cam.k = 0; }
} else {
// At rest the camera is exactly the plain top-down view, and stays that
// way through a resize.
cam.x = innerWidth / 2; cam.y = LVH / 2; cam.ang = 0; cam.zoom = 1;
}
}
const camOn = () => cam.zoom !== 1 || cam.ang !== 0;
// Screen pixels to garden pixels, so the cursor still lights and startles
// the right patch of ground while the camera is riding along.
function toWorld(sx, sy) {
if (!camOn()) return [sx, sy];
const dx = (sx - innerWidth / 2) / cam.zoom, dy = (sy - LVH / 2) / cam.zoom;
const c = Math.cos(cam.ang), sn = Math.sin(cam.ang);
return [cam.x + c * dx - sn * dy, cam.y + sn * dx + c * dy];
}
// ---------- Light and ripples ----------
const ptr = { x: -1e4, y: -1e4, active: false, seen: 0 };
const rest = () => [innerWidth * 0.32, LVH * 0.12];
const light = { x: rest()[0], y: rest()[1], z: 900, tx: rest()[0], ty: rest()[1], idle: true };
const pending = [];
let lastPtr = { x: 0, y: 0, t: 0 };
let touch = null;
addEventListener('pointerdown', e => { if (e.pointerType === 'touch') touch = { x: e.clientX, y: e.clientY, t: performance.now(), sy: scrollY }; }, { passive: true, capture: true });
addEventListener('pointerup', e => {
if (e.pointerType !== 'touch' || !touch) return;
const tap = performance.now() - touch.t < 400 && Math.hypot(e.clientX - touch.x, e.clientY - touch.y) <= 10 && Math.abs(scrollY - touch.sy) < 2;
touch = null;
if (!tap) return;
const [wx, wy] = toWorld(e.clientX, e.clientY);
light.tx = wx; light.ty = wy; light.idle = false;
ptr.x = wx; ptr.y = wy; ptr.active = true; ptr.seen = performance.now();
if (e.target.closest && e.target.closest('main.card,.g-sheet,a,button,input,label,.g-ride')) return;
if (knockBird(wx, wy)) return;
if (sdPondJS(wx, wy) < 0) splash({ x: wx, y: wy, r: 20, s: 0.4 });
}, { passive: true });
addEventListener('pointercancel', () => { touch = null; }, { passive: true });
addEventListener('pointermove', e => {
if (e.pointerType === 'touch') return;
const [wx, wy] = toWorld(e.clientX, e.clientY);
light.tx = wx; light.ty = wy; light.idle = false;
ptr.x = wx; ptr.y = wy; ptr.active = true; ptr.seen = performance.now();
const cur = birdUnder(wx, wy) ? 'pointer' : '';
if (cur !== mainCursor) { mainCursor = cur; mainEl.style.cursor = cur; }
const now = performance.now();
if (sdPondJS(wx, wy) < 0 && now - lastPtr.t > 30) {
const speed = Math.hypot(wx - lastPtr.x, wy - lastPtr.y);
splash({ x: wx, y: wy, r: 14 + Math.min(12, speed * 0.3), s: 0.07 + Math.min(0.2, speed * 0.008) });
lastPtr.t = now;
}
lastPtr.x = wx; lastPtr.y = wy;
}, { passive: true });
document.addEventListener('pointerleave', () => { light.idle = true; ptr.active = false; });
addEventListener('pointerdown', e => {
if (e.pointerType === 'touch') return;
const [wx, wy] = toWorld(e.clientX, e.clientY);
if (knockBird(wx, wy)) return;
if (sdPondJS(wx, wy) < 0) splash({ x: wx, y: wy, r: 20, s: 0.4 });
});
const mainEl = form; let mainCursor = '';
function birdUnder(x, y) {
return fauna.birds.some(bd => (!bd.state || bd.state === 'fly') && Math.hypot(bd.x - x, bd.y - y) < 34);
}
function splash(d) {
pending.push(d);
for (const fs of fauna.fish) {
const dd = Math.hypot(fs.x - d.x, fs.y - d.y);
if (dd < 140 && d.s > 0.06) { fs.scare = Math.max(fs.scare || 0, 1.6 * (0.5 + d.s)); fs.sx = d.x; fs.sy = d.y; }
}
}
let nextDrip = 0, nextFishRipple = 0;
function drip(now) {
if (now < nextDrip || ponds.length === 0 || reduceMotion.matches) return;
nextDrip = now + 2000 + Math.random() * 3500;
const c = ponds[Math.floor(Math.random() * ponds.length)];
const a = Math.random() * 6.283, d = Math.random() * c.r * 0.7;
pending.push({ x: c.x + Math.cos(a) * d, y: c.y + Math.sin(a) * d, r: 10 + Math.random() * 8, s: 0.08 + Math.random() * 0.08 });
}
const H_AMP = 18;
const pondData = new Float32Array(MAXP * 4);
let start = performance.now(), last = start, readyFrames = 0, simAcc = 0;
function adopt() {
let s = null;
try { s = JSON.parse(sessionStorage.getItem(KEY) || 'null'); } catch (e) {}
if (!s || s.size !== sceneSize(LVW, LVH) || !fresh(s.at)) return;
last = performance.now();
start = last - (s.t * 1000 + Date.now() - s.at);
light.x = s.light.x; light.y = s.light.y;
try { unpackFauna(s.fauna); } catch (e) {}
if (Array.isArray(s.motes)) motes = s.motes;
}
adopt();
let posterMode = false;
function checkpoint() {
if (!ready || lost) return;
try {
sessionStorage.setItem(KEY, JSON.stringify({ size: sceneSize(LVW, LVH), at: Date.now(), t: (performance.now() - start) / 1000, light: { x: light.x, y: light.y }, fauna: packFauna(), motes }));
} catch (e) {}
}
function keep() {
try {
if (!shown || camOn() || lost || !ready) return;
// A still of the garden alone (no cards), shown at once by the next page while its scene wakes up.
posterMode = true; render(performance.now());
const k = 0.6, c = document.createElement('canvas');
c.width = Math.round(innerWidth * k); c.height = Math.round(LVH * k);
c.getContext('2d').drawImage(canvas, 0, 0, c.width, c.height);
sessionStorage.setItem(KEY + '.poster', JSON.stringify({ size: sceneSize(LVW, LVH), at: Date.now(), dark: isDark > 0.5, url: c.toDataURL('image/jpeg', 0.72) }));
} catch (e) {} finally { posterMode = false; checkpoint(); }
}
addEventListener('pagehide', keep);
document.addEventListener('visibilitychange', () => { if (document.hidden) checkpoint(); });
addEventListener('pageshow', e => { if (e.persisted) adopt(); });
function setPondUniforms(prog) {
gl.uniform4fv(prog.u.u_pond, pondData);
gl.uniform1i(prog.u.u_np, ponds.length);
gl.uniform1f(prog.u.u_pk, POND_K * dpr);
}
function simulate(steps) {
gl.viewport(0, 0, simW, simH);
gl.disable(gl.BLEND);
const texel = [1 / simW, 1 / simH];
for (let step = 0; step < steps; step++) {
const nxt = 1 - cur;
gl.bindFramebuffer(gl.FRAMEBUFFER, simFB[nxt]);
gl.useProgram(sim.p);
gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, simTex[cur]);
gl.uniform1i(sim.u.u_prev, 0);
gl.uniform2f(sim.u.u_texel, texel[0], texel[1]);
gl.uniform2f(sim.u.u_res, W, H);
gl.uniform1f(sim.u.u_dpr, dpr);
setPondUniforms(sim);
drawQuad(sim);
cur = nxt;
}
while (pending.length) {
const d = pending.shift();
const nxt = 1 - cur;
gl.bindFramebuffer(gl.FRAMEBUFFER, simFB[nxt]);
gl.useProgram(drop.p);
gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, simTex[cur]);
gl.uniform1i(drop.u.u_prev, 0);
gl.uniform2f(drop.u.u_texel, texel[0], texel[1]);
gl.uniform2f(drop.u.u_res, W, H);
gl.uniform2f(drop.u.u_center, d.x * dpr, d.y * dpr);
gl.uniform1f(drop.u.u_radius, d.r * dpr);
gl.uniform1f(drop.u.u_strength, d.s);
drawQuad(drop);
cur = nxt;
}
gl.bindFramebuffer(gl.FRAMEBUFFER, cauFB);
gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE);
gl.useProgram(cau.p);
gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, simTex[cur]);
gl.uniform1i(cau.u.u_sim, 0);
gl.uniform2f(cau.u.u_texel, texel[0], texel[1]);
gl.uniform2f(cau.u.u_res, W, H);
gl.uniform1f(cau.u.u_dpr, dpr);
gl.uniform3f(cau.u.u_light, light.x * dpr, light.y * dpr, light.z * dpr);
gl.uniform1f(cau.u.u_hAmp, H_AMP * dpr);
setPondUniforms(cau);
gl.bindBuffer(gl.ARRAY_BUFFER, mesh.vb);
gl.enableVertexAttribArray(cau.a.a_uv);
gl.vertexAttribPointer(cau.a.a_uv, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, mesh.ib);
gl.drawElements(gl.TRIANGLES, mesh.count, gl.UNSIGNED_INT, 0);
gl.disable(gl.BLEND);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
const SAMPLERS = ['u_sim', 'u_caust', 'u_prims', 'u_tGrass', 'u_tGrass2', 'u_tSand', 'u_tDirt', 'u_tBark', 'u_decal', 'u_b0', 'u_b1', 'u_b2', 'u_b3', 'u_atmo', 'u_soft'];
function sceneUniforms(prog, t) {
gl.useProgram(prog.p);
const su = prog.u;
gl.uniform2f(su.u_res, W, H);
gl.uniform1f(su.u_dpr, dpr);
gl.uniform1f(su.u_time, t);
gl.uniform3f(su.u_light, light.x * dpr, light.y * dpr, light.z * dpr);
gl.uniform1f(su.u_lr, 22 * dpr);
gl.uniform1i(su.u_ng, ng);
if (su.u_ng0) gl.uniform1i(su.u_ng0, ngS);
gl.uniform1f(su.u_tile, TILE * dpr);
gl.uniform1i(su.u_tilesX, tilesX);
gl.uniform3fv(su.u_ground, colors.ground);
gl.uniform3fv(su.u_ground2, colors.ground2);
gl.uniform1f(su.u_dark, isDark);
setPondUniforms(prog);
const binds = [hasSim ? simTex[cur] : blankTex, hasSim ? cauTex : blankTex, objTex, tex.grass, tex.grass2, tex.sand, tex.dirt, tex.bark, decalTex,
material?.tx[0], material?.tx[1], material?.tx[2], material?.tx[3], atmo?.tx[0], soft?.tx[0]];
if (su.u_dyn) { gl.uniform4fv(su.u_dyn, dynData); gl.uniform1i(su.u_nd, nd); }
const fx = fauna.foxes[0];
if (su.u_fox) {
gl.uniform4f(su.u_fox, fx ? fx.x * dpr : 0, fx ? fx.y * dpr : 0, fx?.h ?? 0, fx ? 1.4 * dpr : 0);
gl.uniform4f(su.u_fox2, fx?.gait ?? 0, fx?.wag ?? 0, fx ? (fx.z ?? 11) * 1.4 * dpr : 0, fx?.stride ?? 0);
}
let unit = 0;
SAMPLERS.forEach((name, i) => { if (!su[name]) return; gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, binds[i] || blankTex); gl.uniform1i(su[name], unit++); });
if (su.u_texel) gl.uniform2f(su.u_texel, 1 / simW, 1 / simH);
if (su.u_hAmp) gl.uniform1f(su.u_hAmp, H_AMP * dpr);
if (su.u_hasSim) gl.uniform1f(su.u_hasSim, hasSim ? 1 : 0);
}
let shown = false, lost = false;
// A lost context gives the page back to paper rather than leave a hidden card.
canvas.addEventListener('webglcontextlost', () => { lost = true; root.classList.remove('garden-scene'); canvas.remove(); if (posterEl) posterEl.remove(); for (const el of document.querySelectorAll('.g-ride,.g-toast')) el.remove(); document.body.classList.remove('g-riding', 'g-night'); });
function render(now) {
const dt = Math.max(0, Math.min(0.05, (now - last) / 1000)); last = now;
const t = reduceMotion.matches ? 0 : Math.max(0, (now - start) / 1000);
const ease = light.idle && !reduceMotion.matches ? -Math.expm1(-dt / 0.29) : 1;
if (light.idle) {
const r0 = rest();
light.tx = r0[0] + Math.sin(t * 0.21) * innerWidth * 0.18;
light.ty = r0[1] + Math.cos(t * 0.17) * LVH * 0.08;
}
light.x += (light.tx - light.x) * ease;
light.y += (light.ty - light.y) * ease;
for (let i = 0; i < MAXP; i++) {
const c = ponds[i];
pondData[i*4+0] = c ? c.x * dpr : 0; pondData[i*4+1] = c ? c.y * dpr : 0; pondData[i*4+2] = c ? c.r * dpr : 0; pondData[i*4+3] = 0;
}
if (ptr.active && now - ptr.seen > 12000) { ptr.active = false; light.idle = true; }
stepCam(dt);
const fox = fauna.foxes[0];
const foxX = fox?.x, foxY = fox?.y;
updateFauna(dt, t);
if (fox) updateFoxPose(fox, Math.hypot(fox.x - foxX, fox.y - foxY), dt, t);
const live = !baking || camOn();
if (live) { objMode = 1; buildObjects(t); }
else {
if (objMode !== 2 || rebake) {
objMode = 2;
buildStill();
}
if (rebake) {
rebake = false;
renderTarget(material, bakeP, 0);
renderTarget(soft, softP, 0);
}
buildMoving(t);
}
drip(now);
if (now > nextFishRipple && fauna.fish.length && !reduceMotion.matches) {
nextFishRipple = now + 3500 + Math.random() * 5000;
const fs = fauna.fish[Math.floor(Math.random() * fauna.fish.length)];
pending.push({ x: fs.x, y: fs.y, r: 9, s: 0.12 });
}
if (hasSim) { simAcc = Math.min(simAcc + dt * 60, 3); const n = Math.floor(simAcc); if (n) { simAcc -= n; simulate(n); } }
paintPrints(t);
if (!live) renderTarget(atmo, atmoP, t);
gl.viewport(0, 0, W, H);
const prog = live ? scene : compP;
sceneUniforms(prog, t);
gl.uniform4f(prog.u.u_cam, cam.x * dpr, cam.y * dpr, cam.ang, cam.zoom);
if (!live) gl.uniform1f(prog.u.u_sway, reduceMotion.matches ? 0 : 1);
drawQuad(prog);
drawAir(t, dt);
if (!shown && !posterMode && ((texReady >= 5 && ++readyFrames >= 2) || now - bornAt > 1500)) {
shown = true; root.classList.add('garden-scene');
if (posterEl) { posterEl.classList.add('g-gone'); setTimeout(() => posterEl.remove(), 400); }
}
}
const bornAt = performance.now();
let drawn = 0, idleSince = performance.now(), looping = true;
for (const ev of ['pointermove', 'pointerdown', 'keydown', 'wheel', 'touchstart']) addEventListener(ev, () => { idleSince = performance.now(); }, { passive: true });
// Wait for the programs, then measure once which resolution this device holds.
function warm() {
if (!progs.every(settle)) return false;
if (!scene.ok) { canvas.dispatchEvent(new Event('webglcontextlost')); return false; }
baking = !!(bakeP.ok && compP.ok && atmoP.ok && softP.ok && gl.getParameter(gl.MAX_DRAW_BUFFERS) >= 4);
if (!(sim && sim.ok && drop.ok && cau.ok)) hasSim = false;
ready = true;
if (tier < 0) {
const px = new Uint8Array(4);
for (tier = 0; tier < TIERS.length; tier++) {
scale = top() * TIERS[tier]; applyScale();
render(performance.now()); gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
const t0 = performance.now();
for (let k = 0; k < 4; k++) render(performance.now());
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
if ((performance.now() - t0) / 4 < 9 || tier === TIERS.length - 1) break;
}
try { sessionStorage.setItem(TIER_KEY, String(tier)); } catch (e) {}
} else applyScale();
last = performance.now();
return true;
}
function frame(now) {
if (lost || document.hidden) { looping = false; return; }
requestAnimationFrame(frame);
if (!ready && !warm()) return;
const slow = tier === TIERS.length - 1 || (now - idleSince > 12000 && !camOn());
if (now - drawn < (slow ? 31 : 14.5)) return;
drawn = now;
render(now);
}
document.addEventListener('visibilitychange', () => { if (!document.hidden && !looping && !lost) { looping = true; last = performance.now(); requestAnimationFrame(frame); } });
requestAnimationFrame(frame);
live = true;
// ---------- Ride group, day/night switch and toast ----------
const rideBox = document.createElement('div');
rideBox.innerHTML = "<div class=\"g-ride\" role=\"group\" aria-label=\"Ride along\">\n <button type=\"button\" id=\"ride-bird\" aria-pressed=\"false\" aria-label=\"See through a bird\" title=\"See through a bird\">\n <svg class=\"at-day\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M1.5 14.5C3.6 9.6 8 8.2 10.9 11.3L12 12.6l1.1-1.3c2.9-3.1 7.3-1.7 9.4 3.2-2.7-2.2-5.7-2.3-7.9-.3l-2 1.9a.9.9 0 0 1-1.2 0l-2-1.9c-2.2-2-5.2-1.9-7.9.3z\"/></svg>\n <svg class=\"at-night\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 7.6c.5-1.5 1.6-2.7 3-3.6 2.2-1.4 4.6-1.5 5.6-.2 1.1 1.5.6 4.3-1.1 6.6-1 1.4-2.3 2.4-3.6 2.9 1 .3 1.8 1 2.3 1.9.7 1.4.4 2.9-.7 3.4-1.1.5-2.6-.2-3.6-1.6-.6-.8-.9-1.7-1-2.5h-1.8c-.1.8-.4 1.7-1 2.5-1 1.4-2.5 2.1-3.6 1.6-1.1-.5-1.4-2-.7-3.4.5-.9 1.3-1.6 2.3-1.9-1.3-.5-2.6-1.5-3.6-2.9C2.8 8.1 2.3 5.3 3.4 3.8c1-1.3 3.4-1.2 5.6.2 1.4.9 2.5 2.1 3 3.6zM12 8.2c-.5 0-.9.5-.9 1.4 0 .7.2 2.1.4 3.2.1.6.3 1 .5 1s.4-.4.5-1c.2-1.1.4-2.5.4-3.2 0-.9-.4-1.4-.9-1.4z\"/></svg>\n </button>\n <button type=\"button\" id=\"ride-fox\" aria-pressed=\"false\" aria-label=\"See through the fox\" title=\"See through the fox\">\n <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path fill-rule=\"evenodd\" d=\"M2.6 2.8l5.6 3.6h7.6l5.6-3.6-1.1 7.4c-.4 2.6-1.8 4.9-3.9 6.5L12 20.6l-4.4-3.9c-2.1-1.6-3.5-3.9-3.9-6.5zM8.7 10.2a1.15 1.15 0 1 0 0 2.3 1.15 1.15 0 0 0 0-2.3zm6.6 0a1.15 1.15 0 1 0 0 2.3 1.15 1.15 0 0 0 0-2.3zM12 15.2l-1.4 1 1.4 1.2 1.4-1.2z\"/></svg>\n </button>\n <button type=\"button\" id=\"garden-theme\" aria-label=\"Day and night\" title=\"Day and night\"><svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"\"/></svg></button>\n <button type=\"button\" id=\"garden-bare\" aria-pressed=\"false\" aria-label=\"Just the garden\" title=\"Just the garden\"><svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M4 9V5.5A1.5 1.5 0 0 1 5.5 4H9v2H6v3zM15 4h3.5A1.5 1.5 0 0 1 20 5.5V9h-2V6h-3zM20 15v3.5a1.5 1.5 0 0 1-1.5 1.5H15v-2h3v-3zM9 20H5.5A1.5 1.5 0 0 1 4 18.5V15h2v3h3z\"/></svg></button>\n <span class=\"g-exit\" id=\"ride-exit\">Esc to step out</span>\n</div>\n\n<div class=\"g-toast\" id=\"g-toast\" role=\"status\"></div>";
document.body.append(...rideBox.children);
const THEME_ICON = { system: 'M12 2.5a9.5 9.5 0 1 0 0 19 9.5 9.5 0 0 0 0-19zm0 2v15a7.5 7.5 0 0 1 0-15z', light: 'M12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10zM11 1h2v3h-2zM11 20h2v3h-2zM1 11h3v2H1zM20 11h3v2h-3zM4.2 5.6l1.4-1.4 2.1 2.1-1.4 1.4zM16.3 17.7l1.4-1.4 2.1 2.1-1.4 1.4zM4.2 18.4l2.1-2.1 1.4 1.4-2.1 2.1zM16.3 6.3l2.1-2.1 1.4 1.4-2.1 2.1z', dark: 'M20.6 14.9A9 9 0 0 1 9.1 3.4a9 9 0 1 0 11.5 11.5z' };
const themeBtn = document.getElementById('garden-theme');
const themeNow = () => root.dataset.theme === 'light' || root.dataset.theme === 'dark' ? root.dataset.theme : 'system';
function paintTheme() {
const th = themeNow(), name = { system: 'match the system', light: 'day', dark: 'night' }[th];
themeBtn.querySelector('path').setAttribute('d', THEME_ICON[th]);
themeBtn.title = 'Day and night: ' + name; themeBtn.setAttribute('aria-label', themeBtn.title);
}
themeBtn.addEventListener('click', () => {
const order = ['system', 'light', 'dark'], nx = order[(order.indexOf(themeNow()) + 1) % 3];
try { if (nx === 'system') localStorage.removeItem('zds.theme'); else localStorage.setItem('zds.theme', nx); } catch (e) {}
if (nx === 'system') delete root.dataset.theme; else root.dataset.theme = nx;
paintTheme();
showToast(nx === 'system' ? 'Day and night follow your system.' : nx === 'light' ? 'Day.' : 'Night.');
});
new MutationObserver(paintTheme).observe(root, { attributes: true, attributeFilter: ['data-theme'] });
paintTheme();
const toast = document.getElementById('g-toast');
let toastTimer;
function showToast(msg) {
toast.textContent = msg;
toast.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove('show'), 2800);
}
// ---------- Ride along ----------
var rideReady = false;
const rideBtns = { bird: document.getElementById('ride-bird'), fox: document.getElementById('ride-fox') };
const rideExit = document.getElementById('ride-exit');
// After dark the birds have gone to roost, so the wing you ride is a moth's.
function pickFlier() {
if (isDark > 0.5 && fauna.butterflies.length) { cam.kind = 'moth'; return fauna.butterflies[0]; }
cam.kind = 'bird';
return fauna.birds.find(b => !b.state || b.state === 'fly') || fauna.birds[0];
}
function setRide(mode) {
if (cam.mode === mode) mode = null;
if (mode === 'bird') cam.subject = pickFlier();
else if (mode === 'fox') { cam.kind = 'fox'; cam.subject = fauna.foxes[0]; }
else { cam.subject = null; cam.kind = null; }
if (!cam.subject) mode = null;
cam.mode = mode;
document.body.classList.toggle('g-riding', !!mode);
rideExit.classList.toggle('show', !!mode);
for (const k in rideBtns) rideBtns[k].setAttribute('aria-pressed', String(k === mode));
if (mode) showToast(mode === 'fox' ? 'Riding with the fox. Esc to step out.'
: cam.kind === 'moth' ? 'Riding with a moth. Esc to step out.' : 'Riding with a bird. Esc to step out.');
}
// Day and night swap the flier under the first button, label and all, even
// mid-ride when the theme changes.
// var, not const: readTokens runs before the buttons exist and must find this
// false rather than a dead zone.
function refreshRide() {
if (!rideReady) return;
const night = isDark > 0.5;
const label = night ? 'See through a moth' : 'See through a bird';
rideBtns.bird.setAttribute('aria-label', label);
rideBtns.bird.title = label;
if (cam.mode === 'bird') {
const want = pickFlier();
if (want) cam.subject = want;
}
}
rideBtns.bird.addEventListener('click', () => setRide('bird'));
rideBtns.fox.addEventListener('click', () => setRide('fox'));
addEventListener('keydown', e => { if (e.key === 'Escape' && cam.mode) setRide(null); });
// Just the garden: the page steps aside (and the browser goes full screen where it can) until the button or Esc brings it back.
const bareBtn = document.getElementById('garden-bare');
function setBare(on) {
document.body.classList.toggle('g-bare', on);
bareBtn.setAttribute('aria-pressed', String(on));
const fs = document.fullscreenElement;
if (on && !fs && root.requestFullscreen) root.requestFullscreen({ navigationUI: 'hide' }).catch(() => {});
if (!on && fs && document.exitFullscreen) document.exitFullscreen().catch(() => {});
if (on) showToast('Just the garden. Tap the button again to come back.');
}
bareBtn.addEventListener('click', () => setBare(!document.body.classList.contains('g-bare')));
document.addEventListener('fullscreenchange', () => { if (!document.fullscreenElement && document.body.classList.contains('g-bare')) setBare(false); });
addEventListener('keydown', e => { if (e.key === 'Escape' && !cam.mode && document.body.classList.contains('g-bare')) setBare(false); });
rideReady = true;
refreshRide();
})();
let posterEl = null, live = false;
try {
const p = JSON.parse(sessionStorage.getItem(KEY + '.poster') || 'null'), de = document.documentElement;
const dark = de.dataset.theme ? de.dataset.theme === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
if (p && p.size === sceneSize(innerWidth, sceneHeight()) && fresh(p.at) && p.dark === dark && /^data:image\/jpeg;base64,[A-Za-z0-9+/=]+$/.test(p.url)) {
posterEl = document.createElement('div'); posterEl.id = 'garden-poster'; posterEl.setAttribute('aria-hidden', 'true');
posterEl.style.backgroundImage = 'url(' + p.url + ')';
document.body.prepend(posterEl); de.classList.add('garden-scene');
}
} catch (e) {}
const idle = () => (window.requestIdleCallback ? requestIdleCallback(start, { timeout: 1500 }) : setTimeout(start, 200));
// A poster gives the scene's start a head start; if the scene can't run after all, the poster goes and the page is paper again.
const go = () => { start(); if (!live) { probe.remove(); if (posterEl) { posterEl.remove(); posterEl = null; document.documentElement.classList.remove('garden-scene'); } } };
if (posterEl) requestAnimationFrame(() => setTimeout(go, 0));
else if (document.readyState === 'complete') idle(); else addEventListener('load', idle, { once: true });
})();