Agent Harness
Публичная копия обвязки агентной разработки: гейты, journeys, скиллы и шаблоны. Без ключей и личных данных.
Публичная копия обвязки агентной разработки: гейты, journeys, скиллы и шаблоны. Без ключей и личных данных.
Принят владельцем вручную — без оценки ИИ. Очки за вклад не начислены. Оценка восстановлена по объёму правки.
| +добавлено | import * as THREE from 'three'; |
| +добавлено | |
| +добавлено | // Dust Devils (Wind hero). Three small twisters spin up round the target and dance. Each is a |
| +добавлено | // point vortex in the floor plane with its own circulation (1 : 0.8 : 0.62), so every devil is |
| +добавлено | // carried round by the others' induced flow (u = G / 2 pi r, the same G its force field swirls |
| +добавлено | // dust with) on top of a soft tether and a slow wander: they weave and braid instead of orbiting |
| +добавлено | // rigidly. Each devil is a Rankine vortex in the shared force field (every loose particle in the |
| +добавлено | // arena is caught), a raymarched dust column (a capsule volume: dust in a wall round a clear core, |
| +добавлено | // helical streaks wound up it and turning with it, a squat turbulent skirt at the foot, the top |
| +добавлено | // flaring out and thinning), a few sunlit dust sheets peeling off it (helix analytic ribbons with |
| +добавлено | // streaky breakup + lens distortion), a skirt of particles rolling at its foot, leaves, grit and |
| +добавлено | // glints, and it scours a dark track into the floor as it goes (char 'line' splats). |
| +добавлено | // Anticipation: three whorls stir on the floor while the caster's focus gathers wind. Release: the |
| +добавлено | // whorls shoot up into funnels. Climax: the tether tightens and the devils spiral into one another |
| +добавлено | // over the target, each merge pumping the survivor up, until the merged column blows out in a |
| +добавлено | // rolling dust ring with a shock force through every particle. Aftermath: leaves rain down, the |
| +добавлено | // dust settles, the braided tracks stay on the floor (~25 s). |
| +добавлено | |
| +добавлено | const N = 3; // devils |
| +добавлено | const NH = 5; // dust-sheet ribbons per devil (fx) |
| +добавлено | const NV = 6; // column volumes (two live casts) |
| +добавлено | const STATES = 16; // one per cast record |
| +добавлено | const TAU = Math.PI * 2; |
| +добавлено | const GAM = [1, 0.8, 0.62]; // relative circulation (and size) |
| +добавлено | const H0 = 5.2; // funnel height at size 1 (m) |
| +добавлено | const MERGE = 1.6; // longest merge spiral (s) |
| +добавлено | const TAIL = 1.6; // after the blow-out (s) |
| +добавлено | |
| +добавлено | // p0 (foot xyz, seed) p1 (height, foot radius, top radius, turns) p2 (angle, lean x, lean z, width) |
| +добавлено | // p3 (bend x, bend z, reveal, alpha). The axis snakes: lean (the top lags the walk) + a mid bend. |
| +добавлено | // turns == 0 is the column itself: a strip up the axis as wide as the funnel (an impostor). |
| +добавлено | const PATH_GLSL = /* glsl */` |
| +добавлено | vec3 ribbonPath(float t, vec4 p0, vec4 p1, vec4 p2, vec4 p3, out float width) { |
| +добавлено | float rr = mix(p1.y, p1.z, pow(t, 1.35)) * (1.0 + 0.11 * sin(t * 8.0 + p0.w * 6.2831853 - uTime * 3.3)); |
| +добавлено | bool column = p1.w == 0.0; |
| +добавлено | float th = p2.x + t * p1.w * 6.2831853, r = column ? 0.0 : rr; |
| +добавлено | width = column ? 2.0 * rr : p2.w * mix(0.4, 1.3, t); |
| +добавлено | vec3 axis = vec3(p2.y, 0.0, p2.z) * (t * t) + vec3(p3.x, 0.0, p3.y) * sin(3.14159265 * t); |
| +добавлено | return p0.xyz + axis + vec3(cos(th) * r, t * p1.x, sin(th) * r); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // Lit like the media particles (sun HG phase + sky): streaky dust flowing up the helix, with a |
| +добавлено | // weak cylindrical lens. |
| +добавлено | const DUST_SHADE = /* glsl */` |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform vec3 uAmbient; |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform highp sampler3D uNoise3D; |
| +добавлено | uniform float uDistort; |
| +добавлено | vec3 ribbonShade(RibbonFrag r, out vec3 media, out float alpha, out float distortion) { |
| +добавлено | float u = r.uv.x, v = r.uv.y; |
| +добавлено | vec3 vd = normalize(cameraPosition - r.p0.xyz - vec3(0.0, r.p1.x * u, 0.0)); |
| +добавлено | vec3 light = uSunColor * hgPhase(dot(uSunDir, -vd), 0.35) * 4.0 * PI * 0.6 + uAmbient * 1.4; |
| +добавлено | float ends = smoothstep(0.0, 0.07, u) * (1.0 - smoothstep(0.7, 1.0, u)) * (1.0 - smoothstep(r.p3.z - 0.15, r.p3.z, u)); |
| +добавлено | vec4 n = texture(uNoise3D, vec3(u * 1.3 - uTime * 0.42 + r.p0.w, v * 0.11 + r.p0.w * 0.7, u * 0.2 + r.p0.w * 0.31)); |
| +добавлено | float edge = exp(-2.2 * v * v); |
| +добавлено | float body = 0.3 + 0.7 * smoothstep(0.3, 0.7, n.r + 0.25 * (edge - 0.5)); |
| +добавлено | alpha = r.p3.w * edge * body * ends * (1.0 - 0.5 * u); |
| +добавлено | media = r.color * light * (0.8 + 0.3 * n.g); |
| +добавлено | distortion = uDistort * v * exp(-3.0 * v * v) * 2.33 * ends * min(r.p3.w * 3.0, 1.0); |
| +добавлено | return vec3(0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // The column (a capsule volume per devil). Cylindrical coordinates round the snaking axis: dust in |
| +добавлено | // a wall round a clearer core, thickest low down; tileable noise indexed by the twisted azimuth |
| +добавлено | // (three tiles per turn, so the atan seam tiles) minus the spin, so streaks wind up the column and |
| +добавлено | // turn with it while their texture climbs; a squat skirt with a noise-torn edge at the foot; the |
| +добавлено | // top flares, tears and thins out. |
| +добавлено | const DEVIL_GLSL = /* glsl */` |
| +добавлено | uniform vec4 uDev; // foot x, z, height m, seed |
| +добавлено | uniform vec4 uDev2; // lean x, z (top offset), bend x, z (mid offset) |
| +добавлено | uniform vec4 uDev3; // foot radius, top radius, spin rad, density |
| +добавлено | uniform vec3 uSand; |
| +добавлено | void volumeSample(vec3 pw, vec3 pl, out float sigma, out vec3 albedo, out vec3 emission) { |
| +добавлено | sigma = 0.0; albedo = vec3(0.0); emission = vec3(0.0); |
| +добавлено | float H = uDev.z, t = pw.y / H; |
| +добавлено | if (t < 0.0 || t > 1.2) return; |
| +добавлено | float tc = min(t, 1.0), s = uDev3.y; |
| +добавлено | vec2 q = pw.xz - (uDev.xy + uDev2.xy * tc * tc + uDev2.zw * sin(PI * tc)); |
| +добавлено | float r = length(q); |
| +добавлено | float R = mix(uDev3.x, s, pow(tc, 1.35)); |
| +добавлено | float Rk = 1.5 * s, hk = 0.4 * s + 0.12; |
| +добавлено | if (r > max(1.9 * R, 1.5 * Rk)) return; |
| +добавлено | float tw = atan(q.y, q.x) + uDev3.z + pw.y * 1.3 / max(s, 0.3); |
| +добавлено | vec3 np = vec3(r * 0.6 / s + uDev.w, tw * (3.0 / 6.2831853), pw.y * 0.2 / s - uTime * 0.45); |
| +добавлено | float n1 = noise3(np); |
| +добавлено | float n2 = noise3(np * vec3(2.3, 2.0, 2.6) + vec3(0.21, 0.0, 0.43)); |
| +добавлено | float detail = 1.0 - smoothstep(0.15, 0.5, gVolDt / s); |
| +добавлено | float n = n1 * 0.65 + (0.35 * n2 - 0.175) * detail + 0.0875 * (1.0 - detail); |
| +добавлено | float streak = smoothstep(0.38, 0.7, n); |
| +добавлено | float wall = exp(-pow((r - 0.72 * R) / (0.32 * R), 2.0)) + 0.15 * exp(-r * r / (0.15 * R * R)); |
| +добавлено | float top = 1.0 - smoothstep(0.65, 1.1, t + (n1 - 0.5) * 0.4); |
| +добавлено | float skirt = exp(-pw.y / hk) * (1.0 - smoothstep(0.35 * Rk, Rk, r + (n1 - 0.5) * 0.8 * Rk)); |
| +добавлено | sigma = uDev3.w * ((wall * (1.25 - 0.7 * tc) * top) * mix(0.1, 1.0, streak) + 0.9 * skirt * (0.4 + n2)) / s; |
| +добавлено | albedo = uSand * (0.8 + 0.35 * n2); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const _a = new THREE.Vector3(), _b = new THREE.Vector3(), _up = new THREE.Vector3(0, 1, 0); |
| +добавлено | const smooth = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); }; |
| +добавлено | const backOut = (x) => { x = Math.min(1, Math.max(0, x)); const c = 1.7; return 1 + (c + 1) * (x - 1) ** 3 + c * (x - 1) ** 2; }; |
| +добавлено | // reused option objects (the shared systems read fields; a literal per call would allocate) |
| +добавлено | const TRK = { x: 0, z: 0, x2: 0, z2: 0, radius: 0.2, width: 0.2, char: 0, crack: 0, pattern: 'line', seed: 0 }; |
| +добавлено | const RNG = { x: 0, z: 0, radius: 2, width: 0.5, char: 0, crack: 0, pattern: 'ring', seed: 0 }; |
| +добавлено | const SHK = { pos: new THREE.Vector3(), radius0: 0.3, radius1: 4, duration: 0.6, thickness: 0.6, distortion: 0.04, intensity: 0, ground: true }; |
| +добавлено | |
| +добавлено | export default { |
| +добавлено | id: 'dust-devils', name: 'Dust Devils', element: 'wind', order: 10, hue: '#d8b88a', |
| +добавлено | shape: 'area', radius: 0.3, |
| +добавлено | params: { |
| +добавлено | size: 1, strength: 1, weave: 1, spread: 1, duration: 4.4, dust: 1, debris: 1, streaks: 1, grit: 1, refraction: 1, tracks: 1, |
| +добавлено | sand: '#a28b6c', air: '#fff1dc', |
| +добавлено | }, |
| +добавлено | ranges: { |
| +добавлено | size: [0.5, 1.8, 0.01], strength: [0.3, 2.5, 0.01], weave: [0.2, 2.5, 0.01], spread: [0.4, 2, 0.01], duration: [1.5, 9, 0.1], |
| +добавлено | dust: [0, 3, 0.01], debris: [0, 3, 0.01], streaks: [0, 3, 0.01], grit: [0, 3, 0.01], refraction: [0, 3, 0.01], tracks: [0, 2, 0.01], |
| +добавлено | }, |
| +добавлено | presets: { |
| +добавлено | 'red planet': { sand: '#a3532c', air: '#ffcfae', grit: 0.4, tracks: 1.6, dust: 1.3 }, |
| +добавлено | 'ash devils': { sand: '#4b4743', air: '#d9dce6', grit: 0, debris: 0.4, dust: 1.4, streaks: 0.6 }, |
| +добавлено | 'autumn whirl': { sand: '#7c6a4c', air: '#fff6e0', debris: 2.8, dust: 0.55, size: 1.2, weave: 1.4 }, |
| +добавлено | }, |
| +добавлено | timing: { charge: 0.9, impact: 0.4, linger: 4.4 + MERGE + TAIL - 0.4 }, |
| +добавлено | kinds: { |
| +добавлено | dust: { style: 'media', drag: 0.35, buoyancy: 0.25, curl: 0.5, curlScale: 0.3, forceResponse: 2.4, life: [1.0, 1.7], size: [0.22, 0.8], sizePow: 0.6, color: ['#a28b6c', '#b29977'], alpha: [0.18, 0], density: 2.4, erosion: 0.55, fadeIn: 0.2, fadeOut: 0.4, lightResponse: 1.3 }, |
| +добавлено | skirt: { style: 'media', drag: 1.3, buoyancy: 0.12, curl: 0.6, curlScale: 0.25, forceResponse: 1.4, life: [0.8, 1.5], size: [0.3, 1.05], color: ['#a28b6c', '#b29977'], alpha: [0.15, 0], density: 1.7, erosion: 0.6, fadeIn: 0.12, fadeOut: 0.45 }, |
| +добавлено | burst: { style: 'media', drag: 2.0, buoyancy: 0.08, curl: 1.1, curlScale: 0.35, forceResponse: 0.6, life: [1.8, 3.0], size: [0.5, 1.9], sizePow: 0.55, color: ['#a28b6c', '#b29977'], alpha: [0.18, 0.04], density: 1.8, erosion: 0.55, fadeIn: 0.05, fadeOut: 0.6 }, |
| +добавлено | }, |
| +добавлено | |
| +добавлено | create(fx) { |
| +добавлено | const S = this, P = fx.particles; |
| +добавлено | const E = { |
| +добавлено | gather: P.emitter('wind.streak', { shape: 'shell', radius: 1.5, spread: 0.4, radial: -3.5 }), |
| +добавлено | gust: P.emitter('wind.streak', { shape: 'sphere', radius: 0.3, spread: 2, radial: 5 }), |
| +добавлено | dust: P.emitter('dust-devils.dust', { shape: 'ring', radius: 0.5, spread: 0.35, radial: 0.15 }), |
| +добавлено | skirt: P.emitter('dust-devils.skirt', { shape: 'ring', radius: 0.9, spread: 0.4, radial: 1.1 }), |
| +добавлено | stir: P.emitter('dust-devils.skirt', { shape: 'disk', radius: 0.8, spread: 0.3, radial: 0.4 }), |
| +добавлено | kick: P.emitter('dust-devils.skirt', { shape: 'sphere', radius: 0.3, spread: 1.2 }), |
| +добавлено | burst: P.emitter('dust-devils.burst', { shape: 'ring', radius: 0.8, spread: 0.7, radial: 6.5 }), |
| +добавлено | plume: P.emitter('dust-devils.burst', { shape: 'sphere', radius: 0.7, spread: 0.8 }), |
| +добавлено | leaf: P.emitter('wind.leaf', { shape: 'ring', radius: 0.9, spread: 0.9, radial: -0.4 }), |
| +добавлено | leafBurst: P.emitter('wind.leaf', { shape: 'ring', radius: 0.6, spread: 1.6, radial: 4 }), |
| +добавлено | pebble: P.emitter('wind.pebble', { shape: 'ring', radius: 0.6, spread: 0.8 }), |
| +добавлено | mote: P.emitter('wind.mote', { shape: 'ring', radius: 0.6, spread: 0.6 }), |
| +добавлено | haze: P.emitter('wind.haze', { shape: 'ring', radius: 0.5, spread: 0.3 }), |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const distortU = { value: 0.05 }; |
| +добавлено | const ribs = new fx.AnalyticRibbons({ max: 48, segments: 48, pathGLSL: PATH_GLSL, shadeGLSL: DUST_SHADE, target: 'fx', uniforms: { uDistort: distortU } }); |
| +добавлено | fx.scenes.fx.add(ribs.mesh); |
| +добавлено | const sandLin = new THREE.Color(); |
| +добавлено | const vols = []; |
| +добавлено | for (let i = 0; i < NV; i++) { |
| +добавлено | const v = fx.volumes.add({ |
| +добавлено | shape: 'capsule', glsl: DEVIL_GLSL, maxSteps: 24, |
| +добавлено | uniforms: { uDev: { value: new THREE.Vector4() }, uDev2: { value: new THREE.Vector4() }, uDev3: { value: new THREE.Vector4() }, uSand: { value: sandLin } }, |
| +добавлено | }); |
| +добавлено | v.visible = false; v.g = 0.4; v.shadowTap = 0.5; |
| +добавлено | vols.push({ v, used: false }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const devil = () => ({ |
| +добавлено | x: 0, z: 0, vx: 0, vz: 0, sx: 0, sz: 0, scale: 1, env: 0, fade: 1, boost: 0, spin: 0, ph: 0, absorbed: false, |
| +добавлено | force: null, vol: null, helix: new Array(NH).fill(null), hp: new Float32Array(NH * 5), |
| +добавлено | mx: 0, mz: 0, lx: 0, lz: 0, bx: 0, bz: 0, |
| +добавлено | }); |
| +добавлено | const states = Array.from({ length: STATES }, () => ({ |
| +добавлено | d: [devil(), devil(), devil()], cx: 0, cz: 0, L: 0, hitT: 0, merging: false, collapsed: false, tc: 0, mergeAt: 0, merged: -1, |
| +добавлено | light: null, shock: null, shockT: 0, seedF: 0, a0: 0, ph0: 0, contact: new Float32Array(N * 3), |
| +добавлено | })); |
| +добавлено | |
| +добавлено | const sand = new THREE.Color(), air = new THREE.Color(), tmp = new THREE.Color(); |
| +добавлено | const col = { sand: '', air: '' }; |
| +добавлено | function applyColors(p) { |
| +добавлено | sand.set(p.sand); air.set(p.air); sandLin.set(p.sand); |
| +добавлено | if (col.sand !== p.sand) { |
| +добавлено | col.sand = p.sand; |
| +добавлено | const hi = `#${tmp.set(p.sand).multiplyScalar(1.1).getHexString()}`; |
| +добавлено | for (const k of ['dust-devils.dust', 'dust-devils.skirt', 'dust-devils.burst']) P.setKind(k, { color: [p.sand, hi] }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function releaseAll(st) { |
| +добавлено | for (const dv of st.d) { |
| +добавлено | if (dv.vol) { dv.vol.used = false; dv.vol.v.visible = false; dv.vol = null; } |
| +добавлено | for (let i = 0; i < NH; i++) { dv.helix[i]?.release(); dv.helix[i] = null; } |
| +добавлено | dv.force?.release(); dv.force = null; |
| +добавлено | } |
| +добавлено | st.light?.release(); st.light = null; |
| +добавлено | st.shock?.release(); st.shock = null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- the dance: a three-strand braid (each devil's track circles the target while its radius |
| +добавлено | // swings in and out, 120 degrees apart, so the tracks cross over and under one another), plus the |
| +добавлено | // point-vortex flow each devil induces on the others: when two pass close they swing round |
| +добавлено | // each other and are flung apart. Substepped; the tether tightens to merge them at the end. |
| +добавлено | function braid(st, p, i, L, out) { |
| +добавлено | const R = 2.0 * p.spread * (1 + 0.45 * Math.sin(1.6 * p.weave * L + i * TAU / N + st.ph0)); |
| +добавлено | const a = st.a0 + 0.75 * p.weave * L + i * TAU / N; |
| +добавлено | out.x = st.cx + Math.cos(a) * R; out.z = st.cz + Math.sin(a) * R; |
| +добавлено | } |
| +добавлено | function dance(st, p, dt) { |
| +добавлено | const steps = Math.max(1, Math.ceil(dt * 90)), h = dt / steps, d = st.d, s0 = d[0]; |
| +добавлено | const mk = st.merging ? smooth(0, 0.8, st.L - st.mergeAt) : 0; |
| +добавлено | const k = 1.6 + 2.4 * mk, lag = 1 - Math.exp(-h * (3 + 3 * mk)), delta2 = 0.3; |
| +добавлено | for (let n = 0; n < steps; n++) { |
| +добавлено | const L = st.L - dt + (n + 1) * h; |
| +добавлено | for (let i = 0; i < N; i++) { |
| +добавлено | const a = d[i]; |
| +добавлено | if (a.absorbed) continue; |
| +добавлено | let ux = 0, uz = 0; |
| +добавлено | for (let j = 0; j < N; j++) { |
| +добавлено | const b = d[j]; |
| +добавлено | if (j === i || b.absorbed) continue; |
| +добавлено | const dx = a.x - b.x, dz = a.z - b.z, g = 13 * p.strength * b.scale * b.env / (TAU * (dx * dx + dz * dz + delta2)); |
| +добавлено | ux += g * dz; uz -= g * dx; // the same sense as the force field's swirl |
| +добавлено | } |
| +добавлено | // tether: the braid track while dancing; merging, the others home on the biggest, which |
| +добавлено | // spirals into the target |
| +добавлено | braid(st, p, i, L, _a); |
| +добавлено | let tx = _a.x + (st.cx - _a.x) * mk, tz = _a.z + (st.cz - _a.z) * mk; |
| +добавлено | if (i > 0 && mk > 0) { tx += (s0.x - tx) * mk; tz += (s0.z - tz) * mk; } |
| +добавлено | ux -= k * (a.x - tx); uz -= k * (a.z - tz); |
| +добавлено | const sp = Math.hypot(ux, uz), cap = 6; |
| +добавлено | if (sp > cap) { ux *= cap / sp; uz *= cap / sp; } |
| +добавлено | a.vx += (ux - a.vx) * lag; a.vz += (uz - a.vz) * lag; |
| +добавлено | } |
| +добавлено | for (let i = 0; i < N; i++) { |
| +добавлено | const a = d[i]; |
| +добавлено | if (a.absorbed) continue; |
| +добавлено | a.x += a.vx * h; a.z += a.vz * h; |
| +добавлено | const r = Math.hypot(a.x, a.z); // stay inside the pillar ring |
| +добавлено | if (r > 12.5) { a.x *= 12.5 / r; a.z *= 12.5 / r; } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ribbons, force, emission and world response for one devil. grow: height fraction |
| +добавлено | function devilFrame(c, st, p, dv, i, dt, grow, unwind, charging) { |
| +добавлено | const e = dv.env * dv.fade, s = dv.scale * (1 + dv.boost), H = H0 * s * grow; |
| +добавлено | const sm = 1 - Math.exp(-dt * 3); |
| +добавлено | dv.sx += (dv.vx - dv.sx) * sm; dv.sz += (dv.vz - dv.sz) * sm; |
| +добавлено | dv.spin += dt * 3.4 * p.strength / Math.sqrt(s) * (0.4 + 0.6 * e) * (1 + 2 * dv.boost); |
| +добавлено | // the top lags the walk and sways; the middle bends across it |
| +добавлено | dv.lx = -dv.sx * 0.45 * s + Math.sin(st.L * 1.1 + dv.ph * 3) * 0.3 * s; |
| +добавлено | dv.lz = -dv.sz * 0.45 * s + Math.cos(st.L * 0.9 + dv.ph * 2) * 0.3 * s; |
| +добавлено | dv.bx = Math.sin(st.L * 1.7 + dv.ph) * 0.28 * s; dv.bz = Math.cos(st.L * 1.4 + dv.ph * 1.3) * 0.28 * s; |
| +добавлено | const F = dv.force; |
| +добавлено | if (F) { |
| +добавлено | F.pos.set(dv.x, 0, dv.z); F.dir.copy(_up); |
| +добавлено | F.p[0] = 0.45 * s; F.p[1] = 13 * s * p.strength * e; F.p[2] = 3.6 * p.strength * e; F.p[3] = 0.6 * p.strength * e; |
| +добавлено | F.w = Math.max(H, 1) * 1.05; |
| +добавлено | } |
| +добавлено | const on = e > 0.01 ? 1 : 0, hp = dv.hp, vo = dv.vol?.v; |
| +добавлено | if (vo) { |
| +добавлено | const rT = 0.78 * s * unwind, ra = Math.max(1.9 * rT, 2.25 * rT) + 0.5 * Math.hypot(dv.lx, dv.lz) + Math.hypot(dv.bx, dv.bz) + 0.1; |
| +добавлено | vo.uniforms.uDev.value.set(dv.x, dv.z, Math.max(H, 0.3), st.seedF * 5 + i * 0.37); |
| +добавлено | vo.uniforms.uDev2.value.set(dv.lx, dv.lz, dv.bx, dv.bz); |
| +добавлено | vo.uniforms.uDev3.value.set(0.24 * s * unwind, rT, -dv.spin, 1.6 * e * p.dust); |
| +добавлено | vo.position.set(dv.x + 0.5 * dv.lx, 0.5 * H, dv.z + 0.5 * dv.lz); |
| +добавлено | vo.scale.set(ra, 0.5 * H + 0.3, ra); |
| +добавлено | vo.visible = on > 0; |
| +добавлено | } |
| +добавлено | for (let j = 0; j < NH; j++) { |
| +добавлено | const r = dv.helix[j], o = j * 5; |
| +добавлено | if (!r) continue; |
| +добавлено | r.p0.set(dv.x, 0.02, dv.z, hp[o + 4] / TAU + st.seedF + i * 0.31); |
| +добавлено | r.p1.set(H * hp[o + 3], hp[o + 1] * s * unwind, hp[o + 2] * s * unwind, -hp[o]); |
| +добавлено | r.p2.set(hp[o + 4] - dv.spin * (0.85 + 0.1 * hp[o]), dv.lx, dv.lz, 0.5 * s); |
| +добавлено | r.p3.set(dv.bx, dv.bz, 1.15, 0.38 * e * p.dust); |
| +добавлено | r.color.copy(sand); r.intensity = on; |
| +добавлено | } |
| +добавлено | if (e < 0.02) return; |
| +добавлено | // what the wind carries |
| +добавлено | if (charging) { |
| +добавлено | E.stir.pos.set(dv.x, 0.1, dv.z); E.stir.radius = 0.7 * s; E.stir.size = 0.5 * s; E.stir.vel.set(0, 0.3, 0); |
| +добавлено | E.stir.rate(170 * p.dust * e, dt); |
| +добавлено | E.leaf.pos.set(dv.x, 0.15, dv.z); E.leaf.radius = 0.8 * s; E.leaf.vel.set(0, 1.6, 0); E.leaf.rate(30 * p.debris * e, dt); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | const hn = Math.pow(fx.rand(), 1.3); |
| +добавлено | E.dust.pos.set(dv.x + dv.lx * hn * hn + dv.bx * Math.sin(Math.PI * hn), hn * H, dv.z + dv.lz * hn * hn + dv.bz * Math.sin(Math.PI * hn)); |
| +добавлено | E.dust.radius = (0.25 + 0.6 * Math.pow(hn, 1.35)) * s; E.dust.size = s * (0.45 + 0.5 * hn); |
| +добавлено | E.dust.vel.set(dv.sx * 0.3, 0.9, dv.sz * 0.3); |
| +добавлено | E.dust.rate(90 * p.dust * e, dt); |
| +добавлено | E.skirt.pos.set(dv.x, 0.12, dv.z); E.skirt.radius = 0.75 * s; E.skirt.size = s; E.skirt.vel.set(dv.sx * 0.4, 0.25, dv.sz * 0.4); |
| +добавлено | E.skirt.rate(100 * p.dust * e, dt); |
| +добавлено | E.mote.pos.set(dv.x, 0.3 + 1.2 * fx.rand() * s, dv.z); E.mote.radius = 0.6 * s; E.mote.vel.set(0, 1.4, 0); |
| +добавлено | E.mote.rate(70 * p.grit * e, dt); |
| +добавлено | E.leaf.pos.set(dv.x, 0.2, dv.z); E.leaf.radius = 0.9 * s; E.leaf.vel.set(0, 2.6, 0); E.leaf.rate(7 * p.debris * e, dt); |
| +добавлено | E.pebble.pos.set(dv.x, 0.15, dv.z); E.pebble.radius = 0.55 * s; E.pebble.vel.set(0, 3.8, 0); E.pebble.rate(9 * p.debris * e, dt); |
| +добавлено | const hz = 0.15 + 0.6 * fx.rand(); |
| +добавлено | E.haze.pos.set(dv.x + dv.lx * hz * hz, hz * H, dv.z + dv.lz * hz * hz); E.haze.radius = 0.5 * s; E.haze.size = 0.5 * s; E.haze.vel.set(0, 0.8, 0); |
| +добавлено | E.haze.rate(6 * p.refraction * e, dt); |
| +добавлено | // a dark scoured track behind it |
| +добавлено | const mdx = dv.x - dv.mx, mdz = dv.z - dv.mz; |
| +добавлено | if (mdx * mdx + mdz * mdz > 0.36 && p.tracks > 0 && e > 0.4) { |
| +добавлено | TRK.x = dv.mx; TRK.z = dv.mz; TRK.x2 = dv.x; TRK.z2 = dv.z; TRK.width = 0.26 * s; TRK.radius = 0.26 * s; |
| +добавлено | TRK.char = 0.45 * p.tracks * e; TRK.crack = 0; TRK.seed = (c.seed + i * 17 + Math.floor(st.L * 10)) % 100; |
| +добавлено | fx.ground.splat(TRK); |
| +добавлено | dv.mx = dv.x; dv.mz = dv.z; |
| +добавлено | } |
| +добавлено | // the pool's ripples swirl when a devil walks over or near it |
| +добавлено | const pool = fx.ARENA.pool; |
| +добавлено | const qx = Math.max(Math.abs(dv.x - pool.center.x) - pool.half.x, 0), qz = Math.max(Math.abs(dv.z - pool.center.y) - pool.half.y, 0); |
| +добавлено | const pd = Math.hypot(qx, qz), reach = 1.6 * s; |
| +добавлено | if (pd < reach && fx.pool) { |
| +добавлено | fx.pool.swirl(Math.min(Math.max(dv.x, pool.center.x - pool.half.x), pool.center.x + pool.half.x), |
| +добавлено | Math.min(Math.max(dv.z, pool.center.y - pool.half.y), pool.center.y + pool.half.y), 2.2 * e * p.strength * (1 - pd / reach)); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // dummies caught by a devil get buffeted round it; first contact kicks dust off them |
| +добавлено | function buffet(st, p, dt) { |
| +добавлено | st.hitT -= dt; |
| +добавлено | for (let k = 0; k < st.contact.length; k++) st.contact[k] = Math.max(0, st.contact[k] - dt); |
| +добавлено | if (st.hitT > 0) return; |
| +добавлено | st.hitT = 0.15; |
| +добавлено | for (let i = 0; i < N; i++) { |
| +добавлено | const dv = st.d[i], e = dv.env * dv.fade, s = dv.scale * (1 + dv.boost), R = 1.3 * s; |
| +добавлено | if (e < 0.2) continue; |
| +добавлено | for (let m = 0; m < fx.dummies.length && m < 3; m++) { |
| +добавлено | const dm = fx.dummies[m], dx = dm.pos.x - dv.x, dz = dm.pos.z - dv.z, dd = Math.hypot(dx, dz); |
| +добавлено | if (dd > R) continue; |
| +добавлено | dm.hit(_b.set(dz - dx * 0.3, 0, -dx - dz * 0.3), 0.28 * e * p.strength * (1 - dd / R) + 0.05); |
| +добавлено | if (st.contact[i * 3 + m] <= 0) { |
| +добавлено | st.contact[i * 3 + m] = 1.2; |
| +добавлено | E.kick.pos.set(dm.pos.x, 0.5, dm.pos.z); E.kick.vel.set(dz * 1.5, 1.2, -dx * 1.5); E.kick.size = 0.8; E.kick.burst(40 * p.dust); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function blowOut(c, st, p) { |
| +добавлено | const s0 = st.d[0], s = s0.scale * (1 + s0.boost), x = s0.x, z = s0.z; |
| +добавлено | st.collapsed = true; st.tc = st.L; |
| +добавлено | for (const dv of st.d) if (dv !== s0) { dv.absorbed = true; dv.fade = 0; dv.force?.release(); dv.force = null; } |
| +добавлено | E.burst.pos.set(x, 0.3, z); E.burst.radius = 0.9 * s; E.burst.radial = 6.5 * Math.sqrt(p.size); E.burst.size = 1.1 * s; E.burst.vel.set(0, 0.5, 0); |
| +добавлено | E.burst.burst(300 * p.dust); |
| +добавлено | E.burst.radial = 3 * Math.sqrt(p.size); E.burst.spread = 1.4; E.burst.burst(140 * p.dust); E.burst.spread = 0.7; |
| +добавлено | E.plume.pos.set(x, 2.2 * s, z); E.plume.radius = 1.0 * s; E.plume.size = s; E.plume.vel.set(0, 1.6, 0); E.plume.burst(110 * p.dust); |
| +добавлено | E.leafBurst.pos.set(x, 0.6, z); E.leafBurst.vel.set(0, 5.5, 0); E.leafBurst.burst(70 * p.debris); |
| +добавлено | E.pebble.pos.set(x, 0.2, z); E.pebble.radius = 0.8; E.pebble.vel.set(0, 4.5, 0); E.pebble.burst(40 * p.debris); |
| +добавлено | E.gust.pos.set(x, 1.2, z); E.gust.vel.set(0, 1, 0); E.gust.burst(220 * p.streaks); |
| +добавлено | SHK.pos.set(x, 0.05, z); SHK.radius0 = 0.4; SHK.radius1 = 6.5 * s; SHK.duration = 0.7; SHK.thickness = 0.8; SHK.distortion = 0.06 * p.refraction; SHK.ground = true; |
| +добавлено | fx.shocks?.spawn(SHK); |
| +добавлено | SHK.pos.set(x, 1.4, z); SHK.radius1 = 3.5 * s; SHK.duration = 0.4; SHK.thickness = 0.6; SHK.distortion = 0.035 * p.refraction; SHK.ground = false; |
| +добавлено | fx.shocks?.spawn(SHK); |
| +добавлено | RNG.x = x; RNG.z = z; RNG.radius = 2.4 * s; RNG.width = 0.55 * s; RNG.char = 0.4 * p.tracks; RNG.seed = c.seed % 97; |
| +добавлено | if (p.tracks > 0) fx.ground.splat(RNG); |
| +добавлено | st.shock = fx.forces.acquire(); |
| +добавлено | if (st.shock) { st.shock.type = 4; st.shock.pos.set(x, 0.8, z); st.shock.p[0] = 0.3; st.shock.p[1] = 1.2; st.shock.p[2] = 45 * p.strength; st.shock.p[3] = 0; } |
| +добавлено | st.shockT = 0; |
| +добавлено | for (const dm of fx.dummies) { |
| +добавлено | const dx = dm.pos.x - x, dz = dm.pos.z - z, dd = Math.hypot(dx, dz), R = 3.2 * s; |
| +добавлено | if (dd < R) dm.hit(_b.set(dx, 0, dz), 1.1 * p.strength * (1 - dd / R) + 0.2); |
| +добавлено | } |
| +добавлено | fx.rig.shake(0.32, 8); |
| +добавлено | if (!fx.reduced) { fx.rig.punch(1.6, 0.1); fx.rig.hitstop(0.035); } |
| +добавлено | c.durations.linger = Math.min(c.durations.linger, c.t + TAIL); |
| +добавлено | } |
| +добавлено | |
| +добавлено | return { |
| +добавлено | onParam(k) { if (k === 'sand' || k === 'air') applyColors(S.params); }, |
| +добавлено | tick() { ribs.update(); }, |
| +добавлено | |
| +добавлено | phase(c, name) { |
| +добавлено | const p = S.params, st = states[c.index]; |
| +добавлено | applyColors(p); |
| +добавлено | if (name === 'charge') { |
| +добавлено | releaseAll(st); |
| +добавлено | st.L = 0; st.hitT = 0; st.merging = false; st.collapsed = false; st.shockT = 0; st.merged = -1; |
| +добавлено | st.seedF = (c.seed % 997) / 997; |
| +добавлено | st.contact.fill(0); |
| +добавлено | st.mergeAt = p.duration; |
| +добавлено | c.durations.linger = p.duration + MERGE + TAIL - c.durations.impact; |
| +добавлено | // centre on the target, inside the pillar ring |
| +добавлено | st.cx = c.to.x; st.cz = c.to.z; |
| +добавлено | const r = Math.hypot(st.cx, st.cz); |
| +добавлено | if (r > 11) { st.cx *= 11 / r; st.cz *= 11 / r; } |
| +добавлено | st.a0 = Math.atan2(c.to.z - c.from.z, c.to.x - c.from.x) + Math.PI / 2 + fx.rand() * 0.6; |
| +добавлено | st.ph0 = fx.rand() * TAU; |
| +добавлено | for (let i = 0; i < N; i++) { |
| +добавлено | const dv = st.d[i]; |
| +добавлено | braid(st, p, i, 0, dv); |
| +добавлено | dv.vx = dv.vz = dv.sx = dv.sz = 0; |
| +добавлено | dv.scale = p.size * GAM[i]; dv.env = 0; dv.fade = 1; dv.boost = 0; dv.spin = fx.rand() * TAU; dv.ph = fx.rand() * TAU; |
| +добавлено | dv.absorbed = false; dv.mx = dv.x; dv.mz = dv.z; |
| +добавлено | for (let j = 0; j < NH; j++) { |
| +добавлено | const o = j * 5; |
| +добавлено | dv.hp[o] = 2.0 + 1.0 * fx.rand(); // turns |
| +добавлено | dv.hp[o + 1] = 0.22 + 0.1 * fx.rand(); // foot radius |
| +добавлено | dv.hp[o + 2] = 0.8 + 0.35 * fx.rand(); // top radius |
| +добавлено | dv.hp[o + 3] = 0.82 + 0.22 * fx.rand(); // height |
| +добавлено | dv.hp[o + 4] = (j + 0.35 * fx.rand()) * TAU / NH; |
| +добавлено | dv.helix[j] = ribs.acquire(); |
| +добавлено | } |
| +добавлено | dv.force = fx.forces.acquire(); |
| +добавлено | if (dv.force) dv.force.type = 1; |
| +добавлено | dv.vol = null; |
| +добавлено | for (let k = 0; k < NV; k++) if (!vols[k].used) { dv.vol = vols[k]; vols[k].used = true; break; } |
| +добавлено | } |
| +добавлено | st.light = fx.lights.acquire(); |
| +добавлено | if (st.light) { st.light.range = 5; st.light.intensity = 0; st.light.color.copy(air).lerp(sand, 0.4); } |
| +добавлено | } else if (name === 'release') { |
| +добавлено | st.light?.release(); st.light = null; |
| +добавлено | fx.rig.shake(0.12, 9); |
| +добавлено | E.gust.pos.copy(c.from); E.gust.vel.subVectors(c.to, c.from).setY(0).setLength(7); E.gust.burst(120 * p.streaks); |
| +добавлено | for (const dv of st.d) { |
| +добавлено | const s = dv.scale; |
| +добавлено | E.skirt.pos.set(dv.x, 0.12, dv.z); E.skirt.radius = 0.7 * s; E.skirt.size = s; E.skirt.vel.set(0, 0.6, 0); E.skirt.burst(70 * p.dust); |
| +добавлено | E.leafBurst.pos.set(dv.x, 0.3, dv.z); E.leafBurst.vel.set(0, 3.5, 0); E.leafBurst.burst(8 * p.debris); |
| +добавлено | SHK.pos.set(dv.x, 0.05, dv.z); SHK.radius0 = 0.2; SHK.radius1 = 3.2 * s; SHK.duration = 0.5; SHK.thickness = 0.5; SHK.distortion = 0.04 * p.refraction; SHK.ground = true; |
| +добавлено | fx.shocks?.spawn(SHK); |
| +добавлено | } |
| +добавлено | } else if (name === 'done') releaseAll(st); |
| +добавлено | }, |
| +добавлено | |
| +добавлено | update(c, dt) { |
| +добавлено | const p = S.params, st = states[c.index], d = st.d; |
| +добавлено | distortU.value = 0.03 * p.refraction; |
| +добавлено | if (c.phase === 'charge') { |
| +добавлено | // the focus gathers wind; three whorls stir on the floor |
| +добавлено | const k = Math.min(1, c.t / c.durations.charge), f = c.from; |
| +добавлено | E.gather.pos.copy(f); E.gather.rate(520 * p.streaks * (0.3 + 0.7 * k), dt); |
| +добавлено | if (st.light) { st.light.pos.copy(f); st.light.intensity = 3 * k; } |
| +добавлено | for (let i = 0; i < N; i++) { |
| +добавлено | d[i].env = 0.25 + 0.45 * k; |
| +добавлено | devilFrame(c, st, p, d[i], i, dt, 0.12 + 0.16 * k, 1.25 - 0.25 * k, true); |
| +добавлено | } |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | st.L += dt; |
| +добавлено | const L = st.L; |
| +добавлено | if (!st.merging && L >= st.mergeAt) st.merging = true; |
| +добавлено | if (!st.collapsed) dance(st, p, dt); |
| +добавлено | const s0 = d[0]; |
| +добавлено | // merging: a devil that reaches the biggest is swallowed and pumps it up |
| +добавлено | if (st.merging && !st.collapsed) { |
| +добавлено | let left = 0; |
| +добавлено | for (let i = 1; i < N; i++) { |
| +добавлено | const dv = d[i]; |
| +добавлено | if (dv.absorbed) continue; |
| +добавлено | if (dv.fade < 1) dv.fade = Math.max(0, dv.fade - dt / 0.3); |
| +добавлено | else if (Math.hypot(dv.x - s0.x, dv.z - s0.z) < 0.5 * (dv.scale + s0.scale)) { |
| +добавлено | dv.fade -= 1e-3; |
| +добавлено | s0.boost += 0.2; |
| +добавлено | E.kick.pos.set(s0.x, 0.6, s0.z); E.kick.vel.set(0, 2, 0); E.kick.size = 1.2 * s0.scale; E.kick.burst(70 * p.dust); |
| +добавлено | fx.rig.shake(0.08, 10); |
| +добавлено | } |
| +добавлено | if (dv.fade <= 0) { dv.absorbed = true; dv.force?.release(); dv.force = null; } |
| +добавлено | else left++; |
| +добавлено | } |
| +добавлено | // all swallowed: the merged devil stands a beat at full height, then blows out |
| +добавлено | if (left === 0 && st.merged < 0) st.merged = L; |
| +добавлено | if ((st.merged >= 0 && L > st.merged + 0.5) || L > st.mergeAt + MERGE) blowOut(c, st, p); |
| +добавлено | } |
| +добавлено | // envelopes: spin up after release; the survivor unwinds after the blow-out |
| +добавлено | const up = smooth(0, 0.6, L), grow = 0.28 + 0.72 * backOut(L / 0.55); |
| +добавлено | for (let i = 0; i < N; i++) { |
| +добавлено | const dv = d[i]; |
| +добавлено | if (dv.absorbed && i > 0) { dv.env = 0; devilFrame(c, st, p, dv, i, dt, grow, 1, false); continue; } |
| +добавлено | let g = grow, unwind = 1; |
| +добавлено | if (st.collapsed) { |
| +добавлено | const x = smooth(0, 0.9, L - st.tc); |
| +добавлено | dv.env = 1 - x; unwind = 1 + 1.3 * x; g = grow * (1 + 0.25 * x); |
| +добавлено | } else dv.env = 0.55 + 0.45 * up; |
| +добавлено | dv.boost = Math.min(dv.boost, 0.5); |
| +добавлено | devilFrame(c, st, p, dv, i, dt, g, unwind, false); |
| +добавлено | } |
| +добавлено | buffet(st, p, dt); |
| +добавлено | // the blow-out's shock shell runs out through every loose particle |
| +добавлено | if (st.shock) { |
| +добавлено | st.shockT += dt; |
| +добавлено | const x = st.shockT / 0.7; |
| +добавлено | if (x >= 1) { st.shock.release(); st.shock = null; } |
| +добавлено | else { st.shock.p[0] = 0.3 + 7 * Math.pow(x, 0.5); st.shock.p[2] = 45 * p.strength * (1 - x); } |
| +добавлено | } |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { U, ARENA, COMMON_GLSL, ARENA_GLSL, GROUND_GLSL, FX_VERT_HEAD, FX_FRAG_HEAD, FX_OUT_GLSL, FX_BLENDING, LINES_BLENDING, arenaSDF } from './common.js'; |
| +добавлено | import { STRIP_GLSL, instanced, put4 } from './Ribbons.js'; |
| +добавлено | import { arenaUniforms } from '../scene/arenaMaterial.js'; |
| +добавлено | import { Q } from '../engine/quality.js'; |
| +добавлено | |
| +добавлено | // Lightning (PLAN 2.5 "Bolt path", 3 Lightning). Every bolt is evaluated per vertex from a handful |
| +добавлено | // of per-instance numbers, after Reed & Wyvill 1994: |
| +добавлено | // P(t) = mix(A,B,t) + (U n1(t) + V n2(t)) L jag sum_k rough^k noise(t f 2^k + seed_k) sqrt(sin(pi t)) |
| +добавлено | // with piecewise-linear lattice noise, which makes each octave exactly one level of midpoint |
| +добавлено | // displacement. One instance = one bolt = a main channel (256 segments), 8 branches (32) and |
| +добавлено | // 12 sub-branches (12), 656 segments. All cores are one full-res draw (lines scene), all glows one |
| +добавлено | // half-res draw (fx scene, emission only). Branch layout comes from branchSeed, so a restrike is |
| +добавлено | // the same seed with a new branchSeed: the channel stays, the branches change (real return strokes |
| +добавлено | // re-use the ionised channel). |
| +добавлено | // |
| +добавлено | // Optional per-bolt fields (their defaults draw the plain bolt other spells were written against): |
| +добавлено | // rough octave gain, 0.5 smooth .. ~0.65 (real channels: fractal dimension ~1.3) |
| +добавлено | // fine 1 adds an eighth octave, one zigzag per segment |
| +добавлено | // vary 0..1 width and brightness change along the strand, knots where it heads at the eye |
| +добавлено | // stroke 0..1 how far the return stroke has climbed from b towards a (1 = all of it) |
| +добавлено | // dart t of a dart leader's head running a -> b, < 0 off |
| +добавлено | // branchLevel 0..1 branch brightness and width relative to the channel |
| +добавлено | // residual 0..1 the cooling channel: it widens and breaks up into beads |
| +добавлено | // A floor mirror image of every bolt (High and up: a child of cores, one more draw) stands in for |
| +добавлено | // the planar reflection, which no tier affords: puddles and the pool show the real jagged channel. |
| +добавлено | // |
| +добавлено | // Hashes are integer PCG (Jarzynski & Olano 2020) so the JS mirror point() matches the GPU bit for |
| +добавлено | // bit; seeds are integers in [0, 2^24) (they travel as float attributes). |
| +добавлено | |
| +добавлено | const STRANDS = [ // segments, count, first strand id |
| +добавлено | { seg: 256, n: 1 }, { seg: 32, n: 8 }, { seg: 12, n: 12 }, |
| +добавлено | ]; |
| +добавлено | const MAIN = { freq: 2, octaves: 7 }; // finest lattice = 2 * 2^6 = 128 cells; `fine` adds one more, one cell per segment |
| +добавлено | |
| +добавлено | const BOLT_VERT = /* glsl */` |
| +добавлено | in vec4 aA; // a.xyz, seed |
| +добавлено | in vec4 aB; // b.xyz, branch seed |
| +добавлено | in vec4 aShape; // branches, sub-branches, jag, core width (m) |
| +добавлено | in vec4 aCore; // core rgb * intensity, reveal |
| +добавлено | in vec4 aGlow; // glow rgb * intensity, glow width multiplier |
| +добавлено | in vec4 aMisc; // snap to arena, octave gain, extra octave, variation along the strand |
| +добавлено | in vec4 aFx; // return-stroke reach, dart head, branch level, residual |
| +добавлено | out vec2 vUv; // along the strand, across (-1..1) |
| +добавлено | out vec3 vColor; |
| +добавлено | out vec3 vEdge; // the core's saturated sheath |
| +добавлено | out float vViewZ; |
| +добавлено | out float vS; // metres along the strand |
| +добавлено | #ifdef BOLT_MIRROR |
| +добавлено | out vec3 vW; // mirrored world position |
| +добавлено | #endif |
| +добавлено | float gGain = 0.5; // octave gain, per bolt |
| +добавлено | |
| +добавлено | uint pcg(uint v) { |
| +добавлено | uint s = v * 747796405u + 2891336453u; |
| +добавлено | uint w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u; |
| +добавлено | return (w >> 22u) ^ w; |
| +добавлено | } |
| +добавлено | float urand(uint v) { return float(pcg(v)) * (1.0 / 4294967296.0); } |
| +добавлено | // piecewise-linear value noise on the integer lattice, -1..1 |
| +добавлено | float lnoise(float x, uint salt) { |
| +добавлено | float i = floor(x); |
| +добавлено | uint k = uint(i) + salt; |
| +добавлено | return mix(urand(k), urand(k + 1u), x - i) * 2.0 - 1.0; |
| +добавлено | } |
| +добавлено | vec3 perp(vec3 t) { return normalize(cross(t, abs(t.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0))); } |
| +добавлено | // freeEnd 1: envelope sqrt(sin(pi t / 2)) pins only the start, so branch tips wander |
| +добавлено | vec3 boltPath(vec3 A, vec3 B, float t, uint seed, float jag, float freq, int octaves, float freeEnd) { |
| +добавлено | vec3 d = B - A; |
| +добавлено | float L = length(d); |
| +добавлено | vec3 T = d / max(L, 1e-6), Ub = perp(T), Vb = cross(T, Ub); |
| +добавлено | float n1 = 0.0, n2 = 0.0, amp = 1.0, f = freq; |
| +добавлено | for (int k = 0; k < 8; k++) { |
| +добавлено | if (k >= octaves) break; |
| +добавлено | uint s = pcg(seed + uint(k) * 0x9E3779B9u); |
| +добавлено | n1 += amp * lnoise(t * f, s); |
| +добавлено | n2 += amp * lnoise(t * f, s ^ 0x5bd1e995u); |
| +добавлено | amp *= gGain; f *= 2.0; |
| +добавлено | } |
| +добавлено | float env = sqrt(max(sin(PI * t * (1.0 - 0.5 * freeEnd)), 0.0)); |
| +добавлено | return mix(A, B, t) + (Ub * n1 + Vb * n2) * (L * jag * env); |
| +добавлено | } |
| +добавлено | // 25-50 degrees off the parent tangent, random azimuth |
| +добавлено | vec3 deviate(vec3 T, uint h) { |
| +добавлено | float th = radians(mix(25.0, 50.0, urand(h + 1u))), ph = 2.0 * PI * urand(h + 2u); |
| +добавлено | vec3 Ub = perp(T), Vb = cross(T, Ub); |
| +добавлено | return cos(th) * T + sin(th) * (cos(ph) * Ub + sin(ph) * Vb); |
| +добавлено | } |
| +добавлено | // ground-crawl arcs: project onto the nearest arena surface (exact for planes and capsules) |
| +добавлено | vec3 snapArena(vec3 p) { return p - arenaNormal(p) * (arenaSDF(p) - 0.03); } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vUv = vec2(0.0); vColor = vec3(0.0); vEdge = vec3(0.0); vViewZ = 1.0; vS = 0.0; |
| +добавлено | #ifdef BOLT_MIRROR |
| +добавлено | vW = vec3(0.0); |
| +добавлено | if (aShape.w < 0.02) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; } // only real channels: not arcs hugging the floor |
| +добавлено | #endif |
| +добавлено | float t = position.x; |
| +добавлено | int strand = int(position.z), nb = int(aShape.x), ns = int(aShape.y); |
| +добавлено | vec3 A = aA.xyz, B = aB.xyz; |
| +добавлено | uint seed = pcg(uint(aA.w)), bseed = uint(aB.w); |
| +добавлено | float L = length(B - A), jag = aShape.z, reveal = aCore.w; |
| +добавлено | gGain = aMisc.y; |
| +добавлено | float vary = aMisc.w, stroke = aFx.x, dart = aFx.y, res = aFx.w; |
| +добавлено | |
| +добавлено | // strand frame: main channel, branch off it, or sub-branch off a branch |
| +добавлено | vec3 sA = A, sB = B; |
| +добавлено | uint sSeed = seed; |
| +добавлено | float freq = ${MAIN.freq.toFixed(1)}, freeEnd = 0.0, vis = reveal, wMul = 1.0, iMul = 1.0, sJag = jag, len = L, tm = t; |
| +добавлено | int oct = ${MAIN.octaves} + int(aMisc.z); |
| +добавлено | if (strand > 0) { |
| +добавлено | bool sub = strand > 8; |
| +добавлено | int bi = sub ? (strand - 9) % max(nb, 1) : strand - 1; |
| +добавлено | if (sub ? (strand - 9 >= ns || nb == 0) : bi >= nb) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; } |
| +добавлено | uint bh = pcg(bseed + uint(bi) * 0x632BE5ABu); |
| +добавлено | float tb = mix(0.05, 0.75, urand(bh)); |
| +добавлено | tm = tb; |
| +добавлено | sA = boltPath(A, B, tb, seed, jag, freq, oct, 0.0); |
| +добавлено | // smoothed parent tangent (the per-segment one is as jagged as the bolt) |
| +добавлено | vec3 Tm = normalize(boltPath(A, B, tb + 0.05, seed, jag, freq, oct, 0.0) - sA); |
| +добавлено | len = mix(0.15, 0.4, urand(bh + 3u)) * L; |
| +добавлено | sB = sA + deviate(Tm, bh) * len; |
| +добавлено | sSeed = pcg(bh + 4u); freq = 2.0; oct = 5; freeEnd = 1.0; sJag = jag * 1.3; |
| +добавлено | vis = (reveal - tb) * L / len; // the leader runs on along the branch at the same speed |
| +добавлено | wMul = 0.55; iMul = 0.45; |
| +добавлено | if (sub) { |
| +добавлено | uint sh = pcg(bseed + uint(strand) * 0x2C1B3C6Du); |
| +добавлено | float ts = mix(0.1, 0.7, urand(sh)); |
| +добавлено | vec3 q0 = boltPath(sA, sB, ts, sSeed, sJag, freq, oct, 1.0); |
| +добавлено | vec3 Tq = normalize(boltPath(sA, sB, ts + 0.1, sSeed, sJag, freq, oct, 1.0) - q0); |
| +добавлено | float len2 = mix(0.3, 0.6, urand(sh + 3u)) * len; |
| +добавлено | vis = (vis - ts) * len / len2; |
| +добавлено | sA = q0; sB = q0 + deviate(Tq, sh) * len2; len = len2; |
| +добавлено | sSeed = pcg(sh + 4u); freq = 1.5; oct = 3; |
| +добавлено | wMul = 0.35; iMul = 0.25; |
| +добавлено | } |
| +добавлено | // branches thin and dim towards their tips, and carry far less current than the channel |
| +добавлено | wMul *= (1.0 - 0.6 * t) * (0.6 + 0.4 * aFx.z); iMul *= (1.0 - 0.7 * t) * aFx.z * (1.0 - res) * (1.0 - res); |
| +добавлено | } |
| +добавлено | if (vis <= 0.0) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; } |
| +добавлено | |
| +добавлено | // the fronts below ramp over a distance like the ribbon's width, or the wide glow shows a flat cap |
| +добавлено | #ifdef BOLT_GLOW |
| +добавлено | float soft = 1.5; |
| +добавлено | #else |
| +добавлено | float soft = 0.25; |
| +добавлено | #endif |
| +добавлено | // return stroke: lit up from the ground end, its front burning hottest; a dim leader above it |
| +добавлено | if (stroke < 1.0) { |
| +добавлено | float below = (tm - (1.0 - stroke)) * L; |
| +добавлено | iMul *= mix(0.1, 1.0 + 3.0 * exp(-max(below, 0.0) / 1.5), smoothstep(-soft, 0.0, below)); |
| +добавлено | } |
| +добавлено | // dart leader: a bright head running down the old channel, a fading tail, the cold channel ahead |
| +добавлено | if (dart >= 0.0) { |
| +добавлено | float behind = (dart - tm) * L; |
| +добавлено | iMul *= mix(0.12, 1.0 + 7.0 * exp(-max(behind, 0.0) / 2.0), smoothstep(-soft, 0.0, behind)); |
| +добавлено | } |
| +добавлено | // the channel is never uniform: log-normal brightness knots, a width that wanders and swells |
| +добавлено | // towards the ground, where the current is highest |
| +добавлено | float wVar = 1.0, x = t * len; |
| +добавлено | if (vary > 0.0) { |
| +добавлено | uint hv = sSeed ^ 0x3C6EF372u; |
| +добавлено | float n2 = lnoise(x * 1.9, hv + 97u); |
| +добавлено | iMul *= exp(vary * (0.75 * lnoise(x * 0.45, hv) + 0.45 * n2 + 0.25 * lnoise(x * 5.3, hv + 311u))); |
| +добавлено | wVar = 1.0 + vary * (0.4 * lnoise(x * 0.8, hv + 191u) + 0.2 * n2); |
| +добавлено | if (strand == 0) { wVar *= 1.0 + vary * 0.7 * t * t; iMul *= 1.0 + vary * 0.6 * t * t; } |
| +добавлено | } |
| +добавлено | // the cooling channel diffuses and breaks into beads |
| +добавлено | if (res > 0.0) { |
| +добавлено | float b = 0.5 + 0.35 * lnoise(x * 1.3, sSeed + 733u) + 0.15 * lnoise(x * 4.1, sSeed + 1009u); |
| +добавлено | iMul *= smoothstep(res * 1.15 - 0.3, res * 1.15 + 0.05, b); |
| +добавлено | wVar *= 1.0 + 1.2 * res; |
| +добавлено | } |
| +добавлено | #ifdef BOLT_GLOW |
| +добавлено | oct = max(oct - 2, 2); // the wide glow follows the big kinks only: no fans at every zigzag |
| +добавлено | float hs = strand == 0 ? 8.0 : strand <= 8 ? 4.0 : 2.0; |
| +добавлено | #else |
| +добавлено | float hs = strand == 0 ? 4.0 : strand <= 8 ? 2.0 : 1.0; |
| +добавлено | #endif |
| +добавлено | |
| +добавлено | // stepped leader: vertices past the tip fold onto it (zero-area triangles) |
| +добавлено | float tt = min(t, vis), h = hs / float(strand == 0 ? ${STRANDS[0].seg} : strand <= 8 ? ${STRANDS[1].seg} : ${STRANDS[2].seg}); |
| +добавлено | vec3 p = boltPath(sA, sB, tt, sSeed, sJag, freq, oct, freeEnd); |
| +добавлено | vec3 pP = boltPath(sA, sB, max(tt - h, 0.0), sSeed, sJag, freq, oct, freeEnd); |
| +добавлено | vec3 pN = boltPath(sA, sB, min(tt + h, 1.0), sSeed, sJag, freq, oct, freeEnd); |
| +добавлено | if (aMisc.x > 0.5) { p = snapArena(p); pP = snapArena(pP); pN = snapArena(pN); } |
| +добавлено | // the growing leader's tip burns brighter over its last ~30 cm |
| +добавлено | if (vis < 1.0) iMul *= 1.0 + 3.0 * exp(-(vis - tt) * len / 0.3); |
| +добавлено | |
| +добавлено | // the strip's side comes from a tangent a few segments long, so the zigzag can't twist the ribbon |
| +добавлено | vec3 Ts = pN - pP, eye = p - cameraPosition; |
| +добавлено | float mu = dot(Ts, eye); |
| +добавлено | mu *= mu / max(dot(Ts, Ts) * dot(eye, eye), 1e-6); // cos^2 of the angle to the eye ray |
| +добавлено | // looking down a stretch of channel integrates more of it: knots where it heads at the eye |
| +добавлено | iMul *= 1.0 + vary * 2.0 * mu * mu; |
| +добавлено | #ifdef BOLT_MIRROR |
| +добавлено | // below the floor; ripples and a rough surface smear it the further it is from the plane |
| +добавлено | float hgt = max(p.y, 0.0), blur = 2.0 + 0.3 * min(hgt, 10.0); |
| +добавлено | p.xz += vec2(sin(hgt * 3.7 + uTime * 5.0), cos(hgt * 2.9 - uTime * 4.0)) * 0.012 * min(hgt, 8.0); |
| +добавлено | p.y = -p.y; Ts.y = -Ts.y; |
| +добавлено | vW = p; |
| +добавлено | wVar *= blur; iMul /= blur; |
| +добавлено | #endif |
| +добавлено | |
| +добавлено | vViewZ = -(viewMatrix * vec4(p, 1.0)).z; |
| +добавлено | vS = x; |
| +добавлено | vec3 side = stripSide(p, Ts); |
| +добавлено | float aa; |
| +добавлено | #ifdef BOLT_GLOW |
| +добавлено | float hw = wireHalfWidth(aShape.w * wMul * wVar * aGlow.w, vViewZ, pxPerMetre(uFxResolution.y), aa); |
| +добавлено | // a wide ribbon seen end-on is a fan, and a branch passing the lens a wedge across the frame |
| +добавлено | hw = min(hw * smoothstep(0.0, 0.25, 1.0 - mu), 0.07 * vViewZ); |
| +добавлено | // no flat end caps: the ribbon fades out over about its own width |
| +добавлено | vColor = aGlow.rgb * iMul * aa * smoothstep(0.0, min(1.5 * hw, 0.3 * len), min(t, min(vis, 1.0) - t) * len); |
| +добавлено | #else |
| +добавлено | float hw = min(wireHalfWidth(aShape.w * wMul * wVar, vViewZ, pxPerMetre(uResolution.y), aa), 0.012 * vViewZ); |
| +добавлено | vColor = aCore.rgb * iMul * aa; |
| +добавлено | vEdge = aGlow.rgb * iMul * aa; |
| +добавлено | #endif |
| +добавлено | vUv = vec2(t, position.y); |
| +добавлено | gl_Position = projectionMatrix * viewMatrix * vec4(p + side * position.y * hw, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // A hot filament twisting inside a softer body inside a saturated sheath: the tone mapper clips the |
| +добавлено | // middle of a return stroke, the falloff and the wander are what keep it from being a flat stripe. |
| +добавлено | const CORE_FRAG = /* glsl */` |
| +добавлено | in vec2 vUv; |
| +добавлено | in vec3 vColor; |
| +добавлено | in vec3 vEdge; |
| +добавлено | in float vS; |
| +добавлено | out vec4 fragColor; |
| +добавлено | void main() { |
| +добавлено | float y = vUv.y, r2 = y * y, env = 1.0 - r2; |
| +добавлено | float o = y - 0.3 * sin(vS * 9.0 + 2.1 * sin(vS * 3.7)); |
| +добавлено | float body = exp(-r2 * 5.0); |
| +добавлено | fragColor = vec4((vColor * (0.62 * exp(-o * o * 26.0) + 0.38 * body) + vEdge * 2.0 * (1.0 - body)) * env * env, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // The mirrored strip, kept only where the eye ray meets a visible floor or the pool: Fresnel, and |
| +добавлено | // the same puddle mask and char the floor material uses. |
| +добавлено | const MIRROR_FRAG = COMMON_GLSL + GROUND_GLSL + /* glsl */` |
| +добавлено | uniform sampler2D uSceneDepth; |
| +добавлено | uniform sampler2D uStoneNoise; |
| +добавлено | in vec2 vUv; |
| +добавлено | in vec3 vColor; |
| +добавлено | in vec3 vW; |
| +добавлено | out vec4 fragColor; |
| +добавлено | void main() { |
| +добавлено | vec3 rd = vW - cameraPosition; |
| +добавлено | vec3 q = cameraPosition + rd * (-cameraPosition.y / min(rd.y, -1e-4)); |
| +добавлено | float qz = -(viewMatrix * vec4(q, 1.0)).z; |
| +добавлено | if (dot(q.xz, q.xz) > ${(ARENA.radius * ARENA.radius).toFixed(1)} || linearDepth(texelFetch(uSceneDepth, ivec2(gl_FragCoord.xy), 0).r) < qz - 0.12) discard; |
| +добавлено | vec2 pq = abs(q.xz - vec2(${ARENA.pool.center.x.toFixed(3)}, ${ARENA.pool.center.y.toFixed(3)})); |
| +добавлено | float refl = 1.0; |
| +добавлено | if (pq.x > ${ARENA.pool.half.x.toFixed(3)} || pq.y > ${ARENA.pool.half.y.toFixed(3)}) { |
| +добавлено | vec4 g = groundA(q.xz); |
| +добавлено | float wt = clamp(g.z, 0.0, 1.0); |
| +добавлено | float puddle = smoothstep(0.35, 0.7, wt * (0.6 + 0.8 * texture(uStoneNoise, q.xz * 0.11 + 0.31).g)); |
| +добавлено | refl = mix(0.16, 1.0, max(puddle, wt * 0.5)) * (1.0 - 0.9 * clamp(g.y, 0.0, 1.0)); |
| +добавлено | } |
| +добавлено | float nv = 1.0 - clamp((cameraPosition.y - q.y) / length(cameraPosition - q), 0.0, 1.0), nv2 = nv * nv; |
| +добавлено | float env = 1.0 - vUv.y * vUv.y; |
| +добавлено | // the real channel is thousands of times brighter than anything else in the frame, so even 2-5% |
| +добавлено | // Fresnel off a wet slab reads strongly: boosted, with the grazing end capped |
| +добавлено | fragColor = vec4(vColor * (env * env * refl * min(8.0 * (0.02 + 0.98 * nv2 * nv2 * nv), 1.0)), 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const GLOW_FRAG = /* glsl */` |
| +добавлено | in vec2 vUv; |
| +добавлено | in vec3 vColor; |
| +добавлено | in float vViewZ; |
| +добавлено | void main() { |
| +добавлено | float v2 = vUv.y * vUv.y; |
| +добавлено | // a tight halo hugging the core plus the wide glow; both reach 0 at the strip edge, bloom does the rest |
| +добавлено | float g = 0.55 * (exp(-v2 * 3.0) - 0.0498) + 0.45 * (exp(-v2 * 18.0)); |
| +добавлено | fxOut(vec3(0.0), 0.0, vColor * max(g, 0.0) * softFade(vViewZ, 0.5), vec2(0.0), vViewZ); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- JS mirror of the main channel ------------------------------------------------------- |
| +добавлено | function pcg(v) { |
| +добавлено | const s = (Math.imul(v, 747796405) + 2891336453) >>> 0; |
| +добавлено | const w = Math.imul((s >>> ((s >>> 28) + 4)) ^ s, 277803737) >>> 0; |
| +добавлено | return ((w >>> 22) ^ w) >>> 0; |
| +добавлено | } |
| +добавлено | const urand = (v) => pcg(v >>> 0) / 4294967296; |
| +добавлено | function lnoise(x, salt) { |
| +добавлено | const i = Math.floor(x), k = (i + salt) >>> 0; |
| +добавлено | const a = urand(k), b = urand((k + 1) >>> 0); |
| +добавлено | return (a + (b - a) * (x - i)) * 2 - 1; |
| +добавлено | } |
| +добавлено | const _d = new THREE.Vector3(), _u = new THREE.Vector3(), _v = new THREE.Vector3(), _q = new THREE.Vector3(); |
| +добавлено | const UP = new THREE.Vector3(0, 1, 0), RIGHT = new THREE.Vector3(1, 0, 0); |
| +добавлено | function boltPathJS(A, B, t, seed, jag, freq, octaves, gain, out) { |
| +добавлено | _d.subVectors(B, A); |
| +добавлено | const L = _d.length(); |
| +добавлено | _d.multiplyScalar(1 / Math.max(L, 1e-6)); |
| +добавлено | _u.crossVectors(_d, Math.abs(_d.y) < 0.99 ? UP : RIGHT).normalize(); |
| +добавлено | _v.crossVectors(_d, _u); |
| +добавлено | let n1 = 0, n2 = 0, amp = 1, f = freq; |
| +добавлено | for (let k = 0; k < octaves; k++) { |
| +добавлено | const s = pcg((seed + Math.imul(k, 0x9E3779B9)) >>> 0); |
| +добавлено | n1 += amp * lnoise(t * f, s); |
| +добавлено | n2 += amp * lnoise(t * f, (s ^ 0x5bd1e995) >>> 0); |
| +добавлено | amp *= gain; f *= 2; |
| +добавлено | } |
| +добавлено | const k = L * jag * Math.sqrt(Math.max(Math.sin(Math.PI * t), 0)); |
| +добавлено | return out.lerpVectors(A, B, t).addScaledVector(_u, n1 * k).addScaledVector(_v, n2 * k); |
| +добавлено | } |
| +добавлено | const sdfAt = (p, dx, dy, dz) => arenaSDF(_q.set(p.x + dx, p.y + dy, p.z + dz)); |
| +добавлено | function snapJS(p) { |
| +добавлено | const e = 0.01, d = arenaSDF(p); |
| +добавлено | _d.set(sdfAt(p, e, 0, 0) - sdfAt(p, -e, 0, 0), sdfAt(p, 0, e, 0) - sdfAt(p, 0, -e, 0), sdfAt(p, 0, 0, e) - sdfAt(p, 0, 0, -e)).normalize(); |
| +добавлено | return p.addScaledVector(_d, -(d - 0.03)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const DEFAULTS = { |
| +добавлено | seed: 1, branchSeed: 1, branches: 8, subBranches: 12, jag: 0.11, width: 0.03, |
| +добавлено | intensity: 60, glowWidth: 12, reveal: 1, snapToArena: false, |
| +добавлено | rough: 0.5, fine: 0, vary: 0, stroke: 1, dart: -1, branchLevel: 1, residual: 0, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | export class Bolts { |
| +добавлено | constructor({ max = 32 } = {}) { |
| +добавлено | this.max = max; |
| +добавлено | const geo = new THREE.InstancedBufferGeometry(); |
| +добавлено | const pos = [], index = []; |
| +добавлено | let strand = 0; |
| +добавлено | for (const { seg, n } of STRANDS) { |
| +добавлено | for (let j = 0; j < n; j++, strand++) { |
| +добавлено | const base = pos.length / 3; |
| +добавлено | for (let i = 0; i <= seg; i++) pos.push(i / seg, -1, strand, i / seg, 1, strand); |
| +добавлено | for (let i = 0; i < seg; i++) { |
| +добавлено | const a = base + i * 2; |
| +добавлено | index.push(a, a + 1, a + 2, a + 1, a + 3, a + 2); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); |
| +добавлено | geo.setIndex(index); |
| +добавлено | this.attrs = ['aA', 'aB', 'aShape', 'aCore', 'aGlow', 'aMisc', 'aFx'].map((n) => instanced(geo, n, max)); |
| +добавлено | this._arrays = this.attrs.map((x) => x.array); |
| +добавлено | geo.instanceCount = 0; |
| +добавлено | this.geometry = geo; |
| +добавлено | this.segments = STRANDS.reduce((s, x) => s + x.seg * x.n, 0); |
| +добавлено | |
| +добавлено | this.uniforms = { ...U }; |
| +добавлено | const head = COMMON_GLSL + ARENA_GLSL + STRIP_GLSL + BOLT_VERT; |
| +добавлено | this.cores = new THREE.Mesh(geo, new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms: this.uniforms, ...LINES_BLENDING, side: THREE.DoubleSide, |
| +добавлено | vertexShader: head, fragmentShader: CORE_FRAG, |
| +добавлено | })); |
| +добавлено | this.glows = new THREE.Mesh(geo, new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms: this.uniforms, ...FX_BLENDING, side: THREE.DoubleSide, defines: { BOLT_GLOW: 1 }, |
| +добавлено | vertexShader: FX_VERT_HEAD + head, |
| +добавлено | fragmentShader: FX_FRAG_HEAD + COMMON_GLSL + FX_OUT_GLSL + GLOW_FRAG, |
| +добавлено | })); |
| +добавлено | this.cores.frustumCulled = this.glows.frustumCulled = false; |
| +добавлено | this.cores.visible = this.glows.visible = false; |
| +добавлено | if (Q.reflectFx) { |
| +добавлено | const mirror = new THREE.Mesh(geo, new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms: { ...this.uniforms, uStoneNoise: arenaUniforms.uStoneNoise }, ...LINES_BLENDING, depthTest: false, side: THREE.DoubleSide, defines: { BOLT_MIRROR: 1 }, |
| +добавлено | vertexShader: head, fragmentShader: MIRROR_FRAG, |
| +добавлено | })); |
| +добавлено | mirror.frustumCulled = false; |
| +добавлено | this.cores.add(mirror); |
| +добавлено | } |
| +добавлено | |
| +добавлено | this.bolts = Array.from({ length: max }, (_, index) => ({ |
| +добавлено | index, active: false, ...DEFAULTS, |
| +добавлено | a: new THREE.Vector3(), b: new THREE.Vector3(), |
| +добавлено | color: new THREE.Color(), glowColor: new THREE.Color(), |
| +добавлено | // JS mirror of the main channel (sparks, the line light); out is returned |
| +добавлено | point(t, out) { |
| +добавлено | boltPathJS(this.a, this.b, t, pcg(this.seed >>> 0), this.jag, MAIN.freq, MAIN.octaves + (this.fine ? 1 : 0), this.rough, out); |
| +добавлено | return this.snapToArena ? snapJS(out) : out; |
| +добавлено | }, |
| +добавлено | release() { this.active = false; }, |
| +добавлено | })); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // a, b: Vector3 (copied); colours: THREE.Color (copied). glowColor is multiplied by intensity, |
| +добавлено | // so keep it ~0.05-0.2 in magnitude. Returns null when all 32 are live. |
| +добавлено | acquire(opts = {}) { |
| +добавлено | for (const h of this.bolts) { |
| +добавлено | if (h.active) continue; |
| +добавлено | Object.assign(h, DEFAULTS); |
| +добавлено | h.seed = (Math.random() * 16777216) | 0; |
| +добавлено | h.branchSeed = (Math.random() * 16777216) | 0; |
| +добавлено | h.color.setRGB(0.82, 0.9, 1.0); // ~20000 K: near-white with a blue cast |
| +добавлено | h.glowColor.setRGB(0.05, 0.075, 0.2); |
| +добавлено | for (const k in opts) { |
| +добавлено | const v = opts[k]; |
| +добавлено | if (v && v.isVector3) h[k].copy(v); else if (v && v.isColor) h[k].copy(v); else h[k] = v; |
| +добавлено | } |
| +добавлено | h.active = true; |
| +добавлено | return h; |
| +добавлено | } |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | update() { |
| +добавлено | let top = 0, dirty = false; |
| +добавлено | const X = this._arrays, a = X[0], b = X[1], s = X[2], c = X[3], g = X[4], m = X[5], e = X[6]; |
| +добавлено | for (const h of this.bolts) { |
| +добавлено | const o = h.index * 4, on = h.active && h.intensity > 0 && h.reveal > 0; |
| +добавлено | dirty = put4(c, o, h.color.r * h.intensity, h.color.g * h.intensity, h.color.b * h.intensity, on ? h.reveal : 0) || dirty; |
| +добавлено | if (!on) continue; |
| +добавлено | top = h.index + 1; |
| +добавлено | dirty = put4(a, o, h.a.x, h.a.y, h.a.z, h.seed) || dirty; |
| +добавлено | dirty = put4(b, o, h.b.x, h.b.y, h.b.z, h.branchSeed) || dirty; |
| +добавлено | dirty = put4(s, o, h.branches, h.subBranches, h.jag, h.width) || dirty; |
| +добавлено | dirty = put4(g, o, h.glowColor.r * h.intensity, h.glowColor.g * h.intensity, h.glowColor.b * h.intensity, h.glowWidth) || dirty; |
| +добавлено | dirty = put4(m, o, h.snapToArena ? 1 : 0, h.rough, h.fine ? 1 : 0, h.vary) || dirty; |
| +добавлено | dirty = put4(e, o, h.stroke, h.dart, h.branchLevel, h.residual) || dirty; |
| +добавлено | } |
| +добавлено | if (dirty) for (const x of this.attrs) x.needsUpdate = true; |
| +добавлено | this.geometry.instanceCount = top; |
| +добавлено | this.cores.visible = this.glows.visible = top > 0; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import { COMMON_GLSL, NOISE_GLSL, WORLD_GLSL, FORCES_GLSL, FX_VERT_HEAD, FX_FRAG_HEAD, FX_OUT_GLSL } from './common.js'; |
| +добавлено | |
| +добавлено | // Shaders for FluidVolume.js (see its header for the design). Every sim pass is one fullscreen |
| +добавлено | // draw over a 2D atlas holding a 3D grid; all lookups are explicit LOD 0 (implicit-gradient |
| +добавлено | // samples inside data-dependent loops make ANGLE's FXC unroll them). |
| +добавлено | |
| +добавлено | export const MAX_SRC = 8; |
| +добавлено | |
| +добавлено | const HEAD = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | precision highp sampler2D; |
| +добавлено | #define texture(s, p) textureLod(s, p, 0.0) |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // 3D grid in a 2D atlas: slice k is tile (k % tiles.x, k / tiles.x), each tile dim.xy texels. |
| +добавлено | // Voxel centres sit at i + 0.5 in voxel units. |
| +добавлено | const GRID_GLSL = /* glsl */` |
| +добавлено | struct Grid { vec3 dim; vec2 tiles; vec2 inv; }; |
| +добавлено | ivec2 gridTexel(Grid g, ivec3 v) { |
| +добавлено | v = clamp(v, ivec3(0), ivec3(g.dim) - 1); |
| +добавлено | int tx = int(g.tiles.x); |
| +добавлено | return ivec2((v.z % tx) * int(g.dim.x) + v.x, (v.z / tx) * int(g.dim.y) + v.y); |
| +добавлено | } |
| +добавлено | vec4 gridFetch(sampler2D t, Grid g, ivec3 v) { return texelFetch(t, gridTexel(g, v), 0); } |
| +добавлено | vec2 sliceOrigin(Grid g, float k) { float row = floor((k + 0.5) / g.tiles.x); return vec2(k - row * g.tiles.x, row) * g.dim.xy; } |
| +добавлено | // trilinear: hardware bilinear inside two slices, lerp between them (clamped so tiles never bleed) |
| +добавлено | vec4 gridSample(sampler2D t, Grid g, vec3 p) { |
| +добавлено | vec3 q = clamp(p, vec3(0.5), g.dim - 0.5); |
| +добавлено | float z = q.z - 0.5, k0 = floor(z), f = z - k0, k1 = min(k0 + 1.0, g.dim.z - 1.0); |
| +добавлено | vec4 a = textureLod(t, (sliceOrigin(g, k0) + q.xy) * g.inv, 0.0); |
| +добавлено | vec4 b = textureLod(t, (sliceOrigin(g, k1) + q.xy) * g.inv, 0.0); |
| +добавлено | return mix(a, b, f); |
| +добавлено | } |
| +добавлено | bool gridVoxel(Grid g, out ivec3 v) { |
| +добавлено | ivec2 p = ivec2(gl_FragCoord.xy), d = ivec2(g.dim.xy), tile = p / d; |
| +добавлено | v = ivec3(p - tile * d, tile.y * int(g.tiles.x) + tile.x); |
| +добавлено | return v.z < int(g.dim.z); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // transfer function shared by the light pass and the raymarch |
| +добавлено | // temperature th: 0 ambient, 1 = uLook1.x kelvin (the spell's flame temperature) |
| +добавлено | const LOOK_GLSL = /* glsl */` |
| +добавлено | uniform vec4 uLook0; // emission gain, soot extinction (1/m per unit), flame extinction (1/m), absorb (black flame) |
| +добавлено | uniform vec4 uLook1; // kelvin at th = 1, ambient kelvin, fuel extinction (1/m per unit), chroma (render only) |
| +добавлено | uniform vec3 uTint; |
| +добавлено | float kelvinOf(float th) { return uLook1.y + (uLook1.x - uLook1.y) * th; } |
| +добавлено | float flameOf(float th) { return smoothstep(0.12, 0.5, th); } |
| +добавлено | // Kirchhoff: hot soot and flame gas emit as much as they absorb, emission = sigma_abs * B(T). An |
| +добавлено | // opaque hot region therefore shows its own surface temperature (a blackbody), cooled soot is |
| +добавлено | // black smoke, and a thin flame sheet is a faint, see-through glow. B(T) in the visible band |
| +добавлено | // follows Planck's ~exp(-hc / (lambda k T)) at lambda ~ 600 nm (softened 2x for the display range): |
| +добавлено | // far steeper than T^4, so 1000 K soot is a dull red ember and 2400 K is ~4x the reference. |
| +добавлено | float glowOf(float th) { |
| +добавлено | float T = kelvinOf(th), k = exp(12000.0 / uLook1.x - 12000.0 / max(T, 400.0)); |
| +добавлено | return k / (1.0 + 0.08 * k) * smoothstep(0.08, 0.25, th); |
| +добавлено | } |
| +добавлено | float sigmaHot(vec4 s) { return uLook0.y * max(s.b, 0.0) + uLook0.z * flameOf(s.r); } |
| +добавлено | float sigmaOf(vec4 s) { return sigmaHot(s) * (1.0 + 6.0 * uLook0.w * flameOf(s.r)) + uLook1.z * max(s.g, 0.0); } |
| +добавлено | vec3 emitOf(vec4 s) { |
| +добавлено | float th = max(s.r, 0.0), g = glowOf(th) * sigmaHot(s) * uLook0.x * (1.0 - uLook0.w); |
| +добавлено | return g > 1e-4 ? blackbody(kelvinOf(th)) * g * uTint : vec3(0.0); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const SIM_HEAD = HEAD + COMMON_GLSL + GRID_GLSL + /* glsl */` |
| +добавлено | uniform vec3 uDim; |
| +добавлено | uniform vec2 uTiles; |
| +добавлено | uniform vec2 uInv; |
| +добавлено | uniform vec3 uOrigin; // world position of the grid's min corner |
| +добавлено | uniform float uH; // voxel size (m) |
| +добавлено | uniform float uSimDt; |
| +добавлено | uniform vec3 uShift; // how far the domain moved this step (voxels): new origin - old origin |
| +добавлено | uniform vec4 uObst; // a solid sphere (an Aegis dome): centre in voxels minus half a voxel, radius in voxels (0: none) |
| +добавлено | Grid G() { return Grid(uDim, uTiles, uInv); } |
| +добавлено | // cells below the arena floor, and inside the sphere, are solid |
| +добавлено | bool solid(ivec3 v) { |
| +добавлено | if (float(v.y) + 0.5 < -uOrigin.y / uH) return true; |
| +добавлено | if (uObst.w <= 0.0) return false; // (uniform: no sphere, no cost) |
| +добавлено | vec3 o = vec3(v) - uObst.xyz; |
| +добавлено | return dot(o, o) < uObst.w * uObst.w; |
| +добавлено | } |
| +добавлено | bool outside(ivec3 v) { return any(lessThan(v, ivec3(0))) || any(greaterThanEqual(v, ivec3(uDim))); } |
| +добавлено | // open boundary: still air outside the box (one-voxel fade) |
| +добавлено | vec4 sampleOpen(sampler2D t, vec3 p) { |
| +добавлено | vec3 o = max(max(-p, p - uDim), 0.0); |
| +добавлено | float w = clamp(1.0 - max(o.x, max(o.y, o.z)), 0.0, 1.0); |
| +добавлено | return w > 0.0 ? gridSample(t, G(), p) * w : vec4(0.0); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // 1. semi-Lagrangian advection of velocity and scalars (RK2 backtrace), in the moving frame |
| +добавлено | export const ADVECT = SIM_HEAD + /* glsl */` |
| +добавлено | uniform sampler2D uV; |
| +добавлено | uniform sampler2D uS; |
| +добавлено | layout(location = 0) out vec4 oV; |
| +добавлено | layout(location = 1) out vec4 oS; |
| +добавлено | void main() { |
| +добавлено | ivec3 v; |
| +добавлено | if (!gridVoxel(G(), v)) { oV = vec4(0.0); oS = vec4(0.0); return; } |
| +добавлено | vec3 p = vec3(v) + 0.5 + uShift; // this cell's world point, in the previous grid |
| +добавлено | float k = uSimDt / uH; |
| +добавлено | vec3 u1 = sampleOpen(uV, p).xyz; |
| +добавлено | vec3 u2 = sampleOpen(uV, p - 0.5 * k * u1).xyz; |
| +добавлено | vec3 q = p - k * u2; |
| +добавлено | oV = sampleOpen(uV, q); |
| +добавлено | oS = sampleOpen(uS, q); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // 2. MacCormack correction (Selle et al. 2008), clamped to the old field's extrema around the |
| +добавлено | // departure point, so it never overshoots |
| +добавлено | export const CORRECT = SIM_HEAD + /* glsl */` |
| +добавлено | uniform sampler2D uV; |
| +добавлено | uniform sampler2D uS; |
| +добавлено | uniform sampler2D uVf; |
| +добавлено | uniform sampler2D uSf; |
| +добавлено | uniform float uMacCormack; |
| +добавлено | layout(location = 0) out vec4 oV; |
| +добавлено | layout(location = 1) out vec4 oS; |
| +добавлено | void main() { |
| +добавлено | ivec3 v; |
| +добавлено | if (!gridVoxel(G(), v)) { oV = vec4(0.0); oS = vec4(0.0); return; } |
| +добавлено | vec4 vf = gridFetch(uVf, G(), v), sf = gridFetch(uSf, G(), v); |
| +добавлено | if (uMacCormack < 0.5) { oV = vf; oS = sf; return; } |
| +добавлено | float k = uSimDt / uH; |
| +добавлено | vec3 c = vec3(v) + 0.5; |
| +добавлено | vec3 r = c + k * vf.xyz; |
| +добавлено | vec4 vb = gridSample(uVf, G(), r), sb = gridSample(uSf, G(), r); |
| +добавлено | vec4 v0 = sampleOpen(uV, c + uShift), s0 = sampleOpen(uS, c + uShift); |
| +добавлено | vec4 vn = vf + 0.5 * (v0 - vb), sn = sf + 0.5 * (s0 - sb); |
| +добавлено | ivec3 i0 = ivec3(floor(c + uShift - k * vf.xyz - 0.5)); |
| +добавлено | vec4 vlo = vec4(1e4), vhi = vec4(-1e4), slo = vec4(1e4), shi = vec4(-1e4); |
| +добавлено | for (int n = 0; n < 8; n++) { |
| +добавлено | ivec3 o = i0 + ivec3(n & 1, (n >> 1) & 1, n >> 2); |
| +добавлено | vec4 a = vec4(0.0), b = vec4(0.0); |
| +добавлено | if (!outside(o)) { a = gridFetch(uV, G(), o); b = gridFetch(uS, G(), o); } |
| +добавлено | vlo = min(vlo, a); vhi = max(vhi, a); slo = min(slo, b); shi = max(shi, b); |
| +добавлено | } |
| +добавлено | oV = clamp(vn, vlo, vhi); |
| +добавлено | oS = clamp(sn, slo, shi); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // 3. vorticity w = curl u (rgb) and |w| (a) |
| +добавлено | export const CURL = SIM_HEAD + /* glsl */` |
| +добавлено | uniform sampler2D uV; |
| +добавлено | out vec4 oC; |
| +добавлено | vec3 at(ivec3 v) { return gridFetch(uV, G(), v).xyz; } |
| +добавлено | void main() { |
| +добавлено | ivec3 v; |
| +добавлено | if (!gridVoxel(G(), v)) { oC = vec4(0.0); return; } |
| +добавлено | vec3 L = at(v - ivec3(1, 0, 0)), R = at(v + ivec3(1, 0, 0)), D = at(v - ivec3(0, 1, 0)); |
| +добавлено | vec3 U = at(v + ivec3(0, 1, 0)), B = at(v - ivec3(0, 0, 1)), F = at(v + ivec3(0, 0, 1)); |
| +добавлено | vec3 w = vec3((U.z - D.z) - (F.y - B.y), (F.x - B.x) - (R.z - L.z), (R.y - L.y) - (U.x - D.x)) * (0.5 / uH); |
| +добавлено | oC = vec4(w, length(w)); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // 4. sources, combustion, cooling, buoyancy, vorticity confinement, external forces |
| +добавлено | export const REACT = SIM_HEAD + NOISE_GLSL + WORLD_GLSL + FORCES_GLSL + /* glsl */` |
| +добавлено | uniform sampler2D uV; |
| +добавлено | uniform sampler2D uS; |
| +добавлено | uniform sampler2D uC; |
| +добавлено | uniform vec4 uSrcP[${MAX_SRC}]; // world centre, radius m |
| +добавлено | uniform vec4 uSrcA[${MAX_SRC}]; // fuel, temperature, soot, noise amount 0..1 |
| +добавлено | uniform vec4 uSrcV[${MAX_SRC}]; // velocity m/s, radial speed m/s |
| +добавлено | uniform vec4 uSrcB[${MAX_SRC}]; // mode (0 per second, 1 at least), noise frequency 1/m, seed, velocity coupling 1/s |
| +добавлено | uniform int uSrcN; |
| +добавлено | uniform vec4 uBurn; // ignition temperature, burn rate 1/s, heat per fuel, soot per fuel |
| +добавлено | uniform vec4 uDecay; // cooling 1/s, radiative cooling, soot decay 1/s, fuel decay 1/s |
| +добавлено | uniform vec4 uForce; // buoyancy m/s2 per th, soot weight m/s2 per unit, vorticity confinement, expansion per fuel |
| +добавлено | uniform vec4 uFlow; // external force coupling, damping 1/s, -, - |
| +добавлено | layout(location = 0) out vec4 oV; |
| +добавлено | layout(location = 1) out vec4 oS; |
| +добавлено | float magAt(ivec3 v) { return gridFetch(uC, G(), v).a; } |
| +добавлено | void main() { |
| +добавлено | ivec3 v; |
| +добавлено | if (!gridVoxel(G(), v) || solid(v)) { oV = vec4(0.0); oS = vec4(0.0); return; } |
| +добавлено | vec3 vel = gridFetch(uV, G(), v).xyz; |
| +добавлено | vec4 s = gridFetch(uS, G(), v); |
| +добавлено | vec3 pw = uOrigin + (vec3(v) + 0.5) * uH; |
| +добавлено | float dt = uSimDt; |
| +добавлено | for (int i = 0; i < ${MAX_SRC}; i++) { |
| +добавлено | if (i >= uSrcN) break; |
| +добавлено | vec4 P = uSrcP[i]; |
| +добавлено | vec3 d = pw - P.xyz; |
| +добавлено | float r = length(d); |
| +добавлено | if (r >= P.w) continue; |
| +добавлено | vec4 A = uSrcA[i], B = uSrcB[i], W = uSrcV[i]; |
| +добавлено | float w = 1.0 - smoothstep(0.3 * P.w, P.w, r); |
| +добавлено | if (A.w > 0.0) { // lumpy, flickering source: the noise scrolls up through it |
| +добавлено | vec3 np = pw * B.y + vec3(B.z, B.z * 0.37 - uTime * 0.8 * B.y, B.z * 0.71); |
| +добавлено | w *= mix(1.0, smoothstep(0.3, 0.7, noise3(np * 0.25)), A.w); |
| +добавлено | } |
| +добавлено | if (w <= 0.0) continue; |
| +добавлено | vec3 target = W.xyz + (r > 1e-4 ? d / r : vec3(0.0)) * W.w; |
| +добавлено | vel = mix(vel, target, w * (1.0 - exp(-B.w * dt))); |
| +добавлено | if (B.x < 0.5) s.rgb += vec3(A.y, A.x, A.z) * (w * dt); |
| +добавлено | else s.rgb = max(s.rgb, vec3(A.y, A.x, A.z) * w); |
| +добавлено | } |
| +добавлено | // combustion: hot fuel burns into heat and soot, and the gas expands (a divergence source) |
| +добавлено | float th = max(s.r, 0.0), fuel = max(s.g, 0.0), soot = max(s.b, 0.0); |
| +добавлено | float burn = fuel * (1.0 - exp(-uBurn.y * dt)) * smoothstep(0.5 * uBurn.x, uBurn.x, th); |
| +добавлено | fuel -= burn; |
| +добавлено | th += burn * uBurn.z; |
| +добавлено | soot += burn * uBurn.w; |
| +добавлено | float expand = burn / max(dt, 1e-4) * uForce.w; |
| +добавлено | // Newton cooling, plus radiative loss (exact step of dth/dt = -c th^4) |
| +добавлено | th *= exp(-uDecay.x * dt); |
| +добавлено | th /= pow(1.0 + 3.0 * uDecay.y * dt * th * th * th, 1.0 / 3.0); |
| +добавлено | soot *= exp(-uDecay.z * dt); |
| +добавлено | fuel *= exp(-uDecay.w * dt); |
| +добавлено | // hot gas rises, soot is heavy |
| +добавлено | vec3 acc = vec3(0.0, uForce.x * th - uForce.y * soot, 0.0); |
| +добавлено | // vorticity confinement (Fedkiw et al. 2001): spin the small eddies back up |
| +добавлено | vec4 c = gridFetch(uC, G(), v); |
| +добавлено | vec3 eta = vec3(magAt(v + ivec3(1, 0, 0)) - magAt(v - ivec3(1, 0, 0)), magAt(v + ivec3(0, 1, 0)) - magAt(v - ivec3(0, 1, 0)), |
| +добавлено | magAt(v + ivec3(0, 0, 1)) - magAt(v - ivec3(0, 0, 1))); |
| +добавлено | float el = length(eta); |
| +добавлено | if (el > 1e-4) acc += uForce.z * uH * cross(eta / el, c.xyz); |
| +добавлено | // the shared force field (wind, vortices, shocks...) pushes the gas like it pushes particles |
| +добавлено | float kill = 0.0; |
| +добавлено | acc += forceAccel(pw, vel, kill) * uFlow.x; |
| +добавлено | vel = (vel + acc * dt) * exp(-uFlow.y * dt); |
| +добавлено | oV = vec4(clamp(vel, -60.0, 60.0), 0.0); |
| +добавлено | oS = vec4(min(th, 4.0), min(fuel, 4.0), min(soot, 8.0), expand); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // 5. divergence minus the combustion expansion (b = h^2 (div u - e)), plus a warm-start pressure |
| +добавлено | export const DIVERGE = SIM_HEAD + /* glsl */` |
| +добавлено | uniform sampler2D uV; |
| +добавлено | uniform sampler2D uS; |
| +добавлено | uniform sampler2D uP; |
| +добавлено | uniform float uWarm; |
| +добавлено | out vec4 oP; |
| +добавлено | vec3 at(ivec3 v) { return solid(v) ? vec3(0.0) : gridFetch(uV, G(), v).xyz; } |
| +добавлено | void main() { |
| +добавлено | ivec3 v; |
| +добавлено | if (!gridVoxel(G(), v) || solid(v)) { oP = vec4(0.0); return; } |
| +добавлено | float div = (at(v + ivec3(1, 0, 0)).x - at(v - ivec3(1, 0, 0)).x + at(v + ivec3(0, 1, 0)).y - at(v - ivec3(0, 1, 0)).y |
| +добавлено | + at(v + ivec3(0, 0, 1)).z - at(v - ivec3(0, 0, 1)).z) * (0.5 / uH); |
| +добавлено | float e = gridFetch(uS, G(), v).a; |
| +добавлено | float p0 = sampleOpen(uP, vec3(v) + 0.5 + uShift).r * uWarm; |
| +добавлено | oP = vec4(p0, uH * uH * (div - e), 0.0, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // pressure neighbours: open air (p = 0) outside the box, Neumann at the floor |
| +добавлено | const PRESSURE_N = /* glsl */` |
| +добавлено | float pN(ivec3 n, float pc) { |
| +добавлено | if (solid(n)) return pc; |
| +добавлено | return outside(n) ? 0.0 : gridFetch(uP, G(), n).r; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // 6. Jacobi iteration |
| +добавлено | export const JACOBI = SIM_HEAD + /* glsl */` |
| +добавлено | uniform sampler2D uP; |
| +добавлено | out vec4 oP; |
| +добавлено | ${PRESSURE_N} |
| +добавлено | void main() { |
| +добавлено | ivec3 v; |
| +добавлено | if (!gridVoxel(G(), v)) { oP = vec4(0.0); return; } |
| +добавлено | vec4 c = gridFetch(uP, G(), v); |
| +добавлено | if (solid(v)) { oP = vec4(0.0, c.g, 0.0, 0.0); return; } |
| +добавлено | float s = pN(v + ivec3(1, 0, 0), c.r) + pN(v - ivec3(1, 0, 0), c.r) + pN(v + ivec3(0, 1, 0), c.r) |
| +добавлено | + pN(v - ivec3(0, 1, 0), c.r) + pN(v + ivec3(0, 0, 1), c.r) + pN(v - ivec3(0, 0, 1), c.r); |
| +добавлено | oP = vec4((s - c.g) / 6.0, c.g, 0.0, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // 7. projection: subtract the pressure gradient; no flow into the floor |
| +добавлено | export const PROJECT = SIM_HEAD + /* glsl */` |
| +добавлено | uniform sampler2D uV; |
| +добавлено | uniform sampler2D uS; |
| +добавлено | uniform sampler2D uP; |
| +добавлено | layout(location = 0) out vec4 oV; |
| +добавлено | layout(location = 1) out vec4 oS; |
| +добавлено | ${PRESSURE_N} |
| +добавлено | void main() { |
| +добавлено | ivec3 v; |
| +добавлено | if (!gridVoxel(G(), v) || solid(v)) { oV = vec4(0.0); oS = vec4(0.0); return; } |
| +добавлено | float pc = gridFetch(uP, G(), v).r; |
| +добавлено | vec3 g = vec3(pN(v + ivec3(1, 0, 0), pc) - pN(v - ivec3(1, 0, 0), pc), pN(v + ivec3(0, 1, 0), pc) - pN(v - ivec3(0, 1, 0), pc), |
| +добавлено | pN(v + ivec3(0, 0, 1), pc) - pN(v - ivec3(0, 0, 1), pc)) * (0.5 / uH); |
| +добавлено | vec3 vel = gridFetch(uV, G(), v).xyz - g; |
| +добавлено | if (solid(v - ivec3(0, 1, 0))) vel.y = max(vel.y, 0.0); |
| +добавлено | oV = vec4(vel, 0.0); |
| +добавлено | oS = vec4(gridFetch(uS, G(), v).rgb, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // 8. lighting volume at half resolution, one RGBA texel per 2x2x2 block: |
| +добавлено | // r sun optical depth (march to the box exit) g sky optical depth (march straight up) |
| +добавлено | // b occupancy: 0 if nothing within ~3 voxels, else 1 + |vorticity| (drives the sub-grid detail) |
| +добавлено | // a fire light: blurred Kirchhoff emission around the cell (the self-illumination source) |
| +добавлено | export const LIGHT = SIM_HEAD + NOISE_GLSL + LOOK_GLSL + /* glsl */` |
| +добавлено | uniform sampler2D uS; |
| +добавлено | uniform sampler2D uC; |
| +добавлено | uniform vec3 uCDim; |
| +добавлено | uniform vec2 uCTiles; |
| +добавлено | uniform vec2 uCInv; |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec4 uLightP; // sun step (voxels), fire-light tap spacing (voxels), fire-light gain, empty below (1/m) |
| +добавлено | out vec4 o0; |
| +добавлено | bool inBox(vec3 q) { return all(greaterThanEqual(q, vec3(0.0))) && all(lessThanEqual(q, uDim)); } |
| +добавлено | void main() { |
| +добавлено | ivec3 c; |
| +добавлено | if (!gridVoxel(Grid(uCDim, uCTiles, uCInv), c)) { o0 = vec4(0.0); return; } |
| +добавлено | vec3 p = (vec3(c) + 0.5) * 2.0; // fine voxel units: the centre of this cell's 2x2x2 block |
| +добавлено | // 27 taps around the cell: occupancy (dilated) and the fire light |
| +добавлено | float pw = 0.0, occ = 0.0; |
| +добавлено | for (int k = 0; k < 27; k++) { |
| +добавлено | vec3 o = vec3(float(k % 3), float((k / 3) % 3), float(k / 9)) - 1.0; |
| +добавлено | vec4 st = gridSample(uS, G(), p + o * uLightP.y); |
| +добавлено | float th = max(st.r, 0.0); |
| +добавлено | occ = max(occ, sigmaOf(st) + th + max(st.g, 0.0)); |
| +добавлено | pw += glowOf(th) * min(sigmaHot(st), 4.0) / (1.0 + dot(o, o)); |
| +добавлено | } |
| +добавлено | float tau = 0.0, tauU = 0.0; |
| +добавлено | occ = occ > max(uLightP.w, 1e-3) ? occ : 0.0; |
| +добавлено | if (occ > 0.0) { |
| +добавлено | float st = uLightP.x; |
| +добавлено | vec3 q = p + uSunDir * (0.5 * st); |
| +добавлено | for (int i = 0; i < 48; i++) { |
| +добавлено | if (!inBox(q)) break; |
| +добавлено | tau += sigmaOf(gridSample(uS, G(), q)); |
| +добавлено | q += uSunDir * st; |
| +добавлено | } |
| +добавлено | tau *= st * uH; |
| +добавлено | q = p + vec3(0.0, 2.0, 0.0); |
| +добавлено | for (int i = 0; i < 10; i++) { |
| +добавлено | if (q.y > uDim.y) break; |
| +добавлено | tauU += sigmaOf(gridSample(uS, G(), q)) * 4.0 * uH; |
| +добавлено | q.y += 4.0; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | float vort = gridSample(uC, G(), p).a; |
| +добавлено | o0 = vec4(tau, tauU, occ > 0.0 ? 1.0 + vort : 0.0, pw * (uLook0.x * (1.0 - uLook0.w) * uLightP.z / 27.0)); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- render: raymarch the domain box in the half-res FX pass --------------------------------- |
| +добавлено | export const RENDER_VERT = FX_VERT_HEAD + /* glsl */` |
| +добавлено | out vec3 vWorld; |
| +добавлено | void main() { |
| +добавлено | vec4 w = modelMatrix * vec4(position, 1.0); |
| +добавлено | vWorld = w.xyz; |
| +добавлено | gl_Position = projectionMatrix * viewMatrix * w; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export const RENDER_FRAG = FX_FRAG_HEAD + '#define texture(s, p) textureLod(s, p, 0.0)\n' + COMMON_GLSL + NOISE_GLSL + FX_OUT_GLSL + GRID_GLSL + LOOK_GLSL + /* glsl */` |
| +добавлено | uniform sampler2D uS; |
| +добавлено | uniform sampler2D uL0; |
| +добавлено | uniform vec3 uDim; |
| +добавлено | uniform vec2 uTiles; |
| +добавлено | uniform vec2 uInv; |
| +добавлено | uniform vec3 uCDim; |
| +добавлено | uniform vec2 uCTiles; |
| +добавлено | uniform vec2 uCInv; |
| +добавлено | uniform vec3 uOrigin; |
| +добавлено | uniform float uH; |
| +добавлено | uniform vec4 uMarch; // step (m), max steps, sub-grid amplitude (voxels), sub-grid frequency (tiles / m) |
| +добавлено | uniform vec4 uMarch2; // edge fade (voxels), m per FX pixel at 1 m, bottom face open (0/1), - |
| +добавлено | uniform vec4 uLit; // HG g, sun gain, sky gain, fire-light gain |
| +добавлено | uniform vec3 uSootColor; |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform vec3 uAmbient; |
| +добавлено | in vec3 vWorld; |
| +добавлено | |
| +добавлено | Grid G() { return Grid(uDim, uTiles, uInv); } |
| +добавлено | Grid CG() { return Grid(uCDim, uCTiles, uCInv); } |
| +добавлено | |
| +добавлено | float gSunPh; |
| +добавлено | float gMs; // multiple-scattering weight from the albedo |
| +добавлено | vec3 gFire; // fire-light colour (blackbody at a typical flame-edge temperature) x gain |
| +добавлено | // per metre: extinction, in-scattered radiance (soot only), emitted radiance |
| +добавлено | // returns false in empty space (nothing within ~3 voxels) |
| +добавлено | bool sampleAt(vec3 pw, out float sg, out vec3 sc, out vec3 em) { |
| +добавлено | sg = 0.0; sc = vec3(0.0); em = vec3(0.0); |
| +добавлено | vec3 p = (pw - uOrigin) / uH; |
| +добавлено | vec4 l0 = gridSample(uL0, CG(), p * 0.5); |
| +добавлено | if (l0.b <= 0.0) return false; |
| +добавлено | // sub-grid detail (in the spirit of wavelet turbulence): displace the lookup with band-limited |
| +добавлено | // curl noise drifting up with the gas, strongest where the resolved flow is turbulent |
| +добавлено | vec3 n = curl3(pw * uMarch.w + vec3(0.0, -uTime * 0.28, 0.0)) + 0.5 * curl3(pw * (uMarch.w * 2.03) + vec3(0.31, -uTime * 0.61, 0.17)); |
| +добавлено | vec4 s = gridSample(uS, G(), p + n * (uMarch.z * clamp(0.2 + max(l0.b - 1.0, 0.0) * 0.06, 0.2, 1.0))); |
| +добавлено | // fade out towards the open faces so the box never shows |
| +добавлено | vec3 e = min(p, uDim - p); |
| +добавлено | float ed = min(min(e.x, e.z), uMarch2.z > 0.5 ? min(e.y, uDim.y - p.y) : uDim.y - p.y); |
| +добавлено | // (the fade distance is jittered by the same noise, so a cloud that reaches a face frays |
| +добавлено | // into wisps instead of showing a straight cut) |
| +добавлено | float fade = smoothstep(0.5, uMarch2.x, ed + 1.6 * (n.x + n.z)); |
| +добавлено | s.rgb *= fade * fade; |
| +добавлено | sg = sigmaOf(s); |
| +добавлено | em = emitOf(s); |
| +добавлено | float ss = uLook0.y * max(s.b, 0.0); |
| +добавлено | if (ss < 1e-4) return true; |
| +добавлено | // sun: single scattering through the precomputed optical depth, plus two wider, weaker octaves |
| +добавлено | // standing in for multiple scattering (Wrenninge 2015); sky through the optical depth above |
| +добавлено | float t = l0.r; |
| +добавлено | // multiple-scattering octaves scale with albedo: dark soot barely scatters twice, so it keeps |
| +добавлено | // its form shading (lit tops, near-black undersides) instead of glowing flat |
| +добавлено | vec3 sun = uSunColor * uLit.y * (exp(-t) * gSunPh + gMs * (0.4 * exp(-0.5 * t) + 0.15 * exp(-0.25 * t))); |
| +добавлено | vec3 sky = uAmbient * uLit.z * (0.1 + 0.9 * exp(-0.6 * l0.g)); |
| +добавлено | sc = ss * uSootColor * (sun + sky + gFire * l0.a); |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vec3 rd = normalize(vWorld - cameraPosition); |
| +добавлено | vec3 dd = mix(rd, vec3(1e-6), lessThan(abs(rd), vec3(1e-6))); |
| +добавлено | vec3 bmin = uOrigin, bmax = uOrigin + uDim * uH; |
| +добавлено | vec3 ta = (bmin - cameraPosition) / dd, tb = (bmax - cameraPosition) / dd; |
| +добавлено | vec3 lo = min(ta, tb), hi = max(ta, tb); |
| +добавлено | float t0 = max(max(max(lo.x, lo.y), lo.z), 0.0), t1 = min(min(hi.x, hi.y), hi.z); |
| +добавлено | float cosV = dot(rd, -vec3(viewMatrix[0][2], viewMatrix[1][2], viewMatrix[2][2])); |
| +добавлено | t1 = min(t1, sceneViewZ() / cosV); |
| +добавлено | if (t1 <= t0) discard; |
| +добавлено | // step: a fraction of a voxel, never finer than the pixel footprint |
| +добавлено | float target = max(uMarch.x, 0.5 * (t0 + t1) * uMarch2.y); |
| +добавлено | int steps = int(clamp(ceil((t1 - t0) / target), 4.0, uMarch.y)); |
| +добавлено | float dt = (t1 - t0) / float(steps); |
| +добавлено | float mu = dot(uSunDir, rd); |
| +добавлено | // soot: forward lobe + a weak back lobe, normalised so isotropic = 1 |
| +добавлено | gSunPh = mix(hgPhase(mu, uLit.x), hgPhase(mu, -0.25), 0.25) * 4.0 * PI; |
| +добавлено | gFire = blackbody(kelvinOf(0.75)) * uTint * uLit.w; |
| +добавлено | gMs = clamp(dot(uSootColor, vec3(1.0)), 0.0, 1.0); |
| +добавлено | float T = 1.0, zs = 0.0, ws = 0.0, sgP = 0.0, tP = t0; |
| +добавлено | vec3 scat = vec3(0.0), emit = vec3(0.0), scP = vec3(0.0), emP = vec3(0.0); |
| +добавлено | bool emptyP = true; |
| +добавлено | int i = 0; |
| +добавлено | for (int n = 0; n <= 256; n++) { |
| +добавлено | if (T < 0.01) break; |
| +добавлено | float t = t0 + float(i) * dt; |
| +добавлено | float sg; vec3 sc, em; |
| +добавлено | bool occ = sampleAt(cameraPosition + rd * t, sg, sc, em); |
| +добавлено | if (i > 0) { |
| +добавлено | // trapezoid slab between this sample and the previous one, energy conserving |
| +добавлено | float L = t - tP, s = 0.5 * (sg + sgP); |
| +добавлено | vec3 S = 0.5 * (sc + scP), E = 0.5 * (em + emP); |
| +добавлено | if (s > 1e-5) { |
| +добавлено | float tr = exp(-s * L), a = T * (1.0 - tr); |
| +добавлено | scat += S * (a / s); |
| +добавлено | emit += E * (a / s); |
| +добавлено | zs += a * (t - 0.5 * L); ws += a; |
| +добавлено | T *= tr; |
| +добавлено | } else emit += T * E * L; |
| +добавлено | } |
| +добавлено | sgP = sg; scP = sc; emP = em; tP = t; |
| +добавлено | if (i >= steps) break; |
| +добавлено | i = min(i + (!occ && emptyP ? 2 : 1), steps); // stride over empty space |
| +добавлено | emptyP = !occ; |
| +добавлено | } |
| +добавлено | float alpha = 1.0 - T; |
| +добавлено | if (alpha < 0.002 && dot(emit, emit) < 1e-6) discard; |
| +добавлено | float z = (ws > 0.0 ? zs / ws : t0) * cosV; |
| +добавлено | fxOut(scat / max(alpha, 1e-4), alpha, emit, vec2(0.0), z); |
| +добавлено | }`; |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { FullscreenQuad, rawPass } from '../engine/fullscreen.js'; |
| +добавлено | import { U, FX_BLENDING } from './common.js'; |
| +добавлено | import { Q } from '../engine/quality.js'; |
| +добавлено | import * as BASE from './FluidVolume.glsl.js'; |
| +добавлено | |
| +добавлено | // Shader revisions over the base sources, applied at load. A stale anchor throws, so a change to the |
| +добавлено | // base can never silently drop one of these. |
| +добавлено | function patch(src, from, to) { |
| +добавлено | if (!src.includes(from)) throw new Error(`FluidVolume: shader anchor not found: ${from.slice(0, 60)}`); |
| +добавлено | return src.replace(from, () => to); |
| +добавлено | } |
| +добавлено | const edit = (src, ...pairs) => pairs.reduce((out, [from, to]) => patch(out, from, to), src); |
| +добавлено | |
| +добавлено | // sim: resolved turbulence (a curl-noise force on hot gas), soot that radiates its heat away so sooty |
| +добавлено | // gas chills into dark lanes, and soot that thins by erosion instead of fading as a whole |
| +добавлено | const REACT = edit(BASE.REACT, |
| +добавлено | ['uniform vec4 uFlow; // external force coupling, damping 1/s, -, -', |
| +добавлено | 'uniform vec4 uFlow; // external force coupling, damping 1/s, -, -\nuniform vec4 uTurb; // turbulence m/s2, turbulence frequency tiles/m, soot erosion units/s, soot radiative cooling'], |
| +добавлено | ['th /= pow(1.0 + 3.0 * uDecay.y * dt * th * th * th, 1.0 / 3.0);', |
| +добавлено | 'th /= pow(1.0 + 3.0 * uDecay.y * dt * th * th * th * (1.0 + uTurb.w * soot), 1.0 / 3.0);'], |
| +добавлено | ['soot *= exp(-uDecay.z * dt);', |
| +добавлено | 'soot = max(soot * exp(-uDecay.z * dt) - uTurb.z * dt, 0.0);'], |
| +добавлено | [' // the shared force field (wind, vortices, shocks...)', |
| +добавлено | ' if (uTurb.x > 0.0) acc += curl3(pw * uTurb.y + vec3(0.0, -uTime * 0.6 * uTurb.y, 0.0)) * (uTurb.x * min(th, 1.0));\n // the shared force field (wind, vortices, shocks...)'], |
| +добавлено | ); |
| +добавлено | |
| +добавлено | // render: everything from the sampler down. Three changes from the base: |
| +добавлено | // - the march. The base stretched a whole number of steps over each ray, so the step count jumped |
| +добавлено | // along contours of ray length (stripes). Now the spacing is one constant per domain on a lattice |
| +добавлено | // anchored at the ray's entry, and every decision that could move the lattice is made harmless: |
| +добавлено | // an empty-space stride that lands in gas steps back onto the lattice (the occupancy grid is |
| +добавлено | // axis-aligned, so stride landings differing per pixel showed as vertical stripes, worst on the |
| +добавлено | // coarse Low grid), and an optically thick slab is refined in place through its midpoint, blended |
| +добавлено | // in continuously (the old halving shifted the rest of the ray by half a step: rings). Every |
| +добавлено | // result is a continuous function of the pixel, so no per-pixel jitter is needed (it showed as a |
| +добавлено | // dot grid at half res). |
| +добавлено | // - near fade: density ramps in over uMarch2.w^-1 metres from the camera, so a camera inside a cloud |
| +добавлено | // sees wisps and depth instead of a flat wall. |
| +добавлено | // - the detail. With detail on (uDetail.y > 0), a Worley cell lookup erodes soot and chills the gas |
| +добавлено | // along the cell creases: cauliflower silhouettes and mottled burning surfaces at any grid size. |
| +добавлено | // The curl displacement is one octave, band-limited to the march step by the JS (a finer octave |
| +добавлено | // only aliased into hair). |
| +добавлено | const RENDER_BODY = /* glsl */` |
| +добавлено | uniform vec4 uDetail; // soot erosion (units), cell pattern frequency (tiles/m, 0 = off), heat chill 0..1, largest empty-space stride |
| +добавлено | uniform vec3 uDetailC; // pattern centre: it rides the gas |
| +добавлено | float gSunPh; |
| +добавлено | float gMs; // multiple-scattering weight from the albedo |
| +добавлено | vec3 gFire; // fire-light colour (blackbody at a typical flame-edge temperature) x gain |
| +добавлено | vec3 gKc; // per-channel extinction scale of the light on its way in (coloured gas) |
| +добавлено | // per metre: extinction, in-scattered radiance (soot only), emitted radiance |
| +добавлено | // returns false in empty space (nothing within ~3 voxels) |
| +добавлено | bool sampleAt(vec3 pw, out float sg, out vec3 sc, out vec3 em) { |
| +добавлено | sg = 0.0; sc = vec3(0.0); em = vec3(0.0); |
| +добавлено | vec3 p = (pw - uOrigin) / uH; |
| +добавлено | vec4 l0 = gridSample(uL0, CG(), p * 0.5); |
| +добавлено | if (l0.b <= 0.0) return false; |
| +добавлено | // sub-grid detail (in the spirit of wavelet turbulence): displace the lookup with band-limited |
| +добавлено | // curl noise drifting up with the gas, strongest where the resolved flow is turbulent |
| +добавлено | vec3 n = curl3(pw * uMarch.w + vec3(0.0, -uTime * 0.28, 0.0)); |
| +добавлено | vec4 s = gridSample(uS, G(), p + n * (uMarch.z * clamp(0.2 + max(l0.b - 1.0, 0.0) * 0.06, 0.2, 1.0))); |
| +добавлено | // fade out towards the open faces so the box never shows |
| +добавлено | vec3 e = min(p, uDim - p); |
| +добавлено | float ed = min(min(e.x, e.z), uMarch2.z > 0.5 ? min(e.y, uDim.y - p.y) : uDim.y - p.y); |
| +добавлено | // (the fade distance is jittered by the same noise, so a cloud that reaches a face frays |
| +добавлено | // into wisps instead of showing a straight cut) |
| +добавлено | float fade = smoothstep(0.5, uMarch2.x, ed + 1.6 * (n.x + n.z)); |
| +добавлено | s.rgb *= fade * fade; |
| +добавлено | if (uDetail.y > 0.0) { |
| +добавлено | // Worley fbm from one fetch: f2 cells (big billows), f4 (the lobes on them), f8 (the |
| +добавлено | // cauliflower on those). Thin gas erodes harder than the core, so billows keep firm tops |
| +добавлено | // while their trailing edges tear into ragged wisps |
| +добавлено | vec3 wv = texture(uNoise3D, (pw - uDetailC) * uDetail.y + n * 0.05).gba; |
| +добавлено | float crease = 1.0 - dot(wv, vec3(0.45, 0.35, 0.2)); |
| +добавлено | float thin = exp(-s.b / max(uDetail.x, 1e-3)); |
| +добавлено | s.b = max(s.b - uDetail.x * crease * (1.0 + thin), 0.0); |
| +добавлено | s.r *= 1.0 - uDetail.z * crease; |
| +добавлено | } |
| +добавлено | sg = sigmaOf(s); |
| +добавлено | em = emitOf(s); |
| +добавлено | float ss = uLook0.y * max(s.b, 0.0); |
| +добавлено | if (ss < 1e-4) return true; |
| +добавлено | // sun: single scattering through the precomputed optical depth, plus two wider, weaker octaves |
| +добавлено | // standing in for multiple scattering (Wrenninge 2015); sky through the optical depth above |
| +добавлено | float t = l0.r; |
| +добавлено | // multiple-scattering octaves scale with albedo: dark soot barely scatters twice, so it keeps |
| +добавлено | // its form shading (lit tops, near-black undersides) instead of glowing flat |
| +добавлено | vec3 tc = t * gKc; |
| +добавлено | vec3 sun = uSunColor * uLit.y * (exp(-tc) * gSunPh + gMs * (0.4 * exp(-0.5 * tc) + 0.15 * exp(-0.25 * tc))); |
| +добавлено | vec3 sky = uAmbient * uLit.z * (0.04 + 0.96 * exp(-0.7 * l0.g * gKc)); // deep cores go near black |
| +добавлено | sc = ss * uSootColor * (sun + sky + gFire * l0.a); |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | |
| +добавлено | vec3 gRd; |
| +добавлено | // a sample on the ray, with the near fade applied (all three outputs are linear in density) |
| +добавлено | bool tap(float t, out float sg, out vec3 sc, out vec3 em) { |
| +добавлено | bool o = sampleAt(cameraPosition + gRd * t, sg, sc, em); |
| +добавлено | float k = clamp(t * uMarch2.w, 0.0, 1.0); |
| +добавлено | k *= k * (3.0 - 2.0 * k); |
| +добавлено | sg *= k; sc *= k; em *= k; |
| +добавлено | return o; |
| +добавлено | } |
| +добавлено | // the integrator state, and one trapezoid slab (energy conserving) from ta over L |
| +добавлено | float gT, gZs, gWs; |
| +добавлено | vec3 gScat, gEmit; |
| +добавлено | void slab(float ta, float L, float sa, vec3 ca, vec3 ea, float sb, vec3 cb, vec3 eb) { |
| +добавлено | float s = 0.5 * (sa + sb); |
| +добавлено | vec3 S = 0.5 * (ca + cb), E = 0.5 * (ea + eb); |
| +добавлено | if (s > 1e-5) { |
| +добавлено | float tr = exp(-s * L), a = gT * (1.0 - tr); |
| +добавлено | gScat += S * (a / s); |
| +добавлено | gEmit += E * (a / s); |
| +добавлено | gZs += a * (ta + 0.5 * L); gWs += a; |
| +добавлено | gT *= tr; |
| +добавлено | } else gEmit += gT * E * L; |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vec3 rd = normalize(vWorld - cameraPosition); |
| +добавлено | gRd = rd; |
| +добавлено | vec3 dd = mix(rd, vec3(1e-6), lessThan(abs(rd), vec3(1e-6))); |
| +добавлено | vec3 bmin = uOrigin, bmax = uOrigin + uDim * uH; |
| +добавлено | vec3 ta = (bmin - cameraPosition) / dd, tb = (bmax - cameraPosition) / dd; |
| +добавлено | vec3 lo = min(ta, tb), hi = max(ta, tb); |
| +добавлено | float t0 = max(max(max(lo.x, lo.y), lo.z), 0.0), t1 = min(min(hi.x, hi.y), hi.z); |
| +добавлено | float cosV = dot(rd, -vec3(viewMatrix[0][2], viewMatrix[1][2], viewMatrix[2][2])); |
| +добавлено | t1 = min(t1, sceneViewZ() / cosV); |
| +добавлено | if (t1 <= t0) discard; |
| +добавлено | float dt = uMarch.x; |
| +добавлено | float mu = dot(uSunDir, rd); |
| +добавлено | // soot: forward lobe + a weak back lobe, normalised so isotropic = 1 |
| +добавлено | gSunPh = mix(hgPhase(mu, uLit.x), hgPhase(mu, -0.25), 0.25) * 4.0 * PI; |
| +добавлено | gFire = blackbody(kelvinOf(0.75)) * uTint * uLit.w; |
| +добавлено | gMs = clamp(dot(uSootColor, vec3(1.0)), 0.0, 1.0); |
| +добавлено | // chroma > 0: a coloured gas (chlorine) takes its colour from depth, not from its albedo alone. |
| +добавлено | // The channels it absorbs (where the albedo is below its brightest) fade faster on the way in, |
| +добавлено | // so thin gas scatters near white and deep gas goes yellow-green; 0 = grey extinction |
| +добавлено | gKc = 1.0 + uLook1.w * (1.0 - uSootColor / max(max(uSootColor.r, uSootColor.g), max(uSootColor.b, 1e-3))); |
| +добавлено | gT = 1.0; gZs = 0.0; gWs = 0.0; gScat = vec3(0.0); gEmit = vec3(0.0); |
| +добавлено | // the lattice: t0 + i dt, ending in a partial step at t1 (continuous in t0, t1 and dt) |
| +добавлено | float t = t0, sgP; vec3 scP, emP; |
| +добавлено | bool occP = tap(t, sgP, scP, emP); |
| +добавлено | float empties = occP ? 0.0 : 1.0; |
| +добавлено | for (int n = 0; n < 256; n++) { |
| +добавлено | if (gT < 0.03 || t >= t1) break; |
| +добавлено | // stride over empty space (the occupancy is dilated ~3 voxels, so skipped points are empty) |
| +добавлено | float stride = clamp(empties - 1.0, 1.0, uDetail.w); |
| +добавлено | float tn = min(t + dt * stride, t1), sg; vec3 sc, em; |
| +добавлено | bool occ = tap(tn, sg, sc, em); |
| +добавлено | if (occ && stride > 1.0) { // landed in gas: back onto the next lattice point |
| +добавлено | tn = min(t + dt, t1); |
| +добавлено | occ = tap(tn, sg, sc, em); |
| +добавлено | empties = 0.0; |
| +добавлено | } |
| +добавлено | float L = tn - t, w = smoothstep(0.8, 1.6, 0.5 * (sg + sgP) * L); |
| +добавлено | if (w > 0.0) { |
| +добавлено | // optically thick (a surface): also integrate it as two half slabs through the midpoint, and |
| +добавлено | // blend the two estimates by thickness, so the surface sits where it is, not on the lattice |
| +добавлено | float T0 = gT, z0 = gZs, w0 = gWs; vec3 s0 = gScat, e0 = gEmit; |
| +добавлено | float sgM; vec3 scM, emM; |
| +добавлено | tap(t + 0.5 * L, sgM, scM, emM); |
| +добавлено | slab(t, 0.5 * L, sgP, scP, emP, sgM, scM, emM); |
| +добавлено | slab(t + 0.5 * L, 0.5 * L, sgM, scM, emM, sg, sc, em); |
| +добавлено | float T2 = gT, z2 = gZs, w2 = gWs; vec3 s2 = gScat, e2 = gEmit; |
| +добавлено | gT = T0; gZs = z0; gWs = w0; gScat = s0; gEmit = e0; |
| +добавлено | if (w < 1.0) slab(t, L, sgP, scP, emP, sg, sc, em); |
| +добавлено | gT = mix(gT, T2, w); gZs = mix(gZs, z2, w); gWs = mix(gWs, w2, w); gScat = mix(gScat, s2, w); gEmit = mix(gEmit, e2, w); |
| +добавлено | } else slab(t, L, sgP, scP, emP, sg, sc, em); |
| +добавлено | sgP = sg; scP = sc; emP = em; t = tn; |
| +добавлено | empties = occ ? 0.0 : empties + 1.0; |
| +добавлено | } |
| +добавлено | // stopped on opacity: the unmarched rest is more of the same gas, so renormalise to opaque |
| +добавлено | // (else the last 3% lets a bright HDR sky print its clouds through thick dark smoke) |
| +добавлено | if (gT < 0.03) { float k = 1.0 / (1.0 - gT); gScat *= k; gEmit *= k; gT = 0.0; } |
| +добавлено | float alpha = 1.0 - gT; |
| +добавлено | if (alpha < 0.002 && dot(gEmit, gEmit) < 1e-6) discard; |
| +добавлено | float z = (gWs > 0.0 ? gZs / gWs : t0) * cosV; |
| +добавлено | fxOut(gScat / max(alpha, 1e-4), alpha, gEmit, vec2(0.0), z); |
| +добавлено | }`; |
| +добавлено | const bodyAt = BASE.RENDER_FRAG.indexOf('float gSunPh;'); |
| +добавлено | if (bodyAt < 0) throw new Error('FluidVolume: render body anchor not found'); |
| +добавлено | const RENDER_FRAG = BASE.RENDER_FRAG.slice(0, bodyAt) + RENDER_BODY; |
| +добавлено | const GL = { ...BASE, REACT, RENDER_FRAG }; |
| +добавлено | |
| +добавлено | // GPU 3D combustion fluid (shared system; Fire is the first user). |
| +добавлено | // |
| +добавлено | // Each domain is an axis-aligned box of cubic voxels simulated on the GPU and raymarched in the |
| +добавлено | // half-res FX pass. 3D grids live in 2D atlases (slices tiled), so every sim pass is one |
| +добавлено | // fullscreen draw into a viewport covering the used tiles; trilinear lookups are two hardware |
| +добавлено | // bilinear taps in neighbouring slices. HalfFloat targets, ping-ponged. |
| +добавлено | // |
| +добавлено | // Fields: velocity (m/s), scalars (temperature th, fuel, soot, expansion), vorticity, pressure + |
| +добавлено | // divergence, and a half-res light volume. One step per frame (dt <= 1/30): |
| +добавлено | // 1 advect semi-Lagrangian, RK2 backtrace, compensated for the domain's own motion |
| +добавлено | // 2 correct MacCormack, clamped to the departure cell's extrema (no overshoot) |
| +добавлено | // 3 curl vorticity |
| +добавлено | // 4 react sources -> combustion (fuel + heat -> heat, soot, gas expansion) -> cooling -> |
| +добавлено | // buoyancy (heat up, soot down) -> vorticity confinement -> forceAccel() from |
| +добавлено | // the shared force field (wind, vortex, shock... spells push fire) -> damping |
| +добавлено | // 5 diverge b = h^2 (div u - expansion), warm-started pressure |
| +добавлено | // 6 jacobi Q-dependent iterations (12 / 14 / 16 / 20; Low profile 6), warm-started |
| +добавлено | // 7 project u -= grad p; the floor (world y < 0) is solid, the other faces are open air |
| +добавлено | // 8 light half-res: sun optical depth (march to the box exit), sky optical depth (march |
| +добавлено | // up), |vorticity|, occupancy, and the fire's own light (blurred blackbody |
| +добавлено | // emission, the "low mip" that lights the smoke orange from inside) |
| +добавлено | // Render: march the box from the camera to min(exit, scene depth), trapezoid slabs, skipping |
| +добавлено | // empty space through the light volume's occupancy. Emission is blackbody(T) x T^4 with an |
| +добавлено | // optical-thickness shoulder; soot scatters sun (HG + multiple-scattering octaves), sky and |
| +добавлено | // fire light. Sub-grid detail: the lookup is displaced by band-limited curl noise drifting with the |
| +добавлено | // gas, scaled by the resolved vorticity (wavelet-turbulence-like upres). The samples sit on a |
| +добавлено | // lattice from the ray's entry at one spacing per domain, refined in place at surfaces (see RENDER_BODY). |
| +добавлено | // |
| +добавлено | // API |
| +добавлено | // const fluid = FluidVolume.get(fx) create once (adds itself to fx.systems; meshes go in |
| +добавлено | // fx.scenes.fx so the warm-up compiles them) |
| +добавлено | // const d = fluid.acquire({ size: [x, y, z], res, position }) null when the pool is full |
| +добавлено | // size metres (rounded to whole voxels); res = voxels along the longest axis (default |
| +добавлено | // Q.fluidRes: 32 / 48 / 64 / 96 by tier; elongated boxes may ask for more if they |
| +добавлено | // fit the atlas). Fields start empty. |
| +добавлено | // d.position world centre (Vector3); move it to follow a source, advection compensates |
| +добавлено | // d.emit(src) this frame only (call every frame for a continuous source; max 8/frame): |
| +добавлено | // { pos, radius, fuel, temp, soot, vel, radial, noise, noiseScale, seed, |
| +добавлено | // coupling, burst } |
| +добавлено | // burst: values are 'at least' this (one-shot fill); else per second. |
| +добавлено | // temp is th (1 = the flame temperature). coupling: 1/s pull of the |
| +добавлено | // velocity towards vel + radial * outward (large = set). |
| +добавлено | // d.heat CPU estimate of the domain's heat (th m^3), for driving lights |
| +добавлено | // d.clear() empty the fields; d.release() back to the pool |
| +добавлено | // sim fields ignition, burnRate, heat release (heatPerFuel), sootYield, expansion, |
| +добавлено | // cooling, radiative, sootDecay, fuelDecay, buoyancy, sootWeight, |
| +добавлено | // vorticity, forceCoupling, damping; opt-in, 0 = off: turbulence (m/s2 on hot |
| +добавлено | // gas), turbulenceFreq (tiles/m), sootCool (soot radiates heat: dark lanes), |
| +добавлено | // sootErode (units/s, soot thins from its edges, keeping its billows) |
| +добавлено | // look fields emission, temperature (K at th = 1), tint (Color), sootColor (albedo), |
| +добавлено | // sootDensity, flameDensity, fuelDensity, absorb (0..1 black flame: hot gas |
| +добавлено | // absorbs instead of glowing), g (HG), sun, sky, fireLight, upres |
| +добавлено | // (voxels), upresScale (feature size, voxels), edgeFade (voxels), visible; |
| +добавлено | // opt-in cell detail: detailFreq (tiles/m, 0 = off; band-limited to the march |
| +добавлено | // step), detailErode (soot units), detailHeat (0..1), detailCenter (Vector3); |
| +добавлено | // nearFade (m: density ramps in over this distance from the camera); |
| +добавлено | // chroma (0 = grey; > 0 the gas's colour deepens with depth, thin gas paler) |
| +добавлено | // d.obstacle Vector4: a solid sphere in the sim (world centre xyz, radius m; w = 0 none): |
| +добавлено | // gas flows round it and none is left inside (a fireball on an Aegis dome) |
| +добавлено | // cost fields emptyBelow (extinction 1/m below which gas is skipped as empty), |
| +добавлено | // stepScale (march spacing x; wide thin layers can afford coarser) |
| +добавлено | // No allocation after construction; nothing recompiles (tier settings are uniforms or pass counts). |
| +добавлено | |
| +добавлено | const TIER_RES = { low: 32, medium: 48, high: 64, ultra: 96 }; |
| +добавлено | const TIER_SLOTS = { low: 1, medium: 2, high: 2, ultra: 2 }; |
| +добавлено | const TIER_ITERS = { low: 12, medium: 14, high: 16, ultra: 20 }; |
| +добавлено | const TIER_STEP = { low: 1.3, medium: 1.15, high: 1.0, ultra: 0.8 }; // render step, voxels |
| +добавлено | const TIER_MAXSTEPS = { low: 56, medium: 80, high: 112, ultra: 160 }; |
| +добавлено | |
| +добавлено | const DEFAULTS = { |
| +добавлено | ignition: 0.3, burnRate: 3, heatPerFuel: 0.8, sootYield: 0.5, expansion: 1, |
| +добавлено | cooling: 0.5, radiative: 0.25, sootDecay: 0.12, fuelDecay: 0.3, |
| +добавлено | buoyancy: 5, sootWeight: 0.4, vorticity: 6, forceCoupling: 1, damping: 0.15, |
| +добавлено | emission: 4, temperature: 1900, sootDensity: 3, flameDensity: 0.35, fuelDensity: 0, absorb: 0, |
| +добавлено | g: 0.45, sun: 1, sky: 1, fireLight: 0.5, upres: 1.4, upresScale: 4, edgeFade: 5, visible: true, |
| +добавлено | turbulence: 0, turbulenceFreq: 0.5, sootCool: 0, sootErode: 0, detailFreq: 0, detailErode: 0, detailHeat: 0, nearFade: 0.4, |
| +добавлено | emptyBelow: 0, stepScale: 1, chroma: 0, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // the tiles a grid of n voxels takes in a W x H atlas, or null if it does not fit |
| +добавлено | function tileLayout(nx, ny, nz, W, H) { |
| +добавлено | const tx = Math.floor(W / nx), ty = Math.floor(H / ny); |
| +добавлено | if (tx < 1 || ty < 1) return null; |
| +добавлено | const tilesX = Math.min(tx, nz), tilesY = Math.ceil(nz / tilesX); |
| +добавлено | return tilesY <= ty ? [tilesX, tilesY] : null; |
| +добавлено | } |
| +добавлено | const atlasSize = (N) => { const t = Math.ceil(Math.sqrt(N)); return [t * N, Math.ceil(N / t) * N]; }; |
| +добавлено | |
| +добавлено | function target(w, h, count, format = THREE.RGBAFormat) { |
| +добавлено | return new THREE.WebGLRenderTarget(w, h, { |
| +добавлено | count, type: THREE.HalfFloatType, format, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | wrapS: THREE.ClampToEdgeWrapping, wrapT: THREE.ClampToEdgeWrapping, depthBuffer: false, stencilBuffer: false, generateMipmaps: false, |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | class FluidDomain { |
| +добавлено | constructor(sys, W, H, cW, cH) { |
| +добавлено | this.sys = sys; |
| +добавлено | this.W = W; this.H = H; this.cW = cW; this.cH = cH; |
| +добавлено | this.state = [target(W, H, 2), target(W, H, 2)]; // (velocity, scalars) |
| +добавлено | this.tmp = target(W, H, 2); |
| +добавлено | this.curl = target(W, H, 1); |
| +добавлено | this.press = [target(W, H, 1, THREE.RGFormat), target(W, H, 1, THREE.RGFormat)]; |
| +добавлено | this.light = target(cW, cH, 1); |
| +добавлено | this.all = [...this.state, this.tmp, this.curl, ...this.press]; |
| +добавлено | this.dim = new THREE.Vector3(8, 8, 8); |
| +добавлено | this.tiles = new THREE.Vector2(1, 1); |
| +добавлено | this.cdim = new THREE.Vector3(4, 4, 4); |
| +добавлено | this.ctiles = new THREE.Vector2(1, 1); |
| +добавлено | this.h = 0.1; |
| +добавлено | this.size = new THREE.Vector3(); |
| +добавлено | this.position = new THREE.Vector3(); |
| +добавлено | this.origin = new THREE.Vector3(); |
| +добавлено | this.lastOrigin = new THREE.Vector3(); |
| +добавлено | this.tint = new THREE.Color(1, 1, 1); |
| +добавлено | this.sootColor = new THREE.Color(0.13, 0.12, 0.11); |
| +добавлено | this.detailCenter = new THREE.Vector3(); |
| +добавлено | this.obstacle = new THREE.Vector4(); |
| +добавлено | this.srcP = Array.from({ length: GL.MAX_SRC }, () => new THREE.Vector4()); |
| +добавлено | this.srcA = Array.from({ length: GL.MAX_SRC }, () => new THREE.Vector4()); |
| +добавлено | this.srcV = Array.from({ length: GL.MAX_SRC }, () => new THREE.Vector4()); |
| +добавлено | this.srcB = Array.from({ length: GL.MAX_SRC }, () => new THREE.Vector4()); |
| +добавлено | this.nSrc = 0; |
| +добавлено | this.active = false; |
| +добавлено | this.cur = 0; this.pc = 0; this.fresh = true; |
| +добавлено | this.heat = 0; this.fuelPool = 0; |
| +добавлено | Object.assign(this, DEFAULTS); |
| +добавлено | } |
| +добавлено | |
| +добавлено | setGrid(nx, ny, nz, tiles, cn, ctiles, h) { |
| +добавлено | this.dim.set(nx, ny, nz); |
| +добавлено | this.tiles.set(tiles[0], tiles[1]); |
| +добавлено | this.cdim.set(cn[0], cn[1], cn[2]); |
| +добавлено | this.ctiles.set(ctiles[0], ctiles[1]); |
| +добавлено | this.h = h; |
| +добавлено | this.size.set(nx * h, ny * h, nz * h); |
| +добавлено | for (const t of this.all) t.viewport.set(0, 0, tiles[0] * nx, tiles[1] * ny); |
| +добавлено | this.light.viewport.set(0, 0, ctiles[0] * cn[0], ctiles[1] * cn[1]); |
| +добавлено | } |
| +добавлено | |
| +добавлено | emit(s) { |
| +добавлено | if (!this.active || this.nSrc >= GL.MAX_SRC) return; |
| +добавлено | const i = this.nSrc++, v = s.vel, burst = s.burst ? 1 : 0; |
| +добавлено | this.srcP[i].set(s.pos.x, s.pos.y, s.pos.z, s.radius ?? 0.5); |
| +добавлено | this.srcA[i].set(s.fuel ?? 0, s.temp ?? 0, s.soot ?? 0, s.noise ?? 0); |
| +добавлено | this.srcV[i].set(v ? v.x : 0, v ? v.y : 0, v ? v.z : 0, s.radial ?? 0); |
| +добавлено | this.srcB[i].set(burst, s.noiseScale ?? 1, s.seed ?? 0, s.coupling ?? 0); |
| +добавлено | // CPU mirror of the heat budget (drives lights): effective volume of the soft sphere |
| +добавлено | const r = s.radius ?? 0.5, vol = 1.6 * r * r * r * (1 - 0.5 * (s.noise ?? 0)), k = burst ? 1 : this.sys.dt; |
| +добавлено | this.fuelPool += (s.fuel ?? 0) * vol * k; |
| +добавлено | this.heat += (s.temp ?? 0) * vol * k * 0.5; |
| +добавлено | } |
| +добавлено | |
| +добавлено | clear() { this.fresh = true; } |
| +добавлено | |
| +добавлено | release() { this.active = false; this.mesh.visible = false; this.nSrc = 0; } |
| +добавлено | } |
| +добавлено | |
| +добавлено | const _c = new THREE.Color(), _v = new THREE.Vector3(); |
| +добавлено | const quadCam = new THREE.Camera(); |
| +добавлено | |
| +добавлено | export class FluidVolume { |
| +добавлено | static get(fx) { |
| +добавлено | if (!fx.fluid) { fx.fluid = new FluidVolume(fx); fx.systems.push(fx.fluid); } |
| +добавлено | return fx.fluid; |
| +добавлено | } |
| +добавлено | |
| +добавлено | constructor(fx) { |
| +добавлено | this.fx = fx; |
| +добавлено | this.renderer = fx.renderer; |
| +добавлено | const tier = Q.tier; |
| +добавлено | this.res = Q.fluidRes ?? TIER_RES[tier] ?? 64; |
| +добавлено | this.iterations = Q.fluidIterations ?? TIER_ITERS[tier] ?? 20; |
| +добавлено | this.stepVox = TIER_STEP[tier] ?? 0.85; |
| +добавлено | this.maxSteps = TIER_MAXSTEPS[tier] ?? 112; |
| +добавлено | this.dt = 1 / 60; |
| +добавлено | const [W, H] = atlasSize(this.res), [cW, cH] = atlasSize(Math.ceil(this.res / 2)); |
| +добавлено | |
| +добавлено | // sim uniforms shared by reference across every pass; set per domain before its passes |
| +добавлено | const su = this.su = { |
| +добавлено | uDim: { value: new THREE.Vector3() }, uTiles: { value: new THREE.Vector2() }, uInv: { value: new THREE.Vector2(1 / W, 1 / H) }, |
| +добавлено | uOrigin: { value: new THREE.Vector3() }, uH: { value: 0.1 }, uSimDt: { value: 1 / 60 }, uShift: { value: new THREE.Vector3() }, |
| +добавлено | uObst: { value: new THREE.Vector4() }, |
| +добавлено | }; |
| +добавлено | const tex = () => ({ value: null }); |
| +добавлено | const pass = (frag, own) => new FullscreenQuad(rawPass(frag, { ...U, ...su, ...own })); |
| +добавлено | const v4s = () => ({ value: Array.from({ length: GL.MAX_SRC }, () => new THREE.Vector4()) }); |
| +добавлено | this.look = { |
| +добавлено | uLook0: { value: new THREE.Vector4() }, uLook1: { value: new THREE.Vector4() }, uTint: { value: new THREE.Vector3(1, 1, 1) }, |
| +добавлено | }; |
| +добавлено | this.passes = { |
| +добавлено | advect: pass(GL.ADVECT, { uV: tex(), uS: tex() }), |
| +добавлено | correct: pass(GL.CORRECT, { uV: tex(), uS: tex(), uVf: tex(), uSf: tex(), uMacCormack: { value: 1 } }), |
| +добавлено | curl: pass(GL.CURL, { uV: tex() }), |
| +добавлено | react: pass(GL.REACT, { |
| +добавлено | uV: tex(), uS: tex(), uC: tex(), uSrcP: v4s(), uSrcA: v4s(), uSrcV: v4s(), uSrcB: v4s(), uSrcN: { value: 0 }, |
| +добавлено | uBurn: { value: new THREE.Vector4() }, uDecay: { value: new THREE.Vector4() }, uForce: { value: new THREE.Vector4() }, uFlow: { value: new THREE.Vector4() }, uTurb: { value: new THREE.Vector4() }, |
| +добавлено | }), |
| +добавлено | diverge: pass(GL.DIVERGE, { uV: tex(), uS: tex(), uP: tex(), uWarm: { value: 0.9 } }), |
| +добавлено | jacobi: pass(GL.JACOBI, { uP: tex() }), |
| +добавлено | project: pass(GL.PROJECT, { uV: tex(), uS: tex(), uP: tex() }), |
| +добавлено | light: pass(GL.LIGHT, { |
| +добавлено | ...this.look, uS: tex(), uC: tex(), uCDim: { value: new THREE.Vector3() }, uCTiles: { value: new THREE.Vector2() }, |
| +добавлено | uCInv: { value: new THREE.Vector2(1 / cW, 1 / cH) }, uLightP: { value: new THREE.Vector4(2.5, 3, 1, 0) }, |
| +добавлено | }), |
| +добавлено | }; |
| +добавлено | for (const p of Object.values(this.passes)) this.renderer.compile(p.mesh, quadCam); |
| +добавлено | |
| +добавлено | // domains: each owns its targets and a box proxy in the fx scene |
| +добавлено | const box = new THREE.BoxGeometry(1, 1, 1); |
| +добавлено | const slots = Q.fluidDomains ?? TIER_SLOTS[tier] ?? 2; |
| +добавлено | this.domains = []; |
| +добавлено | for (let i = 0; i < slots; i++) { |
| +добавлено | const d = new FluidDomain(this, W, H, cW, cH); |
| +добавлено | d.material = new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: GL.RENDER_VERT, fragmentShader: GL.RENDER_FRAG, |
| +добавлено | ...FX_BLENDING, depthTest: false, side: THREE.BackSide, |
| +добавлено | uniforms: { |
| +добавлено | ...U, uS: tex(), uL0: { value: d.light.texture }, |
| +добавлено | uDim: { value: d.dim }, uTiles: { value: d.tiles }, uInv: { value: new THREE.Vector2(1 / W, 1 / H) }, |
| +добавлено | uCDim: { value: d.cdim }, uCTiles: { value: d.ctiles }, uCInv: { value: new THREE.Vector2(1 / cW, 1 / cH) }, |
| +добавлено | uOrigin: { value: d.origin }, uH: { value: 0.1 }, |
| +добавлено | uMarch: { value: new THREE.Vector4() }, uMarch2: { value: new THREE.Vector4() }, uLit: { value: new THREE.Vector4() }, |
| +добавлено | uSootColor: { value: new THREE.Vector3() }, uDetail: { value: new THREE.Vector4() }, uDetailC: { value: d.detailCenter }, |
| +добавлено | uLook0: { value: new THREE.Vector4() }, uLook1: { value: new THREE.Vector4() }, uTint: { value: new THREE.Vector3(1, 1, 1) }, |
| +добавлено | }, |
| +добавлено | }); |
| +добавлено | d.mesh = new THREE.Mesh(box, d.material); |
| +добавлено | d.mesh.visible = false; |
| +добавлено | d.mesh.frustumCulled = false; |
| +добавлено | fx.scenes.fx.add(d.mesh); |
| +добавлено | this.domains.push(d); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // run every pass once now (ANGLE finishes some programs at first draw), then forget it |
| +добавлено | const d0 = this.domains[0]; |
| +добавлено | this.layout(d0, [1, 1, 1], 8); |
| +добавлено | d0.active = true; |
| +добавлено | this.clearDomain(d0); |
| +добавлено | this.step(d0, 1 / 60); |
| +добавлено | d0.active = false; |
| +добавлено | d0.fresh = true; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // pick voxel counts for a box of `size` metres with `res` voxels on its longest axis |
| +добавлено | layout(d, size, res) { |
| +добавлено | const big = Math.max(size[0], size[1], size[2]); |
| +добавлено | for (let r = Math.max(8, Math.round(res)); r >= 8; r -= 2) { |
| +добавлено | const h = big / r; |
| +добавлено | const nx = Math.max(4, Math.round(size[0] / h)), ny = Math.max(4, Math.round(size[1] / h)), nz = Math.max(4, Math.round(size[2] / h)); |
| +добавлено | const cx = Math.ceil(nx / 2), cy = Math.ceil(ny / 2), cz = Math.ceil(nz / 2); |
| +добавлено | const t = tileLayout(nx, ny, nz, d.W, d.H), ct = tileLayout(cx, cy, cz, d.cW, d.cH); |
| +добавлено | if (!t || !ct) continue; |
| +добавлено | d.setGrid(nx, ny, nz, t, [cx, cy, cz], ct, h); |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | acquire({ size = [4, 4, 4], res = this.res, position = null } = {}) { |
| +добавлено | const d = this.domains.find((x) => !x.active); |
| +добавлено | if (!d || !this.layout(d, size, res)) return null; |
| +добавлено | Object.assign(d, DEFAULTS); |
| +добавлено | d.tint.setRGB(1, 1, 1); |
| +добавлено | d.sootColor.setRGB(0.13, 0.12, 0.11); |
| +добавлено | d.detailCenter.set(0, 0, 0); |
| +добавлено | d.obstacle.set(0, 0, 0, 0); |
| +добавлено | if (position) d.position.copy(position); |
| +добавлено | d.active = true; |
| +добавлено | d.fresh = true; |
| +добавлено | d.nSrc = 0; d.heat = 0; d.fuelPool = 0; |
| +добавлено | return d; |
| +добавлено | } |
| +добавлено | |
| +добавлено | get active() { return this.domains.some((d) => d.active); } |
| +добавлено | |
| +добавлено | clearDomain(d) { |
| +добавлено | const r = this.renderer, prev = r.getRenderTarget(), alpha = r.getClearAlpha(); |
| +добавлено | r.getClearColor(_c); |
| +добавлено | r.setClearColor(0x000000, 0); |
| +добавлено | for (const t of d.all) { r.setRenderTarget(t); r.clear(true, false, false); } |
| +добавлено | r.setRenderTarget(d.light); r.clear(true, false, false); |
| +добавлено | r.setClearColor(_c, alpha); |
| +добавлено | r.setRenderTarget(prev); |
| +добавлено | d.cur = 0; d.pc = 0; d.fresh = false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | draw(name, out) { |
| +добавлено | const p = this.passes[name]; |
| +добавлено | p.render(this.renderer, out); |
| +добавлено | return p.material.uniforms; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // one sim step for domain d |
| +добавлено | step(d, dt) { |
| +добавлено | const su = this.su, P = this.passes; |
| +добавлено | d.origin.copy(d.position).addScaledVector(d.size, -0.5); |
| +добавлено | su.uDim.value.copy(d.dim); su.uTiles.value.copy(d.tiles); |
| +добавлено | su.uOrigin.value.copy(d.origin); su.uH.value = d.h; su.uSimDt.value = dt; |
| +добавлено | su.uShift.value.subVectors(d.origin, d.lastOrigin).divideScalar(d.h); |
| +добавлено | d.lastOrigin.copy(d.origin); |
| +добавлено | const ob = d.obstacle; |
| +добавлено | su.uObst.value.set((ob.x - d.origin.x) / d.h - 0.5, (ob.y - d.origin.y) / d.h - 0.5, (ob.z - d.origin.z) / d.h - 0.5, ob.w / d.h); |
| +добавлено | const A = d.state[d.cur], B = d.state[1 - d.cur]; |
| +добавлено | let u; |
| +добавлено | |
| +добавлено | u = P.advect.material.uniforms; u.uV.value = A.textures[0]; u.uS.value = A.textures[1]; |
| +добавлено | this.draw('advect', d.tmp); |
| +добавлено | u = P.correct.material.uniforms; u.uV.value = A.textures[0]; u.uS.value = A.textures[1]; u.uVf.value = d.tmp.textures[0]; u.uSf.value = d.tmp.textures[1]; |
| +добавлено | this.draw('correct', B); |
| +добавлено | su.uShift.value.set(0, 0, 0); |
| +добавлено | P.curl.material.uniforms.uV.value = B.textures[0]; |
| +добавлено | this.draw('curl', d.curl); |
| +добавлено | |
| +добавлено | u = P.react.material.uniforms; |
| +добавлено | u.uV.value = B.textures[0]; u.uS.value = B.textures[1]; u.uC.value = d.curl.texture; |
| +добавлено | u.uSrcN.value = d.nSrc; |
| +добавлено | for (let i = 0; i < d.nSrc; i++) { |
| +добавлено | u.uSrcP.value[i].copy(d.srcP[i]); u.uSrcA.value[i].copy(d.srcA[i]); u.uSrcV.value[i].copy(d.srcV[i]); u.uSrcB.value[i].copy(d.srcB[i]); |
| +добавлено | } |
| +добавлено | u.uBurn.value.set(d.ignition, d.burnRate, d.heatPerFuel, d.sootYield); |
| +добавлено | u.uDecay.value.set(d.cooling, d.radiative, d.sootDecay, d.fuelDecay); |
| +добавлено | u.uForce.value.set(d.buoyancy, d.sootWeight, d.vorticity, d.expansion); |
| +добавлено | u.uFlow.value.set(d.forceCoupling, d.damping, 0, 0); |
| +добавлено | u.uTurb.value.set(d.turbulence, d.turbulenceFreq, d.sootErode, d.sootCool); |
| +добавлено | this.draw('react', A); |
| +добавлено | |
| +добавлено | u = P.diverge.material.uniforms; |
| +добавлено | u.uV.value = A.textures[0]; u.uS.value = A.textures[1]; u.uP.value = d.press[d.pc].texture; |
| +добавлено | this.draw('diverge', d.press[1 - d.pc]); |
| +добавлено | d.pc = 1 - d.pc; |
| +добавлено | const J = P.jacobi.material.uniforms; |
| +добавлено | for (let i = 0; i < this.iterations; i++) { |
| +добавлено | J.uP.value = d.press[d.pc].texture; |
| +добавлено | this.draw('jacobi', d.press[1 - d.pc]); |
| +добавлено | d.pc = 1 - d.pc; |
| +добавлено | } |
| +добавлено | u = P.project.material.uniforms; |
| +добавлено | u.uV.value = A.textures[0]; u.uS.value = A.textures[1]; u.uP.value = d.press[d.pc].texture; |
| +добавлено | this.draw('project', B); |
| +добавлено | d.cur = 1 - d.cur; |
| +добавлено | |
| +добавлено | // CPU heat mirror: pending fuel burns at the sim's rate, heat cools at its rate |
| +добавлено | const burned = d.fuelPool * (1 - Math.exp(-d.burnRate * dt)); |
| +добавлено | d.fuelPool -= burned; |
| +добавлено | d.heat = (d.heat + burned * d.heatPerFuel) * Math.exp(-(d.cooling + 0.6 * d.radiative) * dt); |
| +добавлено | } |
| +добавлено | |
| +добавлено | setLook(d, u) { |
| +добавлено | u.uLook0.value.set(d.emission, d.sootDensity, d.flameDensity, d.absorb); |
| +добавлено | u.uLook1.value.set(d.temperature, 300, d.fuelDensity, d.chroma); |
| +добавлено | u.uTint.value.set(d.tint.r, d.tint.g, d.tint.b); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // main calls this every frame inside the timed 'sim' section |
| +добавлено | update(dt, camera) { |
| +добавлено | this.dt = Math.min(dt, 1 / 30); |
| +добавлено | const r = this.renderer, prev = r.getRenderTarget(); |
| +добавлено | const fxH = U.uFxResolution.value.y, mPerPx = 1 / (0.5 * fxH * camera.projectionMatrix.elements[5]); |
| +добавлено | for (const d of this.domains) { |
| +добавлено | d.mesh.visible = d.active && d.visible; |
| +добавлено | if (!d.active) continue; |
| +добавлено | if (d.fresh) { this.clearDomain(d); d.origin.copy(d.position).addScaledVector(d.size, -0.5); d.lastOrigin.copy(d.origin); } |
| +добавлено | if (dt > 0) this.step(d, this.dt); |
| +добавлено | d.nSrc = 0; |
| +добавлено | d.origin.copy(d.position).addScaledVector(d.size, -0.5); |
| +добавлено | // light volume (also while paused: the sun may move) |
| +добавлено | const su = this.su, L = this.passes.light.material.uniforms; |
| +добавлено | su.uDim.value.copy(d.dim); su.uTiles.value.copy(d.tiles); su.uOrigin.value.copy(d.origin); su.uH.value = d.h; |
| +добавлено | L.uS.value = d.state[d.cur].textures[1]; L.uC.value = d.curl.texture; |
| +добавлено | L.uCDim.value.copy(d.cdim); L.uCTiles.value.copy(d.ctiles); |
| +добавлено | L.uLightP.value.set(2.5, 2, d.fireLight, d.emptyBelow); |
| +добавлено | this.setLook(d, this.look); |
| +добавлено | this.draw('light', d.light); |
| +добавлено | // render uniforms |
| +добавлено | const m = d.material.uniforms; |
| +добавлено | m.uS.value = d.state[d.cur].textures[1]; |
| +добавлено | m.uH.value = d.h; |
| +добавлено | this.setLook(d, m); |
| +добавлено | // sample spacing: a fraction of a voxel, never finer than the pixel footprint at the domain's |
| +добавлено | // distance, and coarse enough that the box's diagonal fits the step budget |
| +добавлено | const auto = Math.min(1, Q.auto?.steps ?? 1), steps = Math.max(8, Math.floor(this.maxSteps * auto)); |
| +добавлено | const dist = _v.subVectors(camera.position, d.position).length(); |
| +добавлено | const dtm = Math.max(this.stepVox * d.stepScale * d.h / auto, dist * mPerPx, d.size.length() / steps); |
| +добавлено | // displacement: one curl octave, its finest band (1/16 tile) no finer than the march step |
| +добавлено | m.uMarch.value.set(dtm, steps, d.upres, Math.min(1 / (4 * d.upresScale * d.h), 1 / (16 * dtm))); |
| +добавлено | m.uMarch2.value.set(d.edgeFade, mPerPx, d.origin.y > -0.5 * d.h ? 1 : 0, 1 / Math.max(d.nearFade, 0.01)); |
| +добавлено | // the empty-space stride stays inside the occupancy's ~3 voxel dilation; the cell pattern's |
| +добавлено | // main octaves (a quarter and an eighth of a tile) stay above the sample spacing |
| +добавлено | m.uDetail.value.set(d.detailErode, Math.min(d.detailFreq, 1 / (12 * dtm)), d.detailHeat, Math.max(1, Math.floor(3 * d.h / dtm))); |
| +добавлено | m.uLit.value.set(d.g, d.sun, d.sky, 1); |
| +добавлено | m.uSootColor.value.set(d.sootColor.r, d.sootColor.g, d.sootColor.b); |
| +добавлено | d.mesh.position.copy(d.position); |
| +добавлено | d.mesh.scale.copy(d.size); |
| +добавлено | d.mesh.updateMatrixWorld(); |
| +добавлено | } |
| +добавлено | r.setRenderTarget(prev); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { FullscreenQuad, rawPass } from '../engine/fullscreen.js'; |
| +добавлено | import { U, COMMON_GLSL, GROUND_GLSL } from './common.js'; |
| +добавлено | |
| +добавлено | // The half-res FX pass (PLAN 2.5 "FX target"): one MRT with one blend state for every soft |
| +добавлено | // translucent thing (media, volumes, glows, distortion), never sorted (weighted-blended OIT). |
| +добавлено | // 1. depth prepass: the FX depth buffer gets the FARTHEST full-res depth of each footprint, so |
| +добавлено | // nothing in front of the background is rejected at silhouettes |
| +добавлено | // 2. the fx scene draws into (media, weight + distortion, emission) |
| +добавлено | // 3. composite at full res: nearest-depth upsample (a full-res pixel nearer than every FX tap |
| +добавлено | // rejects FX, which kills halos at pillar edges), distortion with distortion-driven chromatic |
| +добавлено | // aberration, the WBOIT resolve, emission, the void's negative shell, and debug views. |
| +добавлено | export const DEBUG_VIEWS = { off: 0, overdraw: 1, emission: 2, media: 3, distortion: 4, 'ground A': 5, 'ground B': 6, particles: 7 }; |
| +добавлено | |
| +добавлено | const PREPASS = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | uniform highp sampler2D uSceneDepth; |
| +добавлено | uniform vec2 uRatio; // full / fx resolution |
| +добавлено | uniform vec2 uResolution; |
| +добавлено | void main() { |
| +добавлено | ivec2 b = ivec2(floor(floor(gl_FragCoord.xy) * uRatio)); // block origin, same as sceneViewZ |
| +добавлено | ivec2 m = ivec2(uResolution) - 1; |
| +добавлено | float d = texelFetch(uSceneDepth, min(b, m), 0).r; |
| +добавлено | d = max(d, texelFetch(uSceneDepth, min(b + ivec2(1, 0), m), 0).r); |
| +добавлено | d = max(d, texelFetch(uSceneDepth, min(b + ivec2(0, 1), m), 0).r); |
| +добавлено | d = max(d, texelFetch(uSceneDepth, min(b + ivec2(1, 1), m), 0).r); |
| +добавлено | gl_FragDepth = d; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const COMPOSITE = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp sampler2D; |
| +добавлено | ${COMMON_GLSL} |
| +добавлено | ${GROUND_GLSL} |
| +добавлено | uniform sampler2D uScene; |
| +добавлено | uniform sampler2D uMedia; |
| +добавлено | uniform sampler2D uWeight; |
| +добавлено | uniform sampler2D uEmit; |
| +добавлено | uniform highp sampler2D uFxDepth; |
| +добавлено | uniform highp sampler2D uSceneDepth; |
| +добавлено | uniform highp sampler2D uPartState; |
| +добавлено | uniform vec4 uParams; // smoke occludes glow, distortion scale, CA, - |
| +добавлено | uniform vec4 uInvert; // centre uv, radius (uv, aspect-corrected), amount |
| +добавлено | in vec2 vUv; |
| +добавлено | out vec4 outColor; |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | float zf = linearDepth(texture(uSceneDepth, vUv).r); |
| +добавлено | vec2 hp = vUv * uFxResolution - 0.5; |
| +добавлено | ivec2 b = ivec2(floor(hp)); |
| +добавлено | ivec2 m = ivec2(uFxResolution) - 1; |
| +добавлено | ivec2 t0 = clamp(b, ivec2(0), m), t1 = clamp(b + ivec2(1, 0), ivec2(0), m); |
| +добавлено | ivec2 t2 = clamp(b + ivec2(0, 1), ivec2(0), m), t3 = clamp(b + ivec2(1, 1), ivec2(0), m); |
| +добавлено | float z0 = linearDepth(texelFetch(uFxDepth, t0, 0).r), z1 = linearDepth(texelFetch(uFxDepth, t1, 0).r); |
| +добавлено | float z2 = linearDepth(texelFetch(uFxDepth, t2, 0).r), z3 = linearDepth(texelFetch(uFxDepth, t3, 0).r); |
| +добавлено | float tol = 0.04 * zf + 0.05; |
| +добавлено | vec4 d4 = abs(vec4(z0, z1, z2, z3) - zf); |
| +добавлено | vec4 med, wt, em; |
| +добавлено | bool fx = true; |
| +добавлено | if (max(max(d4.x, d4.y), max(d4.z, d4.w)) < tol) { |
| +добавлено | med = texture(uMedia, vUv); wt = texture(uWeight, vUv); em = texture(uEmit, vUv); |
| +добавлено | } else { |
| +добавлено | // nearest-depth tap; if this pixel is in front of all of them, the FX there was drawn |
| +добавлено | // against something farther (a silhouette), so drop it |
| +добавлено | ivec2 t = t0; float best = d4.x; |
| +добавлено | if (d4.y < best) { best = d4.y; t = t1; } |
| +добавлено | if (d4.z < best) { best = d4.z; t = t2; } |
| +добавлено | if (d4.w < best) { best = d4.w; t = t3; } |
| +добавлено | if (zf < min(min(z0, z1), min(z2, z3)) - tol) fx = false; |
| +добавлено | med = texelFetch(uMedia, t, 0); wt = texelFetch(uWeight, t, 0); em = texelFetch(uEmit, t, 0); |
| +добавлено | } |
| +добавлено | if (!fx) { med = vec4(0.0, 0.0, 0.0, 1.0); wt = vec4(0.0); em = vec4(0.0); } |
| +добавлено | |
| +добавлено | float rev = clamp(med.a, 0.0, 1.0); |
| +добавлено | vec3 accum = med.rgb / max(wt.r, 1e-4); |
| +добавлено | vec2 dist = wt.gb * uParams.y; |
| +добавлено | vec2 suv = vUv + dist; |
| +добавлено | vec3 scene; |
| +добавлено | if (uParams.z > 0.0 && dot(dist, dist) > 1e-8) { |
| +добавлено | vec2 ca = dist * uParams.z * 0.6; |
| +добавлено | scene = vec3(texture(uScene, suv + ca).r, texture(uScene, suv).g, texture(uScene, suv - ca).b); |
| +добавлено | } else scene = texture(uScene, suv).rgb; |
| +добавлено | vec3 col = scene * rev + accum * (1.0 - rev) + em.rgb * mix(1.0, rev, uParams.x); |
| +добавлено | |
| +добавлено | // void collapse: a brief photographic-negative shell |
| +добавлено | if (uInvert.w > 0.0) { |
| +добавлено | vec2 q = (vUv - uInvert.xy) * vec2(uResolution.x / uResolution.y, 1.0); |
| +добавлено | float r = length(q); |
| +добавлено | float shell = smoothstep(uInvert.z, uInvert.z * 0.8, r) * uInvert.w; |
| +добавлено | float l = dot(col, vec3(0.2126, 0.7152, 0.0722)); |
| +добавлено | col = mix(col, vec3(0.6, 0.5, 1.0) * max(1.2 - l, 0.0) * 0.6, shell); |
| +добавлено | } |
| +добавлено | |
| +добавлено | if (uDebug > 0.5) { |
| +добавлено | int v = int(uDebug + 0.5); |
| +добавлено | if (v == 1) col = scene * 0.15 + vec3(1.0, 0.25, 0.05) * em.r * 25.0; // overdraw: fxOut wrote a constant |
| +добавлено | else if (v == 2) col = em.rgb; |
| +добавлено | else if (v == 3) col = accum * (1.0 - rev); |
| +добавлено | else if (v == 4) col = vec3(0.5 + dist * 40.0, 0.5); |
| +добавлено | else if (v == 5) col = groundA(mix(uGroundRect.xy, uGroundRect.xy + uGroundRect.z, vUv)).rgb * vec3(1.0, 0.6, 1.0) + vec3(0.0, 0.0, groundA(mix(uGroundRect.xy, uGroundRect.xy + uGroundRect.z, vUv)).a); |
| +добавлено | else if (v == 6) col = groundB(mix(uGroundRect.xy, uGroundRect.xy + uGroundRect.z, vUv)).rgb + groundB(mix(uGroundRect.xy, uGroundRect.xy + uGroundRect.z, vUv)).a * 0.5; |
| +добавлено | else if (v == 7) { vec4 s = texture(uPartState, vUv); col = s.w < 1e8 ? fract(abs(s.xyz) * 0.1) : vec3(0.02); } |
| +добавлено | } |
| +добавлено | outColor = vec4(col, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export class FxTarget { |
| +добавлено | constructor(renderer) { |
| +добавлено | this.renderer = renderer; |
| +добавлено | this.rt = new THREE.WebGLRenderTarget(1, 1, { |
| +добавлено | count: 3, type: THREE.HalfFloatType, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, generateMipmaps: false, |
| +добавлено | depthTexture: new THREE.DepthTexture(1, 1, THREE.FloatType), |
| +добавлено | }); |
| +добавлено | this.comp = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, depthBuffer: false, generateMipmaps: false }); |
| +добавлено | this.ratio = new THREE.Vector2(2, 2); |
| +добавлено | this.prepass = new FullscreenQuad(rawPass(PREPASS, { uSceneDepth: U.uSceneDepth, uRatio: { value: this.ratio }, uResolution: U.uResolution }, { |
| +добавлено | depthTest: true, depthWrite: true, depthFunc: THREE.AlwaysDepth, colorWrite: false, |
| +добавлено | })); |
| +добавлено | this.params = { smokeOccludesGlow: 0.5, distortion: 1, ca: 0.35 }; |
| +добавлено | this.invert = new THREE.Vector4(); |
| +добавлено | this.composite = new FullscreenQuad(rawPass(COMPOSITE, { |
| +добавлено | ...U, uScene: { value: null }, uMedia: { value: this.rt.textures[0] }, uWeight: { value: this.rt.textures[1] }, uEmit: { value: this.rt.textures[2] }, |
| +добавлено | uFxDepth: { value: this.rt.depthTexture }, uPartState: { value: null }, |
| +добавлено | uParams: { value: new THREE.Vector4() }, uInvert: { value: this.invert }, |
| +добавлено | })); |
| +добавлено | } |
| +добавлено | |
| +добавлено | setSize(w, h, scale) { |
| +добавлено | const fw = Math.max(1, Math.ceil(w * scale)), fh = Math.max(1, Math.ceil(h * scale)); |
| +добавлено | this.rt.setSize(fw, fh); |
| +добавлено | this.comp.setSize(w, h); |
| +добавлено | this.ratio.set(w / fw, h / fh); |
| +добавлено | U.uFxResolution.value.set(fw, fh); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // sceneTex: resolved HDR (opaque + refract + lines); returns the composited HDR texture |
| +добавлено | render(fxScene, camera, sceneTex, timer, partState = null) { |
| +добавлено | const r = this.renderer; |
| +добавлено | timer?.begin('fx'); |
| +добавлено | r.setRenderTarget(this.rt); |
| +добавлено | r.setClearColor(0x000000, 1); |
| +добавлено | r.clear(true, true, false); |
| +добавлено | this.prepass.render(r, this.rt); |
| +добавлено | r.render(fxScene, camera); |
| +добавлено | timer?.begin('fxComp'); |
| +добавлено | const u = this.composite.material.uniforms; |
| +добавлено | u.uScene.value = sceneTex; |
| +добавлено | u.uPartState.value = partState; |
| +добавлено | u.uParams.value.set(this.params.smokeOccludesGlow, this.params.distortion, this.params.ca, 0); |
| +добавлено | this.composite.render(r, this.comp); |
| +добавлено | return this.comp.texture; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { FullscreenQuad, rawPass } from '../engine/fullscreen.js'; |
| +добавлено | import { ARENA, COMMON_GLSL, U } from './common.js'; |
| +добавлено | |
| +добавлено | // Ground reaction field: a floor-aligned 40 x 40 m ping-pong pair (RGBA16F MRT, linear, clamp) |
| +добавлено | // A = (heat, char, wet, frost) B = (crack, acid, corruption, glow) |
| +добавлено | // The sim pass steps every reaction, applies this frame's splats (uniform-bounded loop) and |
| +добавлено | // adds this frame's particle paint (paintScene, drawn additively into a cleared paint target). |
| +добавлено | // Frost, crack and corruption above 1 are "potential": a front advances into a neighbour with |
| +добавлено | // max(neighbour) - drop, so the initial potential sets the reach. Fronts are gated by a baked |
| +добавлено | // mask (frost: dendrite tips + noise, crack: voronoi vein network, corruption: warped veins). |
| +добавлено | // Slow decays use stochastic rounding: fp16 has 10 mantissa bits, so a tau = 25 s decay at |
| +добавлено | // 144 Hz (0.03% per frame) would otherwise round to no change at all. |
| +добавлено | // |
| +добавлено | // Partial update: a 1024^2 MRT pass is bandwidth bound (~0.11 ms on a 3060 even as a plain |
| +добавлено | // copy), so a frame only touches part of the field. Splats (and touch()) register regions |
| +добавлено | // that are stepped every frame (up to 4 "fast" boxes clustered from the live regions, padded |
| +добавлено | // by how far their fronts can reach); the rest is stepped in 32 rotating row bands with each |
| +добавлено | // band's accumulated dt, so slow decays still run everywhere. Last frame's rects are copied |
| +добавлено | // so both ping-pong targets stay identical outside what was stepped. Boxes may overlap (an |
| +добавлено | // overlap is just computed twice, identically). Paint only lands inside the fast boxes: |
| +добавлено | // spells that paint with particles must touch() their area. |
| +добавлено | |
| +добавлено | export const MAX_SPLATS = 16, MAX_PROBES = 16; |
| +добавлено | const SPLAT_VEC4 = 5, MAX_REGIONS = 32, MAX_BOXES = 4, BANDS = 32; |
| +добавлено | const PATTERNS = { radial: 0, lichtenberg: 1, ring: 2, noise: 3, line: 4 }; |
| +добавлено | // craters: where a heavy radial crack splat (crack >= 2: a meteor, not a spike's base) landed, so |
| +добавлено | // the floor draws its fractures radiating from there and concentric between them. (x, z, radius, |
| +добавлено | // strength fading with the cracks); the arena material reads them by reference. |
| +добавлено | // ponytail: one field, so module-level; the oldest/weakest of 4 is overwritten |
| +добавлено | export const CRACK_SOURCES = Array.from({ length: 4 }, () => new THREE.Vector4()); |
| +добавлено | // hot line cracks (fissure vents): A = (x, z, x2, z2), B = (half-width, strength, seed, -); the arena |
| +добавлено | // floor draws the main fissure and en-echelon side cracks along them instead of the cell network |
| +добавлено | export const FISSURE_A = Array.from({ length: 4 }, () => new THREE.Vector4()); |
| +добавлено | export const FISSURE_B = Array.from({ length: 4 }, () => new THREE.Vector4()); |
| +добавлено | |
| +добавлено | // particle paint: RawShaderMaterial (GLSL3) with ...PAINT_BLENDING and PAINT_FRAG_HEAD, drawn |
| +добавлено | // into paintScene with paintCamera (ortho, ground rect). Outputs are per-frame increments. |
| +добавлено | export const PAINT_BLENDING = { |
| +добавлено | transparent: true, depthTest: false, depthWrite: false, |
| +добавлено | blending: THREE.CustomBlending, |
| +добавлено | blendEquation: THREE.AddEquation, blendSrc: THREE.OneFactor, blendDst: THREE.OneFactor, |
| +добавлено | blendEquationAlpha: THREE.AddEquation, blendSrcAlpha: THREE.OneFactor, blendDstAlpha: THREE.OneFactor, |
| +добавлено | }; |
| +добавлено | export const PAINT_FRAG_HEAD = /* glsl */` |
| +добавлено | layout(location = 0) out vec4 gA; // heat, char, wet, frost (added) |
| +добавлено | layout(location = 1) out vec4 gB; // crack, acid, corruption, glow (added) |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const f = (x) => x.toFixed(4); |
| +добавлено | // per-frame helpers live at module level: no closures allocated in update() |
| +добавлено | const area = (b) => (b.z - b.x) * (b.w - b.y); |
| +добавлено | const contains = (a, b) => a.x <= b.x && a.y <= b.y && a.z >= b.z && a.w >= b.w; |
| +добавлено | const decay = (dt, tau) => Math.exp(-dt / tau); |
| +добавлено | const G = ARENA.ground, P = ARENA.pool; |
| +добавлено | |
| +добавлено | const FIELD_GLSL = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | precision highp sampler2D; |
| +добавлено | ${COMMON_GLSL} |
| +добавлено | // always 1. Loop bounds read it so ANGLE's D3D compiler (FXC) keeps loops rolled (fast compile) |
| +добавлено | uniform int uOne; |
| +добавлено | const vec2 G_MIN = vec2(${f(G.min.x)}, ${f(G.min.y)}); |
| +добавлено | const float G_SIZE = ${f(G.size)}; |
| +добавлено | vec2 texelWorld(vec2 fragCoord, float n) { return G_MIN + fragCoord / n * G_SIZE; } |
| +добавлено | bool inPool(vec2 xz) { return all(lessThan(abs(xz - vec2(${f(P.center.x)}, ${f(P.center.y)})), vec2(${f(P.half.x)}, ${f(P.half.y)}))); } |
| +добавлено | float vnoise(vec2 x) { |
| +добавлено | vec2 i = floor(x), u = fract(x); |
| +добавлено | u = u * u * (3.0 - 2.0 * u); |
| +добавлено | return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x), mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y); |
| +добавлено | } |
| +добавлено | float fbm2(vec2 x) { return vnoise(x) * 0.5 + vnoise(x * 2.03 + 17.1) * 0.3 + vnoise(x * 4.11 + 3.7) * 0.2; } |
| +добавлено | // value noise periodic in x (period per) and optionally y (perY > 0); integer periods only |
| +добавлено | float vnoiseP(vec2 x, float per, float perY) { |
| +добавлено | vec2 i = floor(x), u = fract(x); |
| +добавлено | u = u * u * (3.0 - 2.0 * u); |
| +добавлено | vec2 i0 = vec2(mod(i.x, per), perY > 0.0 ? mod(i.y, perY) : i.y); |
| +добавлено | vec2 i1 = vec2(mod(i.x + 1.0, per), perY > 0.0 ? mod(i.y + 1.0, perY) : i.y + 1.0); |
| +добавлено | return mix(mix(hash12(i0), hash12(vec2(i1.x, i0.y)), u.x), mix(hash12(vec2(i0.x, i1.y)), hash12(i1), u.x), u.y); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // Static gate mask, baked once at field resolution (world-locked): |
| +добавлено | // r frost needles (ridged streaks on hexagonal axes), g crack veins (voronoi edges, 2 scales), b corruption veins (warped), a fbm |
| +добавлено | const MASK_FRAG = FIELD_GLSL + /* glsl */` |
| +добавлено | uniform float uNeedle; // needles across per metre: 9, fewer on a coarse field (a needle under ~2 texels is noise, and fronts gated on noise grow a maze) |
| +добавлено | in vec2 vUv; |
| +добавлено | out vec4 outColor; |
| +добавлено | // distance to the nearest voronoi edge (F2-F1 bisector distance, Quilez), in cells |
| +добавлено | float voronoiEdge(vec2 x, float seed) { |
| +добавлено | vec2 i = floor(x), fr = fract(x), mg, mr; |
| +добавлено | float md = 8.0; |
| +добавлено | for (int y = -uOne; y <= uOne; y++) for (int k = -uOne; k <= uOne; k++) { |
| +добавлено | vec2 g = vec2(k, y), o = hash33(vec3(i + g, seed)).xy, r = g + o - fr; |
| +добавлено | float d = dot(r, r); |
| +добавлено | if (d < md) { md = d; mr = r; mg = g; } |
| +добавлено | } |
| +добавлено | md = 8.0; |
| +добавлено | for (int y = -2 * uOne; y <= 2 * uOne; y++) for (int k = -2 * uOne; k <= 2 * uOne; k++) { |
| +добавлено | vec2 g = mg + vec2(k, y), o = hash33(vec3(i + g, seed)).xy, r = g + o - fr; |
| +добавлено | if (dot(mr - r, mr - r) > 1e-5) md = min(md, dot(0.5 * (mr + r), normalize(r - mr))); |
| +добавлено | } |
| +добавлено | return md; |
| +добавлено | } |
| +добавлено | void main() { |
| +добавлено | vec2 w = G_MIN + vUv * G_SIZE; |
| +добавлено | // five fbms in one rolled loop: crack warp xy, corruption warp xy, frost wobble |
| +добавлено | float nv[5]; |
| +добавлено | for (int j = 0; j < 5 * uOne; j++) nv[j] = fbm2(w * (j < 2 ? 0.9 : j < 4 ? 1.7 : 5.0) + float(j) * 9.1); |
| +добавлено | // ice grows needles along its hexagonal axes: thin ridged streaks at 0/60/120 degrees |
| +добавлено | // (long along the axis, ~3 cm across), wobbled a little so they aren't ruler-straight |
| +добавлено | float frost = 0.0; |
| +добавлено | for (int k = 0; k < 3 * uOne; k++) { |
| +добавлено | float an = float(k) * 1.0472; |
| +добавлено | vec2 q = mat2(cos(an), sin(an), -sin(an), cos(an)) * w + vec2(0.0, (nv[4] - 0.5) * 0.25); |
| +добавлено | frost = max(frost, 1.0 - abs(vnoise(vec2(q.x * 1.3, q.y * uNeedle) + float(k) * 31.7) * 2.0 - 1.0)); |
| +добавлено | } |
| +добавлено | vec2 wc = w + (vec2(nv[0], nv[1]) - 0.5) * 0.6; |
| +добавлено | vec2 wv = w + (vec2(nv[2], nv[3]) - 0.5) * 1.4; |
| +добавлено | // edge distance in metres for: crack plates (~1.4 m), sub-cracks (~0.45 m), and corruption's |
| +добавлено | // strongly warped ~0.9 m cells (organic tendrils). One rolled loop = one inlined voronoi. |
| +добавлено | vec3 e; |
| +добавлено | for (int l = 0; l < 3 * uOne; l++) { |
| +добавлено | float cell = l == 0 ? 1.4 : l == 1 ? 0.45 : 0.9; |
| +добавлено | e[l] = voronoiEdge((l == 2 ? wv : wc) / cell, float(l + 1)) * cell; |
| +добавлено | } |
| +добавлено | // >= 2 texels wide at 1024^2, so a diagonal vein stays 4-connected for the fronts. Noise |
| +добавлено | // removes about half the sub-crack edges: cracks fork and dead-end instead of closing cells. |
| +добавлено | float gaps = vnoise(w * 1.6 + 70.0); |
| +добавлено | float crack = max((1.0 - smoothstep(0.02, 0.08, e.x)) * smoothstep(0.25, 0.35, gaps), |
| +добавлено | (1.0 - smoothstep(0.01, 0.06, e.y)) * 0.75 * smoothstep(0.5, 0.6, gaps)); |
| +добавлено | float corr = 1.0 - smoothstep(0.02, 0.08, e.z); |
| +добавлено | // a: tileable fbm, 60 cells across the field; the sim samples it as splat noise (snoise) |
| +добавлено | float a = 0.0, amp = 0.5; |
| +добавлено | for (int o = 0; o < 3 * uOne; o++) { float per = 60.0 * float(1 << o); a += vnoiseP(vUv * per, per, per) * amp; amp *= o == 0 ? 0.6 : 0.67; } |
| +добавлено | outColor = vec4(frost, crack, corr, clamp((a - 0.5) * 1.6 + 0.5, 0.0, 1.0)); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const SIM_FRAG = FIELD_GLSL + /* glsl */` |
| +добавлено | uniform sampler2D uA; |
| +добавлено | uniform sampler2D uB; |
| +добавлено | uniform sampler2D uMask; |
| +добавлено | uniform vec4 uSplat[${MAX_SPLATS * SPLAT_VEC4}]; |
| +добавлено | uniform int uSplatCount; |
| +добавлено | uniform float uSeed; |
| +добавлено | uniform float uRound; // dither offset in ulps: -0.5 if fp16 writes round to nearest, 0 if they truncate |
| +добавлено | // per-step factors, [0..6] for the fast boxes (this frame's dt), [7..13] for the band (its |
| +добавлено | // accumulated dt): |
| +добавлено | // 0 heat decay, heat diffusion alpha, char gain, char decay |
| +добавлено | // 1 evaporation, wet decay, melt, frost decay |
| +добавлено | // 2 frost advance p, frost drop/texel, frost threshold, frost drop factor on water |
| +добавлено | // 3 crack p, crack drop, crack decay, acid decay |
| +добавлено | // 4 corruption p, corruption drop, corruption decay, glow decay |
| +добавлено | // 5 acid alpha, pool quench, cleanse, dt |
| +добавлено | // 6 neighbour decay for the frost, crack, corruption fronts (1 in fast steps), unused |
| +добавлено | uniform vec4 uK[14]; |
| +добавлено | uniform vec4 uFast[${MAX_BOXES}]; // texel rects [x0, y0, x1, y1): stepped with uK[0..6] (+ splats) ... |
| +добавлено | uniform vec4 uBand; // ... or with uK[7..13]; any other drawn texel is copied unchanged |
| +добавлено | uniform sampler2D uPaintA; // this frame's particle paint (increments), added in fast texels |
| +добавлено | uniform sampler2D uPaintB; |
| +добавлено | uniform int uPaintOn; |
| +добавлено | layout(location = 0) out vec4 oA; |
| +добавлено | layout(location = 1) out vec4 oB; |
| +добавлено | |
| +добавлено | // smooth tileable noise from the mask's fbm channel; x in noise cells (60 per field width). |
| +добавлено | // A fetch instead of inlined value noise: the splat loop compiles ~10x faster under FXC. |
| +добавлено | float snoise(vec2 x) { return textureLod(uMask, x * (1.0 / 60.0), 0.0).a; } |
| +добавлено | |
| +добавлено | // coverage of splat i at world xz w (single exit: early returns in this loop slow FXC down) |
| +добавлено | float splatShape(int i, vec2 w) { |
| +добавлено | vec4 s0 = uSplat[i * 5], s3 = uSplat[i * 5 + 3], s4 = uSplat[i * 5 + 4]; |
| +добавлено | int pat = int(s0.w); |
| +добавлено | float R = s0.z, seed = s3.x, m = 0.0; |
| +добавлено | float ca = cos(s3.y), sa = sin(s3.y); |
| +добавлено | vec2 nd = mat2(ca, sa, -sa, ca) * (w - s0.xy) / R; |
| +добавлено | float r = length(nd); |
| +добавлено | float n = snoise(nd * 3.0 + seed * 7.31); |
| +добавлено | if (pat == 4) { // line (x, z) -> (x2, z2), half-width s4.x: jagged, tapered at both ends |
| +добавлено | vec2 ab = s3.zw - s0.xy, q = w - s0.xy; |
| +добавлено | float L = max(length(ab), 1e-3); |
| +добавлено | vec2 t = ab / L; |
| +добавлено | float along = dot(q, t); |
| +добавлено | float off = dot(q, vec2(-t.y, t.x)) + (snoise(vec2(along * 2.2, seed * 7.31)) - 0.5) * s4.x * 3.0; |
| +добавлено | float h = clamp(along / L, 0.0, 1.0); |
| +добавлено | float hw = s4.x * (0.35 + 0.65 * sqrt(clamp(min(h, 1.0 - h) * 6.0, 0.0, 1.0))); |
| +добавлено | m = smoothstep(hw, hw * 0.2, abs(off)) * (0.7 + 0.3 * snoise(w * 9.0 + seed)) * step(-hw, along) * step(along, L + hw); |
| +добавлено | } else if (r < 1.6) { |
| +добавлено | if (pat == 0) m = smoothstep(1.0, 0.35, r + (n - 0.5) * 0.45) * (0.65 + 0.5 * n); |
| +добавлено | else if (pat == 2) { // ring at R, width s4.x (metres); s4.y > 0: lobed and broken (radius wanders) |
| +добавлено | vec2 cs = nd / max(r, 1e-3); |
| +добавлено | float lob = (snoise(cs * 1.4 + seed * 3.7) - 0.5) * 3.0 * s4.y; |
| +добавлено | float x = (r - 1.0 - lob) * R / s4.x + (n - 0.5) * 1.2; |
| +добавлено | m = exp(-x * x * 2.0) * (0.6 + 0.6 * n) * mix(1.0, smoothstep(0.3, 0.55, snoise(cs * 2.7 + seed * 1.9)), min(s4.y * 3.0, 1.0)); |
| +добавлено | } else if (pat == 3) m = smoothstep(1.0, 0.6, r) * smoothstep(0.45, 0.62, snoise(nd * 2.2 + seed * 3.1 + 0.5) + (1.0 - r) * 0.15); |
| +добавлено | else { |
| +добавлено | // lichtenberg: polar ridged noise stretched along the radius, so ridges run outward. |
| +добавлено | // Angle is periodic (no seam). Each octave doubles the channels, starts further out, |
| +добавлено | // wanders more, thins with radius and only shows near its parent channel: a fork. |
| +добавлено | float th = atan(nd.y, nd.x) / 6.2831853 + 0.5; |
| +добавлено | float lr = log(max(r, 0.03)), near = 1.0; |
| +добавлено | for (int o = 0; o < 4 * uOne; o++) { |
| +добавлено | float fo = float(o), k = 7.0 * float(1 << o); |
| +добавлено | float warp = (snoise(nd * (1.5 + fo) + seed + fo * 3.3) - 0.5) * (0.25 / k + 0.02); // turns |
| +добавлено | float ridge = 1.0 - abs(vnoiseP(vec2((th + warp) * k, lr * 0.6 + seed * 13.0 + fo * 5.1), k, 0.0) * 2.0 - 1.0); |
| +добавлено | float reach = smoothstep(0.05 + fo * 0.12, 0.15 + fo * 0.15, r); |
| +добавлено | m = max(m, pow(ridge, (30.0 + fo * 12.0) * (0.5 + 1.5 * r)) * near * reach * (1.0 - fo * 0.1)); |
| +добавлено | near *= smoothstep(0.2, 0.6, ridge); |
| +добавлено | } |
| +добавлено | float core = smoothstep(0.32, 0.0, r + (n - 0.5) * 0.3); |
| +добавлено | m = max(core, m) * smoothstep(1.0, 0.55, r + (n - 0.5) * 0.3); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return m; |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | ivec2 p = ivec2(gl_FragCoord.xy), hi = textureSize(uA, 0) - 1; |
| +добавлено | float n = float(hi.x + 1); |
| +добавлено | vec4 a = texelFetch(uA, p, 0), b = texelFetch(uB, p, 0); |
| +добавлено | vec2 fc = gl_FragCoord.xy; |
| +добавлено | bool fast = false; |
| +добавлено | for (int i = 0; i < ${MAX_BOXES} * uOne; i++) fast = fast || (all(greaterThanEqual(fc, uFast[i].xy)) && all(lessThan(fc, uFast[i].zw))); |
| +добавлено | bool band = all(greaterThanEqual(fc, uBand.xy)) && all(lessThan(fc, uBand.zw)); |
| +добавлено | // copy: keeps both ping-pong targets identical outside what was stepped |
| +добавлено | if (!fast && !band) { oA = a; oB = b; return; } |
| +добавлено | vec4 uK0 = fast ? uK[0] : uK[7], uK1 = fast ? uK[1] : uK[8], uK2 = fast ? uK[2] : uK[9]; |
| +добавлено | vec4 uK3 = fast ? uK[3] : uK[10], uK4 = fast ? uK[4] : uK[11], uK5 = fast ? uK[5] : uK[12]; |
| +добавлено | vec4 uK6 = fast ? uK[6] : uK[13]; |
| +добавлено | ivec2 pl = ivec2(max(p.x - 1, 0), p.y), pr = ivec2(min(p.x + 1, hi.x), p.y); |
| +добавлено | ivec2 pd = ivec2(p.x, max(p.y - 1, 0)), pu = ivec2(p.x, min(p.y + 1, hi.y)); |
| +добавлено | vec4 aL = texelFetch(uA, pl, 0), aR = texelFetch(uA, pr, 0), aD = texelFetch(uA, pd, 0), aU = texelFetch(uA, pu, 0); |
| +добавлено | vec4 bL = texelFetch(uB, pl, 0), bR = texelFetch(uB, pr, 0), bD = texelFetch(uB, pd, 0), bU = texelFetch(uB, pu, 0); |
| +добавлено | // diagonals of frost only: an 8-neighbour count tells a dendrite tip (1) from a flat front (3) |
| +добавлено | float fDL = texelFetch(uA, ivec2(pl.x, pd.y), 0).w, fDR = texelFetch(uA, ivec2(pr.x, pd.y), 0).w; |
| +добавлено | float fUL = texelFetch(uA, ivec2(pl.x, pu.y), 0).w, fUR = texelFetch(uA, ivec2(pr.x, pu.y), 0).w; |
| +добавлено | vec4 mask = texelFetch(uMask, p, 0); |
| +добавлено | vec2 w = texelWorld(gl_FragCoord.xy, n); |
| +добавлено | vec3 rnd = hash33(vec3(gl_FragCoord.xy, uSeed)); |
| +добавлено | float dt = uK5.w; |
| +добавлено | |
| +добавлено | float heat = a.x, chr = a.y, wet = a.z, frost = a.w; |
| +добавлено | float crack = b.x, acid = b.y, corr = b.z, glow = b.w; |
| +добавлено | float fVis = min(frost, 1.0); |
| +добавлено | |
| +добавлено | // heat: 5-tap diffusion, decay, water evaporates (latent heat cools), frost melts to wet |
| +добавлено | heat += (aL.x + aR.x + aD.x + aU.x - 4.0 * heat) * uK0.y; |
| +добавлено | heat *= uK0.x; |
| +добавлено | float evap = min(wet, uK1.x * heat); |
| +добавлено | wet -= evap; |
| +добавлено | heat -= evap * 0.35; |
| +добавлено | // branch-free on purpose here and below: FXC (ANGLE/D3D) compile time grows with every if |
| +добавлено | frost = heat > 0.05 ? min(frost, 1.0) : frost; // heat kills potential: no spreading into fire |
| +добавлено | float melt = min(frost, uK1.z * heat); |
| +добавлено | frost -= melt; |
| +добавлено | wet += melt; |
| +добавлено | heat = max(heat - melt * 0.5, 0.0); |
| +добавлено | // char grows where hot and dry, then fades |
| +добавлено | chr += uK0.z * smoothstep(0.15, 0.7, heat) * (1.0 - min(wet, 1.0)); |
| +добавлено | chr *= uK0.w; |
| +добавлено | wet *= uK1.y; |
| +добавлено | |
| +добавлено | // frost front: dendrite tips advance at full rate, flat fronts at a fifth; water freezes |
| +добавлено | // freely and with a smaller drop, so puddles and the pool ice over in sheets |
| +добавлено | float frozenN = step(0.2, aL.w) + step(0.2, aR.w) + step(0.2, aD.w) + step(0.2, aU.w) |
| +добавлено | + step(0.2, fDL) + step(0.2, fDR) + step(0.2, fUL) + step(0.2, fUR); |
| +добавлено | float fMax = max(max(max(aL.w, aR.w), max(aD.w, aU.w)), max(max(fDL, fDR), max(fUL, fUR)) - uK2.y * 0.414); |
| +добавлено | bool onWater = wet > 0.3; |
| +добавлено | // New frost nucleates by a Packard-style snowflake rule: where exactly one 8-neighbour is |
| +добавлено | // frozen (a tip), flanks (2-3 neighbours) rarely, so fingers stay thin and fork instead of |
| +добавлено | // merging into a disc. Inside existing frost the potential flows freely to feed the tips. |
| +добавлено | float fGate = onWater || frost > 0.2 ? 1.0 : step(uK2.z, mask.r) * (frozenN < 1.5 ? 1.0 : frozenN < 2.5 ? 0.02 : 0.001); |
| +добавлено | // band steps decay the neighbours too (uK6): over its long dt, undecayed neighbours would |
| +добавлено | // refill every texel and stall the decay of whole frozen areas. Per frame it's negligible |
| +добавлено | // and the fast steps keep the reach the look was tuned with. |
| +добавлено | // the drop per texel (so a front's reach) varies over ~3 m patches, x0.55..1.6: frost reaches |
| +добавлено | // further where the stone is colder, and a splat's front grows into lobes, never a circle |
| +добавлено | float fReach = onWater ? uK2.w : 0.55 + 1.05 * textureLod(uMask, w * ${f(1 / 150)}, 0.0).a; |
| +добавлено | float fGrow = fMax * uK6.x - uK2.y * fReach; |
| +добавлено | float fOld = fVis; |
| +добавлено | frost *= uK1.w; |
| +добавлено | frost = max(frost, fGrow * step(rnd.x, uK2.x * fGate) * step(heat, 0.05)); |
| +добавлено | wet += max(fOld - min(frost, 1.0), 0.0) * 0.8 * step(heat, 0.05); // natural thaw -> puddle |
| +добавлено | |
| +добавлено | // crack front along the vein network |
| +добавлено | float cMax = max(max(bL.x, bR.x), max(bD.x, bU.x)); |
| +добавлено | crack *= uK3.z; |
| +добавлено | crack = max(crack, (cMax * uK6.y - uK3.y) * step(rnd.y, uK3.x * step(0.45, mask.g))); |
| +добавлено | |
| +добавлено | // corruption: spreads as a lobed stain (faster where the fbm is high), falling off with distance |
| +добавлено | // from its source; the arena material draws the crack network through it, so the field itself |
| +добавлено | // carries no veins (a vein-gated front read as one even tiling of glowing cells) |
| +добавлено | float vMax = max(max(bL.z, bR.z), max(bD.z, bU.z)); |
| +добавлено | corr *= uK4.z; |
| +добавлено | float vGate = 0.15 + 0.85 * mask.a * mask.a; |
| +добавлено | corr = max(corr, (vMax * uK6.z - uK4.y) * step(rnd.z, uK4.x * vGate)); |
| +добавлено | corr = max(corr - uK5.z * glow, 0.0); // holy light burns corruption away |
| +добавлено | |
| +добавлено | // acid: slow decay, slight spread; glow: fast decay |
| +добавлено | acid += (bL.y + bR.y + bD.y + bU.y - 4.0 * acid) * uK5.x; |
| +добавлено | acid *= uK3.w; |
| +добавлено | glow *= uK4.w; |
| +добавлено | |
| +добавлено | // the pool stays full; frost on it is the ice sheet (frost x wet), heat is quenched |
| +добавлено | float pool = inPool(w) ? 1.0 : 0.0; |
| +добавлено | wet = max(wet, pool); |
| +добавлено | heat *= mix(1.0, uK5.y, pool); |
| +добавлено | |
| +добавлено | vec4 A = vec4(heat, chr, wet, frost), B = vec4(crack, acid, corr, glow); |
| +добавлено | if (fast && uPaintOn == 1) { A += texelFetch(uPaintA, p, 0); B += texelFetch(uPaintB, p, 0); } |
| +добавлено | int splats = fast ? uSplatCount : 0; // splats always lie inside the fast boxes |
| +добавлено | for (int i = 0; i < splats; i++) { |
| +добавлено | float m = splatShape(i, w); |
| +добавлено | vec4 s1 = uSplat[i * 5 + 1], s2 = uSplat[i * 5 + 2]; |
| +добавлено | A.xyz += s1.xyz * m; |
| +добавлено | B.yw += s2.yw * m; |
| +добавлено | // potential channels take the max (re-splatting doesn't stack reach); negative erases |
| +добавлено | A.w = s1.w >= 0.0 ? max(A.w, s1.w * m) : A.w + s1.w * m; |
| +добавлено | B.x = s2.x >= 0.0 ? max(B.x, s2.x * m) : B.x + s2.x * m; |
| +добавлено | B.z = s2.z >= 0.0 ? max(B.z, s2.z * m) : B.z + s2.z * m; |
| +добавлено | } |
| +добавлено | |
| +добавлено | A = clamp(A, vec4(0.0), vec4(2.0, 1.0, 1.0, 4.0)); |
| +добавлено | B = clamp(B, vec4(0.0), vec4(4.0, 1.0, 4.0, 8.0)); |
| +добавлено | // stochastic rounding (1 ulp of dither, placed for how this GPU converts to fp16) keeps the |
| +добавлено | // tiny per-step decays unbiased; then snap dust to exact zero so idle texels stay 0 |
| +добавлено | vec4 ulpA = exp2(floor(log2(max(A, 6.2e-5))) - 10.0), ulpB = exp2(floor(log2(max(B, 6.2e-5))) - 10.0); |
| +добавлено | A += (rnd.x + uRound) * ulpA; |
| +добавлено | B += (fract(rnd.x + 0.618) + uRound) * ulpB; |
| +добавлено | oA = A * step(1.0 / 1024.0, A); |
| +добавлено | oB = B * step(1.0 / 1024.0, B); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export class GroundField { |
| +добавлено | // partial: false steps the whole field every frame (reference / debugging, ~0.1 ms at 1024^2) |
| +добавлено | constructor(renderer, size = 1024, { partial = true } = {}) { |
| +добавлено | this.renderer = renderer; |
| +добавлено | this.size = size; |
| +добавлено | this.partial = partial; |
| +добавлено | const opts = { |
| +добавлено | type: THREE.HalfFloatType, format: THREE.RGBAFormat, count: 2, |
| +добавлено | minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | wrapS: THREE.ClampToEdgeWrapping, wrapT: THREE.ClampToEdgeWrapping, |
| +добавлено | depthBuffer: false, generateMipmaps: false, |
| +добавлено | }; |
| +добавлено | this.targets = [new THREE.WebGLRenderTarget(size, size, opts), new THREE.WebGLRenderTarget(size, size, opts)]; |
| +добавлено | this.parity = 0; |
| +добавлено | // live-tunable rates (world units, seconds); turned into per-step factors in update() |
| +добавлено | this.params = { |
| +добавлено | heatTau: 2.5, heatDiffusion: 0.012, charRate: 1.4, charTau: 25, |
| +добавлено | evaporation: 0.9, wetTau: 45, melt: 1.2, frostTau: 7, |
| +добавлено | frostSpeed: 1.6, frostDrop: 0.4, frostThreshold: 0.88, frostWaterDrop: 0.2, |
| +добавлено | crackSpeed: 4, crackDrop: 0.6, crackTau: 9, |
| +добавлено | corruptionSpeed: 1.1, corruptionDrop: 0.4, corruptionTau: 14, |
| +добавлено | acidTau: 14, acidSpread: 0.0015, glowTau: 1, poolQuench: 0.3, cleanse: 1.5, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // the sim texelFetches r/g/b; splats sample a (tileable) filtered, so repeat + linear |
| +добавлено | this.mask = new THREE.WebGLRenderTarget(size, size, { |
| +добавлено | minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, wrapS: THREE.RepeatWrapping, wrapT: THREE.RepeatWrapping, |
| +добавлено | depthBuffer: false, generateMipmaps: false, |
| +добавлено | }); |
| +добавлено | const maskQuad = new FullscreenQuad(rawPass(MASK_FRAG, { uOne: { value: 1 }, uNeedle: { value: 9 * Math.min(1, size / 1024) } })); |
| +добавлено | |
| +добавлено | this.splatVecs = Array.from({ length: MAX_SPLATS * SPLAT_VEC4 }, () => new THREE.Vector4()); |
| +добавлено | this.splatCount = 0; |
| +добавлено | this.seed = 0; |
| +добавлено | this.simMat = rawPass(SIM_FRAG, { |
| +добавлено | uA: { value: null }, uB: { value: null }, uMask: { value: this.mask.texture }, |
| +добавлено | uSplat: { value: this.splatVecs }, uSplatCount: { value: 0 }, uSeed: { value: 0 }, uRound: { value: -0.5 }, uOne: { value: 1 }, |
| +добавлено | uK: { value: Array.from({ length: 14 }, () => new THREE.Vector4()) }, |
| +добавлено | uFast: { value: Array.from({ length: MAX_BOXES }, () => new THREE.Vector4()) }, uBand: { value: new THREE.Vector4() }, |
| +добавлено | uPaintA: { value: null }, uPaintB: { value: null }, uPaintOn: { value: 0 }, |
| +добавлено | }); |
| +добавлено | // partial-update bookkeeping (world-space regions -> texel rects); all preallocated |
| +добавлено | this.time = 0; |
| +добавлено | this.regions = Array.from({ length: MAX_REGIONS }, () => ({ x0: 0, z0: 0, x1: 0, z1: 0, until: -1 })); |
| +добавлено | this.boxes = this.simMat.uniforms.uFast.value; // texel rects [x0, y0, x1, y1) stepped this frame |
| +добавлено | this.boxCount = 0; |
| +добавлено | this._lastBoxes = Array.from({ length: MAX_BOXES }, () => new THREE.Vector4()); |
| +добавлено | this._lastBoxCount = 0; |
| +добавлено | this._lastBand = new THREE.Vector4(); |
| +добавлено | this._q = new THREE.Vector4(); |
| +добавлено | this._u = new THREE.Vector4(); |
| +добавлено | this.band = 0; |
| +добавлено | this.bandDt = new Float32Array(BANDS); |
| +добавлено | this._full = true; // next update steps everything (after clear) |
| +добавлено | this.quad = new FullscreenQuad(this.simMat); |
| +добавлено | |
| +добавлено | // particle paint: x right, y = +z (camera below the floor looking up keeps both axes positive). |
| +добавлено | // Its own target, so overlapping fast boxes can't add the same paint twice. |
| +добавлено | this.paintTarget = new THREE.WebGLRenderTarget(size, size, { ...opts, minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter }); |
| +добавлено | this.simMat.uniforms.uPaintA.value = this.paintTarget.textures[0]; |
| +добавлено | this.simMat.uniforms.uPaintB.value = this.paintTarget.textures[1]; |
| +добавлено | this._clearColor = new THREE.Color(); |
| +добавлено | this.paintScene = new THREE.Scene(); |
| +добавлено | this.paintCamera = new THREE.OrthographicCamera(G.min.x, G.min.x + G.size, G.min.y + G.size, G.min.y, 0, 200); |
| +добавлено | this.paintCamera.position.set(0, -100, 0); |
| +добавлено | this.paintCamera.up.set(0, 0, 1); |
| +добавлено | this.paintCamera.lookAt(0, 0, 0); |
| +добавлено | this.paintCamera.updateMatrixWorld(); |
| +добавлено | |
| +добавлено | this._initProbes(); |
| +добавлено | // issue every compile now: with KHR_parallel_shader_compile they build concurrently and |
| +добавлено | // only the mask bake waits; the sim program (~0.4 s cold under ANGLE/D3D11, FXC) keeps |
| +добавлено | // compiling in the background until the first update() |
| +добавлено | const cam = new THREE.Camera(), prev = renderer.getRenderTarget(); |
| +добавлено | // fp16 render-target writes truncate on some GPUs (ANGLE/D3D11 measured: 1 + 0.75 ulp -> 1) |
| +добавлено | // and round on others; a truncating GPU with +-0.5 ulp dither decays ~20% too fast |
| +добавлено | const roundQuad = new FullscreenQuad(rawPass(/* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | layout(location = 0) out vec4 o0; |
| +добавлено | layout(location = 1) out vec4 o1; |
| +добавлено | void main() { o0 = vec4(1.0 + 0.75 / 1024.0); o1 = vec4(0.0); }`)); |
| +добавлено | for (const q of [maskQuad, this.quad, this.probeQuad, roundQuad]) renderer.compile(q.mesh, cam); |
| +добавлено | maskQuad.render(renderer, this.mask); |
| +добавлено | maskQuad.material.dispose(); |
| +добавлено | roundQuad.render(renderer, this.paintTarget); |
| +добавлено | const half = new Uint16Array(4); |
| +добавлено | renderer.readRenderTargetPixels(this.paintTarget, 0, 0, 1, 1, half, undefined, 0); |
| +добавлено | roundQuad.material.dispose(); |
| +добавлено | this.fp16Truncates = half[0] === 0x3c00; |
| +добавлено | this.simMat.uniforms.uRound.value = this.fp16Truncates ? 0 : -0.5; |
| +добавлено | renderer.setRenderTarget(prev); |
| +добавлено | this.clear(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | get current() { return this.targets[this.parity]; } |
| +добавлено | |
| +добавлено | // queue a splat for the next update (<= 16 per frame; extras are dropped) |
| +добавлено | splat({ x = 0, z = 0, radius = 1, heat = 0, char = 0, wet = 0, frost = 0, crack = 0, acid = 0, corruption = 0, glow = 0, |
| +добавлено | pattern = 'radial', seed = Math.random() * 100, angle = 0, x2 = x, z2 = z, width = 0, lobe = 0 } = {}) { |
| +добавлено | if (this.splatCount >= MAX_SPLATS) return false; |
| +добавлено | const v = this.splatVecs, o = this.splatCount * SPLAT_VEC4; |
| +добавлено | v[o].set(x, z, radius, PATTERNS[pattern] ?? 0); |
| +добавлено | v[o + 1].set(heat, char, wet, frost); |
| +добавлено | v[o + 2].set(crack, acid, corruption, glow); |
| +добавлено | v[o + 3].set(seed % 100, angle, x2, z2); |
| +добавлено | const w = width || (pattern === 'line' ? radius : radius * 0.18); |
| +добавлено | v[o + 4].set(w, lobe, 0, 0); // line half-width / ring width, ring lobes |
| +добавлено | this.splatCount++; |
| +добавлено | if (pattern === 'radial' && crack >= 2) { |
| +добавлено | let i = 0; |
| +добавлено | for (let j = 1; j < 4; j++) if (CRACK_SOURCES[j].w < CRACK_SOURCES[i].w) i = j; |
| +добавлено | CRACK_SOURCES[i].set(x, z, radius, crack); |
| +добавлено | } |
| +добавлено | if (pattern === 'line' && crack >= 1.5 && heat > 0.1 && w >= 0.25) { |
| +добавлено | // a growing vent re-splats from the same start every frame: update its slot, else the weakest |
| +добавлено | let i = -1, m = 0; |
| +добавлено | for (let j = 0; j < 4; j++) { |
| +добавлено | const a = FISSURE_A[j]; |
| +добавлено | if (FISSURE_B[j].y > 0 && Math.abs(a.x - x) < 0.05 && Math.abs(a.y - z) < 0.05) i = j; |
| +добавлено | if (FISSURE_B[j].y < FISSURE_B[m].y) m = j; |
| +добавлено | } |
| +добавлено | if (i < 0) { i = m; FISSURE_B[i].set(0, 0, 0, 0); } |
| +добавлено | FISSURE_A[i].set(x, z, x2, z2); |
| +добавлено | FISSURE_B[i].set(Math.max(w, FISSURE_B[i].x), Math.max(crack, FISSURE_B[i].y), seed % 97, 0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // region the splat's effects live in: its footprint, plus how far fronts and heat can |
| +добавлено | // travel, for as long as they keep moving (afterwards the bands carry the slow decay) |
| +добавлено | const p = this.params; |
| +добавлено | const ext = pattern === 'line' ? w * 2.5 : radius * 1.6; |
| +добавлено | const reach = Math.max(frost / p.frostDrop, crack / p.crackDrop, corruption / p.corruptionDrop, 0); |
| +добавлено | const life = Math.min(20, Math.max(heat > 0 ? 3 * p.heatTau : 0, glow > 0 ? 3 * p.glowTau : 0, |
| +добавлено | frost > 0 ? reach / p.frostSpeed * 1.5 + 1 : 0, crack > 0 ? reach / p.crackSpeed * 1.5 + 1 : 0, |
| +добавлено | corruption > 0 ? reach / p.corruptionSpeed * 2 + 1 : 0, 0.5)); |
| +добавлено | const m = ext + reach + (heat > 0 ? 0.6 : 0.1); |
| +добавлено | this._region(Math.min(x, x2) - m, Math.min(z, z2) - m, Math.max(x, x2) + m, Math.max(z, z2) + m, life); |
| +добавлено | // ice on the pool spreads in a sheet much further than on stone: keep the whole pool live |
| +добавлено | if (frost > 0 && Math.abs(x - P.center.x) < P.half.x + m && Math.abs(z - P.center.y) < P.half.y + m) |
| +добавлено | this._region(P.center.x - P.half.x, P.center.y - P.half.y, P.center.x + P.half.x, P.center.y + P.half.y, life); |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // keep a world area stepped every frame for `seconds` (e.g. where particles paint) |
| +добавлено | touch(x, z, radius, seconds = 1) { this._region(x - radius, z - radius, x + radius, z + radius, seconds); } |
| +добавлено | |
| +добавлено | _region(x0, z0, x1, z1, seconds) { |
| +добавлено | let r = null, soonest = this.regions[0]; |
| +добавлено | for (const q of this.regions) { |
| +добавлено | if (q.until < this.time) { r = q; break; } |
| +добавлено | if (q.until < soonest.until) soonest = q; |
| +добавлено | } |
| +добавлено | let until = this.time + seconds; |
| +добавлено | if (!r) { |
| +добавлено | // ponytail: all slots live -> merge into the soonest-expiring one (a superset, still correct) |
| +добавлено | r = soonest; |
| +добавлено | x0 = Math.min(x0, r.x0); z0 = Math.min(z0, r.z0); x1 = Math.max(x1, r.x1); z1 = Math.max(z1, r.z1); |
| +добавлено | until = Math.max(until, r.until); |
| +добавлено | } |
| +добавлено | r.x0 = x0; r.z0 = z0; r.x1 = x1; r.z1 = z1; r.until = until; |
| +добавлено | } |
| +добавлено | |
| +добавлено | update(dt) { |
| +добавлено | this.time += dt; |
| +добавлено | const cd = decay(dt, this.params.crackTau); |
| +добавлено | for (const c of CRACK_SOURCES) c.w *= cd; |
| +добавлено | for (const b of FISSURE_B) b.y *= cd; |
| +добавлено | const n = this.size, k = this.simMat.uniforms.uK.value; |
| +добавлено | const band = this.simMat.uniforms.uBand.value; |
| +добавлено | for (const b of this.boxes) b.set(0, 0, 0, 0); |
| +добавлено | if (this._full || !this.partial) { |
| +добавлено | this.boxes[0].set(0, 0, n, n); |
| +добавлено | this.boxCount = 1; |
| +добавлено | band.set(0, 0, 0, 0); |
| +добавлено | this._full = false; |
| +добавлено | } else { |
| +добавлено | this._cluster(); |
| +добавлено | const h = n / BANDS; |
| +добавлено | band.set(0, this.band * h, n, (this.band + 1) * h); |
| +добавлено | } |
| +добавлено | for (let i = 0; i < BANDS; i++) this.bandDt[i] += dt; |
| +добавлено | if (band.w === 0) this.bandDt.fill(0); // full step: every band is current |
| +добавлено | this._factors(k, 0, dt, false); |
| +добавлено | this._factors(k, 7, this.bandDt[this.band], true); |
| +добавлено | // ponytail: texels that just left the fast boxes get their band's whole accumulated dt |
| +добавлено | // (slightly early decay at a region's edge); per-texel step times would need a channel |
| +добавлено | this.bandDt[this.band] = 0; |
| +добавлено | this._step(); |
| +добавлено | this.band = (this.band + 1) % BANDS; |
| +добавлено | this._readProbes(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // live regions -> <= 4 texel boxes (overlap allowed). A region joins a box when the union |
| +добавлено | // is cheaper than drawing both, else opens a box; with all 4 open it joins the cheapest. |
| +добавлено | // Then boxes whose union is cheaper than the pair are fused. |
| +добавлено | // ponytail: greedy, order dependent; fine for a handful of spells, k-means if arenas get busy |
| +добавлено | _cluster() { |
| +добавлено | const n = this.size, B = this.boxes, q = this._q, u = this._u, s = n / G.size; |
| +добавлено | let nb = 0; |
| +добавлено | for (const r of this.regions) { |
| +добавлено | if (r.until < this.time) continue; |
| +добавлено | q.set(Math.round((r.x0 - G.min.x) * s), Math.round((r.z0 - G.min.y) * s), Math.round((r.x1 - G.min.x) * s), Math.round((r.z1 - G.min.y) * s)); |
| +добавлено | q.clampScalar(0, n); |
| +добавлено | if (q.z <= q.x || q.w <= q.y) continue; |
| +добавлено | // join the box where the union costs least extra over drawing both; only when that |
| +добавлено | // saves texels, unless all boxes are taken |
| +добавлено | let best = -1, extra = Infinity; |
| +добавлено | for (let i = 0; i < nb; i++) { |
| +добавлено | const b = B[i]; |
| +добавлено | u.set(Math.min(b.x, q.x), Math.min(b.y, q.y), Math.max(b.z, q.z), Math.max(b.w, q.w)); |
| +добавлено | const e = area(u) - area(b) - area(q); |
| +добавлено | if ((e < 0 || nb === MAX_BOXES) && e < extra) { best = i; extra = e; } |
| +добавлено | } |
| +добавлено | if (best < 0) { B[nb++].copy(q); continue; } |
| +добавлено | const b = B[best]; |
| +добавлено | b.set(Math.min(b.x, q.x), Math.min(b.y, q.y), Math.max(b.z, q.z), Math.max(b.w, q.w)); |
| +добавлено | } |
| +добавлено | for (let i = 0; i < nb; i++) for (let j = i + 1; j < nb; j++) { |
| +добавлено | const a = B[i], b = B[j]; |
| +добавлено | u.set(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.z, b.z), Math.max(a.w, b.w)); |
| +добавлено | if (area(u) >= area(a) + area(b)) continue; |
| +добавлено | a.copy(u); |
| +добавлено | b.copy(B[--nb]); B[nb].set(0, 0, 0, 0); |
| +добавлено | j = i; // a grew: recheck it against everything after it |
| +добавлено | } |
| +добавлено | this.boxCount = nb; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // per-step factors for a step of length dt into uK[o .. o + 6] (layout in SIM_FRAG) |
| +добавлено | _factors(k, o, dt, band) { |
| +добавлено | const p = this.params, dx = G.size / this.size, adv = dt / dx; // front advance probability = speed * adv |
| +добавлено | k[o].set(decay(dt, p.heatTau), Math.min(0.2, p.heatDiffusion * dt / (dx * dx)), p.charRate * dt, decay(dt, p.charTau)); |
| +добавлено | k[o + 1].set(p.evaporation * dt, decay(dt, p.wetTau), p.melt * dt, decay(dt, p.frostTau)); |
| +добавлено | k[o + 2].set(Math.min(1, p.frostSpeed * adv), p.frostDrop * dx, p.frostThreshold, p.frostWaterDrop); |
| +добавлено | k[o + 3].set(Math.min(1, p.crackSpeed * adv), p.crackDrop * dx, decay(dt, p.crackTau), decay(dt, p.acidTau)); |
| +добавлено | k[o + 4].set(Math.min(1, p.corruptionSpeed * adv), p.corruptionDrop * dx, decay(dt, p.corruptionTau), decay(dt, p.glowTau)); |
| +добавлено | k[o + 5].set(Math.min(0.2, p.acidSpread * dt / (dx * dx)), decay(dt, p.poolQuench), p.cleanse * dt, dt); |
| +добавлено | if (band) k[o + 6].set(k[o + 1].w, k[o + 3].z, k[o + 4].z, 0); |
| +добавлено | else k[o + 6].set(1, 1, 1, 0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | _step() { |
| +добавлено | const r = this.renderer, u = this.simMat.uniforms; |
| +добавлено | const src = this.targets[this.parity], dst = this.targets[this.parity ^ 1]; |
| +добавлено | u.uA.value = src.textures[0]; |
| +добавлено | u.uB.value = src.textures[1]; |
| +добавлено | u.uSplatCount.value = this.splatCount; |
| +добавлено | u.uSeed.value = this.seed = (this.seed + 1) % 4096; |
| +добавлено | const prevTarget = r.getRenderTarget(); |
| +добавлено | // scissored draws over everything stepped now or last frame (an overlap just recomputes |
| +добавлено | // the same texels): this frame's boxes, last frame's boxes unless one now covers them, |
| +добавлено | // this band, last frame's band |
| +добавлено | const B = this.boxes, L = this._lastBoxes, nb = this.boxCount; |
| +добавлено | const painting = this.paintScene.children.length > 0 && nb > 0; |
| +добавлено | u.uPaintOn.value = painting ? 1 : 0; |
| +добавлено | if (painting) { |
| +добавлено | r.getClearColor(this._clearColor); |
| +добавлено | const ca = r.getClearAlpha(), autoClear = r.autoClear; |
| +добавлено | r.setRenderTarget(this.paintTarget); |
| +добавлено | r.setClearColor(0x000000, 0); |
| +добавлено | r.clear(true, false, false); // full, unscissored: a fast clear |
| +добавлено | r.autoClear = false; |
| +добавлено | r.render(this.paintScene, this.paintCamera); |
| +добавлено | r.autoClear = autoClear; |
| +добавлено | r.setClearColor(this._clearColor, ca); |
| +добавлено | } |
| +добавлено | dst.scissorTest = true; |
| +добавлено | for (let i = 0; i < nb; i++) this._draw(B[i], dst); |
| +добавлено | for (let i = 0; i < this._lastBoxCount; i++) if (!this._covered(L[i])) this._draw(L[i], dst); |
| +добавлено | this._draw(u.uBand.value, dst); |
| +добавлено | if (!this._covered(this._lastBand)) this._draw(this._lastBand, dst); |
| +добавлено | dst.scissorTest = false; |
| +добавлено | r.setRenderTarget(prevTarget); |
| +добавлено | for (let i = 0; i < nb; i++) L[i].copy(B[i]); |
| +добавлено | this._lastBoxCount = nb; |
| +добавлено | this._lastBand.copy(u.uBand.value); |
| +добавлено | this.splatCount = 0; |
| +добавлено | this.parity ^= 1; |
| +добавлено | U.uGroundA.value = dst.textures[0]; |
| +добавлено | U.uGroundB.value = dst.textures[1]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | _draw(q, dst) { |
| +добавлено | if (q.z <= q.x || q.w <= q.y) return; |
| +добавлено | dst.scissor.set(q.x, q.y, q.z - q.x, q.w - q.y); |
| +добавлено | this.quad.render(this.renderer, dst); |
| +добавлено | } |
| +добавлено | |
| +добавлено | _covered(q) { |
| +добавлено | for (let i = 0; i < this.boxCount; i++) if (contains(this.boxes[i], q)) return true; |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | clear() { |
| +добавлено | const r = this.renderer, prev = r.getRenderTarget(); |
| +добавлено | const cc = r.getClearColor(new THREE.Color()), ca = r.getClearAlpha(); |
| +добавлено | r.setClearColor(0x000000, 0); |
| +добавлено | for (const t of this.targets) { r.setRenderTarget(t); r.clear(true, false, false); } |
| +добавлено | r.setClearColor(cc, ca); |
| +добавлено | r.setRenderTarget(prev); |
| +добавлено | this.splatCount = 0; |
| +добавлено | for (const c of CRACK_SOURCES) c.set(0, 0, 0, 0); |
| +добавлено | for (const b of FISSURE_B) b.set(0, 0, 0, 0); |
| +добавлено | for (const q of this.regions) q.until = -1; |
| +добавлено | this._lastBoxCount = 0; |
| +добавлено | this._lastBand.set(0, 0, 0, 0); |
| +добавлено | this._full = true; |
| +добавлено | // the pool (wet = 1) is restamped by every step; the next update() steps the whole field |
| +добавлено | U.uGroundA.value = this.current.textures[0]; |
| +добавлено | U.uGroundB.value = this.current.textures[1]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- probes: async PBO + fence readback (UW WaterQuery pattern, persistent buffers) --- |
| +добавлено | _initProbes() { |
| +добавлено | this.probes = new Float32Array(MAX_PROBES * 8); // per probe: heat, char, wet, frost, crack, acid, corruption, glow |
| +добавлено | this.probeCount = 0; // probes in the last completed read |
| +добавлено | this._probeN = 0; |
| +добавлено | this._probeXZ = Array.from({ length: MAX_PROBES }, () => new THREE.Vector2()); |
| +добавлено | this.probeRT = new THREE.WebGLRenderTarget(MAX_PROBES * 2, 1, { |
| +добавлено | type: THREE.FloatType, minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, depthBuffer: false, generateMipmaps: false, |
| +добавлено | }); |
| +добавлено | this.probeMat = rawPass(/* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | uniform sampler2D uGroundA; |
| +добавлено | uniform sampler2D uGroundB; |
| +добавлено | uniform vec2 uProbe[${MAX_PROBES}]; |
| +добавлено | out vec4 outColor; |
| +добавлено | void main() { |
| +добавлено | int x = int(gl_FragCoord.x); |
| +добавлено | vec2 uv = (uProbe[x >> 1] - vec2(${f(G.min.x)}, ${f(G.min.y)})) / ${f(G.size)}; |
| +добавлено | outColor = (x & 1) == 0 ? texture(uGroundA, uv) : texture(uGroundB, uv); |
| +добавлено | }`, { uGroundA: U.uGroundA, uGroundB: U.uGroundB, uProbe: { value: this._probeXZ } }); |
| +добавлено | this.probeQuad = new FullscreenQuad(this.probeMat); |
| +добавлено | const gl = this.renderer.getContext(); |
| +добавлено | // storage is allocated at the first readPixels: Chrome counts the allocation as a write, and a |
| +добавлено | // fence between it and the readback write discards its fast readback copy |
| +добавлено | this._pbo = [0, 1].map(() => ({ buffer: gl.createBuffer(), sync: null, count: 0, sized: false })); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // points: [[x, z], ...] (<= 16). Results land in this.probes a few frames later. |
| +добавлено | setProbes(points) { |
| +добавлено | this._probeN = Math.min(points.length, MAX_PROBES); |
| +добавлено | for (let i = 0; i < this._probeN; i++) this._probeXZ[i].set(points[i][0], points[i][1]); |
| +добавлено | } |
| +добавлено | |
| +добавлено | _readProbes() { |
| +добавлено | const gl = this.renderer.getContext(); |
| +добавлено | for (const s of this._pbo) { |
| +добавлено | if (!s.sync || gl.getSyncParameter(s.sync, gl.SYNC_STATUS) !== gl.SIGNALED) continue; |
| +добавлено | gl.deleteSync(s.sync); |
| +добавлено | s.sync = null; |
| +добавлено | gl.bindBuffer(gl.PIXEL_PACK_BUFFER, s.buffer); |
| +добавлено | gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, this.probes, 0, s.count * 8); |
| +добавлено | gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null); |
| +добавлено | this.probeCount = s.count; |
| +добавлено | } |
| +добавлено | if (!this._probeN) return; |
| +добавлено | const s = !this._pbo[0].sync ? this._pbo[0] : !this._pbo[1].sync ? this._pbo[1] : null; |
| +добавлено | if (!s) return; |
| +добавлено | const r = this.renderer, prev = r.getRenderTarget(); |
| +добавлено | this.probeQuad.render(r, this.probeRT); |
| +добавлено | gl.bindBuffer(gl.PIXEL_PACK_BUFFER, s.buffer); |
| +добавлено | if (!s.sized) { gl.bufferData(gl.PIXEL_PACK_BUFFER, MAX_PROBES * 8 * 4, gl.STREAM_READ); s.sized = true; } |
| +добавлено | gl.readPixels(0, 0, this._probeN * 2, 1, gl.RGBA, gl.FLOAT, 0); |
| +добавлено | gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null); |
| +добавлено | s.sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0); |
| +добавлено | s.count = this._probeN; |
| +добавлено | r.setRenderTarget(prev); |
| +добавлено | } |
| +добавлено | |
| +добавлено | dispose() { |
| +добавлено | for (const t of this.targets) t.dispose(); |
| +добавлено | this.mask.dispose(); this.probeRT.dispose(); this.paintTarget.dispose(); this.simMat.dispose(); this.probeMat.dispose(); |
| +добавлено | const gl = this.renderer.getContext(); |
| +добавлено | for (const s of this._pbo) { gl.deleteBuffer(s.buffer); if (s.sync) gl.deleteSync(s.sync); } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { FullscreenQuad, rawPass } from '../engine/fullscreen.js'; |
| +добавлено | import { U } from './common.js'; |
| +добавлено | |
| +добавлено | // Gravitational lensing for the void (PLAN 3), one fullscreen pass, only while a void is alive. |
| +добавлено | // Point-mass (Schwarzschild, weak-field) thin lens as in James, von Tunzelmann, Franklin & Thorne 2015, |
| +добавлено | // "Gravitational lensing by spinning black holes in astrophysics, and in the movie Interstellar" |
| +добавлено | // (CQG 32, 065001): a pixel at angle theta from the lens shows the source at |
| +добавлено | // beta = theta - thetaE^2 * theta / |theta|^2 |
| +добавлено | // so outside thetaE the background is pushed outwards, at thetaE everything behind the hole is smeared |
| +добавлено | // into the Einstein ring, and inside it a mirrored second image wraps the shadow. All angles are in |
| +добавлено | // aspect-corrected screen units (fraction of screen height), from world radii through the projection. |
| +добавлено | // |
| +добавлено | // What makes it hold up in a real scene rather than on a skybox: |
| +добавлено | // - depth: nothing in front of the lens bends (foreground stays sharp), and the deflection eases in |
| +добавлено | // over a couple of Einstein radii behind the lens plane, so there's no seam where the floor |
| +добавлено | // crosses it. Beyond that everything bends like the sky. (The thin-lens ratio D_ls / D_s would be |
| +добавлено | // the physical weight, but it differs between a dummy and the sky right next to it and tears every |
| +добавлено | // depth edge behind the hole; a screen-space pass can't afford to be that honest.) |
| +добавлено | // - lookups never land inside the hole's own image (the opaque horizon may or may not be drawn into |
| +добавлено | // the source), so the Einstein ring shows what surrounds the hole, never black. |
| +добавлено | // - lookups that would leave the screen ease back to the undeflected pixel. |
| +добавлено | // |
| +добавлено | // Accretion disk (lenses[i].disk, optional, cleared by every set()): each pixel near the hole traces |
| +добавлено | // its camera ray as a Schwarzschild null geodesic, x'' = -3/2 h^2 x / r^5 in units of r_s (the |
| +добавлено | // Binet equation u'' + u = 3/2 u^2 written in Cartesian form, h = |x x v| conserved), through a thin |
| +добавлено | // Keplerian disk. Every crossing of the disk plane between the ISCO and the outer edge adds emission |
| +добавлено | // front to back, so the near side passes in front of the shadow, the far side is bent up over it and |
| +добавлено | // its underside under it, and the n >= 1 images hug the shadow. The shadow edge is the critical impact |
| +добавлено | // parameter b_c = 3 sqrt(3) / 2 r_s, with a razor photon ring just outside it. Emission: blackbody at |
| +добавлено | // T ~ r^-3/4 (Shakura-Sunyaev), shifted by g = Doppler * sqrt(1 - r_s / r), intensity ~ g^4, so the |
| +добавлено | // approaching side is much brighter and bluer; banded, differentially rotating turbulence (Omega ~ r^-1.5). |
| +добавлено | // |
| +добавлено | // shell: one expanding photographic-negative spherical shell (the void's collapse), limb-brightened |
| +добавлено | // like a real thin shell seen in projection. |
| +добавлено | const MAX = 2, STEPS = 72; |
| +добавлено | |
| +добавлено | const FRAG = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | precision highp sampler2D; |
| +добавлено | precision highp sampler3D; |
| +добавлено | uniform sampler2D tSrc; |
| +добавлено | uniform sampler2D tDepth; |
| +добавлено | uniform sampler3D uNoise3D; |
| +добавлено | uniform sampler2D uBlackbody; |
| +добавлено | uniform vec4 uA[${MAX}]; // centre (x * aspect, y), thetaE^2 * strength for a source at infinity, shadow radius |
| +добавлено | uniform vec4 uB[${MAX}]; // lens view depth, horizon world radius, ring gain, 1 / depth ramp (m) |
| +добавлено | uniform vec4 uC[${MAX}]; // disk: hole centre (world), r_s (world; 0 = no disk) |
| +добавлено | uniform vec4 uD[${MAX}]; // disk normal, emission scale |
| +добавлено | uniform vec4 uE[${MAX}]; // inner, outer radius (r_s), inner temperature (K), orbital speed (fraction of Kepler) |
| +добавлено | uniform vec4 uF[${MAX}]; // bending 0..1, shadow 0..1, rotation phase (s), one pixel in r_s at the hole |
| +добавлено | uniform vec4 uG[${MAX}]; // tint rgb, spin (rad/s at the inner edge) |
| +добавлено | uniform vec4 uH[${MAX}]; // frame-dragging twist of the background (rad at the Einstein ring), -, -, - |
| +добавлено | uniform vec4 uShell; // centre (world), radius (m) |
| +добавлено | uniform vec4 uShell2; // thickness (m), amount, -, - |
| +добавлено | uniform int uCount; |
| +добавлено | uniform vec2 uNearFar; |
| +добавлено | uniform float uAspect; |
| +добавлено | uniform float uPx; // one pixel in screen-height units |
| +добавлено | uniform vec3 uCamPos; |
| +добавлено | uniform mat3 uCamRot; |
| +добавлено | uniform vec2 uInvP; // 1 / projection[0][0], 1 / projection[1][1] |
| +добавлено | in vec2 vUv; |
| +добавлено | out vec4 fragColor; |
| +добавлено | |
| +добавлено | vec3 blackbody(float k) { return textureLod(uBlackbody, vec2(clamp(log(k / 500.0) / log(40.0), 0.0, 1.0), 0.5), 0.0).rgb; } |
| +добавлено | |
| +добавлено | // critical impact parameter for bending k (k = 1: Schwarzschild, 3 sqrt(3) / 2) |
| +добавлено | float critB(float k) { return k >= 0.6667 ? 2.598076 * k : inversesqrt(max(1.0 - k, 1e-3)); } |
| +добавлено | |
| +добавлено | // banded turbulence in the disk frame: a circle through the noise for the angle (no seam), radius |
| +добавлено | // stretched so the structure runs in long arcs |
| +добавлено | float bands(float a, float rho, float seed, float as) { // rho: 3 * r / r_in (r_s at the usual ISCO) |
| +добавлено | vec2 cs = vec2(cos(a), sin(a)) * as; |
| +добавлено | float n0 = textureLod(uNoise3D, vec3(cs * 0.05 + 0.5, rho * 0.06 + seed * 0.3), 0.0).r; |
| +добавлено | float n1 = textureLod(uNoise3D, vec3(cs * 0.16, rho * 0.15 + seed), 0.0).r; |
| +добавлено | float n2 = textureLod(uNoise3D, vec3(cs * 0.4 + 0.31, rho * 0.45 + seed * 1.7 + 0.17), 0.0).r; |
| +добавлено | float n3 = textureLod(uNoise3D, vec3(cs * 1.1 + 0.63, rho * 1.4 + seed * 2.3 + 0.41), 0.0).r; |
| +добавлено | return (n1 * 0.55 + n2 * 0.3 + n3 * 0.15) * (0.55 + 0.9 * n0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // one pass of the ray (direction v, photon going -v) through the disk plane at xc (r_s units) |
| +добавлено | void diskHit(int i, vec3 xc, vec3 v, vec3 n, vec3 e1, vec3 e2, inout vec3 em, inout float tr) { |
| +добавлено | float rho = length(xc), rin = uE[i].x, rout = uE[i].y; |
| +добавлено | if (rho < rin * 0.8 || rho > rout) return; |
| +добавлено | vec3 eR = xc / rho, eT = cross(n, eR), vd = normalize(v); |
| +добавлено | float x = rho / rin; |
| +добавлено | // Kepler speed (static frame) -> Doppler, times gravitational redshift |
| +добавлено | float beta = min(uE[i].w * sqrt(0.5 / max(rho - 1.0, 0.6)), 0.95); |
| +добавлено | float dop = sqrt(1.0 - beta * beta) / (1.0 - beta * dot(eT, -vd)); |
| +добавлено | float g = dop * sqrt(max(1.0 - uF[i].x / rho, 0.04)); |
| +добавлено | // differential rotation; two half-period-shifted layers hide each layer's shear reset |
| +добавлено | float a0 = atan(dot(eR, e2), dot(eR, e1)); |
| +добавлено | float om = uG[i].w * pow(x, -1.5), P = 3.0; |
| +добавлено | float f0 = fract(uF[i].z / P), f1 = fract(uF[i].z / P + 0.5), w0 = 1.0 - abs(2.0 * f0 - 1.0); |
| +добавлено | // no bending = the blast ring after the collapse: torn into clumps rather than lanes |
| +добавлено | float as = uF[i].x < 1e-3 ? 5.0 : 1.0; |
| +добавлено | float dn = mix(bands(a0 - om * f1 * P, 3.0 * x, 0.53, as), bands(a0 - om * f0 * P, 3.0 * x, 0.0, as), w0); |
| +добавлено | dn = smoothstep(0.3, 0.75, dn); |
| +добавлено | if (as > 1.0) dn *= dn; |
| +добавлено | float edge = smoothstep(rin * 0.8, rin * 1.25, rho) * (1.0 - smoothstep(mix(rin, rout, 0.3), rout, rho)); |
| +добавлено | float dens = edge * (0.35 + 1.8 * dn * dn); |
| +добавлено | float cosI = abs(dot(vd, n)); |
| +добавлено | float a = 1.0 - exp(-2.2 * dens / max(cosI, 0.05)); |
| +добавлено | // thin disk: T ~ r^-3/4 (Shakura-Sunyaev, inner zero softened), hot lanes a little hotter |
| +добавлено | float T = uE[i].z * pow(x, -0.75) * pow(max(1.0 - 0.9 * inversesqrt(max(x, 1.0)), 0.02), 0.25) * 1.6 * (0.85 + 0.3 * dn) * g; |
| +добавлено | float I = uD[i].w * pow(x, -1.8) * g * g * g * (0.15 + 1.4 * dn); |
| +добавлено | em += tr * a * blackbody(T) * uG[i].rgb * I; |
| +добавлено | tr *= 1.0 - a; |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vec2 asp = vec2(uAspect, 1.0), p = vUv * asp; |
| +добавлено | float d = texture(tDepth, vUv).r; |
| +добавлено | float zp = uNearFar.x * uNearFar.y / (uNearFar.y - d * (uNearFar.y - uNearFar.x)); |
| +добавлено | vec3 rd = normalize(uCamRot * vec3((vUv * 2.0 - 1.0) * uInvP, -1.0)); |
| +добавлено | vec3 fwd = uCamRot * vec3(0.0, 0.0, -1.0); |
| +добавлено | float cosV = dot(rd, fwd); |
| +добавлено | |
| +добавлено | vec2 q = p; |
| +добавлено | float shadow = 1.0, ring = 0.0, tr = 1.0; |
| +добавлено | vec3 em = vec3(0.0); |
| +добавлено | for (int i = 0; i < ${MAX}; i++) { |
| +добавлено | if (i >= uCount) break; |
| +добавлено | vec2 t = p - uA[i].xy; |
| +добавлено | float r2 = max(dot(t, t), 1e-10), r = sqrt(r2); |
| +добавлено | float w = clamp((zp - uB[i].x) * uB[i].w, 0.0, 1.0); |
| +добавлено | w *= w * (3.0 - 2.0 * w); |
| +добавлено | q -= t * (uA[i].z * w / r2); |
| +добавлено | float rs = uC[i].w; |
| +добавлено | if (uH[i].x != 0.0) { |
| +добавлено | // frame dragging: the background swirls round a spinning hole, ~1 / r^2 |
| +добавлено | float ang = uH[i].x * w * uA[i].z / (r2 + 0.3 * uA[i].z), cs = cos(ang), sn = sin(ang); |
| +добавлено | vec2 tq = q - uA[i].xy; |
| +добавлено | q = uA[i].xy + mat2(cs, sn, -sn, cs) * tq; |
| +добавлено | } |
| +добавлено | if (rs <= 0.0) { |
| +добавлено | if (zp < uB[i].x - uB[i].y * 1.05) continue; // something in front hides this hole |
| +добавлено | shadow *= smoothstep(uA[i].w - uPx, uA[i].w + uPx, r); |
| +добавлено | // Einstein ring brightening where the magnification 1 / (1 - (thetaE / theta)^4) peaks |
| +добавлено | float te = sqrt(uA[i].z * w), x = (r - te) / (0.1 * te + 2.0 * uPx); |
| +добавлено | ring += uB[i].z * exp(-x * x); |
| +добавлено | continue; |
| +добавлено | } |
| +добавлено | // --- disk: trace the camera ray through the hole's region (units of r_s) |
| +добавлено | float rout = uE[i].y, RB = rout * 1.08 + 3.0; |
| +добавлено | if (zp < uB[i].x - RB * rs) continue; // all of it is behind something in front |
| +добавлено | vec3 o = (uCamPos - uC[i].xyz) / rs; |
| +добавлено | float bo = dot(o, rd), disc = bo * bo - dot(o, o) + RB * RB; |
| +добавлено | vec3 Lm = cross(o, rd); |
| +добавлено | float h2 = dot(Lm, Lm), b = sqrt(h2), k = uF[i].x; |
| +добавлено | float bc = critB(k), aa = uF[i].w; |
| +добавлено | vec3 n = uD[i].xyz; |
| +добавлено | vec3 e1 = normalize(cross(n, abs(n.y) < 0.9 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0))), e2 = cross(n, e1); |
| +добавлено | if (disc > 0.0 && -bo + sqrt(disc) > 0.0) { |
| +добавлено | float t0 = max(-bo - sqrt(disc), 0.0); |
| +добавлено | vec3 x = o + rd * t0, v = rd; |
| +добавлено | float zs = zp / cosV / rs; // scene hit distance along the ray (r_s) |
| +добавлено | bool front = zp < uB[i].x - 2.0 * rs; // something between the camera and the hole |
| +добавлено | if (k < 1e-3) { |
| +добавлено | // no bending (after the collapse): one straight crossing |
| +добавлено | float den = dot(rd, n); |
| +добавлено | float tc = abs(den) > 1e-5 ? -dot(o, n) / den : -1.0; |
| +добавлено | if (tc > 0.0 && tc < zs + 0.3 / rs) diskHit(i, o + rd * tc, rd, n, e1, e2, em, tr); |
| +добавлено | } else { |
| +добавлено | float kb = 1.5 * k * h2, y0 = dot(x, n), travelled = 0.0; |
| +добавлено | float rr = dot(x, x); |
| +добавлено | vec3 acc = -kb * x / (rr * rr * sqrt(rr)); |
| +добавлено | for (int s = 0; s < ${STEPS}; s++) { |
| +добавлено | float rx = sqrt(rr), dt = clamp(0.11 * rx, 0.03, 2.5); |
| +добавлено | // kick-drift-kick leapfrog |
| +добавлено | v += acc * (0.5 * dt); |
| +добавлено | vec3 xn = x + v * dt; |
| +добавлено | rr = dot(xn, xn); |
| +добавлено | acc = -kb * xn / (rr * rr * sqrt(rr)); |
| +добавлено | v += acc * (0.5 * dt); |
| +добавлено | float y1 = dot(xn, n); |
| +добавлено | if (y0 * y1 < 0.0) { |
| +добавлено | vec3 xc = mix(x, xn, y0 / (y0 - y1)); |
| +добавлено | // nearly straight rays meet the scene at its depth; bent ones are images of the far side, |
| +добавлено | // hidden only by what stands in front of the hole |
| +добавлено | bool straight = dot(normalize(v), rd) > 0.985; |
| +добавлено | if (straight ? t0 + travelled + length(xc - x) < zs + 0.3 / rs : !front) diskHit(i, xc, v, n, e1, e2, em, tr); |
| +добавлено | } |
| +добавлено | travelled += dt * length(v); |
| +добавлено | y0 = y1; x = xn; |
| +добавлено | if (rr < 1.0 || tr < 0.01 || (rr > RB * RB && dot(x, v) > 0.0)) break; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | // shadow edge at the critical impact parameter, and the photon ring hugging it |
| +добавлено | float sh = uF[i].y; |
| +добавлено | if (sh > 0.0 && zp > uB[i].x - 1.5 * bc * rs - 0.35) { |
| +добавлено | shadow *= 1.0 - sh * (1.0 - smoothstep(bc - aa, bc + aa, b)); |
| +добавлено | float rw = max(aa * 0.9, 0.006 * bc), xr = (b - bc - 1.6 * rw) / rw; |
| +добавлено | vec3 c = o - rd * bo, ce = c - n * dot(c, n); |
| +добавлено | float beta = 0.5 * min(uE[i].w, 1.9); |
| +добавлено | float dop = sqrt(1.0 - beta * beta) / (1.0 - beta * dot(cross(n, normalize(ce + 1e-5)), -rd)); |
| +добавлено | em += tr * sh * exp(-xr * xr) * blackbody(uE[i].z * 1.3 * dop) * uG[i].rgb * (uD[i].w * 0.7 * dop * dop * dop); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | for (int i = 0; i < ${MAX}; i++) { // keep lookups out of the hole's own image |
| +добавлено | if (i >= uCount) break; |
| +добавлено | if (uC[i].w > 0.0) continue; // a traced hole draws no opaque horizon into the source |
| +добавлено | if (zp < uB[i].x - uB[i].y * 1.05) continue; // in front of the hole: leave it be |
| +добавлено | vec2 t = q - uA[i].xy; |
| +добавлено | float r = length(t), rmin = uA[i].w * 1.08 + 2.0 * uPx; |
| +добавлено | if (r < rmin) q = uA[i].xy + (r > 1e-6 ? t / r : vec2(0.0, 1.0)) * rmin; |
| +добавлено | } |
| +добавлено | |
| +добавлено | vec2 uv = q / asp, e = min(uv, 1.0 - uv); |
| +добавлено | float fade = smoothstep(0.0, 0.06, min(e.x, e.y)); |
| +добавлено | uv = mix(vUv, uv, fade); |
| +добавлено | vec3 col = texture(tSrc, uv).rgb * ((1.0 + ring * fade) * shadow * tr) + em; |
| +добавлено | |
| +добавлено | // photographic-negative spherical shell: path length through it, brightest at its limb |
| +добавлено | if (uShell2.y > 0.0) { |
| +добавлено | vec3 c = uShell.xyz - uCamPos; |
| +добавлено | float tc = dot(c, rd), d2 = dot(c, c) - tc * tc, R = uShell.w, Ri = max(R - uShell2.x, 0.0); |
| +добавлено | float chord = sqrt(max(R * R - d2, 0.0)) - sqrt(max(Ri * Ri - d2, 0.0)); |
| +добавлено | float m = chord / max(sqrt(R * R - Ri * Ri), 1e-4); |
| +добавлено | m *= smoothstep(-0.2, 0.2, zp / cosV - (tc - sqrt(max(R * R - d2, 0.0)))); |
| +добавлено | float l = dot(col, vec3(0.2126, 0.7152, 0.0722)); |
| +добавлено | vec3 neg = vec3(0.55, 0.42, 1.0) * (2.2 / (1.0 + 3.0 * l)) + vec3(0.9, 0.95, 1.0) * 0.6 * exp(-24.0 * (1.0 - m) * (1.0 - m)); |
| +добавлено | col = mix(col, neg, clamp(m * uShell2.y, 0.0, 1.0)); |
| +добавлено | } |
| +добавлено | fragColor = vec4(col, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const _v = new THREE.Vector3(); |
| +добавлено | |
| +добавлено | export class Lens { |
| +добавлено | active = false; // false: render() returns the source untouched, no draw |
| +добавлено | warming = false; // main's warm-up: draw even with no lens, so the program exists before the first void |
| +добавлено | |
| +добавлено | constructor(renderer) { |
| +добавлено | this.renderer = renderer; |
| +добавлено | this.lenses = Array.from({ length: MAX }, () => ({ |
| +добавлено | pos: new THREE.Vector3(), einstein: 1, horizon: 0.4, strength: 0, |
| +добавлено | // accretion disk, traced (see the header). Cleared by set(): write it after set() every frame. |
| +добавлено | disk: { |
| +добавлено | on: false, axis: new THREE.Vector3(0, 1, 0), rs: 0.12, inner: 3, outer: 14, temperature: 4800, beaming: 0.6, |
| +добавлено | intensity: 6, tint: new THREE.Color(1, 1, 1), phase: 0, spin: 2.2, bend: 1, shadow: 1, twist: 0, |
| +добавлено | }, |
| +добавлено | })); |
| +добавлено | // one photographic-negative shell (amount 0 = off); render() still needs active |
| +добавлено | this.shell = { pos: new THREE.Vector3(), radius: 1, thickness: 0.3, amount: 0 }; |
| +добавлено | this.target = new THREE.WebGLRenderTarget(1, 1, { |
| +добавлено | type: THREE.HalfFloatType, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | depthBuffer: false, stencilBuffer: false, generateMipmaps: false, |
| +добавлено | }); |
| +добавлено | const v4 = () => Array.from({ length: MAX }, () => new THREE.Vector4()); |
| +добавлено | this.quad = new FullscreenQuad(rawPass(FRAG, { |
| +добавлено | tSrc: { value: null }, tDepth: { value: null }, uNoise3D: U.uNoise3D, uBlackbody: U.uBlackbody, |
| +добавлено | uA: { value: v4() }, uB: { value: v4() }, uC: { value: v4() }, uD: { value: v4() }, uE: { value: v4() }, uF: { value: v4() }, uG: { value: v4() }, uH: { value: v4() }, |
| +добавлено | uShell: { value: new THREE.Vector4() }, uShell2: { value: new THREE.Vector4() }, |
| +добавлено | uCount: { value: 0 }, uNearFar: { value: new THREE.Vector2() }, uAspect: { value: 1 }, uPx: { value: 1 }, |
| +добавлено | uCamPos: { value: new THREE.Vector3() }, uCamRot: { value: new THREE.Matrix3() }, uInvP: { value: new THREE.Vector2() }, |
| +добавлено | })); |
| +добавлено | const s = renderer.getDrawingBufferSize(new THREE.Vector2()); |
| +добавлено | this.setSize(s.x, s.y); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // i: 0 or 1. Radii in metres: einsteinRadius is the ring for a source at infinity, horizonRadius the |
| +добавлено | // black shadow. strength scales the deflection (the lens "mass") and the ring; 0 switches the lens off. |
| +добавлено | set(i, worldPos, einsteinRadius, horizonRadius, strength = 1) { |
| +добавлено | const l = this.lenses[i]; |
| +добавлено | l.pos.copy(worldPos); |
| +добавлено | l.einstein = einsteinRadius; |
| +добавлено | l.horizon = horizonRadius; |
| +добавлено | l.strength = strength; |
| +добавлено | l.disk.on = false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | setSize(width, height) { |
| +добавлено | const w = Math.max(1, Math.floor(width)), h = Math.max(1, Math.floor(height)); |
| +добавлено | this.target.setSize(w, h); |
| +добавлено | const u = this.quad.material.uniforms; |
| +добавлено | u.uAspect.value = w / h; |
| +добавлено | u.uPx.value = 1 / h; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // srcTex: composited HDR; depthTex: resolved scene depth; camera: the one that rendered them |
| +добавлено | render(srcTex, depthTex, camera) { |
| +добавлено | if (!this.active) return srcTex; |
| +добавлено | const u = this.quad.material.uniforms, aspect = u.uAspect.value; |
| +добавлено | const k = camera.projectionMatrix.elements[5] * 0.5; // metres at view depth 1 -> screen-height units |
| +добавлено | let n = 0; |
| +добавлено | for (const l of this.lenses) { |
| +добавлено | if (!(l.strength > 0)) continue; |
| +добавлено | _v.copy(l.pos).applyMatrix4(camera.matrixWorldInverse); |
| +добавлено | const z = -_v.z; |
| +добавлено | const D = l.disk, dk = D.on && D.rs > 0; |
| +добавлено | if (z <= camera.near && !dk) continue; |
| +добавлено | _v.applyMatrix4(camera.projectionMatrix); |
| +добавлено | const zz = Math.max(z, camera.near), te = l.einstein * k / zz; |
| +добавлено | u.uA.value[n].set((_v.x * 0.5 + 0.5) * aspect, _v.y * 0.5 + 0.5, z > camera.near ? te * te * l.strength : 0, l.horizon * k / zz); |
| +добавлено | u.uB.value[n].set(z, l.horizon, dk ? 0 : 1.5 * Math.min(l.strength, 2), 1 / Math.max(2 * l.einstein, 0.1)); |
| +добавлено | u.uC.value[n].set(l.pos.x, l.pos.y, l.pos.z, dk ? D.rs : 0); |
| +добавлено | u.uH.value[n].set(dk ? D.twist : 0, 0, 0, 0); |
| +добавлено | if (dk) { |
| +добавлено | u.uD.value[n].set(D.axis.x, D.axis.y, D.axis.z, D.intensity); |
| +добавлено | u.uE.value[n].set(D.inner, D.outer, D.temperature, D.beaming); |
| +добавлено | u.uF.value[n].set(D.bend, D.shadow, D.phase, u.uPx.value * zz / (k * D.rs)); |
| +добавлено | u.uG.value[n].set(D.tint.r, D.tint.g, D.tint.b, D.spin); |
| +добавлено | } |
| +добавлено | n++; |
| +добавлено | } |
| +добавлено | const sh = this.shell; |
| +добавлено | u.uShell.value.set(sh.pos.x, sh.pos.y, sh.pos.z, sh.radius); |
| +добавлено | u.uShell2.value.set(sh.thickness, Math.max(sh.amount, 0), 0, 0); |
| +добавлено | if (!n && !this.warming && !(sh.amount > 0)) return srcTex; |
| +добавлено | u.uCount.value = n; |
| +добавлено | u.tSrc.value = srcTex; |
| +добавлено | u.tDepth.value = depthTex; |
| +добавлено | u.uNearFar.value.set(camera.near, camera.far); |
| +добавлено | const e = camera.matrixWorld.elements, pe = camera.projectionMatrix.elements; |
| +добавлено | u.uCamPos.value.set(e[12], e[13], e[14]); |
| +добавлено | u.uCamRot.value.setFromMatrix4(camera.matrixWorld); |
| +добавлено | u.uInvP.value.set(1 / pe[0], 1 / pe[5]); |
| +добавлено | |
| +добавлено | const r = this.renderer, prev = r.getRenderTarget(), clear = r.autoClear; |
| +добавлено | r.autoClear = false; |
| +добавлено | this.quad.render(r, this.target); |
| +добавлено | r.setRenderTarget(prev); |
| +добавлено | r.autoClear = clear; |
| +добавлено | return this.target.texture; |
| +добавлено | } |
| +добавлено | |
| +добавлено | dispose() { |
| +добавлено | this.target.dispose(); |
| +добавлено | this.quad.material.dispose(); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { U, COMMON_GLSL, NOISE_GLSL, WORLD_GLSL, LIGHTS_GLSL } from './common.js'; |
| +добавлено | import { REFRACT_GLSL } from './Refraction.js'; |
| +добавлено | import { Q } from '../engine/quality.js'; |
| +добавлено | |
| +добавлено | // Raymarched liquid blobs (water whip, acid orb) for the refract pass. Each handle is a chain of |
| +добавлено | // up to 16 smooth-unioned spheres, one instanced draw of 1-4 oriented boxes (back faces, so the |
| +добавлено | // camera may be inside) refitted along the chain every frame. Per pixel: |
| +добавлено | // 1. only the lowest-numbered box the ray crosses goes on (the boxes overlap); then the ray vs |
| +добавлено | // each sphere's shells (groups of 4 first): the short list of spheres that can shape this |
| +добавлено | // ray's surface, the [t0, t1] range to march and the liquid chord. Box corners discard here. |
| +добавлено | // 2. sphere trace (<= 32 steps, Q.volumeSteps / 24) of the listed spheres' smooth union, plus |
| +добавлено | // wobble and acid blisters cached near the surface, with secant steps. Misses that pass within |
| +добавлено | // a pixel of the surface keep partial coverage: alpha-to-coverage makes the MSAA silhouette. |
| +добавлено | // 3. analytic gradient normal, thickness = chord - hit, then Fresnel sky + sun + spell-light |
| +добавлено | // specular over the refracted, Beer-Lambert-tinted scene (+ the acid's inner glow). |
| +добавлено | // gl_FragDepth is the hit, so later passes (smoke, sparks) are occluded by the liquid. |
| +добавлено | // Presets are uniforms only: one program for every handle, no recompiles. |
| +добавлено | |
| +добавлено | // UW's WATER_PRESETS ('tropical', 'toxic green'): absorption and turbidity divided by UW's |
| +добавлено | // 'clarity' knob, since a whip is ~0.4 m thick where UW's sea is metres deep (at clarity 1 water |
| +добавлено | // reads as clear glass). Acid is murkier still, so its own glow rather than the sky shows through. |
| +добавлено | const uw = (a, clarity) => a.map((x) => x / clarity); |
| +добавлено | export const METABALL_PRESETS = { |
| +добавлено | water: { |
| +добавлено | absorption: uw([0.36, 0.045, 0.06], 0.12), turbidity: 0.02 / 0.12, scatterColor: [0.0, 0.085, 0.085], emission: [0, 0, 0], |
| +добавлено | k: 0.25, wobble: 0.02, bubbles: 0, corrosion: 0, ior: 1.33, roughness: 0.03, refraction: 1.6, rim: 0.5, |
| +добавлено | }, |
| +добавлено | acid: { |
| +добавлено | absorption: uw([0.45, 0.1, 1.1], 0.04), turbidity: 0.08 / 0.04, scatterColor: [0.05, 0.1, 0.004], emission: [0.14, 1.0, 0.05], |
| +добавлено | k: 0.3, wobble: 0.025, bubbles: 1, corrosion: 1, ior: 1.36, roughness: 0.07, refraction: 1.2, rim: 0.4, |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const BUBBLE_CELL = 0.12; // m, one blister per cell |
| +добавлено | const BUBBLE_H = BUBBLE_CELL * 0.33 * 0.35; // tallest blister (m) |
| +добавлено | |
| +добавлено | const MAX_BOXES = 4; |
| +добавлено | const SHELL = 0.3; // x k: where the march starts past each sphere (see the shader) |
| +добавлено | |
| +добавлено | const VERT = /* glsl */` |
| +добавлено | out vec3 vWorld; |
| +добавлено | flat out int vBox; |
| +добавлено | void main() { |
| +добавлено | vBox = gl_InstanceID; |
| +добавлено | vec4 w = modelMatrix * instanceMatrix * vec4(position, 1.0); |
| +добавлено | vWorld = w.xyz; |
| +добавлено | gl_Position = projectionMatrix * viewMatrix * w; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const frag = (NS) => /* glsl */` |
| +добавлено | #define NS ${NS} |
| +добавлено | #define BUBBLE_CELL ${BUBBLE_CELL.toFixed(4)} |
| +добавлено | #define BUBBLE_H ${BUBBLE_H.toFixed(5)} |
| +добавлено | #define SHELL ${SHELL.toFixed(2)} |
| +добавлено | #define NG ${NS + 3 >> 2} |
| +добавлено | #define MAX_BOXES ${MAX_BOXES} |
| +добавлено | // spheres: world centre xyz, radius w (m). The same data twice: a uniform array for loops where |
| +добавлено | // every pixel reads sphere i together (constant broadcast), and a texture row (texel i = sphere i) |
| +добавлено | // for the march, where each pixel reads its own short list (divergent constant reads serialize) |
| +добавлено | uniform vec4 uSpheres[NS]; |
| +добавлено | uniform highp sampler2D uSphereTex; |
| +добавлено | uniform int uRow; |
| +добавлено | uniform int uCount; // <= NS (clamped on the CPU) |
| +добавлено | uniform vec4 uGroups[NG]; // bounding sphere of spheres 4g..4g+3 (m) |
| +добавлено | uniform mat4 uBoxInv[MAX_BOXES]; // world -> proxy box g ([-1, 1]^3) |
| +добавлено | flat in int vBox; |
| +добавлено | uniform vec4 uShape; // smooth-union k (m), wobble (m), bubbles 0..1, corrosion 0..1 |
| +добавлено | uniform vec4 uOptics; // ior, roughness, refraction lens scale, rim |
| +добавлено | uniform vec3 uAbsorption; // 1/m |
| +добавлено | uniform float uTurbidity; // 1/m, grey extinction (scattered out; comes back as in-scatter) |
| +добавлено | uniform vec3 uScatter; // in-scatter albedo of the body |
| +добавлено | uniform vec3 uEmission; // HDR radiance, already x intensity x Q.emission |
| +добавлено | uniform int uSteps; |
| +добавлено | uniform float uMetaDebug; // 1 march-step heat map, 2 proxy box, 3 flat coverage, 4 thickness (r = m), 5 stats (steps, list, coverage) |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform vec3 uAmbient; |
| +добавлено | ${COMMON_GLSL} |
| +добавлено | ${NOISE_GLSL} |
| +добавлено | ${WORLD_GLSL} |
| +добавлено | ${LIGHTS_GLSL} |
| +добавлено | ${REFRACT_GLSL} |
| +добавлено | in vec3 vWorld; |
| +добавлено | out vec4 fragColor; |
| +добавлено | |
| +добавлено | // the spheres this ray passes close enough to matter (2-4 on a whip, up to 6 on an orb), as 4-bit |
| +добавлено | // indices packed 8 per uint, so the SDF loops over those few instead of all NS |
| +добавлено | uvec2 gList; |
| +добавлено | int gN; |
| +добавлено | vec3 gAnchor; // sphere 0: surface detail travels with the blob |
| +добавлено | vec4 sph(int i) { return texelFetch(uSphereTex, ivec2(i, uRow), 0); } |
| +добавлено | vec4 sphere(int j) { return sph(int(((j < 8 ? gList.x : gList.y) >> uint((j & 7) * 4)) & 15u)); } |
| +добавлено | |
| +добавлено | // polynomial smooth min (iq) with sphere s; compact support: plain min once |a - b| > k |
| +добавлено | void blend(inout float d, vec3 p, vec4 s, float k) { |
| +добавлено | float a = length(p - s.xyz) - s.w, h = max(k - abs(a - d), 0.0) / k; |
| +добавлено | d = min(a, d) - h * h * k * 0.25; |
| +добавлено | } |
| +добавлено | float base(vec3 p) { |
| +добавлено | float d = 1e4, k = max(uShape.x, 1e-4); |
| +добавлено | for (int j = 0; j < gN; j++) blend(d, p, sphere(j), k); |
| +добавлено | return d; |
| +добавлено | } |
| +добавлено | // the same with its exact gradient: d smin / d a = 1 - h/2 for the smaller argument, h/2 for the |
| +добавлено | // larger, so the normal costs one pass instead of four SDF taps |
| +добавлено | void blendGrad(inout float d, inout vec3 g, vec3 p, vec4 s, float k) { |
| +добавлено | vec3 dp = p - s.xyz; |
| +добавлено | float l = length(dp), a = l - s.w, h = max(k - abs(a - d), 0.0) / k; |
| +добавлено | vec3 ga = dp / max(l, 1e-6); |
| +добавлено | g = a < d ? mix(ga, g, 0.5 * h) : mix(g, ga, 0.5 * h); |
| +добавлено | d = min(a, d) - h * h * k * 0.25; |
| +добавлено | } |
| +добавлено | vec3 baseGrad(vec3 p) { |
| +добавлено | float d = 1e4, k = max(uShape.x, 1e-4); |
| +добавлено | vec3 g = vec3(0.0, 1.0, 0.0); |
| +добавлено | for (int j = 0; j < gN; j++) blendGrad(d, g, p, sphere(j), k); |
| +добавлено | return g; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // three crossed travelling waves: a smooth liquid wobble with a known slope (|grad| <= 7.2) |
| +добавлено | const vec3 W1 = vec3(5.1, 3.3, -2.7), W2 = vec3(-2.2, 6.3, 3.9), W3 = vec3(3.7, -1.9, 5.8); |
| +добавлено | float wobble(vec3 q) { |
| +добавлено | float t = uTime; |
| +добавлено | return (sin(dot(q, W1) + t * 3.1) + sin(dot(q, W2) - t * 2.3) + sin(dot(q, W3) + t * 4.2)) * (1.0 / 3.0); |
| +добавлено | } |
| +добавлено | vec3 wobbleGrad(vec3 q) { |
| +добавлено | float t = uTime; |
| +добавлено | return (W1 * cos(dot(q, W1) + t * 3.1) + W2 * cos(dot(q, W2) - t * 2.3) + W3 * cos(dot(q, W3) + t * 4.2)) * (1.0 / 3.0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // acid blisters: one bubble per cell, jittered so it never crosses the cell wall, swelling over |
| +добавлено | // its life and gone at the wrap (the pop). Returns the height (<= BUBBLE_H, slope <= 0.55), |
| +добавлено | // g its gradient, glow the flare just before the pop. |
| +добавлено | float blister(vec3 q, out vec3 g, out float glow) { |
| +добавлено | vec3 c = floor(q / BUBBLE_CELL), h = hash33(c); |
| +добавлено | float life = fract(h.x * 7.0 + uTime * (0.25 + 0.5 * h.y)); |
| +добавлено | vec3 o = q - (c + 0.5 + (h - 0.5) * 0.3) * BUBBLE_CELL; |
| +добавлено | float rad = max(BUBBLE_CELL * 0.33 * sqrt(life), 1e-4); |
| +добавлено | float s = max(1.0 - dot(o, o) / (rad * rad), 0.0); // 1 - x^2, x = distance / radius |
| +добавлено | g = -1.4 * s * o / rad; |
| +добавлено | glow = s * s * smoothstep(0.7, 1.0, life); |
| +добавлено | return 0.35 * rad * s * s; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // outward displacement (m), |detail| <= pad |
| +добавлено | float detail(vec3 p) { |
| +добавлено | vec3 q = p - gAnchor, g; |
| +добавлено | float glow, d = uShape.y * wobble(q); |
| +добавлено | if (uShape.z > 0.0) d += uShape.z * blister(q, g, glow); |
| +добавлено | return d; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // fine travelling ripples, shading only: a few mm, invisible on the silhouette and not worth a |
| +добавлено | // sin pair in every march step, but they make reflections and refraction shimmer like liquid |
| +добавлено | const vec3 R1 = vec3(17.0, 9.0, -11.0), R2 = vec3(-8.0, 19.0, 12.0); |
| +добавлено | vec3 rippleGrad(vec3 q) { |
| +добавлено | float a = dot(q, R1) + uTime * 7.0, b = dot(q, R2) - uTime * 5.3; |
| +добавлено | return R1 * cos(a) * sin(b) + R2 * sin(a) * cos(b); |
| +добавлено | } |
| +добавлено | |
| +добавлено | #define HIT_PX 0.5 |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | gLightNoShadow = true; // capsule shadows on a liquid highlight aren't worth their loop |
| +добавлено | int ZERO = min(int(uFrame), 0); |
| +добавлено | vec3 ro = cameraPosition, rd = normalize(vWorld - ro); |
| +добавлено | gAnchor = uSpheres[0].xyz; |
| +добавлено | float k = uShape.x, pad = uShape.y + uShape.z * BUBBLE_H; |
| +добавлено | float pxs = 2.0 / (projectionMatrix[1][1] * uResolution.y); // pixel footprint per metre of distance |
| +добавлено | |
| +добавлено | // opaque depth bounds the march: writing gl_FragDepth turns early-z off, so this is the only |
| +добавлено | // cull for blobs behind walls |
| +добавлено | vec3 fwd = -vec3(viewMatrix[0][2], viewMatrix[1][2], viewMatrix[2][2]); |
| +добавлено | float cosV = max(dot(rd, fwd), 1e-4); |
| +добавлено | float tScene = linearDepth(texelFetch(uSceneDepth, ivec2(gl_FragCoord.xy), 0).r) / cosV; |
| +добавлено | |
| +добавлено | // the proxy boxes overlap (neighbours share a sphere, and a whip seen end-on stacks them): every |
| +добавлено | // box would march the whole ray to the same result, so the lowest-numbered box the ray crosses |
| +добавлено | // takes the pixel. Tested 0.1% shrunk, so a pixel on a box edge is kept twice, never dropped. |
| +добавлено | for (int j = 0; j < vBox; j++) { |
| +добавлено | vec3 lo = (uBoxInv[j] * vec4(ro, 1.0)).xyz, ld = (uBoxInv[j] * vec4(rd, 0.0)).xyz; |
| +добавлено | vec3 il = 1.0 / (ld + 1e-12), ta = (-0.999 - lo) * il, tb = (0.999 - lo) * il, tn = min(ta, tb), tf = max(ta, tb); |
| +добавлено | float tN = max(max(tn.x, tn.y), tn.z), tF = min(min(tf.x, tf.y), tf.z); |
| +добавлено | if (tF > tN && tF * cosV > uNearFar.x) discard; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // one ray test per sphere against three shells: |
| +добавлено | // r + k + pad its blend reach: in the list. smin is plain min beyond k, so a sphere |
| +добавлено | // whose reach the ray misses can't shape the surface this ray sees |
| +добавлено | // r + 0.3k + pad + 2px smin bulges k/4 past two equal spheres, so the surface and its |
| +добавлено | // antialiased fringe lie inside these: the march range (rays missing all |
| +добавлено | // of them discard here). ponytail: three near-equal spheres bulge 0.39 k |
| +добавлено | // and get clipped by a few mm in that crease; SHELL 0.5 if it ever shows. |
| +добавлено | // r + k/4 the liquid chord: thickness runs to the exit of the farthest one crossed |
| +добавлено | float t0 = 1e9, t1 = 0.0, tExit = 0.0; |
| +добавлено | gList = uvec2(0u); |
| +добавлено | gN = 0; |
| +добавлено | for (int g = 0; g < NG; g++) { |
| +добавлено | if (g * 4 >= uCount) break; |
| +добавлено | // a group of 4 the ray misses skips 4 tests (a whip ray is near 1-2 of its 4 groups) |
| +добавлено | vec4 G = uGroups[g]; |
| +добавлено | vec3 og = G.xyz - ro; |
| +добавлено | float bg = dot(og, rd), Rg = G.w + k + pad + 2.0 * pxs * max(bg, 0.0); |
| +добавлено | if (dot(og, og) - bg * bg >= Rg * Rg) continue; |
| +добавлено | for (int i = g * 4; i < g * 4 + 4; i++) { |
| +добавлено | if (i >= uCount) break; |
| +добавлено | vec4 s = uSpheres[i]; |
| +добавлено | vec3 oc = s.xyz - ro; |
| +добавлено | float b = dot(oc, rd), c = dot(oc, oc) - b * b; // squared distance ray -> centre |
| +добавлено | float R = s.w + k + pad; |
| +добавлено | if (c >= R * R) continue; |
| +добавлено | if (gN < 8) gList.x |= uint(i) << uint(gN * 4); else gList.y |= uint(i) << uint((gN - 8) * 4); |
| +добавлено | gN++; |
| +добавлено | R = s.w + SHELL * k + pad + 2.0 * pxs * max(b, 0.0); |
| +добавлено | float h = R * R - c; |
| +добавлено | if (h <= 0.0) continue; |
| +добавлено | h = sqrt(h); |
| +добавлено | t0 = min(t0, b - h); |
| +добавлено | t1 = max(t1, b + h); |
| +добавлено | R = s.w + 0.25 * k; |
| +добавлено | h = R * R - c; |
| +добавлено | if (h > 0.0) tExit = max(tExit, b + sqrt(h)); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | t0 = max(t0, 0.0); |
| +добавлено | t1 = min(t1, tScene); |
| +добавлено | if (uMetaDebug > 1.5 && uMetaDebug < 2.5) { gl_FragDepth = gl_FragCoord.z; fragColor = vec4(0.03, 0.0, 0.05, 1.0); return; } |
| +добавлено | if (t0 >= t1) discard; |
| +добавлено | |
| +добавлено | // sphere trace. Far from the blob (base > 2 pad) the undisplaced SDF minus pad is an exact bound |
| +добавлено | // and skips the detail. Near it the displacement D is cached: evaluated on arrival and again |
| +добавлено | // wherever the cached value says we're on the surface (it varies over ~1 m, so it barely moves |
| +добавлено | // across the last few cm; ~2 evaluations per ray instead of one per step). Steps are relaxed by |
| +добавлено | // the displacement's Lipschitz bound. |
| +добавлено | float relax = 1.0 / (1.0 + 7.2 * uShape.y + 0.55 * uShape.z); |
| +добавлено | float t = t0, best = 1e9, tBest = t0, D = 0.0, tP = t0, dP = 1e9; |
| +добавлено | int steps = 0; |
| +добавлено | bool hit = false, haveD = false; |
| +добавлено | for (int i = ZERO; i < uSteps; i++) { |
| +добавлено | steps = i + 1; |
| +добавлено | vec3 p = ro + rd * t; |
| +добавлено | float b = base(p), px = t * pxs; |
| +добавлено | bool far = b > 2.0 * pad; |
| +добавлено | if (!far && !haveD) { D = detail(p); haveD = true; } |
| +добавлено | float d = far ? b - pad : b - D; |
| +добавлено | // the bar rises with the steps taken: grazing rays creep along the surface, so they stop |
| +добавлено | // within a pixel or two of it instead of spending the whole budget |
| +добавлено | float bar = (HIT_PX + float(i) * 0.03125) * px; |
| +добавлено | if (!far && d < bar) { D = detail(p); d = b - D; } // confirm with the displacement here |
| +добавлено | if (!far && d < 0.0 && dP < 1e8) { t -= (t - tP) * -d / (dP - d); hit = true; break; } // crossed: interpolate |
| +добавлено | if (d < best * px) { best = d / px; tBest = t; } |
| +добавлено | if (d < bar) { hit = true; break; } |
| +добавлено | // near the surface d falls almost linearly along the ray, so the secant through the last two |
| +добавлено | // samples lands close to the root: up to 3 safe radii per step (~30% fewer steps); an overshoot |
| +добавлено | // through the surface is caught by the line above |
| +добавлено | float r = far ? d : max(d * relax, b - pad); |
| +добавлено | if (!far && dP < 1e8 && dP > d) r = clamp(d * (t - tP) / (dP - d), r, 3.0 * r); |
| +добавлено | tP = t; |
| +добавлено | dP = far ? 1e9 : d; |
| +добавлено | t += r; |
| +добавлено | if (t > t1) break; |
| +добавлено | } |
| +добавлено | // a miss that grazed within a pixel keeps partial coverage (alpha-to-coverage -> MSAA edge) |
| +добавлено | float cov = hit ? 1.0 : 1.0 - smoothstep(HIT_PX, HIT_PX + 1.0, best); |
| +добавлено | if (uMetaDebug > 4.5) { gl_FragDepth = gl_FragCoord.z; fragColor = vec4(float(steps), float(gN), cov, 1.0); return; } |
| +добавлено | if (uMetaDebug > 0.5 && uMetaDebug < 1.5) { |
| +добавлено | float s = float(steps) / float(uSteps); |
| +добавлено | gl_FragDepth = gl_FragCoord.z; |
| +добавлено | fragColor = vec4(vec3(s, 1.0 - abs(s * 2.0 - 1.0), 1.0 - s) * 2.0 * max(cov, 0.15), 1.0); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | if (cov < 0.01) discard; |
| +добавлено | |
| +добавлено | // analytic normal: smooth union + wobble + blister + ripple gradients (ripples fade once a pixel |
| +добавлено | // spans a good part of their ~0.3 m wavelength, so they never shimmer as aliasing) |
| +добавлено | float tHit = hit ? t : tBest, px = tHit * pxs, glow = 0.0; |
| +добавлено | vec3 p = ro + rd * tHit, q = p - gAnchor, gb = baseGrad(p), gbl = vec3(0.0); |
| +добавлено | if (uShape.z > 0.0) blister(q, gbl, glow); |
| +добавлено | float rip = uShape.y * 0.25 * (1.0 - smoothstep(0.004, 0.03, px)); |
| +добавлено | vec3 n = normalize(gb - uShape.y * wobbleGrad(q) - uShape.z * gbl - rip * rippleGrad(q)); |
| +добавлено | float thick = clamp(tExit - tHit, 0.0, max(tScene - tHit, 0.0)); |
| +добавлено | |
| +добавлено | vec4 clip = projectionMatrix * viewMatrix * vec4(p, 1.0); |
| +добавлено | gl_FragDepth = clamp(clip.z / clip.w * 0.5 + 0.5, 0.0, 1.0); |
| +добавлено | if (uMetaDebug > 3.5) { fragColor = vec4(vec3(thick, thick * 0.5, thick * 0.25), cov); return; } |
| +добавлено | if (uMetaDebug > 2.5) { fragColor = vec4(1.0, 0.0, 1.0, cov); return; } |
| +добавлено | |
| +добавлено | // --- shading ------------------------------------------------------------------------ |
| +добавлено | vec3 v = -rd; |
| +добавлено | float NoV = max(dot(n, v), 0.0); |
| +добавлено | float rough = uOptics.y; |
| +добавлено | float F = fresnelRough(NoV, 0.02, rough); |
| +добавлено | vec3 refl = envReflect(reflect(rd, n), rough); |
| +добавлено | // sun: GGX, alpha floored so the disc acts as a small area light (UW) |
| +добавлено | float aS = max(rough * rough, 0.015); |
| +добавлено | vec3 H = normalize(uSunDir + v); |
| +добавлено | float NoL = max(dot(n, uSunDir), 0.0); |
| +добавлено | vec3 spec = uSunColor * (PI * spellD_GGX(max(dot(n, H), 0.0), aS) * spellV_Smith(max(NoV, 1e-4), NoL, aS) * NoL * fresnel(dot(v, H), 0.02)); |
| +добавлено | vec3 dSpell, sSpell; |
| +добавлено | spellLightPBR(p, n, v, max(rough, 0.06), vec3(0.02), uScatter, dSpell, sSpell); |
| +добавлено | spec += sSpell; |
| +добавлено | |
| +добавлено | // body: the scene through the liquid, absorbed over the thickness, plus in-scatter of the sky, |
| +добавлено | // sun and spell lights; forward scatter glows looking into the sun (UW's crest SSS) |
| +добавлено | float behind; |
| +добавлено | vec3 refr = sceneRefract(p, n, v, uOptics.x, thick * uOptics.z, behind); |
| +добавлено | vec3 T = beerLambert(uAbsorption + uTurbidity, thick); |
| +добавлено | float fwdS = pow(clamp(dot(rd, uSunDir), 0.0, 1.0), 12.0); |
| +добавлено | vec3 inscatter = uScatter * (uAmbient + uSunColor * (max(uSunDir.y, 0.0) + 1.5 * fwdS)) + dSpell; |
| +добавлено | vec3 body = refr * T + inscatter * (1.0 - T); |
| +добавлено | |
| +добавлено | // acid: a glowing core swirling inside the body (noise at two depths along the ray, so it has |
| +добавлено | // parallax), concentrated where thick and dimming to a dark corroded skin at the silhouette; |
| +добавлено | // blisters flare as they pop. Contrast keeps it saturated under AgX instead of a flat pastel. |
| +добавлено | float edge = smoothstep(0.05, 0.6, NoV); |
| +добавлено | vec3 emit = vec3(0.0); |
| +добавлено | if (dot(uEmission, uEmission) > 0.0) { |
| +добавлено | vec3 qs = q + vec3(0.0, uTime * 0.06, 0.0); |
| +добавлено | float swirl = noise3((qs + rd * thick * 0.3) * 0.7) * 0.6 + noise3((qs + rd * thick * 0.7) * 1.3 + 0.5) * 0.4; |
| +добавлено | float core = 1.0 - exp(-thick * 2.0); |
| +добавлено | emit = uEmission * (core * core * (0.1 + 2.5 * swirl * swirl) * mix(1.0, edge * edge, uShape.w) + glow * uShape.z * 4.0); |
| +добавлено | } |
| +добавлено | body *= mix(1.0, 0.25 + 0.75 * edge, uShape.w); |
| +добавлено | |
| +добавлено | // thin bright rim at the silhouette: sky + sun for water, the own glow for acid |
| +добавлено | float rim = pow(1.0 - NoV, 5.0) * uOptics.w; |
| +добавлено | vec3 col = mix(body, refl, F) + spec + emit + rim * mix(uAmbient + uSunColor * 0.3, uEmission * 0.8, uShape.w); |
| +добавлено | fragColor = vec4(col, cov); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const _u = new THREE.Vector3(), _v = new THREE.Vector3(), _w = new THREE.Vector3(), _m = new THREE.Matrix4(); |
| +добавлено | const UP = new THREE.Vector3(0, 1, 0), RIGHT = new THREE.Vector3(1, 0, 0); |
| +добавлено | |
| +добавлено | // Oriented box around spheres first..last (d = [x, y, z, r] per sphere), inflated by pad, written |
| +добавлено | // into m as the BoxGeometry(2, 2, 2) -> world matrix. x runs along the chain (first -> last), y |
| +добавлено | // towards the middle sphere (the bend), z normal to both: a curve fills it far better than an AABB. |
| +добавлено | export function fitBox(d, first, last, pad, m) { |
| +добавлено | const f = first * 4, l = last * 4, mid = ((first + last) >> 1) * 4; |
| +добавлено | _u.set(d[l] - d[f], d[l + 1] - d[f + 1], d[l + 2] - d[f + 2]); |
| +добавлено | if (_u.lengthSq() < 1e-10) _u.set(1, 0, 0); else _u.normalize(); |
| +добавлено | _v.set(d[mid] - d[f], d[mid + 1] - d[f + 1], d[mid + 2] - d[f + 2]); |
| +добавлено | _v.addScaledVector(_u, -_v.dot(_u)); |
| +добавлено | if (_v.lengthSq() < 1e-10) _v.crossVectors(_u, Math.abs(_u.y) < 0.9 ? UP : RIGHT); |
| +добавлено | _v.normalize(); |
| +добавлено | _w.crossVectors(_u, _v); |
| +добавлено | let a0 = Infinity, a1 = -Infinity, b0 = Infinity, b1 = -Infinity, c0 = Infinity, c1 = -Infinity; |
| +добавлено | for (let i = f; i <= l; i += 4) { |
| +добавлено | const x = d[i], y = d[i + 1], z = d[i + 2], r = d[i + 3] + pad; |
| +добавлено | const pu = x * _u.x + y * _u.y + z * _u.z, pv = x * _v.x + y * _v.y + z * _v.z, pw = x * _w.x + y * _w.y + z * _w.z; |
| +добавлено | a0 = Math.min(a0, pu - r); a1 = Math.max(a1, pu + r); |
| +добавлено | b0 = Math.min(b0, pv - r); b1 = Math.max(b1, pv + r); |
| +добавлено | c0 = Math.min(c0, pw - r); c1 = Math.max(c1, pw + r); |
| +добавлено | } |
| +добавлено | const cu = (a0 + a1) / 2, cv = (b0 + b1) / 2, cw = (c0 + c1) / 2; |
| +добавлено | const hu = (a1 - a0) / 2, hv = (b1 - b0) / 2, hw = (c1 - c0) / 2; |
| +добавлено | m.set( |
| +добавлено | _u.x * hu, _v.x * hv, _w.x * hw, _u.x * cu + _v.x * cv + _w.x * cw, |
| +добавлено | _u.y * hu, _v.y * hv, _w.y * hw, _u.y * cu + _v.y * cv + _w.y * cw, |
| +добавлено | _u.z * hu, _v.z * hv, _w.z * hw, _u.z * cu + _v.z * cv + _w.z * cw, |
| +добавлено | 0, 0, 0, 1, |
| +добавлено | ); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // How many boxes a chain gets: its path length over twice its thickness (a whip: 3-4 boxes hugging |
| +добавлено | // its curve; an orb whose satellites circle a core: 1). Boxes overlap by one sphere; a pixel goes to |
| +добавлено | // the first box its ray crosses, which marches the whole ray: no seams. More boxes fit tighter but |
| +добавлено | // cost more in that test (measured: 6 boxes on the whip were slower than 3). |
| +добавлено | function boxCount(d, n, pad) { |
| +добавлено | let path = 0, rMax = 0; |
| +добавлено | for (let i = 0; i < n * 4; i += 4) { |
| +добавлено | rMax = Math.max(rMax, d[i + 3]); |
| +добавлено | if (i) path += Math.hypot(d[i] - d[i - 4], d[i + 1] - d[i - 3], d[i + 2] - d[i - 2]); |
| +добавлено | } |
| +добавлено | return Math.max(1, Math.min(MAX_BOXES, n - 1, Math.round(path / (4 * (rMax + pad))))); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // bounding sphere of each 4 consecutive spheres: [x, y, z, r] per group (centre = mean) |
| +добавлено | function groupBounds(d, n, out) { |
| +добавлено | for (let g = 0; g * 4 < n; g++) { |
| +добавлено | const a = g * 16, e = Math.min(n, g * 4 + 4) * 4, c = e / 4 - g * 4; |
| +добавлено | let x = 0, y = 0, z = 0, r = 0; |
| +добавлено | for (let i = a; i < e; i += 4) { x += d[i] / c; y += d[i + 1] / c; z += d[i + 2] / c; } |
| +добавлено | for (let i = a; i < e; i += 4) r = Math.max(r, Math.hypot(d[i] - x, d[i + 1] - y, d[i + 2] - z) + d[i + 3]); |
| +добавлено | out[g * 4] = x; out[g * 4 + 1] = y; out[g * 4 + 2] = z; out[g * 4 + 3] = r; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function applyPreset(h, name) { |
| +добавлено | const p = METABALL_PRESETS[name] ?? METABALL_PRESETS.water; |
| +добавлено | h.absorption.fromArray(p.absorption); |
| +добавлено | h.scatterColor.fromArray(p.scatterColor); |
| +добавлено | h.emission.fromArray(p.emission); |
| +добавлено | for (const k of ['k', 'wobble', 'bubbles', 'corrosion', 'ior', 'roughness', 'refraction', 'rim', 'turbidity']) h[k] = p[k]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export class Metaballs { |
| +добавлено | constructor({ max = 4, spheres = 16 } = {}) { |
| +добавлено | if (spheres > 16) throw new Error('Metaballs: at most 16 spheres (4-bit per-ray sphere list)'); |
| +добавлено | this.spheres = spheres; |
| +добавлено | this.group = new THREE.Group(); // add to the refract scene; keep it at the identity |
| +добавлено | this.steps = { value: 32 }; |
| +добавлено | this.debug = { value: 0 }; // 1 step heat map, 2 proxy boxes, 3 flat coverage, 4 thickness, 5 stats |
| +добавлено | const geometry = new THREE.BoxGeometry(2, 2, 2); |
| +добавлено | const fragmentShader = frag(spheres); |
| +добавлено | this.data = new Float32Array(spheres * 4 * max); |
| +добавлено | this.tex = new THREE.DataTexture(this.data, spheres, max, THREE.RGBAFormat, THREE.FloatType); |
| +добавлено | this.tex.magFilter = this.tex.minFilter = THREE.NearestFilter; |
| +добавлено | const sphereTex = { value: this.tex }; |
| +добавлено | this.handles = Array.from({ length: max }, (_, row) => { |
| +добавлено | const data = this.data.subarray(row * spheres * 4, (row + 1) * spheres * 4); |
| +добавлено | const uniforms = { |
| +добавлено | ...U, |
| +добавлено | uSpheres: { value: data }, uSphereTex: sphereTex, uRow: { value: row }, uCount: { value: 0 }, |
| +добавлено | uGroups: { value: new Float32Array((spheres + 3 >> 2) * 4) }, |
| +добавлено | uBoxInv: { value: Array.from({ length: MAX_BOXES }, () => new THREE.Matrix4()) }, |
| +добавлено | uShape: { value: new THREE.Vector4() }, uOptics: { value: new THREE.Vector4() }, |
| +добавлено | uAbsorption: { value: new THREE.Color() }, uTurbidity: { value: 0 }, uScatter: { value: new THREE.Color() }, uEmission: { value: new THREE.Color() }, |
| +добавлено | uSteps: this.steps, uMetaDebug: this.debug, |
| +добавлено | }; |
| +добавлено | const mesh = new THREE.InstancedMesh(geometry, new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms, vertexShader: VERT, fragmentShader, |
| +добавлено | side: THREE.BackSide, alphaToCoverage: true, |
| +добавлено | }), MAX_BOXES); |
| +добавлено | mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage); |
| +добавлено | mesh.frustumCulled = false; // boxes move every frame; an off-screen draw rasterizes nothing |
| +добавлено | mesh.matrixAutoUpdate = false; |
| +добавлено | mesh.visible = false; |
| +добавлено | this.group.add(mesh); |
| +добавлено | const h = { |
| +добавлено | mesh, data, active: false, count: 0, visible: true, intensity: 1, |
| +добавлено | absorption: new THREE.Color(), scatterColor: new THREE.Color(), emission: new THREE.Color(), |
| +добавлено | set(i, x, y, z, r) { const o = i * 4; data[o] = x; data[o + 1] = y; data[o + 2] = z; data[o + 3] = r; }, |
| +добавлено | release() { h.active = false; mesh.visible = false; }, |
| +добавлено | }; |
| +добавлено | applyPreset(h, 'water'); |
| +добавлено | return h; |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // preset: 'water' | 'acid'. Returns null when every handle is in use. |
| +добавлено | acquire({ preset = 'water' } = {}) { |
| +добавлено | const h = this.handles.find((x) => !x.active); |
| +добавлено | if (!h) return null; |
| +добавлено | applyPreset(h, preset); |
| +добавлено | Object.assign(h, { active: true, visible: true, count: 0, intensity: 1 }); |
| +добавлено | return h; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // once per frame, after the spells set their spheres and before the refract pass |
| +добавлено | update() { |
| +добавлено | this.tex.needsUpdate = true; // 1 KB |
| +добавлено | this.steps.value = Math.max(8, Math.min(32, Math.round(32 * Q.volumeSteps / 24 * (Q.auto?.steps ?? 1)))); |
| +добавлено | const e = Q.emission * (Q.auto?.emission ?? 1); |
| +добавлено | for (const h of this.handles) { |
| +добавлено | const m = h.mesh, n = Math.min(h.count, this.spheres); |
| +добавлено | m.visible = h.active && h.visible && n > 0; |
| +добавлено | if (!m.visible) continue; |
| +добавлено | const u = m.material.uniforms; |
| +добавлено | u.uCount.value = n; |
| +добавлено | u.uShape.value.set(h.k, h.wobble, h.bubbles, h.corrosion); |
| +добавлено | u.uOptics.value.set(h.ior, h.roughness, h.refraction, h.rim * h.intensity); |
| +добавлено | u.uAbsorption.value.copy(h.absorption); |
| +добавлено | u.uTurbidity.value = h.turbidity; |
| +добавлено | u.uScatter.value.copy(h.scatterColor); |
| +добавлено | u.uEmission.value.copy(h.emission).multiplyScalar(h.intensity * e); |
| +добавлено | // the march shell + the AA fringe (2 px up to ~20 m at 3.3 MP) |
| +добавлено | const pad = h.k * SHELL + h.wobble + h.bubbles * BUBBLE_H + 0.03, boxes = boxCount(h.data, n, pad); |
| +добавлено | for (let b = 0; b < boxes; b++) { |
| +добавлено | fitBox(h.data, Math.floor(b * (n - 1) / boxes), Math.floor((b + 1) * (n - 1) / boxes), pad, _m); |
| +добавлено | m.setMatrixAt(b, _m); |
| +добавлено | u.uBoxInv.value[b].copy(_m).invert(); |
| +добавлено | } |
| +добавлено | groupBounds(h.data, n, u.uGroups.value); |
| +добавлено | m.count = boxes; |
| +добавлено | m.instanceMatrix.needsUpdate = true; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | dispose() { |
| +добавлено | this.tex.dispose(); |
| +добавлено | this.handles[0]?.mesh.geometry.dispose(); |
| +добавлено | for (const h of this.handles) h.mesh.material.dispose(); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // every sphere's extreme points must land inside its fitted box, every sphere inside its group's |
| +добавлено | // bound (dev/metaballs.js runs this) |
| +добавлено | export function metaballsSelfCheck() { |
| +добавлено | const d = new Float32Array(16 * 4), gb = new Float32Array(16), m = new THREE.Matrix4(), inv = new THREE.Matrix4(), p = new THREE.Vector3(); |
| +добавлено | let seed = 7; |
| +добавлено | const rnd = () => ((seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 4294967296); |
| +добавлено | for (let trial = 0; trial < 50; trial++) { |
| +добавлено | const n = 1 + (trial % 16); |
| +добавлено | for (let i = 0; i < n * 4; i++) d[i] = i % 4 === 3 ? 0.05 + rnd() * 0.4 : (rnd() - 0.5) * (trial % 3 ? 6 : 0.01); |
| +добавлено | fitBox(d, 0, n - 1, 0.02, m); |
| +добавлено | inv.copy(m).invert(); |
| +добавлено | for (let i = 0; i < n; i++) for (let a = 0; a < 6; a++) { |
| +добавлено | const s = a & 1 ? -1 : 1, r = d[i * 4 + 3]; |
| +добавлено | p.set(d[i * 4], d[i * 4 + 1], d[i * 4 + 2]).setComponent(a >> 1, d[i * 4 + (a >> 1)] + s * r).applyMatrix4(inv); |
| +добавлено | if (Math.max(Math.abs(p.x), Math.abs(p.y), Math.abs(p.z)) > 1 + 1e-4) throw new Error(`fitBox: sphere ${i} of ${n} pokes out (${p.toArray().map((x) => x.toFixed(3))})`); |
| +добавлено | } |
| +добавлено | groupBounds(d, n, gb); |
| +добавлено | for (let i = 0; i < n; i++) { |
| +добавлено | const o = i * 4, g = (i >> 2) * 4; |
| +добавлено | if (Math.hypot(d[o] - gb[g], d[o + 1] - gb[g + 1], d[o + 2] - gb[g + 2]) + d[o + 3] > gb[g + 3] + 1e-4) throw new Error(`groupBounds: sphere ${i} of ${n} outside its group`); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return 'metaballs ok: fitBox and groupBounds hold 50 random chains'; |
| +добавлено | } |
| +добавлено | import { COMMON_GLSL, NOISE_GLSL, WORLD_GLSL, ARENA_GLSL, LIGHTS_GLSL, FORCES_GLSL, GROUND_GLSL, FX_VERT_HEAD, FX_FRAG_HEAD, FX_OUT_GLSL, ARENA } from './common.js'; |
| +добавлено | import { REFRACT_GLSL } from './Refraction.js'; |
| +добавлено | import { PAINT_FRAG_HEAD } from './GroundField.js'; |
| +добавлено | |
| +добавлено | // Shaders for ParticleFluid.js (see its header for the design). Grid conventions: |
| +добавлено | // - each domain is a yaw-rotated box of nx x ny x nz cubic cells (size h), cell (0,0,0) at |
| +добавлено | // uDomO.xyz; row y = 0 sits under the floor, so the floor is a solid boundary like any other |
| +добавлено | // - MAC velocities: texel (i,j,k) holds u at the face x = i (centre (i, j+.5, k+.5)), v at y = j, |
| +добавлено | // w at z = k, and the cell (i,j,k) itself (type, density, divergence, pressure). Texel indices |
| +добавлено | // run 0..n on every axis (the last one only carries the far faces) |
| +добавлено | // - the 3D grid lives in a 2D atlas: z-slices are tiles of (nx+1) x (ny+1) texels, uDomN.w per |
| +добавлено | // row, one region of uRegionH rows per domain |
| +добавлено | // - local velocities are m/s in the domain frame; pressure p is in m/s (v_face -= p_c - p_nbr) |
| +добавлено | |
| +добавлено | export const MAXD = 2; // live domains at once |
| +добавлено | export const MAX_REC = 48; // emission records per frame |
| +добавлено | export const PW = 256; // particle texture width (fluid and whitewater) |
| +добавлено | const f = (x) => x.toFixed(4); |
| +добавлено | const P = ARENA.pool; |
| +добавлено | |
| +добавлено | const HEAD = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | precision highp sampler2D; |
| +добавлено | `; |
| +добавлено | |
| +добавлено | export const GRID_GLSL = /* glsl */` |
| +добавлено | #define MAXD ${MAXD} |
| +добавлено | uniform vec4 uDomO[MAXD]; // cell (0,0,0) corner (world), cell size h (m) |
| +добавлено | uniform vec4 uDomN[MAXD]; // nx, ny, nz, slice tiles per atlas row |
| +добавлено | uniform vec4 uDomR[MAXD]; // cos yaw, sin yaw, live generation + 1 (0 = free), life-box margin (m) |
| +добавлено | uniform vec4 uDomS[MAXD]; // particle spacing s (m), render radius (m), thickness scale, density drift gain (m/s) |
| +добавлено | uniform vec4 uDomF[MAXD]; // FLIP ratio, wind response, floor drain (1/s), whitewater amount |
| +добавлено | uniform vec2 uAtlas; |
| +добавлено | uniform float uRegionH; |
| +добавлено | // a particle's tag is domain + MAXD * generation: particles of a released domain die with it |
| +добавлено | int tagDomain(float tag) { return int(tag + 0.5) % MAXD; } |
| +добавлено | bool tagLive(float tag) { int t = int(tag + 0.5); return uDomR[t % MAXD].z == float(t / MAXD + 1); } |
| +добавлено | vec3 dirToLocal(int d, vec3 v) { vec2 r = uDomR[d].xy; return vec3(v.x * r.x + v.z * r.y, v.y, v.z * r.x - v.x * r.y); } |
| +добавлено | vec3 dirToWorld(int d, vec3 v) { vec2 r = uDomR[d].xy; return vec3(v.x * r.x - v.z * r.y, v.y, v.x * r.y + v.z * r.x); } |
| +добавлено | vec3 toLocal(int d, vec3 p) { return dirToLocal(d, p - uDomO[d].xyz) / uDomO[d].w; } |
| +добавлено | vec3 toWorld(int d, vec3 g) { return uDomO[d].xyz + dirToWorld(d, g * uDomO[d].w); } |
| +добавлено | ivec2 tileOrigin(int d, int k) { |
| +добавлено | ivec4 n = ivec4(uDomN[d]); |
| +добавлено | return ivec2((k % n.w) * (n.x + 1), d * int(uRegionH) + (k / n.w) * (n.y + 1)); |
| +добавлено | } |
| +добавлено | ivec2 cellTexel(int d, ivec3 c) { return tileOrigin(d, c.z) + c.xy; } |
| +добавлено | bool texelCell(ivec2 px, out int d, out ivec3 c) { |
| +добавлено | d = min(px.y / int(uRegionH), MAXD - 1); |
| +добавлено | ivec4 n = ivec4(uDomN[d]); |
| +добавлено | int y = px.y - d * int(uRegionH); |
| +добавлено | int tx = px.x / (n.x + 1), ty = y / (n.y + 1); |
| +добавлено | c = ivec3(px.x - tx * (n.x + 1), y - ty * (n.y + 1), ty * n.w + tx); |
| +добавлено | return uDomR[d].z > 0.5 && tx < n.w && c.z <= n.z; |
| +добавлено | } |
| +добавлено | bool inCells(ivec3 c, ivec3 n) { return all(greaterThanEqual(c, ivec3(0))) && all(lessThan(c, n)); } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const STATE_GLSL = /* glsl */` |
| +добавлено | uniform highp sampler2D uS0; // pos, age |
| +добавлено | uniform highp sampler2D uS1; // vel, air (aeration 0..1) |
| +добавлено | uniform highp sampler2D uS2; // life, tag, density (/ rest), floor contact |
| +добавлено | ivec2 texelOf(int i) { return ivec2(i % ${PW}, i / ${PW}); } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // hardware-bilinear within a slice, lerp across slices; t in texel units (centres at integers) |
| +добавлено | const SAMPLE_GLSL = /* glsl */` |
| +добавлено | uniform highp sampler2D uVn; // projected face velocities |
| +добавлено | uniform highp sampler2D uDV; // their change this step (FLIP) |
| +добавлено | uniform highp sampler2D uD; // divergence, density, solid mask, type |
| +добавлено | vec4 gridSample(highp sampler2D tex, int d, vec3 t) { |
| +добавлено | vec3 n = uDomN[d].xyz; |
| +добавлено | t = clamp(t, vec3(0.0), n); |
| +добавлено | float k0 = min(floor(t.z), n.z - 1.0); |
| +добавлено | vec2 a = vec2(tileOrigin(d, int(k0))) + t.xy + 0.5, b = vec2(tileOrigin(d, int(k0) + 1)) + t.xy + 0.5; |
| +добавлено | return mix(textureLod(tex, a / uAtlas, 0.0), textureLod(tex, b / uAtlas, 0.0), t.z - k0); |
| +добавлено | } |
| +добавлено | vec3 gridVel(highp sampler2D tex, int d, vec3 g) { |
| +добавлено | return vec3(gridSample(tex, d, g - vec3(0.0, 0.5, 0.5)).x, |
| +добавлено | gridSample(tex, d, g - vec3(0.5, 0.0, 0.5)).y, |
| +добавлено | gridSample(tex, d, g - vec3(0.5, 0.5, 0.0)).z); |
| +добавлено | } |
| +добавлено | float gridDensity(int d, vec3 g) { return gridSample(uD, d, g - 0.5).y; } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | export const FULL_VERT = /* glsl */` |
| +добавлено | in vec3 position; |
| +добавлено | void main() { gl_Position = vec4(position.xy, 0.0, 1.0); }`; |
| +добавлено | |
| +добавлено | // --- P2G: every particle splats momentum + weights into the 3x3x3 texels round its cell. |
| +добавлено | // One point (3x3 texels of a slice) per instance; instances 0..2 are the slices k-1..k+1. |
| +добавлено | export const P2G_VERT = HEAD + GRID_GLSL + STATE_GLSL + /* glsl */` |
| +добавлено | flat out vec3 vVel; |
| +добавлено | flat out vec3 vG; |
| +добавлено | flat out ivec2 vTile; |
| +добавлено | flat out ivec3 vN; |
| +добавлено | flat out int vK; |
| +добавлено | void main() { |
| +добавлено | gl_PointSize = 3.0; |
| +добавлено | gl_Position = vec4(2.0, 2.0, 2.0, 1.0); |
| +добавлено | ivec2 t = texelOf(gl_VertexID); |
| +добавлено | vec4 s0 = texelFetch(uS0, t, 0), s2 = texelFetch(uS2, t, 0); |
| +добавлено | if (s0.w >= s2.x || !tagLive(s2.y)) return; |
| +добавлено | int d = tagDomain(s2.y); |
| +добавлено | vec3 g = toLocal(d, s0.xyz); |
| +добавлено | ivec3 n = ivec3(uDomN[d].xyz); |
| +добавлено | ivec3 c = ivec3(floor(g)); |
| +добавлено | if (!inCells(c, n)) return; |
| +добавлено | int k = c.z + gl_InstanceID - 1; |
| +добавлено | if (k < 0 || k > n.z) return; |
| +добавлено | vTile = tileOrigin(d, k); |
| +добавлено | gl_Position = vec4((vec2(vTile + c.xy) + 0.5) / uAtlas * 2.0 - 1.0, 0.0, 1.0); |
| +добавлено | vVel = dirToLocal(d, texelFetch(uS1, t, 0).xyz); |
| +добавлено | vG = g; vN = n; vK = k; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export const P2G_FRAG = HEAD + /* glsl */` |
| +добавлено | flat in vec3 vVel; |
| +добавлено | flat in vec3 vG; |
| +добавлено | flat in ivec2 vTile; |
| +добавлено | flat in ivec3 vN; |
| +добавлено | flat in int vK; |
| +добавлено | layout(location = 0) out vec4 oA; // sum v w (per face component), sum w (cell centre) |
| +добавлено | layout(location = 1) out vec4 oB; // sum w (per face component) |
| +добавлено | float tri(float x) { return max(1.0 - abs(x), 0.0); } |
| +добавлено | void main() { |
| +добавлено | ivec2 l = ivec2(gl_FragCoord.xy) - vTile; |
| +добавлено | if (l.x < 0 || l.y < 0 || l.x > vN.x || l.y > vN.y) discard; |
| +добавлено | vec3 q = vG - vec3(vec2(l), float(vK)); |
| +добавлено | float wu = tri(q.x) * tri(q.y - 0.5) * tri(q.z - 0.5); |
| +добавлено | float wv = tri(q.x - 0.5) * tri(q.y) * tri(q.z - 0.5); |
| +добавлено | float ww = tri(q.x - 0.5) * tri(q.y - 0.5) * tri(q.z); |
| +добавлено | float wc = tri(q.x - 0.5) * tri(q.y - 0.5) * tri(q.z - 0.5); |
| +добавлено | oA = vec4(vVel * vec3(wu, wv, ww), wc); |
| +добавлено | oB = vec4(wu, wv, ww, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- normalise + classify: air 0, fluid 1, solid 2 (arena SDF at the cell centre) --------- |
| +добавлено | export const MARK_FRAG = HEAD + COMMON_GLSL + ARENA_GLSL + GRID_GLSL + /* glsl */` |
| +добавлено | uniform highp sampler2D uAccA; |
| +добавлено | uniform highp sampler2D uAccB; |
| +добавлено | uniform float uFluidThresh; |
| +добавлено | out vec4 o; |
| +добавлено | void main() { |
| +добавлено | ivec2 px = ivec2(gl_FragCoord.xy); |
| +добавлено | int d; ivec3 c; |
| +добавлено | if (!texelCell(px, d, c)) { o = vec4(0.0); return; } |
| +добавлено | vec4 A = texelFetch(uAccA, px, 0), B = texelFetch(uAccB, px, 0); |
| +добавлено | vec3 v = vec3(B.x > 1e-4 ? A.x / B.x : 0.0, B.y > 1e-4 ? A.y / B.y : 0.0, B.z > 1e-4 ? A.z / B.z : 0.0); |
| +добавлено | float type = 0.0; |
| +добавлено | if (inCells(c, ivec3(uDomN[d].xyz))) { |
| +добавлено | if (arenaSDF(toWorld(d, vec3(c) + 0.5)) < 0.0) type = 2.0; |
| +добавлено | else if (A.w > uFluidThresh) type = 1.0; |
| +добавлено | } |
| +добавлено | o = vec4(v, type); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- divergence (with gravity on the v faces), solid-face mask, density drift correction ---- |
| +добавлено | export const DIV_FRAG = HEAD + GRID_GLSL + /* glsl */` |
| +добавлено | uniform highp sampler2D uV; |
| +добавлено | uniform highp sampler2D uAccA; |
| +добавлено | uniform float uGdt; |
| +добавлено | uniform float uPPC; |
| +добавлено | out vec4 o; |
| +добавлено | bool solidAt(int d, ivec3 c, ivec3 n) { return inCells(c, n) && texelFetch(uV, cellTexel(d, c), 0).w > 1.5; } |
| +добавлено | void main() { |
| +добавлено | ivec2 px = ivec2(gl_FragCoord.xy); |
| +добавлено | int d; ivec3 c; |
| +добавлено | if (!texelCell(px, d, c)) { o = vec4(0.0); return; } |
| +добавлено | vec4 V = texelFetch(uV, px, 0); |
| +добавлено | float dens = texelFetch(uAccA, px, 0).w / uPPC; |
| +добавлено | ivec3 n = ivec3(uDomN[d].xyz); |
| +добавлено | if (!inCells(c, n) || V.w < 0.5 || V.w > 1.5) { o = vec4(0.0, dens, 0.0, V.w); return; } |
| +добавлено | // the + neighbours' texels always exist (indices run to n); their .w is their type |
| +добавлено | vec4 Vx = texelFetch(uV, cellTexel(d, c + ivec3(1, 0, 0)), 0); |
| +добавлено | vec4 Vy = texelFetch(uV, cellTexel(d, c + ivec3(0, 1, 0)), 0); |
| +добавлено | vec4 Vz = texelFetch(uV, cellTexel(d, c + ivec3(0, 0, 1)), 0); |
| +добавлено | bool sxm = solidAt(d, c - ivec3(1, 0, 0), n), sym = solidAt(d, c - ivec3(0, 1, 0), n), szm = solidAt(d, c - ivec3(0, 0, 1), n); |
| +добавлено | bool sxp = Vx.w > 1.5, syp = Vy.w > 1.5, szp = Vz.w > 1.5; |
| +добавлено | float div = (sxp ? 0.0 : Vx.x) - (sxm ? 0.0 : V.x) |
| +добавлено | + (syp ? 0.0 : Vy.y - uGdt) - (sym ? 0.0 : V.y - uGdt) |
| +добавлено | + (szp ? 0.0 : Vz.z) - (szm ? 0.0 : V.z); |
| +добавлено | // over-dense cells push apart (particle drift correction): target an outflow |
| +добавлено | div -= uDomS[d].w * clamp(dens - 1.0, 0.0, 2.0); |
| +добавлено | int mask = (sxm ? 1 : 0) | (sxp ? 2 : 0) | (sym ? 4 : 0) | (syp ? 8 : 0) | (szm ? 16 : 0) | (szp ? 32 : 0); |
| +добавлено | int ns = 6 - int(sxm) - int(sxp) - int(sym) - int(syp) - int(szm) - int(szp); |
| +добавлено | o = vec4(div, dens, float(mask + 64 * ns), 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- Jacobi on the pressure Poisson equation, free surface (air p = 0), Neumann at solids ---- |
| +добавлено | export const JACOBI_FRAG = HEAD + GRID_GLSL + /* glsl */` |
| +добавлено | uniform highp sampler2D uP; |
| +добавлено | uniform highp sampler2D uDc; |
| +добавлено | uniform int uFirst; // warm start from last step's pressure: ignore cells that stopped being fluid |
| +добавлено | out vec4 o; |
| +добавлено | float pAt(int d, ivec3 c, ivec3 n) { |
| +добавлено | if (!inCells(c, n)) return 0.0; |
| +добавлено | ivec2 t = cellTexel(d, c); |
| +добавлено | float p = texelFetch(uP, t, 0).x; |
| +добавлено | if (uFirst == 1) { float ty = texelFetch(uDc, t, 0).w; p *= float(ty > 0.5 && ty < 1.5); } |
| +добавлено | return p; |
| +добавлено | } |
| +добавлено | void main() { |
| +добавлено | ivec2 px = ivec2(gl_FragCoord.xy); |
| +добавлено | int d; ivec3 c; |
| +добавлено | if (!texelCell(px, d, c)) { o = vec4(0.0); return; } |
| +добавлено | vec4 D = texelFetch(uDc, px, 0); |
| +добавлено | if (D.w < 0.5 || D.w > 1.5) { o = vec4(0.0); return; } |
| +добавлено | ivec3 n = ivec3(uDomN[d].xyz); |
| +добавлено | int code = int(D.z + 0.5), mask = code & 63; |
| +добавлено | float s = 0.0; |
| +добавлено | if ((mask & 1) == 0) s += pAt(d, c - ivec3(1, 0, 0), n); |
| +добавлено | if ((mask & 2) == 0) s += pAt(d, c + ivec3(1, 0, 0), n); |
| +добавлено | if ((mask & 4) == 0) s += pAt(d, c - ivec3(0, 1, 0), n); |
| +добавлено | if ((mask & 8) == 0) s += pAt(d, c + ivec3(0, 1, 0), n); |
| +добавлено | if ((mask & 16) == 0) s += pAt(d, c - ivec3(0, 0, 1), n); |
| +добавлено | if ((mask & 32) == 0) s += pAt(d, c + ivec3(0, 0, 1), n); |
| +добавлено | o = vec4((s - D.x) / max(float(code >> 6), 1.0), 0.0, 0.0, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- subtract the pressure gradient (+ gravity), zero solid faces; MRT new velocity + delta --- |
| +добавлено | export const PROJECT_FRAG = HEAD + GRID_GLSL + /* glsl */` |
| +добавлено | uniform highp sampler2D uV; |
| +добавлено | uniform highp sampler2D uP; |
| +добавлено | uniform float uGdt; |
| +добавлено | layout(location = 0) out vec4 oV; |
| +добавлено | layout(location = 1) out vec4 oD; |
| +добавлено | void main() { |
| +добавлено | ivec2 px = ivec2(gl_FragCoord.xy); |
| +добавлено | int d; ivec3 c; |
| +добавлено | if (!texelCell(px, d, c)) { oV = oD = vec4(0.0); return; } |
| +добавлено | ivec3 n = ivec3(uDomN[d].xyz); |
| +добавлено | vec4 V = texelFetch(uV, px, 0); |
| +добавлено | float pc = texelFetch(uP, px, 0).x; |
| +добавлено | bool sc = V.w > 1.5; |
| +добавлено | vec3 vn = V.xyz; |
| +добавлено | vec4 Nx = vec4(0.0), Ny = vec4(0.0), Nz = vec4(0.0); |
| +добавлено | float px_ = 0.0, py_ = 0.0, pz_ = 0.0; |
| +добавлено | if (c.x > 0) { ivec2 t = cellTexel(d, c - ivec3(1, 0, 0)); Nx = texelFetch(uV, t, 0); px_ = texelFetch(uP, t, 0).x; } |
| +добавлено | if (c.y > 0) { ivec2 t = cellTexel(d, c - ivec3(0, 1, 0)); Ny = texelFetch(uV, t, 0); py_ = texelFetch(uP, t, 0).x; } |
| +добавлено | if (c.z > 0) { ivec2 t = cellTexel(d, c - ivec3(0, 0, 1)); Nz = texelFetch(uV, t, 0); pz_ = texelFetch(uP, t, 0).x; } |
| +добавлено | vn.x = (sc || Nx.w > 1.5) ? 0.0 : V.x - (pc - px_); |
| +добавлено | vn.y = (sc || Ny.w > 1.5) ? 0.0 : V.y - uGdt - (pc - py_); |
| +добавлено | vn.z = (sc || Nz.w > 1.5) ? 0.0 : V.z - (pc - pz_); |
| +добавлено | oV = vec4(vn, 0.0); |
| +добавлено | oD = vec4(vn - V.xyz, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- G2P (FLIP/PIC blend), RK2 advection through the grid, forces, collision, emission ------- |
| +добавлено | export const ADVECT_FRAG = HEAD + COMMON_GLSL + ARENA_GLSL + FORCES_GLSL + GRID_GLSL + STATE_GLSL + SAMPLE_GLSL + /* glsl */` |
| +добавлено | #define MAX_REC ${MAX_REC} |
| +добавлено | uniform highp sampler2D uEmit; |
| +добавлено | uniform int uEmitCount; |
| +добавлено | uniform vec2 uSpan[4]; |
| +добавлено | uniform int uSpanCount; |
| +добавлено | uniform float uSimDt; |
| +добавлено | uniform vec4 uHold[MAXD]; // centre, pull (1/s; 0 = off) |
| +добавлено | uniform vec4 uHoldB[MAXD]; // radius (m), swirl (rad/s), -, - |
| +добавлено | uniform vec4 uLaunch[MAXD]; // velocity (m/s), 1 = throw what's held this step |
| +добавлено | layout(location = 0) out vec4 o0; |
| +добавлено | layout(location = 1) out vec4 o1; |
| +добавлено | layout(location = 2) out vec4 o2; |
| +добавлено | bool inPool(vec2 xz) { return all(lessThan(abs(xz - vec2(${f(P.center.x)}, ${f(P.center.y)})), vec2(${f(P.half.x)}, ${f(P.half.y)}))); } |
| +добавлено | |
| +добавлено | // records (5 texels): (start, count, tag, type) (pos, radius) (dir, speed) (length|-, spread, radial, seed) (life, air, swirl, -) |
| +добавлено | bool tryEmit(int idx) { |
| +добавлено | bool inSpan = false; |
| +добавлено | for (int s = 0; s < 4; s++) { |
| +добавлено | if (s >= uSpanCount) break; |
| +добавлено | if (float(idx) >= uSpan[s].x && float(idx) < uSpan[s].y) { inSpan = true; break; } |
| +добавлено | } |
| +добавлено | if (!inSpan) return false; |
| +добавлено | for (int r = 0; r < MAX_REC; r++) { |
| +добавлено | if (r >= uEmitCount) break; |
| +добавлено | vec4 e0 = texelFetch(uEmit, ivec2(0, r), 0); |
| +добавлено | int j = idx - int(e0.x); |
| +добавлено | if (j < 0 || j >= int(e0.y)) continue; |
| +добавлено | vec4 e1 = texelFetch(uEmit, ivec2(1, r), 0), e2 = texelFetch(uEmit, ivec2(2, r), 0); |
| +добавлено | vec4 e3 = texelFetch(uEmit, ivec2(3, r), 0), e4 = texelFetch(uEmit, ivec2(4, r), 0); |
| +добавлено | float fj = float(j); |
| +добавлено | vec3 h = hash31(e3.w * 7.31 + fj * 1.618); |
| +добавлено | vec3 dir = normalize(e2.xyz + vec3(0.0, 1e-6, 0.0)); |
| +добавлено | vec3 pos, vel; |
| +добавлено | if (e0.w < 0.5) { |
| +добавлено | // jet: stratified over the nozzle disc (R2 sequence), spread over this step's stream length |
| +добавлено | mat3 B = basisFrom(dir); |
| +добавлено | float u1 = fract(fj * 0.7548777 + e3.w), u2 = fract(fj * 0.5698403 + e3.w * 1.37); |
| +добавлено | float rr = sqrt(u1), a = u2 * 6.2831853; |
| +добавлено | vec3 radial = B * vec3(cos(a), sin(a), 0.0); |
| +добавлено | float along = (fj + h.x) / e0.y * e3.x; |
| +добавлено | pos = e1.xyz + radial * rr * e1.w - dir * along; |
| +добавлено | vel = dir * e2.w + radial * rr * e3.z + cross(dir, radial) * rr * e1.w * e4.z |
| +добавлено | + (hash31(e3.w + fj * 0.37) - 0.5) * 2.0 * e3.y; |
| +добавлено | vel.y -= 9.81 * along / max(e2.w, 1.0); |
| +добавлено | } else { |
| +добавлено | // ball: uniform in a sphere, base velocity + outward + random |
| +добавлено | vec3 q = randomInSphere(h); |
| +добавлено | pos = e1.xyz + q * e1.w; |
| +добавлено | vel = dir * e2.w + q * e3.z + randomInSphere(hash31(e3.w * 3.1 + fj * 0.71)) * e3.y; |
| +добавлено | } |
| +добавлено | o0 = vec4(pos, 0.0); |
| +добавлено | o1 = vec4(vel, e4.y); |
| +добавлено | o2 = vec4(e4.x * mix(0.8, 1.2, h.z), e0.z, 1.0, 0.0); |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | ivec2 px = ivec2(gl_FragCoord.xy); |
| +добавлено | int idx = px.y * ${PW} + px.x; |
| +добавлено | if (tryEmit(idx)) return; |
| +добавлено | vec4 s0 = texelFetch(uS0, px, 0), s1 = texelFetch(uS1, px, 0), s2 = texelFetch(uS2, px, 0); |
| +добавлено | if (s0.w >= s2.x || !tagLive(s2.y)) { o0 = vec4(0.0, -100.0, 0.0, 1.0); o1 = vec4(0.0); o2 = vec4(0.0); return; } |
| +добавлено | int d = tagDomain(s2.y); |
| +добавлено | float dt = uSimDt, h = uDomO[d].w; |
| +добавлено | vec3 x = s0.xyz, v = s1.xyz; |
| +добавлено | float air = s1.w, age = s0.w + dt, life = s2.x; |
| +добавлено | vec3 g = toLocal(d, x), n = uDomN[d].xyz; |
| +добавлено | vec3 disp; |
| +добавлено | float dens = s2.z, turb = 0.0; // outside the grid a particle keeps its last density |
| +добавлено | if (all(greaterThanEqual(g, vec3(1.0))) && all(lessThanEqual(g, n - 1.0))) { |
| +добавлено | vec3 vl = dirToLocal(d, v); |
| +добавлено | vec3 vpic = gridVel(uVn, d, g); |
| +добавлено | vec3 vflip = vl + gridVel(uDV, d, g); |
| +добавлено | vec3 vnew = mix(vpic, vflip, uDomF[d].x); |
| +добавлено | // RK2 through the grid where the midpoint has water; fast thin streams (CFL > 1 ahead of |
| +добавлено | // a jet's head) and the grid edge move with the particle's own velocity |
| +добавлено | vec3 gm = g + 0.5 * dt * vpic / h; |
| +добавлено | float km = all(greaterThanEqual(gm, vec3(1.0))) && all(lessThanEqual(gm, n - 1.0)) ? smoothstep(0.05, 0.25, gridDensity(d, gm)) : 0.0; |
| +добавлено | vec3 vmid = gridVel(uVn, d, gm); |
| +добавлено | v = dirToWorld(d, vnew); |
| +добавлено | disp = dirToWorld(d, mix(vnew, vmid, km)) * dt; |
| +добавлено | dens = gridDensity(d, g); |
| +добавлено | turb = length(vflip - vpic); |
| +добавлено | } else { |
| +добавлено | // outside the grid: ballistic |
| +добавлено | disp = (v + vec3(0.0, -4.905 * dt, 0.0)) * dt; |
| +добавлено | v.y -= 9.81 * dt; |
| +добавлено | } |
| +добавлено | // torn-off droplets (aerated, alone) feel the air: quadratic drag, terminal speed ~6 m/s |
| +добавлено | float iso = 1.0 - smoothstep(0.08, 0.3, dens); |
| +добавлено | v /= 1.0 + 0.27 * air * iso * length(v) * dt; |
| +добавлено | // airborne water feels the wind and vortices; the bulk barely |
| +добавлено | float kill = 0.0; |
| +добавлено | float resp = uDomF[d].y * (1.0 - 0.85 * smoothstep(0.15, 0.7, dens)); |
| +добавлено | if (resp > 0.0) v += forceAccel(x, v, kill) * resp * dt; |
| +добавлено | // hold (the gathering orb): pulled to the centre, swirling, weightless |
| +добавлено | vec4 H = uHold[d]; |
| +добавлено | if (H.w > 0.0) { |
| +добавлено | vec3 dc = H.xyz - x; |
| +добавлено | float R = uHoldB[d].x, dl = length(dc); |
| +добавлено | // fast water (a jet leaving the orb) is not held |
| +добавлено | float w = (1.0 - smoothstep(R * 1.5, R * 4.0, dl)) * (1.0 - smoothstep(5.0, 9.0, length(v))); |
| +добавлено | if (w > 0.0) { |
| +добавлено | // pulled onto a ball of about R (not a point: outside a grid nothing holds it apart) that |
| +добавлено | // wobbles as a held blob of water does, swirling |
| +добавлено | vec3 dn = dc / max(dl, 1e-3); |
| +добавлено | float wob = 1.0 + 0.22 * sin(dot(dn, vec3(2.3, 3.1, 1.7)) * 2.0 + uTime * 5.3) + 0.12 * sin(dot(dn, vec3(-3.7, 1.3, 2.9)) * 3.0 - uTime * 7.9); |
| +добавлено | vec3 tgt = dc * H.w * max(1.0 - 0.6 * R * wob / max(dl, 1e-3), 0.0) + cross(vec3(0.0, 1.0, 0.0), dc) * uHoldB[d].y; |
| +добавлено | v.y += 9.81 * dt * w; |
| +добавлено | v = mix(v, tgt, w * (1.0 - exp(-dt * 7.0))); |
| +добавлено | disp = mix(disp, v * dt, w); |
| +добавлено | } |
| +добавлено | if (uLaunch[d].w > 0.5 && w > 0.0) { v = uLaunch[d].xyz + (x - H.xyz) * 3.0; disp = v * dt; } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // collision with the arena (floor, rim, pillars, dummies, spikes): free slip + wet friction |
| +добавлено | vec3 xn = x + disp; |
| +добавлено | float r = uDomS[d].x * 0.5, impact = 0.0, contact = 0.0; |
| +добавлено | if (dot(disp, disp) > r * r) { vec3 xm = x + disp * 0.5; if (arenaSDF(xm) < 0.0) xn = xm; } |
| +добавлено | float sd = arenaSDF(xn); |
| +добавлено | if (sd < r) { |
| +добавлено | vec3 nrm = abs(sd - xn.y) < 1e-4 ? vec3(0.0, 1.0, 0.0) : arenaNormal(xn); |
| +добавлено | xn += nrm * (r - sd); |
| +добавлено | float vn = dot(v, nrm); |
| +добавлено | if (vn < 0.0) { v -= nrm * vn; impact = -vn; } |
| +добавлено | v -= (v - nrm * dot(v, nrm)) * min(1.5 * dt, 1.0); |
| +добавлено | contact = 1.0; |
| +добавлено | } |
| +добавлено | // aeration: churn (FLIP vs PIC disagreement), impacts and raw speed trap air; it rises out |
| +добавлено | air *= exp(-dt * 2.4); |
| +добавлено | air = max(air, clamp(turb * 0.1 - 0.25, 0.0, 0.8)); |
| +добавлено | air = max(air, clamp((impact - 4.0) * 0.06, 0.0, 0.7)); |
| +добавлено | // a fast free stream roughens as it goes (turbulent breakup): glassy at the nozzle, not at 10 m |
| +добавлено | air = max(air, clamp((length(v) - 9.0) * 0.012 * age, 0.0, 0.35) * (1.0 - smoothstep(0.3, 0.9, dens))); |
| +добавлено | // puddles drain away (each particle at its own pace, so the sheet thins rather than pops) |
| +добавлено | if (contact > 0.0 && xn.y < 0.5) age += dt * uDomF[d].z * life * (0.4 + 1.2 * hash12(vec2(px) + 0.5)); |
| +добавлено | // life box, the pool (it joins the pool), forces that kill |
| +добавлено | vec3 gn = toLocal(d, xn); |
| +добавлено | float m = uDomR[d].w / h; |
| +добавлено | if (any(lessThan(gn, vec3(-m))) || any(greaterThan(gn, n + m)) || xn.y < -1.0) age = life; |
| +добавлено | if (inPool(xn.xz) && xn.y < 0.02) age = life; |
| +добавлено | if (kill > 0.5) age = life; |
| +добавлено | o0 = vec4(xn, age); |
| +добавлено | o1 = vec4(v, air); |
| +добавлено | o2 = vec4(life, s2.y, dens, contact); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- whitewater (Ihmsen et al. 2012): spawned from aerated fluid particles, classified each |
| +добавлено | // step by the fluid density round them: spray (ballistic), foam (rides the flow, dissipates), |
| +добавлено | // bubbles (buoyant, dragged along) ---------------------------------------------------------- |
| +добавлено | export const WHITE_FRAG = HEAD + COMMON_GLSL + ARENA_GLSL + FORCES_GLSL + GRID_GLSL + STATE_GLSL + SAMPLE_GLSL + /* glsl */` |
| +добавлено | uniform highp sampler2D uW0; // pos, age |
| +добавлено | uniform highp sampler2D uW1; // vel, life |
| +добавлено | uniform highp sampler2D uW2; // tag, density, seed, - |
| +добавлено | uniform float uSimDt; |
| +добавлено | uniform float uFluidN; |
| +добавлено | uniform float uWhiteRate; |
| +добавлено | layout(location = 0) out vec4 o0; |
| +добавлено | layout(location = 1) out vec4 o1; |
| +добавлено | layout(location = 2) out vec4 o2; |
| +добавлено | void main() { |
| +добавлено | ivec2 px = ivec2(gl_FragCoord.xy); |
| +добавлено | vec4 w0 = texelFetch(uW0, px, 0), w1 = texelFetch(uW1, px, 0), w2 = texelFetch(uW2, px, 0); |
| +добавлено | float dt = uSimDt; |
| +добавлено | if (w0.w >= w1.w || !tagLive(w2.x)) { |
| +добавлено | // a dead slot looks at one random fluid particle; trapped air makes it spawn here |
| +добавлено | vec3 hh = hash33(vec3(vec2(px), mod(uFrame, 1009.0))); |
| +добавлено | ivec2 t = texelOf(int(hh.x * uFluidN)); |
| +добавлено | vec4 s0 = texelFetch(uS0, t, 0), s1 = texelFetch(uS1, t, 0), s2 = texelFetch(uS2, t, 0); |
| +добавлено | o0 = vec4(0.0, -100.0, 0.0, 1.0); o1 = vec4(0.0); o2 = vec4(0.0); |
| +добавлено | if (s0.w < s2.x && tagLive(s2.y)) { |
| +добавлено | int d = tagDomain(s2.y); |
| +добавлено | float pot = s1.w * s1.w * uDomF[d].w; |
| +добавлено | if (hh.y < pot * uWhiteRate * dt) { |
| +добавлено | vec3 q = randomInSphere(hash33(hh * 91.7 + 3.1)); |
| +добавлено | float sp = length(s1.xyz); |
| +добавлено | o0 = vec4(s0.xyz + q * uDomS[d].x, 0.0); |
| +добавлено | o1 = vec4(s1.xyz * mix(0.9, 1.15, hh.z) + q * (0.4 + 0.08 * sp), mix(0.7, 2.4, fract(hh.z * 7.3))); |
| +добавлено | o2 = vec4(s2.y, s2.z, hh.z, 0.0); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | int d = tagDomain(w2.x); |
| +добавлено | vec3 x = w0.xyz, v = w1.xyz; |
| +добавлено | float age = w0.w + dt, life = w1.w; |
| +добавлено | vec3 g = toLocal(d, x), n = uDomN[d].xyz; |
| +добавлено | float dens = 0.0; |
| +добавлено | vec3 vf = v; |
| +добавлено | if (all(greaterThanEqual(g, vec3(1.0))) && all(lessThanEqual(g, n - 1.0))) { |
| +добавлено | dens = gridDensity(d, g); |
| +добавлено | vf = dirToWorld(d, gridVel(uVn, d, g)); |
| +добавлено | } |
| +добавлено | float kill = 0.0; |
| +добавлено | if (dens < 0.2 || length(v) > 6.0) { // spray: ballistic, quadratic drag (mm droplets) |
| +добавлено | v.y -= 9.81 * dt; |
| +добавлено | v /= 1.0 + 0.3 * length(v) * dt; |
| +добавлено | v += forceAccel(x, v, kill) * dt; |
| +добавлено | } else if (dens < 0.7) { // foam: advected by the fluid, decays |
| +добавлено | v = mix(v, vf, 1.0 - exp(-dt * 14.0)); |
| +добавлено | age += dt * 0.35; |
| +добавлено | } else { // bubble: buoyancy + drag towards the flow |
| +добавлено | v += (vec3(0.0, 9.81 * 0.8, 0.0) + (vf - v) * 9.0) * dt; |
| +добавлено | age -= dt * 0.5; |
| +добавлено | } |
| +добавлено | vec3 xn = x + v * dt; |
| +добавлено | float sd = arenaSDF(xn); |
| +добавлено | if (sd < 0.012) { |
| +добавлено | vec3 nrm = abs(sd - xn.y) < 1e-4 ? vec3(0.0, 1.0, 0.0) : arenaNormal(xn); |
| +добавлено | xn += nrm * (0.012 - sd); |
| +добавлено | float vn = dot(v, nrm); |
| +добавлено | if (vn < 0.0) v -= nrm * vn; |
| +добавлено | v *= exp(-dt * 3.0); |
| +добавлено | } |
| +добавлено | vec3 gn = toLocal(d, xn); |
| +добавлено | float m = uDomR[d].w / uDomO[d].w; |
| +добавлено | if (any(lessThan(gn, vec3(-m))) || any(greaterThan(gn, n + m)) || kill > 0.5) age = life; |
| +добавлено | o0 = vec4(xn, age); |
| +добавлено | o1 = vec4(v, life); |
| +добавлено | o2 = vec4(w2.x, mix(w2.y, dens, 0.5), w2.z, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- screen-space fluid: velocity-stretched sphere sprites (capsules) ------------------------- |
| +добавлено | const SPRITE_VERT = HEAD + GRID_GLSL + STATE_GLSL + /* glsl */` |
| +добавлено | uniform mat4 viewMatrix; |
| +добавлено | uniform mat4 projectionMatrix; |
| +добавлено | uniform float uShutter; // s of motion stretch |
| +добавлено | in vec3 position; |
| +добавлено | out vec2 vQ; |
| +добавлено | flat out float vHalfL; |
| +добавлено | flat out float vR; |
| +добавлено | flat out float vCz; |
| +добавлено | flat out float vZHalf; |
| +добавлено | flat out float vDom; |
| +добавлено | flat out float vAir; |
| +добавлено | flat out float vThick; |
| +добавлено | flat out float vFlat; |
| +добавлено | void main() { |
| +добавлено | gl_Position = vec4(2.0, 2.0, 2.0, 1.0); |
| +добавлено | ivec2 t = texelOf(gl_InstanceID); |
| +добавлено | vec4 s0 = texelFetch(uS0, t, 0), s2 = texelFetch(uS2, t, 0); |
| +добавлено | if (s0.w >= s2.x || !tagLive(s2.y)) return; |
| +добавлено | int d = tagDomain(s2.y); |
| +добавлено | vec4 s1 = texelFetch(uS1, t, 0); |
| +добавлено | vec4 S = uDomS[d]; |
| +добавлено | // lone airborne particles are droplets (drawn as spray, DROP_VERT), thin water shrinks |
| +добавлено | float iso = s2.w > 0.5 ? 1.0 : smoothstep(0.05, 0.12, s2.z); |
| +добавлено | if (iso <= 0.0) return; |
| +добавлено | // water spread thin on the floor is a film, not beads: its particles grow into flat discs that |
| +добавлено | // overlap (same volume: thinner), so a draining puddle stays one sheet instead of scattered drops |
| +добавлено | float film = s2.w * (1.0 - smoothstep(0.25, 0.7, s2.z)); |
| +добавлено | float k = 1.0 + 1.1 * film; |
| +добавлено | float r = S.y * k * mix(0.5, 1.0, max(smoothstep(0.12, 0.5, s2.z), film)) * iso * smoothstep(0.0, 0.05, s0.w + 0.01) * min(1.0, (s2.x - s0.w) * 3.0 + 0.2); |
| +добавлено | vec4 vc = viewMatrix * vec4(s0.xyz, 1.0); |
| +добавлено | if (-vc.z < 0.2 + r) return; |
| +добавлено | vec3 vv = mat3(viewMatrix) * s1.xyz * uShutter; |
| +добавлено | float L = length(vv.xy); |
| +добавлено | vec2 ax = L > 1e-6 ? vv.xy / L : vec2(1.0, 0.0); |
| +добавлено | float Lc = min(L, 4.0 * r); |
| +добавлено | vHalfL = 0.5 * Lc; |
| +добавлено | vZHalf = L > 1e-6 ? 0.5 * vv.z * Lc / L : 0.0; |
| +добавлено | vec2 q = vec2(position.x * (vHalfL + r), position.y * r); |
| +добавлено | vec3 pv = vec3(vc.xy + ax * q.x + vec2(-ax.y, ax.x) * q.y, vc.z + abs(vZHalf) + r); |
| +добавлено | gl_Position = projectionMatrix * vec4(pv, 1.0); |
| +добавлено | vQ = q; vR = r; vCz = vc.z; vDom = float(d); vAir = s1.w; vThick = S.z / (k * k * k); vFlat = 1.0 - 0.7 * film; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const SPRITE_FRAG_HEAD = HEAD + /* glsl */` |
| +добавлено | in vec2 vQ; |
| +добавлено | flat in float vHalfL; |
| +добавлено | flat in float vR; |
| +добавлено | flat in float vCz; |
| +добавлено | flat in float vZHalf; |
| +добавлено | flat in float vDom; |
| +добавлено | flat in float vAir; |
| +добавлено | flat in float vThick; |
| +добавлено | flat in float vFlat; |
| +добавлено | float spriteD2() { float ux = max(abs(vQ.x) - vHalfL, 0.0); return (ux * ux + vQ.y * vQ.y) / (vR * vR); } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | export const DEPTH_VERT = SPRITE_VERT; |
| +добавлено | export const DEPTH_FRAG = SPRITE_FRAG_HEAD + /* glsl */` |
| +добавлено | uniform mat4 projectionMatrix; |
| +добавлено | out vec4 o; |
| +добавлено | void main() { |
| +добавлено | float d2 = spriteD2(); |
| +добавлено | if (d2 > 1.0) discard; |
| +добавлено | float along = vHalfL > 0.0 ? clamp(vQ.x / vHalfL, -1.0, 1.0) : 0.0; |
| +добавлено | float z = vCz + along * vZHalf + vR * vFlat * sqrt(1.0 - d2); |
| +добавлено | o = vec4(-z, vDom, 0.0, 0.0); |
| +добавлено | vec4 c = projectionMatrix * vec4(0.0, 0.0, z, 1.0); |
| +добавлено | gl_FragDepth = c.z / c.w * 0.5 + 0.5; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export const THICK_FRAG = SPRITE_FRAG_HEAD + /* glsl */` |
| +добавлено | out vec4 o; |
| +добавлено | void main() { |
| +добавлено | float d2 = spriteD2(); |
| +добавлено | if (d2 > 1.0) discard; |
| +добавлено | float th = 2.0 * vR * sqrt(1.0 - d2) * vThick; |
| +добавлено | o = vec4(th, th * vAir, 0.0, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // Narrow-range filter (Truong & Yuksel 2018), separable: taps behind the range are clamped to |
| +добавлено | // its back (which also rounds the silhouettes), taps in front of it are ignored. |
| +добавлено | export const SMOOTH_FRAG = HEAD + /* glsl */` |
| +добавлено | uniform highp sampler2D uZ; |
| +добавлено | uniform vec2 uDir; |
| +добавлено | uniform float uPxScale; // half-res pixels per metre at 1 m |
| +добавлено | uniform float uWorldR; // filter radius (m) |
| +добавлено | uniform float uRange; // depth range (m) |
| +добавлено | out vec4 o; |
| +добавлено | void main() { |
| +добавлено | ivec2 p = ivec2(gl_FragCoord.xy); |
| +добавлено | float z = texelFetch(uZ, p, 0).r; |
| +добавлено | if (z <= 0.0) { o = vec4(0.0); return; } |
| +добавлено | float rpx = clamp(uWorldR * uPxScale / z, 1.0, 24.0); |
| +добавлено | float stepPx = max(1.0, rpx / 8.0); |
| +добавлено | float inv2s2 = 1.0 / (0.5 * rpx * rpx); |
| +добавлено | float lim = z + uRange, lo = z - uRange; |
| +добавлено | ivec2 m = textureSize(uZ, 0) - 1; |
| +добавлено | float sum = z, ws = 1.0; |
| +добавлено | for (int i = 1; i <= 8; i++) { |
| +добавлено | float o_ = float(i) * stepPx; |
| +добавлено | if (o_ > rpx) break; |
| +добавлено | float w = exp(-o_ * o_ * inv2s2); |
| +добавлено | ivec2 dp = ivec2(uDir * o_); |
| +добавлено | float a = texelFetch(uZ, clamp(p + dp, ivec2(0), m), 0).r; |
| +добавлено | float b = texelFetch(uZ, clamp(p - dp, ivec2(0), m), 0).r; |
| +добавлено | a = a <= 0.0 ? lim : min(a, lim); |
| +добавлено | b = b <= 0.0 ? lim : min(b, lim); |
| +добавлено | if (a >= lo) { sum += a * w; ws += w; } |
| +добавлено | if (b >= lo) { sum += b * w; ws += w; } |
| +добавлено | } |
| +добавлено | o = vec4(sum / ws, 0.0, 0.0, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // view-space normal from the smoothed depth (the one-sided difference with the smaller jump) |
| +добавлено | export const NORMAL_FRAG = HEAD + /* glsl */` |
| +добавлено | uniform highp sampler2D uZ; |
| +добавлено | uniform vec2 uProj; // projection [0][0], [1][1] |
| +добавлено | out vec4 o; |
| +добавлено | vec3 viewPos(ivec2 p, float z, vec2 size) { |
| +добавлено | vec2 ndc = (vec2(p) + 0.5) / size * 2.0 - 1.0; |
| +добавлено | return vec3(ndc.x * z / uProj.x, ndc.y * z / uProj.y, -z); |
| +добавлено | } |
| +добавлено | void main() { |
| +добавлено | ivec2 p = ivec2(gl_FragCoord.xy); |
| +добавлено | float z = texelFetch(uZ, p, 0).r; |
| +добавлено | if (z <= 0.0) { o = vec4(0.0); return; } |
| +добавлено | vec2 size = vec2(textureSize(uZ, 0)); |
| +добавлено | ivec2 m = ivec2(size) - 1; |
| +добавлено | vec3 P = viewPos(p, z, size); |
| +добавлено | float zr = texelFetch(uZ, min(p + ivec2(1, 0), m), 0).r, zl = texelFetch(uZ, max(p - ivec2(1, 0), ivec2(0)), 0).r; |
| +добавлено | float zu = texelFetch(uZ, min(p + ivec2(0, 1), m), 0).r, zd = texelFetch(uZ, max(p - ivec2(0, 1), ivec2(0)), 0).r; |
| +добавлено | bool useR = zr > 0.0 && (zl <= 0.0 || abs(zr - z) < abs(zl - z)); |
| +добавлено | bool useU = zu > 0.0 && (zd <= 0.0 || abs(zu - z) < abs(zd - z)); |
| +добавлено | vec3 dx = useR ? viewPos(p + ivec2(1, 0), zr, size) - P : (zl > 0.0 ? P - viewPos(p - ivec2(1, 0), zl, size) : vec3(1.0, 0.0, 0.0)); |
| +добавлено | vec3 dy = useU ? viewPos(p + ivec2(0, 1), zu, size) - P : (zd > 0.0 ? P - viewPos(p - ivec2(0, 1), zd, size) : vec3(0.0, 1.0, 0.0)); |
| +добавлено | vec3 nrm = normalize(cross(dx, dy)); |
| +добавлено | if (nrm.z < 0.0) nrm = -nrm; |
| +добавлено | o = vec4(nrm, z); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- composite (refract pass, full res): Ultra Water's surface shading on the SSF surface ---- |
| +добавлено | // (github.com/Humpalumps/Ultra-Water, MIT): depth-validated refraction, Beer-Lambert absorption, |
| +добавлено | // in-scatter + Atlas-style SSS on thin sheets, roughness-aware Fresnel (Lagarde), GGX sun with |
| +добавлено | // the alpha floor, foam lit as in OceanSurface (here: aeration of the churned body). |
| +добавлено | export const COMPOSITE_VERT = /* glsl */` |
| +добавлено | uniform vec4 uRect; // NDC min xy, max xy |
| +добавлено | void main() { gl_Position = vec4(mix(uRect.xy, uRect.zw, position.xy * 0.5 + 0.5), 0.0, 1.0); }`; |
| +добавлено | |
| +добавлено | export const COMPOSITE_FRAG = /* glsl */` |
| +добавлено | #define MAXD ${MAXD} |
| +добавлено | uniform highp sampler2D uNZ; // half res: view normal, linear depth (0 = empty) |
| +добавлено | uniform highp sampler2D uThick; // half res: thickness (m), thickness x air |
| +добавлено | uniform highp sampler2D uDomTex; // half res raw depth: depth, domain |
| +добавлено | uniform vec2 uSsf; // half-res size |
| +добавлено | uniform mat4 uCamWorld; |
| +добавлено | uniform vec2 uProj; |
| +добавлено | uniform vec4 uLook0[MAXD]; // absorption (1/m), roughness |
| +добавлено | uniform vec4 uLook1[MAXD]; // scatter albedo, refraction strength |
| +добавлено | uniform vec4 uLook2[MAXD]; // emission (HDR), aeration amount |
| +добавлено | uniform vec4 uLook3[MAXD]; // foam tint, SSS strength |
| +добавлено | uniform sampler2D uFoamTex; |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform vec3 uAmbient; |
| +добавлено | ${COMMON_GLSL} |
| +добавлено | ${NOISE_GLSL} |
| +добавлено | ${WORLD_GLSL} |
| +добавлено | ${LIGHTS_GLSL} |
| +добавлено | ${REFRACT_GLSL} |
| +добавлено | out vec4 fragColor; |
| +добавлено | void main() { |
| +добавлено | vec2 uv = gl_FragCoord.xy / uResolution; |
| +добавлено | vec2 hp = uv * uSsf - 0.5; |
| +добавлено | ivec2 b = ivec2(floor(hp)); |
| +добавлено | vec2 fr = hp - vec2(b); |
| +добавлено | ivec2 m = ivec2(uSsf) - 1; |
| +добавлено | vec4 t0 = texelFetch(uNZ, clamp(b, ivec2(0), m), 0), t1 = texelFetch(uNZ, clamp(b + ivec2(1, 0), ivec2(0), m), 0); |
| +добавлено | vec4 t2 = texelFetch(uNZ, clamp(b + ivec2(0, 1), ivec2(0), m), 0), t3 = texelFetch(uNZ, clamp(b + ivec2(1, 1), ivec2(0), m), 0); |
| +добавлено | vec4 w = vec4((1.0 - fr.x) * (1.0 - fr.y), fr.x * (1.0 - fr.y), (1.0 - fr.x) * fr.y, fr.x * fr.y); |
| +добавлено | vec4 valid = vec4(step(1e-6, t0.w), step(1e-6, t1.w), step(1e-6, t2.w), step(1e-6, t3.w)); |
| +добавлено | float cov = dot(w, valid); |
| +добавлено | if (cov < 0.3) discard; |
| +добавлено | // nearest surface wins across depth edges (a droplet in front of the column) |
| +добавлено | float zmin = min(min(t0.w > 0.0 ? t0.w : 1e9, t1.w > 0.0 ? t1.w : 1e9), min(t2.w > 0.0 ? t2.w : 1e9, t3.w > 0.0 ? t3.w : 1e9)); |
| +добавлено | vec4 near = valid * step(vec4(t0.w, t1.w, t2.w, t3.w), vec4(zmin + 0.12 + 0.02 * zmin)); |
| +добавлено | vec4 ww = w * near; |
| +добавлено | ww /= max(dot(ww, vec4(1.0)), 1e-5); |
| +добавлено | vec4 nz = t0 * ww.x + t1 * ww.y + t2 * ww.z + t3 * ww.w; |
| +добавлено | float z = nz.w; |
| +добавлено | // the opaque scene in front hides it (the hardware depth test does the per-sample edge) |
| +добавлено | float sceneZ = linearDepth(texelFetch(uSceneDepth, ivec2(gl_FragCoord.xy), 0).r); |
| +добавлено | if (z > sceneZ + 0.05) discard; |
| +добавлено | vec2 ndc = uv * 2.0 - 1.0; |
| +добавлено | vec3 Pv = vec3(ndc.x * z / uProj.x, ndc.y * z / uProj.y, -z); |
| +добавлено | vec3 Pw = (uCamWorld * vec4(Pv, 1.0)).xyz; |
| +добавлено | vec3 N = normalize((uCamWorld * vec4(normalize(nz.xyz), 0.0)).xyz); |
| +добавлено | ivec2 nb = clamp(ivec2(floor(uv * uSsf)), ivec2(0), m); |
| +добавлено | int d = int(texelFetch(uDomTex, nb, 0).g + 0.5); |
| +добавлено | vec4 L0 = uLook0[d], L1 = uLook1[d], L2 = uLook2[d], L3 = uLook3[d]; |
| +добавлено | vec2 th = texture(uThick, uv).rg; |
| +добавлено | float air = clamp(th.y / max(th.x, 1e-4), 0.0, 1.0); |
| +добавлено | vec3 V = normalize(cameraPosition - Pw); |
| +добавлено | // a film spread on the floor is flat (gravity and surface tension level it within a second), not |
| +добавлено | // the union of its particles' discs: level its normal, and no light comes up through the floor |
| +добавлено | float film = (1.0 - smoothstep(0.05, 0.2, Pw.y)) * (1.0 - smoothstep(0.06, 0.25, th.x)); |
| +добавлено | N = normalize(mix(N, vec3(0.0, 1.0, 0.0), 0.9 * film)); |
| +добавлено | // capillary ripples riding the flow: the surface never reads as polished glass |
| +добавлено | vec3 rip = curl3(Pw * 0.55 + vec3(0.0, uTime * 0.35, 0.0)) + 0.5 * curl3(Pw * 1.7 - vec3(uTime * 0.5, 0.0, 0.0)); |
| +добавлено | N = normalize(N + (rip - N * dot(rip, N)) * (0.07 + 0.12 * air) * (1.0 - 0.6 * film)); |
| +добавлено | float NoV = max(dot(N, V), 1e-3); |
| +добавлено | float rough = L0.w + 0.12 * air; |
| +добавлено | |
| +добавлено | // --- refraction + absorption (depth validated, as Refraction.js / the pool) ---------------- |
| +добавлено | float behind; |
| +добавлено | vec3 refr = sceneRefract(Pw, N, V, 1.33, th.x * L1.w + 0.03, behind); |
| +добавлено | float path = min(th.x, behind * 1.15 + 0.01); |
| +добавлено | vec3 T = exp(-L0.rgb * path); |
| +добавлено | // caustics: light focused by the water on whatever it lies on |
| +добавлено | float cz = linearDepth(texelFetch(uSceneDepth, ivec2(gl_FragCoord.xy), 0).r); |
| +добавлено | vec3 floorP = cameraPosition - V * (cz / max(dot(-V, (uCamWorld * vec4(0.0, 0.0, -1.0, 0.0)).xyz), 0.05)); |
| +добавлено | vec2 cq = floorP.xz * 4.0 + N.xz * 3.0; |
| +добавлено | vec2 cw = cq + vec2(sin(cq.y * 1.3 + uTime * 1.7), cos(cq.x * 1.1 - uTime * 1.4)); |
| +добавлено | float caus = pow(1.0 - abs(sin(cw.x) * sin(cw.y)), 6.0); |
| +добавлено | refr *= 1.0 + caus * 1.6 * smoothstep(0.02, 0.15, path) * exp(-path * 2.0) * max(uSunDir.y, 0.0) * step(floorP.y, 0.08); |
| +добавлено | |
| +добавлено | vec3 sun = uSunColor; |
| +добавлено | vec3 amb = uAmbient * 1.5; |
| +добавлено | float NoL = dot(N, uSunDir); |
| +добавлено | vec3 inscatter = L1.rgb * (amb + sun * max(uSunDir.y, 0.0) * 0.5); |
| +добавлено | // Atlas-style SSS (UW): sun through thin sheets and crests, strongest looking into it |
| +добавлено | float thin = 1.0 - smoothstep(0.02, 0.45, path); |
| +добавлено | float into = pow(clamp(dot(uSunDir, -V), 0.0, 1.0), 4.0); |
| +добавлено | float k1 = L3.w * thin * into * pow(0.5 - 0.5 * NoL, 3.0) * 6.0 * (1.0 - film); |
| +добавлено | float k2 = 0.06 * NoV * NoV; |
| +добавлено | vec3 sss = ((k1 + k2) * sun + 0.05 * max(NoL, 0.0) * sun) * L1.rgb * 8.0; |
| +добавлено | vec3 body = refr * T + (inscatter + sss) * (1.0 - T) + sss * thin * 0.5 * (1.0 - film); |
| +добавлено | |
| +добавлено | // aeration: churned water is a white scattering medium (UW's foam lighting, billows from its |
| +добавлено | // foam texture so it reads as froth, not paint) |
| +добавлено | vec4 ft = texture(uFoamTex, Pw.xz * 0.35 + Pw.y * 0.21 + vec2(0.0, uTime * 0.05)); |
| +добавлено | float milk = (1.0 - exp(-air * path * 6.0)) * L2.w; |
| +добавлено | milk *= mix(0.55, 1.15, ft.r); |
| +добавлено | milk = clamp(milk, 0.0, 1.0); |
| +добавлено | vec3 sd, ss; |
| +добавлено | gLightNoShadow = true; |
| +добавлено | spellLightPBR(Pw, N, V, max(rough, 0.05), vec3(0.02), vec3(0.9) * milk, sd, ss); |
| +добавлено | float ao = mix(0.55, 1.0, smoothstep(0.15, 0.75, ft.g)); |
| +добавлено | vec3 foamLit = mix(L3.rgb, vec3(0.95), milk) * (sun * (0.15 + 0.85 * clamp(NoL * 0.8 + 0.2, 0.0, 1.0)) * mix(ao, 1.0, 0.4) + amb * 1.4 * ao); |
| +добавлено | foamLit += sun * into * 0.4 * (1.0 - milk); |
| +добавлено | body = mix(body, foamLit, milk) + sd; |
| +добавлено | |
| +добавлено | // Fresnel with roughness-aware F90 (Lagarde), sky reflection, GGX sun with an alpha floor |
| +добавлено | float F = fresnelRough(NoV, 0.02, rough); |
| +добавлено | vec3 R = reflect(-V, N); |
| +добавлено | vec3 refl = envReflect(R, rough); |
| +добавлено | float aS = max(rough * rough, 0.012); |
| +добавлено | vec3 H = normalize(uSunDir + V); |
| +добавлено | float nl = max(NoL, 0.0); |
| +добавлено | vec3 spec = sun * (PI * spellD_GGX(max(dot(N, H), 0.0), aS) * spellV_Smith(NoV, nl, aS) * nl * fresnel(max(dot(V, H), 0.0), 0.02)) + ss; |
| +добавлено | vec3 col = mix(body, refl, F * (1.0 - 0.6 * milk)) + spec * (1.0 - 0.5 * milk) + L2.rgb * (1.0 - T.g); |
| +добавлено | // soft edge: the bilinear half-res coverage, rounded by the (smooth) summed thickness |
| +добавлено | fragColor = vec4(col, smoothstep(0.32, 0.62, cov) * smoothstep(0.002, 0.012, th.x)); |
| +добавлено | vec4 cp = projectionMatrix * vec4(Pv, 1.0); |
| +добавлено | gl_FragDepth = cp.z / cp.w * 0.5 + 0.5; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- whitewater sprites (fx pass, WBOIT); the same for the fluid's own torn-off droplets ----- |
| +добавлено | const whiteVert = () => FX_VERT_HEAD + COMMON_GLSL + NOISE_GLSL + ARENA_GLSL + LIGHTS_GLSL + GRID_GLSL + /* glsl */` |
| +добавлено | uniform highp sampler2D uW0; |
| +добавлено | uniform highp sampler2D uW1; |
| +добавлено | uniform highp sampler2D uW2; |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform vec3 uAmbient; |
| +добавлено | uniform vec4 uWhiteLook; // size scale, opacity, -, - |
| +добавлено | out vec2 vUv; |
| +добавлено | out vec3 vLit; |
| +добавлено | out float vAlpha; |
| +добавлено | out float vViewZ; |
| +добавлено | out float vKind; |
| +добавлено | out float vSeed; |
| +добавлено | out float vStretch; |
| +добавлено | out vec2 vFoamUv; |
| +добавлено | void main() { |
| +добавлено | gl_Position = vec4(2.0, 2.0, 2.0, 1.0); |
| +добавлено | vAlpha = 0.0; |
| +добавлено | ivec2 t = ivec2(gl_InstanceID % ${PW}, gl_InstanceID / ${PW}); |
| +добавлено | vec4 w0 = texelFetch(uW0, t, 0), w1 = texelFetch(uW1, t, 0), w2 = texelFetch(uW2, t, 0); |
| +добавлено | if (w0.w >= w1.w || !tagLive(w2.x)) return; |
| +добавлено | vec3 P = w0.xyz, Vel = w1.xyz; |
| +добавлено | float age = w0.w / w1.w, dens = w2.y, seed = w2.z, amt = 1.0; |
| +добавлено | // foam only lies on a surface near the floor; in the air the same churn is just more spray |
| +добавлено | float kind = (dens < 0.2 || length(Vel) > 6.0 || (dens < 0.7 && P.y > 0.35)) ? 0.0 : dens < 0.7 ? 1.0 : 2.0; |
| +добавлено | float size = kind < 0.5 ? 0.0018 + 0.0028 * seed : kind < 1.5 ? (0.05 + 0.08 * seed) * (0.7 + 0.6 * age) : 0.006 + 0.006 * seed; |
| +добавлено | size *= uWhiteLook.x; |
| +добавлено | vec3 cv = (viewMatrix * vec4(P, 1.0)).xyz; |
| +добавлено | float viewZ = -cv.z; |
| +добавлено | if (viewZ < 0.3) return; |
| +добавлено | // at least ~1.2 half-res pixels wide; keep the energy (Humus' phone-wire AA) |
| +добавлено | float px = 2.0 * viewZ / (projectionMatrix[1][1] * uFxResolution.y); |
| +добавлено | float wdt = max(size, 1.2 * px), aa = size / wdt; |
| +добавлено | // a 1/60 s exposure: spray streaks, foam barely |
| +добавлено | vec3 vv = mat3(viewMatrix) * Vel * (kind < 0.5 ? 0.004 : 0.003); |
| +добавлено | float L = min(length(vv.xy), 40.0 * wdt); |
| +добавлено | vec2 ax = length(vv.xy) > 1e-6 ? normalize(vv.xy) : vec2(1.0, 0.0); |
| +добавлено | vec2 q = ax * position.x * (wdt + 0.5 * L) + vec2(-ax.y, ax.x) * position.y * wdt; |
| +добавлено | vFoamUv = P.xz; |
| +добавлено | if (kind > 0.5 && kind < 1.5) { |
| +добавлено | // foam lies on the water: a flat patch on it (edge-on from a low camera, as real lace is), its |
| +добавлено | // lace from one world-space texture so overlapping patches join into one sheet of foam |
| +добавлено | vec3 corner = P + vec3(position.x, 0.0, -position.y) * size * 1.6; // counter-clockwise from above |
| +добавлено | vFoamUv = corner.xz; |
| +добавлено | cv = (viewMatrix * vec4(corner, 1.0)).xyz; |
| +добавлено | q = vec2(0.0); |
| +добавлено | } |
| +добавлено | // foam and bubbles sit at the surface: pull them in front of it (the composite wrote its depth) |
| +добавлено | cv.z += kind > 0.5 ? 0.06 + size : 0.0; |
| +добавлено | gl_Position = projectionMatrix * vec4(cv + vec3(q, 0.0), 1.0); |
| +добавлено | vUv = position.xy; |
| +добавлено | vStretch = (kind > 0.5 && kind < 1.5) ? 0.0 : L / (L + 2.0 * wdt); |
| +добавлено | vViewZ = viewZ; |
| +добавлено | vKind = kind; |
| +добавлено | vSeed = seed; |
| +добавлено | vec3 v = normalize(cameraPosition - P); |
| +добавлено | gLightNoShadow = true; |
| +добавлено | // droplets scatter forward (UW's spray billboard); foam is a white diffuse surface |
| +добавлено | float ph = hgPhase(dot(uSunDir, -v), 0.6); |
| +добавлено | vec3 lit = kind < 0.5 ? 0.9 * (uSunColor * (0.25 + 1.6 * ph) + uAmbient * 1.4) |
| +добавлено | : 0.92 * (uSunColor * (0.3 + 0.7 * max(uSunDir.y, 0.0)) + uAmbient * 2.2); |
| +добавлено | vLit = lit + spellLightScatter(P, v, 0.3) * 0.6; |
| +добавлено | float fade = smoothstep(0.0, 0.06, age) * (1.0 - smoothstep(0.55, 1.0, age)); |
| +добавлено | // a streak spreads its light over its length |
| +добавлено | float smear = (2.0 * wdt) / (L + 2.0 * wdt); |
| +добавлено | vAlpha = (kind < 0.5 ? 0.55 * mix(1.0, smear, 0.6) : kind < 1.5 ? 0.85 : 0.35) * amt * fade * aa * uWhiteLook.y * smoothstep(0.3, 0.9, viewZ); |
| +добавлено | }`; |
| +добавлено | export const WHITE_VERT = whiteVert(); |
| +добавлено | |
| +добавлено | // --- beads: a droplet is a small lens. Instanced quads in the refract pass, full res, shaded as a |
| +добавлено | // sphere of water: sky mirrored on the skin, the world seen upside down through it, a pin-sharp sun |
| +добавлено | // glint. Ligaments are the same thing stretched along their velocity. Used by the fluid's lone |
| +добавлено | // particles (BEAD_VERT) and by water.js's stateless stream droplets (place with BEAD_PLACE_GLSL). |
| +добавлено | export const BEAD_PLACE_GLSL = /* glsl */` |
| +добавлено | out vec2 vUv; |
| +добавлено | out vec3 vP; |
| +добавлено | flat out vec2 vAx; |
| +добавлено | flat out float vStretch; |
| +добавлено | flat out float vAlpha; |
| +добавлено | flat out float vRad; |
| +добавлено | // amt: 0..1 fade, lig: extra length (m) while it is still a ligament |
| +добавлено | void placeBead(vec3 P, vec3 Vel, float size, float amt, float lig) { |
| +добавлено | vec3 cv = (viewMatrix * vec4(P, 1.0)).xyz; |
| +добавлено | float viewZ = -cv.z; |
| +добавлено | if (viewZ < 0.3) return; |
| +добавлено | float px = 2.0 * viewZ / (projectionMatrix[1][1] * uResolution.y); |
| +добавлено | float w = max(size, 0.8 * px), aa = size / w; |
| +добавлено | // a fast shutter (1/400 s): beads, not matchsticks |
| +добавлено | vec3 vv = mat3(viewMatrix) * Vel * 0.0025; |
| +добавлено | float lv = length(vv.xy), L = min(lv + lig, 16.0 * w); |
| +добавлено | vec2 ax = lv > 1e-6 ? vv.xy / lv : vec2(1.0, 0.0); |
| +добавлено | vec2 q = ax * position.x * (w + 0.5 * L) + vec2(-ax.y, ax.x) * position.y * w; |
| +добавлено | gl_Position = projectionMatrix * vec4(cv + vec3(q, 0.0), 1.0); |
| +добавлено | vUv = position.xy; |
| +добавлено | vP = P; |
| +добавлено | vAx = ax; |
| +добавлено | vStretch = L / (L + 2.0 * w); |
| +добавлено | vRad = w / px; // radius (full-res pixels) |
| +добавлено | vAlpha = amt * mix(0.3, 1.0, aa) * smoothstep(0.3, 0.8, viewZ); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | export const BEAD_VERT = COMMON_GLSL + GRID_GLSL + STATE_GLSL + BEAD_PLACE_GLSL + /* glsl */` |
| +добавлено | void main() { |
| +добавлено | gl_Position = vec4(2.0, 2.0, 2.0, 1.0); |
| +добавлено | vAlpha = 0.0; |
| +добавлено | ivec2 t = texelOf(gl_InstanceID); |
| +добавлено | // a lone airborne fluid particle is a droplet, not surface |
| +добавлено | vec4 s0 = texelFetch(uS0, t, 0), s2 = texelFetch(uS2, t, 0); |
| +добавлено | if (s0.w >= s2.x || !tagLive(s2.y) || s2.w > 0.5) return; |
| +добавлено | float amt = 1.0 - smoothstep(0.05, 0.12, s2.z); |
| +добавлено | if (amt <= 0.0) return; |
| +добавлено | float seed = hash12(vec2(t) + 0.5); |
| +добавлено | float size = uDomS[tagDomain(s2.y)].x * mix(0.12, 0.42, seed * seed); |
| +добавлено | placeBead(s0.xyz, texelFetch(uS1, t, 0).xyz, size, amt * smoothstep(0.0, 0.03, s0.w) * min(1.0, (s2.x - s0.w) * 4.0), 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export const BEAD_FRAG = COMMON_GLSL + REFRACT_GLSL + /* glsl */` |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform vec3 uAmbient; |
| +добавлено | in vec2 vUv; |
| +добавлено | in vec3 vP; |
| +добавлено | flat in vec2 vAx; |
| +добавлено | flat in float vStretch; |
| +добавлено | flat in float vAlpha; |
| +добавлено | flat in float vRad; |
| +добавлено | out vec4 fragColor; |
| +добавлено | void main() { |
| +добавлено | if (vAlpha <= 0.002) discard; |
| +добавлено | // the capsule's cross section: x beyond the stretched body are the round ends |
| +добавлено | float qx = sign(vUv.x) * max(abs(vUv.x) - vStretch, 0.0) / max(1.0 - vStretch, 1e-3); |
| +добавлено | float r2 = qx * qx + vUv.y * vUv.y; |
| +добавлено | if (r2 >= 1.0) discard; |
| +добавлено | vec3 nv = vec3(vAx * qx + vec2(-vAx.y, vAx.x) * vUv.y, sqrt(1.0 - r2)); |
| +добавлено | vec3 N = transpose(mat3(viewMatrix)) * nv; |
| +добавлено | vec3 V = normalize(cameraPosition - vP); |
| +добавлено | float F = fresnel(nv.z, 0.02); |
| +добавлено | vec3 refl = envReflect(reflect(-V, N), 0.08); |
| +добавлено | // through the sphere: in, out the far side (exit normal n + rd * chord), so the world is inverted |
| +добавлено | vec3 rd = refract(-V, N, 1.0 / 1.33); |
| +добавлено | vec3 n2 = normalize(N - 2.0 * rd * dot(rd, N)); |
| +добавлено | vec3 od = refract(rd, -n2, 1.33); |
| +добавлено | if (dot(od, od) < 1e-4) od = reflect(rd, -n2); |
| +добавлено | // what is behind it, upside down, plus a little of the wider world it gathers from |
| +добавлено | vec2 uv = (gl_FragCoord.xy - nv.xy * vRad * 5.0) / uResolution; |
| +добавлено | vec3 through = mix(textureLod(uSceneColor, clamp(uv, vec2(0.001), vec2(0.999)), 0.0).rgb, envReflect(od, 0.14), 0.2); |
| +добавлено | vec3 H = normalize(uSunDir + V); |
| +добавлено | float glint = pow(max(dot(N, H), 0.0), 700.0) * 26.0 * step(0.0, uSunDir.y); |
| +добавлено | // a drop is full of internal reflections: it scatters the sun strongly forward and the sky all |
| +добавлено | // round, so in footage spray reads as bright points, never as holes. (The scene behind is the |
| +добавлено | // opaque one: a bead over the fluid surface must not show the floor under the water.) |
| +добавлено | float ph = hgPhase(dot(uSunDir, -V), 0.75); |
| +добавлено | vec3 lit = uSunColor * (0.1 + 1.4 * ph) + uAmbient * 0.35; |
| +добавлено | fragColor = vec4(mix(through, refl, F) * 0.8 + lit + uSunColor * glint, vAlpha * (1.0 - smoothstep(0.75, 1.0, r2))); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export const WHITE_SPRITE_FRAG = FX_FRAG_HEAD + COMMON_GLSL + FX_OUT_GLSL + /* glsl */` |
| +добавлено | uniform sampler2D uFoamTex; |
| +добавлено | in vec2 vUv; |
| +добавлено | in vec3 vLit; |
| +добавлено | in float vAlpha; |
| +добавлено | in float vViewZ; |
| +добавлено | in float vKind; |
| +добавлено | in float vSeed; |
| +добавлено | in float vStretch; |
| +добавлено | in vec2 vFoamUv; |
| +добавлено | void main() { |
| +добавлено | if (vAlpha <= 0.002) discard; |
| +добавлено | float x = abs(vUv.x), ends = 1.0 - vStretch; |
| +добавлено | float dx = max(x - vStretch, 0.0) / max(ends, 1e-3); |
| +добавлено | float r2 = dx * dx + vUv.y * vUv.y; |
| +добавлено | if (r2 >= 1.0) discard; |
| +добавлено | float a = vAlpha; |
| +добавлено | if (vKind > 0.5 && vKind < 1.5) { |
| +добавлено | // foam: UW's lace/billow texture in world space, so neighbouring patches make one sheet |
| +добавлено | // (lace cells a few cm across, so a patch shows lace, not a white coin) |
| +добавлено | vec4 ft = texture(uFoamTex, vFoamUv * 1.6); |
| +добавлено | a *= smoothstep(1.0, 0.3, r2) * smoothstep(0.45, 0.8, ft.r * 0.75 + ft.g * 0.45); |
| +добавлено | } else a *= exp(-2.5 * r2); |
| +добавлено | fxOut(vLit, a, vec3(0.0), vec2(0.0), vViewZ); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- ground paint: fluid touching the floor wets it (GroundField particle paint) -------------- |
| +добавлено | export const PAINT_VERT = HEAD + GRID_GLSL + STATE_GLSL + GROUND_GLSL + /* glsl */` |
| +добавлено | uniform vec4 uPaintA[MAXD]; // per-step increments: heat, char, wet, frost |
| +добавлено | uniform vec4 uPaintB[MAXD]; // crack, acid, corruption, glow |
| +добавлено | uniform float uTexelsPerM; |
| +добавлено | out vec4 vA; |
| +добавлено | out vec4 vB; |
| +добавлено | void main() { |
| +добавлено | gl_Position = vec4(2.0, 2.0, 2.0, 1.0); |
| +добавлено | gl_PointSize = 1.0; |
| +добавлено | vA = vB = vec4(0.0); |
| +добавлено | ivec2 t = texelOf(gl_VertexID); |
| +добавлено | vec4 s0 = texelFetch(uS0, t, 0), s2 = texelFetch(uS2, t, 0); |
| +добавлено | if (s0.w >= s2.x || !tagLive(s2.y) || s2.w < 0.5 || s0.y > 0.25) return; |
| +добавлено | int d = tagDomain(s2.y); |
| +добавлено | vec2 uv = groundUV(s0.xz); |
| +добавлено | gl_Position = vec4(uv * 2.0 - 1.0, 0.0, 1.0); |
| +добавлено | gl_PointSize = clamp(2.0 * uDomS[d].y * uTexelsPerM, 1.0, 8.0); |
| +добавлено | vec4 g = groundA(s0.xz), gb = groundB(s0.xz); |
| +добавлено | vA = uPaintA[d] * max(1.0 - g, 0.0); |
| +добавлено | vB = uPaintB[d] * max(1.0 - gb, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export const PAINT_FRAG = HEAD + PAINT_FRAG_HEAD + /* glsl */` |
| +добавлено | in vec4 vA; |
| +добавлено | in vec4 vB; |
| +добавлено | void main() { |
| +добавлено | float f = 1.0 - length(gl_PointCoord * 2.0 - 1.0); |
| +добавлено | if (f <= 0.0) discard; |
| +добавлено | gA = vA * f; gB = vB * f; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // Ultra Water's foam texture (bakeTextures.js, MIT): R lace, G billow height, BA its gradient |
| +добавлено | export const FOAM_BAKE_FRAG = HEAD + /* glsl */` |
| +добавлено | uniform vec2 uSize; |
| +добавлено | out vec4 outColor; |
| +добавлено | vec2 hash22(vec2 p) { |
| +добавлено | vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); |
| +добавлено | p3 += dot(p3, p3.yzx + 33.33); |
| +добавлено | return fract((p3.xx + p3.yz) * p3.zy); |
| +добавлено | } |
| +добавлено | vec2 voronoi(vec2 p, float period) { |
| +добавлено | vec2 i = floor(p), f = fract(p); |
| +добавлено | float f1 = 8.0, f2 = 8.0; |
| +добавлено | for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) { |
| +добавлено | vec2 g = vec2(x, y); |
| +добавлено | vec2 o = hash22(mod(i + g, period)); |
| +добавлено | float d = length(g + o - f); |
| +добавлено | if (d < f1) { f2 = f1; f1 = d; } else if (d < f2) f2 = d; |
| +добавлено | } |
| +добавлено | return vec2(f1, f2); |
| +добавлено | } |
| +добавлено | float billow(vec2 uv) { |
| +добавлено | vec2 a = voronoi(uv * 7.0 + 0.3, 7.0), b = voronoi(uv * 17.0 + 0.7, 17.0), c = voronoi(uv * 41.0 + 0.1, 41.0); |
| +добавлено | return 0.5 * sqrt(clamp((a.y - a.x) * 2.2, 0.0, 1.0)) + 0.32 * sqrt(clamp((b.y - b.x) * 2.2, 0.0, 1.0)) |
| +добавлено | + 0.18 * sqrt(clamp((c.y - c.x) * 2.2, 0.0, 1.0)); |
| +добавлено | } |
| +добавлено | void main() { |
| +добавлено | vec2 vUv = gl_FragCoord.xy / uSize; |
| +добавлено | vec2 a = voronoi(vUv * 9.0, 9.0); |
| +добавлено | vec2 b = voronoi(vUv * 23.0 + 0.5, 23.0); |
| +добавлено | vec2 c = voronoi(vUv * 61.0, 61.0); |
| +добавлено | float lace = 1.0 - smoothstep(0.0, 0.22, a.y - a.x); |
| +добавлено | float fine = 1.0 - smoothstep(0.0, 0.16, b.y - b.x); |
| +добавлено | float bubbles = smoothstep(0.55, 0.15, c.x); |
| +добавлено | float v = lace * 0.55 + fine * 0.3 + bubbles * 0.25 + (1.0 - a.x) * 0.25; |
| +добавлено | float e = 1.0 / uSize.x; |
| +добавлено | vec2 g = vec2(billow(vUv + vec2(e, 0.0)) - billow(vUv - vec2(e, 0.0)), billow(vUv + vec2(0.0, e)) - billow(vUv - vec2(0.0, e))) / (2.0 * e); |
| +добавлено | outColor = vec4(clamp(v * 0.85, 0.0, 1.0), billow(vUv), clamp(0.5 + g / 64.0, 0.0, 1.0)); |
| +добавлено | }`; |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { U, FX_BLENDING } from './common.js'; |
| +добавлено | import { PAINT_BLENDING } from './GroundField.js'; |
| +добавлено | import { Q } from '../engine/quality.js'; |
| +добавлено | import { |
| +добавлено | MAXD, MAX_REC, PW, FULL_VERT, P2G_VERT, P2G_FRAG, MARK_FRAG, DIV_FRAG, JACOBI_FRAG, PROJECT_FRAG, ADVECT_FRAG, WHITE_FRAG, |
| +добавлено | DEPTH_VERT, DEPTH_FRAG, THICK_FRAG, SMOOTH_FRAG, NORMAL_FRAG, COMPOSITE_VERT, COMPOSITE_FRAG, WHITE_VERT, BEAD_VERT, BEAD_FRAG, WHITE_SPRITE_FRAG, |
| +добавлено | PAINT_VERT, PAINT_FRAG, FOAM_BAKE_FRAG, |
| +добавлено | } from './ParticleFluid.glsl.js'; |
| +добавлено | |
| +добавлено | // Shared GPU particle fluid (water, acid; Tsunami / rain later): FLIP in local box domains, |
| +добавлено | // drawn as a screen-space fluid surface with Ihmsen-style whitewater. |
| +добавлено | // |
| +добавлено | // Simulation (one step per frame, all on the GPU, nothing read back): |
| +добавлено | // - particles: RGBA32F textures, 256 wide, Q.fluidParticles of them (low 8k, medium 16k, |
| +добавлено | // high 32k, ultra 64k), one ring buffer for every domain: an emission overwrites the oldest |
| +добавлено | // slots, so a full pool recycles old puddle water first. S0 pos/age, S1 vel/air, S2 life, |
| +добавлено | // tag (domain + generation), grid density, floor contact |
| +добавлено | // - grid: per domain a yaw-rotated box of cubic MAC cells, packed into a 2D atlas (z-slices |
| +добавлено | // as tiles). Cell size from the box volume and the tier's cell budget (high ~130k cells, |
| +добавлено | // ~0.13 m for a 300 m^3 box); particle spacing h / 2 (8 per cell) |
| +добавлено | // - step: P2G (points, additive, trilinear over 3x3x3 texels via 3 instanced slices) -> |
| +добавлено | // normalise + mark (arena SDF: floor, rim, capsule occluders = solid) -> divergence with |
| +добавлено | // gravity and a density drift term -> Jacobi (warm-started) -> subtract gradient -> G2P |
| +добавлено | // FLIP/PIC blend + RK2 advection, wind/vortex forces (FORCES_GLSL), SDF collision with a |
| +добавлено | // midpoint check against tunnelling, emission and death in the same pass. Outside the grid |
| +добавлено | // (but inside the life box) particles fly ballistic |
| +добавлено | // - whitewater (Ihmsen et al. 2012): dead slots of a second pool sample random fluid |
| +добавлено | // particles and spawn where they carry trapped air (aeration from FLIP/PIC disagreement, |
| +добавлено | // impacts, speed); classified by the fluid density round them as spray, foam or bubbles |
| +добавлено | // Rendering (van der Laan, Green & Sainz 2009; Truong & Yuksel 2018): |
| +добавлено | // - half res: velocity-stretched sphere sprites -> nearest linear depth (+ domain id) and |
| +добавлено | // additive thickness (+ thickness x air), two separable narrow-range filter iterations, |
| +добавлено | // view normals |
| +добавлено | // - full res composite in fx.scenes.refract over the domains' screen rect: depth-tested |
| +добавлено | // against the scene (writes gl_FragDepth), refraction + Beer-Lambert, Ultra Water's shading |
| +добавлено | // (github.com/Humpalumps/Ultra-Water, MIT): in-scatter, Atlas-style SSS through thin sheets, |
| +добавлено | // Lagarde Fresnel, sky reflection, GGX sun, aeration lit like UW's foam with its baked |
| +добавлено | // foam texture, caustics on what the water lies on, spell lights |
| +добавлено | // - whitewater sprites in the half-res FX pass (WBOIT); floor contact paints the ground field |
| +добавлено | // through GroundField's particle paint (no splat budget used) |
| +добавлено | // |
| +добавлено | // API (main does not construct it: a spell does, once: fx.water ??= new ParticleFluid(fx), |
| +добавлено | // then fx.systems.push(fx.water); main calls update(dt, camera) every frame): |
| +добавлено | // const h = fx.water.acquire({ size: [x, y, z] (m; x along yaw), position (floor centre of the |
| +добавлено | // box), yaw (rad, local x = (cos, 0, sin)), preset: 'water' | 'acid', margin, life }) |
| +добавлено | // -> handle, or null when all MAXD domains are taken |
| +добавлено | // h.position / h.yaw move or turn it any frame (the grid is rebuilt every step) |
| +добавлено | // h.jet(pos, dir, speed, radius, dt, air = 0, swirl = 0, spread = 0.03, radial = 0) |
| +добавлено | // this frame's slice of a continuous jet (call every frame); spread |
| +добавлено | // = random velocity (m/s), radial = divergence (m/s at the rim) |
| +добавлено | // h.burst(pos, radius, vel, volume, spread = 0.3, radial = 0, air = 0) a ball of water |
| +добавлено | // h.hold(pos, radius, pull, swirl) / h.hold(null) keep water gathered at pos (weightless) |
| +добавлено | // h.launch(vel) throw what is held (next step), then the hold lets go |
| +добавлено | // look: h.tint + h.clarity (water preset derives absorption / scatter from them; call |
| +добавлено | // h.tintWater() after changing), h.absorption, h.scatter (Vector3), h.roughness, |
| +добавлено | // h.refraction, h.emission (Vector3, HDR), h.aeration (white churn 0..1+), h.foamTint, h.sss |
| +добавлено | // behaviour: h.flip (FLIP ratio), h.wind (force response), h.drain (1/s, puddles soak away), |
| +добавлено | // h.foam (whitewater amount), h.life (s), h.margin (m), h.paintA / h.paintB (ground field |
| +добавлено | // increments per step: heat, char, wet, frost / crack, acid, corruption, glow) |
| +добавлено | // h.spacing, h.h particle spacing and cell size (m), read only |
| +добавлено | // h.release() frees the domain; its particles and whitewater die at once |
| +добавлено | // Profiling: set fx.water.timer = app.timer to split the 'sim' timer into 'fluid sim' and 'ssf' |
| +добавлено | // (fx.water.fine = true: per pass). |
| +добавлено | |
| +добавлено | const TIERS = { |
| +добавлено | low: { n: 8192, cells: 45000, region: [256, 224], iters: 8 }, |
| +добавлено | medium: { n: 16384, cells: 80000, region: [384, 256], iters: 10 }, |
| +добавлено | high: { n: 32768, cells: 130000, region: [512, 320], iters: 12 }, |
| +добавлено | ultra: { n: 65536, cells: 200000, region: [512, 480], iters: 18 }, |
| +добавлено | }; |
| +добавлено | const PPC = 8; // particles per cell at rest |
| +добавлено | const REC_W = 5; // texels per emission record |
| +добавлено | const RADIUS_K = 1.3; // render radius / spacing |
| +добавлено | const SHUTTER = 1 / 110; // motion stretch (s) |
| +добавлено | const absorb = (x) => -Math.log(Math.max(x, 0.03)) * 0.4 + 0.02; // as water.js: tint -> 1/m |
| +добавлено | |
| +добавлено | const _v = new THREE.Vector3(), _c = new THREE.Color(); |
| +добавлено | const QUAD = [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]; |
| +добавлено | |
| +добавлено | // Ultra Water's baked foam texture (bakeTextures.js, MIT: R lace, G billow height, BA its gradient), |
| +добавлено | // baked once per page and shared by every water surface (fluid, streams, Tsunami), all tiers |
| +добавлено | let foamRT = null; |
| +добавлено | export function foamTexture(renderer) { |
| +добавлено | if (foamRT) return foamRT.texture; |
| +добавлено | // 1024: a breaking wave fills a close camera, and at 256 its lace lines magnify into texel blocks |
| +добавлено | foamRT = new THREE.WebGLRenderTarget(1024, 1024, { |
| +добавлено | wrapS: THREE.RepeatWrapping, wrapT: THREE.RepeatWrapping, minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | generateMipmaps: true, depthBuffer: false, |
| +добавлено | }); |
| +добавлено | const g = new THREE.BufferGeometry(); |
| +добавлено | g.setAttribute('position', new THREE.Float32BufferAttribute([-1, -1, 0, 3, -1, 0, -1, 3, 0], 3)); |
| +добавлено | const m = new THREE.Mesh(g, new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: FULL_VERT, fragmentShader: FOAM_BAKE_FRAG, uniforms: { uSize: { value: new THREE.Vector2(1024, 1024) } }, depthTest: false, depthWrite: false, |
| +добавлено | })); |
| +добавлено | m.frustumCulled = false; |
| +добавлено | const prev = renderer.getRenderTarget(); |
| +добавлено | renderer.setRenderTarget(foamRT); |
| +добавлено | renderer.render(m, new THREE.Camera()); |
| +добавлено | renderer.setRenderTarget(prev); |
| +добавлено | g.dispose(); m.material.dispose(); |
| +добавлено | return foamRT.texture; |
| +добавлено | } |
| +добавлено | |
| +добавлено | class FluidHandle { |
| +добавлено | constructor(sys, index) { |
| +добавлено | this.sys = sys; this.index = index; this.active = false; this.gen = 0; |
| +добавлено | this.position = new THREE.Vector3(); this.yaw = 0; this.size = new THREE.Vector3(4, 4, 4); |
| +добавлено | this.h = 0.1; this.spacing = 0.05; this.n = [8, 8, 8]; this.tpr = 1; |
| +добавлено | this.tint = new THREE.Color(); this.clarity = 1; |
| +добавлено | this.absorption = new THREE.Vector3(); this.scatter = new THREE.Vector3(); this.emission = new THREE.Vector3(); |
| +добавлено | this.foamTint = new THREE.Color(); this.paintA = new THREE.Vector4(); this.paintB = new THREE.Vector4(); |
| +добавлено | this.holdPos = new THREE.Vector3(); this.holdOn = false; this.holdR = 0.3; this.pull = 6; this.swirl = 4; |
| +добавлено | this.launchVel = new THREE.Vector3(); this.launching = false; this.thrown = 9; |
| +добавлено | this.acc = 0; |
| +добавлено | this.reset('water'); |
| +добавлено | } |
| +добавлено | |
| +добавлено | reset(preset) { |
| +добавлено | this.flip = 0.96; this.wind = 1; this.drain = 0; this.foam = 1; this.life = 9; this.margin = 1.5; |
| +добавлено | this.roughness = 0.035; this.refraction = 0.6; this.aeration = 1; this.sss = 1; |
| +добавлено | this.emission.set(0, 0, 0); this.paintA.set(0, 0, 0.035, 0); this.paintB.set(0, 0, 0, 0); |
| +добавлено | this.holdOn = false; this.launching = false; this.acc = 0; |
| +добавлено | if (preset === 'acid') { |
| +добавлено | this.tint.set('#7dff3a'); this.clarity = 1; |
| +добавлено | this.absorption.set(11, 2.5, 27); this.scatter.set(0.05, 0.1, 0.004); |
| +добавлено | this.emission.set(0.06, 0.45, 0.02); this.foamTint.setRGB(0.7, 0.95, 0.4); |
| +добавлено | this.paintA.set(0, 0, 0.01, 0); this.paintB.set(0, 0.03, 0, 0); this.roughness = 0.07; |
| +добавлено | } else { |
| +добавлено | this.tint.set('#2fa8ff'); this.clarity = 1; this.foamTint.setRGB(0.62, 0.78, 0.82); |
| +добавлено | this.tintWater(); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // absorption / scatter from tint + clarity (the founding water's mapping) |
| +добавлено | tintWater() { |
| +добавлено | const t = this.tint; |
| +добавлено | this.absorption.set(absorb(t.r), absorb(t.g), absorb(t.b)).multiplyScalar(1 / Math.max(this.clarity, 0.05)); |
| +добавлено | _c.copy(t).lerp(_c.setRGB(1, 1, 1), 0.5); |
| +добавлено | this.scatter.set(_c.r, _c.g, _c.b).multiplyScalar(0.03 + 0.04 / Math.max(this.clarity, 0.2)); |
| +добавлено | return this; |
| +добавлено | } |
| +добавлено | |
| +добавлено | jet(pos, dir, speed, radius, dt, air = 0, swirl = 0, spread = 0.03, radial = 0) { |
| +добавлено | if (!this.active || dt <= 0) return; |
| +добавлено | const s = this.spacing; |
| +добавлено | this.acc += Math.PI * radius * radius * speed * dt / (s * s * s); |
| +добавлено | const n = Math.floor(this.acc); |
| +добавлено | if (n <= 0) return; |
| +добавлено | this.acc -= n; |
| +добавлено | this.sys.record(this, 0, n, pos, radius, dir, speed, speed * dt, spread, radial, air, swirl); |
| +добавлено | } |
| +добавлено | |
| +добавлено | burst(pos, radius, vel, volume, spread = 0.3, radial = 0, air = 0) { |
| +добавлено | if (!this.active) return; |
| +добавлено | const s = this.spacing, n = Math.round(volume / (s * s * s)); |
| +добавлено | if (n <= 0) return; |
| +добавлено | const sp = vel.length(); |
| +добавлено | _v.copy(vel); |
| +добавлено | if (sp < 1e-6) _v.set(0, 1, 0); |
| +добавлено | this.sys.record(this, 1, n, pos, radius, _v, sp, 0, spread, radial, air, 0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | hold(pos, radius = 0.3, pull = 6, swirl = 4) { |
| +добавлено | this.holdOn = !!pos; |
| +добавлено | if (pos) { this.holdPos.copy(pos); this.holdR = radius; this.pull = pull; this.swirl = swirl; } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // throws what is held with vel (+ its spread about the centre) next step, then lets go |
| +добавлено | launch(vel) { this.launchVel.copy(vel); this.launching = true; } |
| +добавлено | |
| +добавлено | release() { |
| +добавлено | if (!this.active) return; |
| +добавлено | this.active = false; this.holdOn = false; this.launching = false; |
| +добавлено | this.sys.released = true; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export class ParticleFluid { |
| +добавлено | constructor(fx) { |
| +добавлено | this.fx = fx; |
| +добавлено | const r = this.renderer = fx.renderer; |
| +добавлено | const T = TIERS[Q.tier] ?? TIERS.high; |
| +добавлено | this.N = Q.fluidParticles ?? T.n; |
| +добавлено | this.PH = Math.ceil(this.N / PW); |
| +добавлено | this.ND = Math.max(PW, this.N >> 1); |
| +добавлено | this.WH = Math.ceil(this.ND / PW); |
| +добавлено | this.cells = T.cells; this.region = T.region; this.iters = T.iters; |
| +добавлено | this.AW = T.region[0]; this.AH = T.region[1] * MAXD; |
| +добавлено | this.timer = null; |
| +добавлено | this.released = false; |
| +добавлено | this.cursor = 0; |
| +добавлено | this.recCount = 0; |
| +добавлено | this.emitted = 0; |
| +добавлено | |
| +добавлено | // --- shared uniforms --- |
| +добавлено | const v4s = () => Array.from({ length: MAXD }, () => new THREE.Vector4()); |
| +добавлено | const su = this.su = { |
| +добавлено | uDomO: { value: v4s() }, uDomN: { value: v4s().map((v) => v.set(1, 1, 1, 1)) }, uDomR: { value: v4s() }, |
| +добавлено | uDomS: { value: v4s() }, uDomF: { value: v4s() }, |
| +добавлено | uAtlas: { value: new THREE.Vector2(this.AW, this.AH) }, uRegionH: { value: T.region[1] }, |
| +добавлено | uS0: { value: null }, uS1: { value: null }, uS2: { value: null }, |
| +добавлено | uW0: { value: null }, uW1: { value: null }, uW2: { value: null }, |
| +добавлено | uVn: { value: null }, uDV: { value: null }, uD: { value: null }, |
| +добавлено | uSimDt: { value: 1 / 60 }, uGdt: { value: 9.81 / 60 }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // --- targets --- |
| +добавлено | const mrt = (w, h, count, type, filter = THREE.NearestFilter, format = THREE.RGBAFormat) => new THREE.WebGLRenderTarget(w, h, { |
| +добавлено | type, format, count, minFilter: filter, magFilter: filter, depthBuffer: false, generateMipmaps: false, |
| +добавлено | }); |
| +добавлено | this.state = [mrt(PW, this.PH, 3, THREE.FloatType), mrt(PW, this.PH, 3, THREE.FloatType)]; |
| +добавлено | this.white = [mrt(PW, this.WH, 3, THREE.FloatType), mrt(PW, this.WH, 3, THREE.FloatType)]; |
| +добавлено | this.cur = 0; this.wcur = 0; |
| +добавлено | const H16 = THREE.HalfFloatType, F32 = THREE.FloatType; |
| +добавлено | this.acc = mrt(this.AW, this.AH, 2, H16); |
| +добавлено | this.V = mrt(this.AW, this.AH, 1, H16); |
| +добавлено | this.D = mrt(this.AW, this.AH, 1, H16, THREE.LinearFilter); |
| +добавлено | this.P = [mrt(this.AW, this.AH, 1, F32, THREE.NearestFilter, THREE.RedFormat), mrt(this.AW, this.AH, 1, F32, THREE.NearestFilter, THREE.RedFormat)]; |
| +добавлено | this.pCur = 0; |
| +добавлено | this.proj = mrt(this.AW, this.AH, 2, H16, THREE.LinearFilter); |
| +добавлено | su.uVn.value = this.proj.textures[0]; su.uDV.value = this.proj.textures[1]; su.uD.value = this.D.texture; |
| +добавлено | // screen-space fluid, half res (sized on first update) |
| +добавлено | this.ssf = new THREE.Vector2(1, 1); |
| +добавлено | this.depthRT = new THREE.WebGLRenderTarget(1, 1, { type: F32, format: THREE.RGFormat, minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, depthBuffer: true, generateMipmaps: false }); |
| +добавлено | this.thickRT = mrt(1, 1, 1, H16, THREE.LinearFilter, THREE.RGFormat); |
| +добавлено | this.smooth = [mrt(1, 1, 1, F32, THREE.NearestFilter, THREE.RedFormat), mrt(1, 1, 1, F32, THREE.NearestFilter, THREE.RedFormat)]; |
| +добавлено | this.nrmRT = mrt(1, 1, 1, F32); |
| +добавлено | this.ssfTargets = [this.depthRT, this.thickRT, ...this.smooth, this.nrmRT]; |
| +добавлено | this._rect = new Float64Array(5); |
| +добавлено | |
| +добавлено | // emission records |
| +добавлено | this.emitData = new Float32Array(REC_W * MAX_REC * 4); |
| +добавлено | this.emitTex = new THREE.DataTexture(this.emitData, REC_W, MAX_REC, THREE.RGBAFormat, THREE.FloatType); |
| +добавлено | this.emitTex.magFilter = this.emitTex.minFilter = THREE.NearestFilter; |
| +добавлено | this.spans = Array.from({ length: 4 }, () => new THREE.Vector2()); |
| +добавлено | this.firstStart = -1; |
| +добавлено | |
| +добавлено | // --- passes --- |
| +добавлено | this.cam = new THREE.Camera(); |
| +добавлено | const tri = new THREE.BufferGeometry(); |
| +добавлено | tri.setAttribute('position', new THREE.Float32BufferAttribute([-1, -1, 0, 3, -1, 0, -1, 3, 0], 3)); |
| +добавлено | tri.boundingSphere = new THREE.Sphere(); |
| +добавлено | const raw = (frag, uniforms, extra = {}) => new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: FULL_VERT, fragmentShader: frag, uniforms, depthTest: false, depthWrite: false, ...extra, |
| +добавлено | }); |
| +добавлено | const quad = (mat) => { const m = new THREE.Mesh(tri, mat); m.frustumCulled = false; return m; }; |
| +добавлено | this.markQ = quad(raw(MARK_FRAG, { ...U, ...su, uAccA: { value: this.acc.textures[0] }, uAccB: { value: this.acc.textures[1] }, uFluidThresh: { value: 0.3 } })); |
| +добавлено | this.divQ = quad(raw(DIV_FRAG, { ...su, uV: { value: this.V.texture }, uAccA: { value: this.acc.textures[0] }, uPPC: { value: PPC } })); |
| +добавлено | this.jacU = { uP: { value: null }, uDc: { value: this.D.texture }, uFirst: { value: 0 } }; |
| +добавлено | this.jacQ = quad(raw(JACOBI_FRAG, { ...su, ...this.jacU })); |
| +добавлено | this.projU = { uV: { value: this.V.texture }, uP: { value: null } }; |
| +добавлено | this.projQ = quad(raw(PROJECT_FRAG, { ...su, ...this.projU })); |
| +добавлено | this.holdU = { uHold: { value: v4s() }, uHoldB: { value: v4s() }, uLaunch: { value: v4s() } }; |
| +добавлено | this.advU = { uEmit: { value: this.emitTex }, uEmitCount: { value: 0 }, uSpan: { value: this.spans }, uSpanCount: { value: 0 } }; |
| +добавлено | this.advQ = quad(raw(ADVECT_FRAG, { ...U, ...su, ...this.holdU, ...this.advU })); |
| +добавлено | this.whiteU = { uFluidN: { value: this.N }, uWhiteRate: { value: 7 } }; |
| +добавлено | this.whiteQ = quad(raw(WHITE_FRAG, { ...U, ...su, ...this.whiteU })); |
| +добавлено | |
| +добавлено | // P2G: N points x 3 slice instances |
| +добавлено | const pg = new THREE.InstancedBufferGeometry(); |
| +добавлено | pg.setAttribute('position', new THREE.BufferAttribute(new Float32Array(this.N), 1)); |
| +добавлено | pg.instanceCount = 3; |
| +добавлено | pg.boundingSphere = new THREE.Sphere(); |
| +добавлено | this.p2g = new THREE.Points(pg, new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: P2G_VERT, fragmentShader: P2G_FRAG, uniforms: su, |
| +добавлено | depthTest: false, depthWrite: false, transparent: true, |
| +добавлено | blending: THREE.CustomBlending, blendEquation: THREE.AddEquation, blendSrc: THREE.OneFactor, blendDst: THREE.OneFactor, |
| +добавлено | blendEquationAlpha: THREE.AddEquation, blendSrcAlpha: THREE.OneFactor, blendDstAlpha: THREE.OneFactor, |
| +добавлено | })); |
| +добавлено | this.p2g.frustumCulled = false; |
| +добавлено | |
| +добавлено | // SSF sprites |
| +добавлено | const sprites = (n) => { |
| +добавлено | const g = new THREE.InstancedBufferGeometry(); |
| +добавлено | g.setAttribute('position', new THREE.Float32BufferAttribute(QUAD, 3)); |
| +добавлено | g.setIndex([0, 1, 2, 0, 2, 3]); |
| +добавлено | g.instanceCount = n; |
| +добавлено | g.boundingSphere = new THREE.Sphere(); |
| +добавлено | return g; |
| +добавлено | }; |
| +добавлено | const spriteU = { ...su, uShutter: { value: SHUTTER } }; |
| +добавлено | this.depthMesh = new THREE.Mesh(sprites(this.N), new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: DEPTH_VERT, fragmentShader: DEPTH_FRAG, uniforms: spriteU, depthTest: true, depthWrite: true, |
| +добавлено | })); |
| +добавлено | this.thickMesh = new THREE.Mesh(sprites(this.N), new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: DEPTH_VERT, fragmentShader: THICK_FRAG, uniforms: spriteU, depthTest: false, depthWrite: false, |
| +добавлено | transparent: true, blending: THREE.CustomBlending, blendEquation: THREE.AddEquation, blendSrc: THREE.OneFactor, blendDst: THREE.OneFactor, |
| +добавлено | })); |
| +добавлено | for (const m of [this.depthMesh, this.thickMesh]) m.frustumCulled = false; |
| +добавлено | this.smU = { uZ: { value: null }, uDir: { value: new THREE.Vector2(1, 0) }, uPxScale: { value: 100 }, uWorldR: { value: 0.12 }, uRange: { value: 0.1 } }; |
| +добавлено | this.smQ = quad(raw(SMOOTH_FRAG, this.smU)); |
| +добавлено | this.nrmU = { uZ: { value: null }, uProj: { value: new THREE.Vector2(1, 1) } }; |
| +добавлено | this.nrmQ = quad(raw(NORMAL_FRAG, this.nrmU)); |
| +добавлено | |
| +добавлено | // UW's foam texture |
| +добавлено | const foamTex = foamTexture(r); |
| +добавлено | |
| +добавлено | // composite (refract pass, full res) |
| +добавлено | const lk = () => ({ value: v4s() }); |
| +добавлено | this.look = { uLook0: lk(), uLook1: lk(), uLook2: lk(), uLook3: lk() }; |
| +добавлено | this.compU = { |
| +добавлено | ...U, ...this.look, |
| +добавлено | uRect: { value: new THREE.Vector4(-1, -1, 1, 1) }, uNZ: { value: this.nrmRT.texture }, uThick: { value: this.thickRT.texture }, |
| +добавлено | uDomTex: { value: this.depthRT.texture }, uSsf: { value: this.ssf }, uCamWorld: { value: new THREE.Matrix4() }, |
| +добавлено | uProj: { value: this.nrmU.uProj.value }, uFoamTex: { value: foamTex }, |
| +добавлено | }; |
| +добавлено | const cg = new THREE.PlaneGeometry(2, 2); |
| +добавлено | this.composite = new THREE.Mesh(cg, new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: COMPOSITE_VERT, fragmentShader: COMPOSITE_FRAG, uniforms: this.compU, |
| +добавлено | transparent: true, depthTest: true, depthWrite: true, |
| +добавлено | blending: THREE.CustomBlending, blendEquation: THREE.AddEquation, blendSrc: THREE.SrcAlphaFactor, blendDst: THREE.OneMinusSrcAlphaFactor, |
| +добавлено | blendEquationAlpha: THREE.AddEquation, blendSrcAlpha: THREE.ZeroFactor, blendDstAlpha: THREE.OneFactor, |
| +добавлено | })); |
| +добавлено | this.composite.frustumCulled = false; |
| +добавлено | this.composite.visible = false; |
| +добавлено | fx.scenes.refract.add(this.composite); |
| +добавлено | |
| +добавлено | // whitewater sprites (fx pass) |
| +добавлено | this.whiteLook = new THREE.Vector4(1, 1, 0, 0); |
| +добавлено | this.whiteMesh = new THREE.Mesh(sprites(this.ND), new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: WHITE_VERT, fragmentShader: WHITE_SPRITE_FRAG, |
| +добавлено | uniforms: { ...U, ...su, uWhiteLook: { value: this.whiteLook }, uFoamTex: { value: foamTex } }, ...FX_BLENDING, |
| +добавлено | })); |
| +добавлено | this.whiteMesh.frustumCulled = false; |
| +добавлено | this.whiteMesh.visible = false; |
| +добавлено | fx.scenes.fx.add(this.whiteMesh); |
| +добавлено | // the fluid's own lone droplets: lens beads (refract pass, full res, after the surface) |
| +добавлено | this.dropMesh = new THREE.Mesh(sprites(this.N), new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: BEAD_VERT, fragmentShader: BEAD_FRAG, uniforms: { ...U, ...su }, |
| +добавлено | transparent: true, depthWrite: false, |
| +добавлено | blending: THREE.CustomBlending, blendEquation: THREE.AddEquation, blendSrc: THREE.SrcAlphaFactor, blendDst: THREE.OneMinusSrcAlphaFactor, |
| +добавлено | blendEquationAlpha: THREE.AddEquation, blendSrcAlpha: THREE.ZeroFactor, blendDstAlpha: THREE.OneFactor, |
| +добавлено | })); |
| +добавлено | this.dropMesh.frustumCulled = false; |
| +добавлено | this.dropMesh.visible = false; |
| +добавлено | this.dropMesh.renderOrder = 3; |
| +добавлено | fx.scenes.refract.add(this.dropMesh); |
| +добавлено | |
| +добавлено | // ground paint (GroundField particle paint) |
| +добавлено | this.paintU = { uPaintA: { value: v4s() }, uPaintB: { value: v4s() } }; |
| +добавлено | const ground = fx.ground; |
| +добавлено | if (ground?.paintScene) { |
| +добавлено | const g = new THREE.BufferGeometry(); |
| +добавлено | g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(this.N), 1)); |
| +добавлено | g.boundingSphere = new THREE.Sphere(); |
| +добавлено | this.paint = new THREE.Points(g, new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: PAINT_VERT, fragmentShader: PAINT_FRAG, |
| +добавлено | uniforms: { ...su, ...this.paintU, uGroundA: U.uGroundA, uGroundB: U.uGroundB, uGroundRect: U.uGroundRect, uTexelsPerM: { value: ground.size / U.uGroundRect.value.z } }, |
| +добавлено | ...PAINT_BLENDING, |
| +добавлено | })); |
| +добавлено | this.paint.frustumCulled = false; |
| +добавлено | this.paint.visible = false; |
| +добавлено | ground.paintScene.add(this.paint); |
| +добавлено | } |
| +добавлено | |
| +добавлено | this.handles = Array.from({ length: MAXD }, (_, i) => new FluidHandle(this, i)); |
| +добавлено | this.clear(); |
| +добавлено | this.warm(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- handles --------------------------------------------------------------------------- |
| +добавлено | acquire({ size = [4, 4, 4], position = null, yaw = 0, preset = 'water', margin = 1.5, life = 9 } = {}) { |
| +добавлено | let h = null; |
| +добавлено | for (const x of this.handles) if (!x.active) { h = x; break; } |
| +добавлено | if (!h) return null; |
| +добавлено | h.reset(preset); |
| +добавлено | h.active = true; |
| +добавлено | h.gen = (h.gen + 1) % 1000; |
| +добавлено | h.size.fromArray(size); |
| +добавлено | if (position) h.position.copy(position); |
| +добавлено | h.yaw = yaw; h.margin = margin; h.life = life; |
| +добавлено | this.fit(h); |
| +добавлено | // stale pressure from the region's last tenant would warm-start the solve wrong |
| +добавлено | const r = this.renderer, prev = r.getRenderTarget(); |
| +добавлено | for (const p of this.P) { r.setRenderTarget(p); r.setClearColor(0x000000, 0); r.clear(true, false, false); } |
| +добавлено | r.setRenderTarget(prev); |
| +добавлено | return h; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // cell size so the box fits the tier's cell budget and the atlas region |
| +добавлено | fit(h) { |
| +добавлено | const [RW, RH] = this.region, s = h.size; |
| +добавлено | let c = Math.cbrt(s.x * s.y * s.z / this.cells); |
| +добавлено | for (let i = 0; i < 400; i++) { |
| +добавлено | const nx = Math.max(4, Math.ceil(s.x / c)), ny = Math.max(4, Math.ceil(s.y / c) + 1), nz = Math.max(4, Math.ceil(s.z / c)); |
| +добавлено | const tpr = Math.floor(RW / (nx + 1)); |
| +добавлено | if (tpr >= 1 && Math.ceil((nz + 1) / tpr) * (ny + 1) <= RH) { |
| +добавлено | h.h = c; h.n[0] = nx; h.n[1] = ny; h.n[2] = nz; h.tpr = tpr; |
| +добавлено | h.spacing = c / Math.cbrt(PPC); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | c *= 1.015; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // an emission record (wraps the ring into two when needed); returns false over budget |
| +добавлено | record(h, type, n, pos, radius, dir, speed, len, spread, radial, air, swirl) { |
| +добавлено | const budget = Math.max(256, this.N >> 3); |
| +добавлено | n = Math.min(n, budget - this.emitted, this.N); |
| +добавлено | if (n <= 0) return false; |
| +добавлено | this.emitted += n; |
| +добавлено | const seed = this.fx.rand(); // deterministic with the cast seed |
| +добавлено | let start = this.cursor; |
| +добавлено | while (n > 0 && this.recCount < MAX_REC) { |
| +добавлено | const take = Math.min(n, this.N - start), o = this.recCount * REC_W * 4, D = this.emitData; |
| +добавлено | if (this.firstStart < 0) this.firstStart = start; |
| +добавлено | D[o] = start; D[o + 1] = take; D[o + 2] = h.index + MAXD * h.gen; D[o + 3] = type; |
| +добавлено | D[o + 4] = pos.x; D[o + 5] = pos.y; D[o + 6] = pos.z; D[o + 7] = radius; |
| +добавлено | D[o + 8] = dir.x; D[o + 9] = dir.y; D[o + 10] = dir.z; D[o + 11] = speed; |
| +добавлено | D[o + 12] = len; D[o + 13] = spread; D[o + 14] = radial; D[o + 15] = seed; |
| +добавлено | D[o + 16] = h.life; D[o + 17] = air; D[o + 18] = swirl; D[o + 19] = 0; |
| +добавлено | this.recCount++; |
| +добавлено | start = (start + take) % this.N; |
| +добавлено | n -= take; |
| +добавлено | } |
| +добавлено | this.cursor = start; |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- frame ------------------------------------------------------------------------------ |
| +добавлено | update(dt, camera) { |
| +добавлено | let live = 0; |
| +добавлено | for (const h of this.handles) if (h.active) live++; |
| +добавлено | if (!live && !this.released) { |
| +добавлено | this.composite.visible = this.whiteMesh.visible = this.dropMesh.visible = false; |
| +добавлено | if (this.paint) this.paint.visible = false; |
| +добавлено | this.recCount = 0; this.emitted = 0; this.firstStart = -1; |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | this.pack(dt); |
| +добавлено | const r = this.renderer, prevRT = r.getRenderTarget(); |
| +добавлено | r.getClearColor(_c); |
| +добавлено | const prevAlpha = r.getClearAlpha(); |
| +добавлено | r.setClearColor(0x000000, 0); |
| +добавлено | if (dt > 0 || this.released) { this.timer?.begin('fluid sim'); this.step(Math.min(Math.max(dt, 1e-4), 1 / 30)); } |
| +добавлено | this.released = false; |
| +добавлено | for (const h of this.handles) { |
| +добавлено | h.thrown += dt; |
| +добавлено | if (h.launching) { h.launching = false; h.holdOn = false; h.thrown = 0; } |
| +добавлено | } |
| +добавлено | this.recCount = 0; this.emitted = 0; this.firstStart = -1; |
| +добавлено | if (live) { this.timer?.begin('ssf'); this.render(camera); } |
| +добавлено | r.setRenderTarget(prevRT); |
| +добавлено | r.setClearColor(_c, prevAlpha); |
| +добавлено | this.composite.visible = this.whiteMesh.visible = this.dropMesh.visible = live > 0; |
| +добавлено | if (this.paint) this.paint.visible = live > 0; |
| +добавлено | } |
| +добавлено | |
| +добавлено | pack(dt) { |
| +добавлено | const su = this.su, d = Math.max(dt, 1 / 240); |
| +добавлено | let any = false; |
| +добавлено | for (const h of this.handles) { |
| +добавлено | const i = h.index; |
| +добавлено | const O = su.uDomO.value[i], N = su.uDomN.value[i], R = su.uDomR.value[i], S = su.uDomS.value[i], F = su.uDomF.value[i]; |
| +добавлено | if (!h.active) { R.z = 0; continue; } |
| +добавлено | any = true; |
| +добавлено | const c = Math.cos(h.yaw), s = Math.sin(h.yaw), hh = h.h, [nx, ny, nz] = h.n; |
| +добавлено | // cell (0,0,0) corner: the box centred on position, one cell row under the floor |
| +добавлено | const lx = nx * hh / 2, ly = hh, lz = nz * hh / 2; |
| +добавлено | O.set(h.position.x - (lx * c - lz * s), h.position.y - ly, h.position.z - (lx * s + lz * c), hh); |
| +добавлено | N.set(nx, ny, nz, h.tpr); |
| +добавлено | R.set(c, s, h.gen + 1, h.margin); |
| +добавлено | const rr = h.spacing * RADIUS_K; |
| +добавлено | S.set(h.spacing, rr, h.spacing ** 3 / (4.19 * rr ** 3), 0.2 * hh / d); |
| +добавлено | F.set(h.flip, h.wind, h.drain, h.foam); |
| +добавлено | const H = this.holdU; |
| +добавлено | H.uHold.value[i].set(h.holdPos.x, h.holdPos.y, h.holdPos.z, h.holdOn ? h.pull : 0); |
| +добавлено | H.uHoldB.value[i].set(h.holdR, h.swirl, 0, 0); |
| +добавлено | H.uLaunch.value[i].set(h.launchVel.x, h.launchVel.y, h.launchVel.z, h.launching ? 1 : 0); |
| +добавлено | const L = this.look; |
| +добавлено | L.uLook0.value[i].set(h.absorption.x, h.absorption.y, h.absorption.z, h.roughness); |
| +добавлено | L.uLook1.value[i].set(h.scatter.x, h.scatter.y, h.scatter.z, h.refraction); |
| +добавлено | L.uLook2.value[i].set(h.emission.x, h.emission.y, h.emission.z, h.aeration); |
| +добавлено | L.uLook3.value[i].set(h.foamTint.r, h.foamTint.g, h.foamTint.b, h.sss); |
| +добавлено | this.paintU.uPaintA.value[i].copy(h.paintA); |
| +добавлено | this.paintU.uPaintB.value[i].copy(h.paintB); |
| +добавлено | // the ground field only accepts paint where it is stepped |
| +добавлено | this.fx.ground?.touch?.(h.position.x, h.position.z, 0.5 * Math.hypot(h.size.x, h.size.z) + h.margin, 0.5); |
| +добавлено | } |
| +добавлено | return any; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // grid passes only over the live domains' atlas regions |
| +добавлено | gridPass(mesh, target) { |
| +добавлено | let d0 = MAXD, d1 = -1; |
| +добавлено | for (const h of this.handles) if (h.active) { d0 = Math.min(d0, h.index); d1 = Math.max(d1, h.index); } |
| +добавлено | if (d1 < 0) { d0 = 0; d1 = MAXD - 1; } |
| +добавлено | const RH = this.region[1]; |
| +добавлено | target.viewport.set(0, d0 * RH, this.AW, (d1 - d0 + 1) * RH); |
| +добавлено | this.renderer.setRenderTarget(target); |
| +добавлено | this.renderer.render(mesh, this.cam); |
| +добавлено | target.viewport.set(0, 0, this.AW, this.AH); |
| +добавлено | } |
| +добавлено | |
| +добавлено | step(dt) { |
| +добавлено | const r = this.renderer, su = this.su, cam = this.cam; |
| +добавлено | su.uSimDt.value = dt; |
| +добавлено | su.uGdt.value = 9.81 * dt; |
| +добавлено | // emission spans: from the first record to the cursor (ring) |
| +добавлено | const a = this.advU; |
| +добавлено | let sc = 0; |
| +добавлено | if (this.recCount) { |
| +добавлено | const A = this.firstStart, B = this.cursor; |
| +добавлено | if (B > A) this.spans[sc++].set(A, B); |
| +добавлено | else { this.spans[sc++].set(A, this.N); if (B > 0) this.spans[sc++].set(0, B); } |
| +добавлено | this.emitTex.needsUpdate = true; |
| +добавлено | } |
| +добавлено | a.uSpanCount.value = sc; |
| +добавлено | a.uEmitCount.value = this.recCount; |
| +добавлено | this.bind(); |
| +добавлено | const T = this.fine ? this.timer : null; |
| +добавлено | // P2G |
| +добавлено | T?.begin('fl p2g'); |
| +добавлено | r.setRenderTarget(this.acc); |
| +добавлено | r.clear(true, false, false); |
| +добавлено | r.render(this.p2g, cam); |
| +добавлено | // grid |
| +добавлено | T?.begin('fl mark'); |
| +добавлено | this.gridPass(this.markQ, this.V); |
| +добавлено | this.gridPass(this.divQ, this.D); |
| +добавлено | T?.begin('fl jacobi'); |
| +добавлено | for (let i = 0; i < this.iters; i++) { |
| +добавлено | this.jacU.uP.value = this.P[this.pCur].texture; |
| +добавлено | this.jacU.uFirst.value = i === 0 ? 1 : 0; |
| +добавлено | this.pCur ^= 1; |
| +добавлено | this.gridPass(this.jacQ, this.P[this.pCur]); |
| +добавлено | } |
| +добавлено | this.projU.uP.value = this.P[this.pCur].texture; |
| +добавлено | T?.begin('fl proj'); |
| +добавлено | this.gridPass(this.projQ, this.proj); |
| +добавлено | T?.begin('fl advect'); |
| +добавлено | // particles: G2P + advect + emit, then whitewater |
| +добавлено | this.cur ^= 1; |
| +добавлено | r.setRenderTarget(this.state[this.cur]); |
| +добавлено | r.render(this.advQ, cam); |
| +добавлено | this.bind(); |
| +добавлено | T?.begin('fl white'); |
| +добавлено | this.wcur ^= 1; |
| +добавлено | r.setRenderTarget(this.white[this.wcur]); |
| +добавлено | r.render(this.whiteQ, cam); |
| +добавлено | this.bind(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | bind() { |
| +добавлено | const su = this.su, s = this.state[this.cur].textures, w = this.white[this.wcur].textures; |
| +добавлено | su.uS0.value = s[0]; su.uS1.value = s[1]; su.uS2.value = s[2]; |
| +добавлено | su.uW0.value = w[0]; su.uW1.value = w[1]; su.uW2.value = w[2]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | resize() { |
| +добавлено | const res = U.uResolution.value; |
| +добавлено | const w = Math.max(1, Math.round(res.x * 0.5)), h = Math.max(1, Math.round(res.y * 0.5)); |
| +добавлено | if (w === this.ssf.x && h === this.ssf.y) return; |
| +добавлено | this.ssf.set(w, h); |
| +добавлено | for (const t of [this.depthRT, this.thickRT, this.nrmRT, ...this.smooth]) t.setSize(w, h); |
| +добавлено | } |
| +добавлено | |
| +добавлено | render(camera) { |
| +добавлено | const r = this.renderer; |
| +добавлено | this.resize(); |
| +добавлено | camera.updateMatrixWorld(); |
| +добавлено | const P = camera.projectionMatrix.elements; |
| +добавлено | this.nrmU.uProj.value.set(P[0], P[5]); |
| +добавлено | // every half-res pass only over the live domains' screen rect (+ the filter's reach) |
| +добавлено | const R = this.compU.uRect.value, w = this.ssf.x, hh = this.ssf.y; |
| +добавлено | this.screenRect(camera, R); |
| +добавлено | const x0 = Math.max(Math.floor((R.x * 0.5 + 0.5) * w) - 2, 0), y0 = Math.max(Math.floor((R.y * 0.5 + 0.5) * hh) - 2, 0); |
| +добавлено | const x1 = Math.min(Math.ceil((R.z * 0.5 + 0.5) * w) + 2, w), y1 = Math.min(Math.ceil((R.w * 0.5 + 0.5) * hh) + 2, hh); |
| +добавлено | const T = this.fine ? this.timer : null; |
| +добавлено | for (const t of this.ssfTargets) { |
| +добавлено | t.scissorTest = false; |
| +добавлено | r.setRenderTarget(t); |
| +добавлено | r.clear(true, t === this.depthRT, false); |
| +добавлено | t.scissor.set(x0, y0, Math.max(x1 - x0, 1), Math.max(y1 - y0, 1)); |
| +добавлено | t.scissorTest = true; |
| +добавлено | } |
| +добавлено | // sprites: nearest depth (+ domain), then additive thickness |
| +добавлено | T?.begin('ssf depth'); |
| +добавлено | r.setRenderTarget(this.depthRT); |
| +добавлено | r.render(this.depthMesh, camera); |
| +добавлено | T?.begin('ssf thick'); |
| +добавлено | r.setRenderTarget(this.thickRT); |
| +добавлено | r.render(this.thickMesh, camera); |
| +добавлено | // narrow-range filter, two separable iterations |
| +добавлено | let rad = 0; |
| +добавлено | for (const h of this.handles) if (h.active) rad = Math.max(rad, h.spacing * RADIUS_K); |
| +добавлено | const s = this.smU; |
| +добавлено | s.uPxScale.value = 0.5 * this.ssf.y * P[5]; |
| +добавлено | s.uWorldR.value = rad * 2.2; |
| +добавлено | s.uRange.value = rad * 2.0; |
| +добавлено | T?.begin('ssf smooth'); |
| +добавлено | let src = this.depthRT.texture; |
| +добавлено | for (let i = 0; i < 4; i++) { |
| +добавлено | s.uZ.value = src; |
| +добавлено | s.uDir.value.set(i & 1 ? 0 : 1, i & 1 ? 1 : 0); |
| +добавлено | r.setRenderTarget(this.smooth[i & 1]); |
| +добавлено | r.render(this.smQ, this.cam); |
| +добавлено | src = this.smooth[i & 1].texture; |
| +добавлено | } |
| +добавлено | T?.begin('ssf normal'); |
| +добавлено | this.nrmU.uZ.value = src; |
| +добавлено | r.setRenderTarget(this.nrmRT); |
| +добавлено | r.render(this.nrmQ, this.cam); |
| +добавлено | for (const t of this.ssfTargets) t.scissorTest = false; |
| +добавлено | this.compU.uCamWorld.value.copy(camera.matrixWorld); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // NDC rect of the live domains: the grid box (+ up to 1 m of what flew out of it) and a held or |
| +добавлено | // just thrown ball |
| +добавлено | screenRect(camera, out) { |
| +добавлено | const B = this._rect; |
| +добавлено | B[0] = B[1] = 1; B[2] = B[3] = -1; B[4] = 0; |
| +добавлено | for (const h of this.handles) { |
| +добавлено | if (!h.active) continue; |
| +добавлено | const c = Math.cos(h.yaw), s = Math.sin(h.yaw), m = Math.min(h.margin, 1) + 0.3; |
| +добавлено | const ex = h.n[0] * h.h / 2 + m, ez = h.n[2] * h.h / 2 + m, ey = h.n[1] * h.h + m; |
| +добавлено | for (let k = 0; k < 8; k++) { |
| +добавлено | const lx = k & 1 ? ex : -ex, lz = k & 2 ? ez : -ez, ly = k & 4 ? ey : -m; |
| +добавлено | this.corner(camera, h.position.x + lx * c - lz * s, h.position.y + ly, h.position.z + lx * s + lz * c); |
| +добавлено | } |
| +добавлено | if (h.holdOn || h.thrown < 1.2) { |
| +добавлено | const e = h.holdR * 4, p = h.holdPos; |
| +добавлено | for (let k = 0; k < 8; k++) this.corner(camera, p.x + (k & 1 ? e : -e), p.y + (k & 4 ? e : -e), p.z + (k & 2 ? e : -e)); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | if (B[4]) out.set(-1, -1, 1, 1); |
| +добавлено | else out.set(Math.max(B[0] - 0.01, -1), Math.max(B[1] - 0.01, -1), Math.min(B[2] + 0.01, 1), Math.min(B[3] + 0.01, 1)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | corner(camera, x, y, z) { |
| +добавлено | const B = this._rect; |
| +добавлено | _v.set(x, y, z).applyMatrix4(camera.matrixWorldInverse); |
| +добавлено | if (_v.z > -camera.near * 1.5) { B[4] = 1; return; } |
| +добавлено | _v.applyMatrix4(camera.projectionMatrix); |
| +добавлено | B[0] = Math.min(B[0], _v.x); B[1] = Math.min(B[1], _v.y); B[2] = Math.max(B[2], _v.x); B[3] = Math.max(B[3], _v.y); |
| +добавлено | } |
| +добавлено | |
| +добавлено | clear() { |
| +добавлено | const r = this.renderer, prev = r.getRenderTarget(); |
| +добавлено | r.setClearColor(0x000000, 0); |
| +добавлено | for (const t of [...this.state, ...this.white, ...this.P]) { r.setRenderTarget(t); r.clear(true, false, false); } |
| +добавлено | r.setRenderTarget(prev); |
| +добавлено | this.cursor = 0; |
| +добавлено | this.bind(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // compile and first-draw every internal program at load (none may compile at cast time) |
| +добавлено | warm() { |
| +добавлено | const at = new THREE.Vector3(0, 0, -30), c = new THREE.Vector3(0, 0.5, -30); |
| +добавлено | const h = this.acquire({ size: [2, 2, 2], position: at }); |
| +добавлено | h.burst(c, 0.3, at.set(0, 0, 0), 0.05); |
| +добавлено | h.jet(c, at.set(0, 1, 0), 4, 0.1, 1 / 60); |
| +добавлено | h.hold(c, 0.3); |
| +добавлено | this.update(1 / 60, this.fx.camera); |
| +добавлено | h.release(); |
| +добавлено | this.update(1 / 60, this.fx.camera); |
| +добавлено | const r = this.renderer, g = this.fx.ground; |
| +добавлено | if (this.paint && g?.paintTarget) { |
| +добавлено | this.paint.visible = true; |
| +добавлено | r.setRenderTarget(g.paintTarget); |
| +добавлено | r.render(this.paint, g.paintCamera); |
| +добавлено | r.setRenderTarget(null); |
| +добавлено | this.paint.visible = false; |
| +добавлено | } |
| +добавлено | this.clear(); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { FullscreenQuad, FULLSCREEN_VERT } from '../engine/fullscreen.js'; |
| +добавлено | import { |
| +добавлено | U, COMMON_GLSL, NOISE_GLSL, WORLD_GLSL, ARENA_GLSL, LIGHTS_GLSL, FORCES_GLSL, GROUND_GLSL, |
| +добавлено | FX_BLENDING, FX_VERT_HEAD, FX_FRAG_HEAD, FX_OUT_GLSL, LINES_BLENDING, ARENA, |
| +добавлено | } from './common.js'; |
| +добавлено | import { Q } from '../engine/quality.js'; |
| +добавлено | |
| +добавлено | // One GPU particle pool for every spell (PLAN 2.5). |
| +добавлено | // - State: three RGBA32F textures, ping-ponged and written by one MRT draw: |
| +добавлено | // S0 = (pos.xyz, age) S1 = (vel.xyz, life) S2 = (kind + size * 0.1, seed, lastCollideTime, custom) |
| +добавлено | // fp16 isn't enough: v * dt drops below fp16 precision at arena scale. |
| +добавлено | // - Behaviour lives in a kind table texture (Niagara-style parameters, not code): sliders write |
| +добавлено | // texels, nothing recompiles. |
| +добавлено | // - Three render styles own row ranges so each draw is homogeneous: |
| +добавлено | // glow full-res additive velocity-stretched sparks / motes (lines scene) |
| +добавлено | // media half-res spherical billboards, weighted-blended OIT (fx scene) |
| +добавлено | // debris instanced lit meshes (opaque scene) |
| +добавлено | // Each range starts with the field-emitter blocks, then a ring buffer the CPU allocates from. |
| +добавлено | // - Emission: per-frame records in a small float texture; texels inside a record respawn from |
| +добавлено | // it. Records only exist on frames that emit, and a texel tests the frame's spans first. |
| +добавлено | // - Kind morphing on collision replaces GPU sub-emitters (droplet -> splash, ember -> smoulder); |
| +добавлено | // field emitters respawn dead texels on the floor where the ground field says so (steam, ground |
| +добавлено | // flames, frost mist) with no CPU involvement. |
| +добавлено | |
| +добавлено | const KW = 11; // kind table texels per kind |
| +добавлено | const MAX_KINDS = 1024; // ~120 spells x ~6 kinds; one 10x1024 RGBA32F table (160 KB) |
| +добавлено | const MAX_REC = 64; // emission records per frame |
| +добавлено | const REC_W = 5; // texels per record |
| +добавлено | const MAX_FIELD = 8; |
| +добавлено | const LOG_N = 2048; // emission log entries per style |
| +добавлено | const STYLES = ['glow', 'media', 'debris']; |
| +добавлено | const PAINT_CHANNELS = ['heat', 'char', 'wet', 'frost', 'crack', 'acid', 'corruption', 'glow']; |
| +добавлено | const SHAPES = { sphere: 0, shell: 1, disk: 2, ring: 3, line: 4, cone: 5 }; |
| +добавлено | const MESHES = ['rock', 'shard', 'leaf']; |
| +добавлено | |
| +добавлено | const KIND_DEFAULTS = { |
| +добавлено | style: 'glow', flicker: 0, drag: 0.5, gravity: 0, buoyancy: 0, curl: 0, curlScale: 0.15, forceResponse: 1, |
| +добавлено | restitution: -1, friction: 0.2, life: [1, 1], size: [0.05, 0.05], stretch: 0, emissive: 1, |
| +добавлено | temp: null, color: ['#ffffff', '#ffffff'], alpha: [1, 0], paints: null, paintAmount: 0.3, |
| +добавлено | morph: null, killOnCollide: false, absorbing: false, toSmokeAt: 0, smokeAlbedo: 0.12, density: 3, |
| +добавлено | distortion: 0, fadeIn: 0.05, fadeOut: 0.3, spin: 0, sizePow: 1, softness: 1, lightResponse: 1, mesh: 'rock', |
| +добавлено | erosion: 0.5, orbit: false, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // --- shared GLSL --------------------------------------------------------------------- |
| +добавлено | const STATE_GLSL = (W) => /* glsl */` |
| +добавлено | uniform highp sampler2D uS0; |
| +добавлено | uniform highp sampler2D uS1; |
| +добавлено | uniform highp sampler2D uS2; |
| +добавлено | uniform highp sampler2D uKinds; |
| +добавлено | const int PW = ${W}; |
| +добавлено | vec4 kindTexel(int kind, int i) { return texelFetch(uKinds, ivec2(i, kind), 0); } |
| +добавлено | ivec2 texelOf(int idx) { return ivec2(idx % PW, idx / PW); } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // instance -> texel: field blocks first, then the live window of the ring |
| +добавлено | const INDEX_GLSL = /* glsl */` |
| +добавлено | uniform int uStyleStart; |
| +добавлено | uniform int uStyleCount; |
| +добавлено | uniform int uFieldCount; |
| +добавлено | uniform int uRingBase; |
| +добавлено | int particleIndex(int id) { |
| +добавлено | int ring = uStyleCount - uFieldCount; |
| +добавлено | int local = id < uFieldCount ? id : uFieldCount + (uRingBase + id - uFieldCount) % max(ring, 1); |
| +добавлено | return uStyleStart + local; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // colour / alpha / size over life, shared by every style |
| +добавлено | const LOOK_GLSL = /* glsl */` |
| +добавлено | struct Look { vec3 color; float alpha; float size; float smoke; float emissive; }; |
| +добавлено | Look particleLook(int kind, float t, float sizeScale) { |
| +добавлено | vec4 k2 = kindTexel(kind, 2), k3 = kindTexel(kind, 3), k4 = kindTexel(kind, 4), k5 = kindTexel(kind, 5); |
| +добавлено | vec4 k7 = kindTexel(kind, 7), k8 = kindTexel(kind, 8); |
| +добавлено | Look l; |
| +добавлено | l.size = mix(k2.z, k2.w, pow(t, k8.w)) * sizeScale; |
| +добавлено | float fade = smoothstep(0.0, max(k8.x, 1e-3), t) * (1.0 - smoothstep(1.0 - max(k8.y, 1e-3), 1.0, t)); |
| +добавлено | l.alpha = mix(k4.a, k5.a, t) * fade; |
| +добавлено | l.emissive = k3.y; |
| +добавлено | if (k3.z > 0.0) { |
| +добавлено | float T = mix(k3.z, k3.w, t); |
| +добавлено | l.color = blackbody(T) * pow(T / max(k3.z, 1.0), 3.0); // hot starts bright and cools fast |
| +добавлено | } else { |
| +добавлено | l.color = mix(k4.rgb, k5.rgb, t); |
| +добавлено | } |
| +добавлено | l.smoke = k7.x > 0.0 ? smoothstep(k7.x, min(k7.x + 0.25, 1.0), t) : 0.0; |
| +добавлено | return l; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // --- sim --------------------------------------------------------------------------------- |
| +добавлено | const SIM_FRAG = (W) => /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | precision highp sampler2D; |
| +добавлено | ${COMMON_GLSL} |
| +добавлено | ${NOISE_GLSL} |
| +добавлено | ${ARENA_GLSL} |
| +добавлено | ${FORCES_GLSL} |
| +добавлено | ${GROUND_GLSL} |
| +добавлено | ${STATE_GLSL(W)} |
| +добавлено | uniform highp sampler2D uEmitTex; |
| +добавлено | uniform int uEmitCount; |
| +добавлено | uniform vec2 uSpan[6]; |
| +добавлено | uniform int uSpanCount; |
| +добавлено | uniform highp sampler2D uFieldTex; |
| +добавлено | uniform int uFieldCount; |
| +добавлено | uniform float uSimDt; |
| +добавлено | layout(location = 0) out vec4 o0; |
| +добавлено | layout(location = 1) out vec4 o1; |
| +добавлено | layout(location = 2) out vec4 o2; |
| +добавлено | |
| +добавлено | void spawn(int kind, vec3 pos, vec3 vel, float lifeScale, float sizeScale, float seed) { |
| +добавлено | vec4 k2 = kindTexel(kind, 2); |
| +добавлено | float life = mix(k2.x, k2.y, hash11(seed * 7.13)) * lifeScale; |
| +добавлено | o0 = vec4(pos, 0.0); |
| +добавлено | o1 = vec4(vel, max(life, 1e-3)); |
| +добавлено | o2 = vec4(float(kind) + clamp(sizeScale, 0.0, 9.99) * 0.1, seed, -1e4, 0.0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | bool tryEmit(int idx) { |
| +добавлено | bool inSpan = false; |
| +добавлено | for (int s = 0; s < 6; s++) { |
| +добавлено | if (s >= uSpanCount) break; |
| +добавлено | if (float(idx) >= uSpan[s].x && float(idx) < uSpan[s].y) { inSpan = true; break; } |
| +добавлено | } |
| +добавлено | if (!inSpan) return false; |
| +добавлено | for (int r = 0; r < ${MAX_REC}; r++) { |
| +добавлено | if (r >= uEmitCount) break; |
| +добавлено | vec4 e0 = texelFetch(uEmitTex, ivec2(0, r), 0); |
| +добавлено | int j = idx - int(e0.x); |
| +добавлено | if (j < 0 || j >= int(e0.y)) continue; |
| +добавлено | vec4 e1 = texelFetch(uEmitTex, ivec2(1, r), 0), e2 = texelFetch(uEmitTex, ivec2(2, r), 0); |
| +добавлено | vec4 e3 = texelFetch(uEmitTex, ivec2(3, r), 0), e4 = texelFetch(uEmitTex, ivec2(4, r), 0); |
| +добавлено | float seed = fract(e3.w + float(j) * 0.618034) * 1000.0 + float(j) * 0.001; |
| +добавлено | vec4 h = hash41(seed); |
| +добавлено | vec3 h2 = hash31(seed + 17.0); |
| +добавлено | int shape = int(e0.w); |
| +добавлено | vec3 pos = e1.xyz, radial = vec3(0.0); |
| +добавлено | if (shape == 0) { vec3 d = randomInSphere(h.xyz); pos += d * e1.w; radial = normalize(d + 1e-5); } |
| +добавлено | else if (shape == 1) { vec3 d = randomOnSphere(h.xy); pos += d * e1.w; radial = d; } |
| +добавлено | else if (shape == 2 || shape == 3) { |
| +добавлено | float a = h.x * 2.0 * PI, r = shape == 2 ? sqrt(h.y) : 1.0; |
| +добавлено | radial = vec3(cos(a), 0.0, sin(a)); |
| +добавлено | pos += radial * r * e1.w; |
| +добавлено | } |
| +добавлено | else if (shape == 4) { |
| +добавлено | vec3 d = randomInSphere(h2); |
| +добавлено | pos = mix(e1.xyz, e3.xyz, h.x) + d * e1.w; |
| +добавлено | radial = normalize(d + 1e-5); |
| +добавлено | } |
| +добавлено | else { // cone around e3.xyz, half-angle e4.w |
| +добавлено | pos += randomInSphere(h2) * e1.w; |
| +добавлено | vec3 ax = normalize(e3.xyz + 1e-6); |
| +добавлено | float ct = mix(1.0, cos(e4.w), h.x), st = sqrt(1.0 - ct * ct), ph = h.y * 2.0 * PI; |
| +добавлено | radial = basisFrom(ax) * vec3(st * cos(ph), st * sin(ph), ct); |
| +добавлено | } |
| +добавлено | vec3 vel = e2.xyz + randomInSphere(hash31(seed + 31.0)) * e2.w + radial * e4.x * mix(0.6, 1.0, h.w); |
| +добавлено | spawn(int(e0.z), pos, vel, e4.z, e4.y, seed); |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // field emitters: dead texels in a block respawn on the floor where the ground field qualifies |
| +добавлено | bool tryField(int idx) { |
| +добавлено | for (int f = 0; f < ${MAX_FIELD}; f++) { |
| +добавлено | if (f >= uFieldCount) break; |
| +добавлено | vec4 f0 = texelFetch(uFieldTex, ivec2(0, f), 0); |
| +добавлено | int j = idx - int(f0.x); |
| +добавлено | if (j < 0 || j >= int(f0.y)) continue; |
| +добавлено | vec4 wa = texelFetch(uFieldTex, ivec2(1, f), 0), wb = texelFetch(uFieldTex, ivec2(2, f), 0); |
| +добавлено | vec4 f3 = texelFetch(uFieldTex, ivec2(3, f), 0); |
| +добавлено | float seed = hash12(vec2(float(idx), mod(uFrame, 4096.0))) * 1000.0; |
| +добавлено | vec4 h = hash41(seed); |
| +добавлено | float a = h.x * 2.0 * PI, r = sqrt(h.y) * ${(ARENA.radius - 0.4).toFixed(2)}; |
| +добавлено | vec2 xz = vec2(cos(a), sin(a)) * r; |
| +добавлено | float s = dot(groundA(xz), wa) + dot(groundB(xz), wb) - f0.w; |
| +добавлено | if (h.z > s * f3.x * uSimDt) return true; // stays dead this frame |
| +добавлено | vec3 pos = vec3(xz.x, 0.04, xz.y); |
| +добавлено | vec2 pq = abs(xz - vec2(${ARENA.pool.center.x.toFixed(3)}, ${ARENA.pool.center.y.toFixed(3)})); |
| +добавлено | if (pq.x < ${ARENA.pool.half.x.toFixed(3)} && pq.y < ${ARENA.pool.half.y.toFixed(3)}) pos.y += ${ARENA.pool.water.toFixed(3)}; |
| +добавлено | vec3 vel = vec3(0.0, f3.w, 0.0) + randomInSphere(hash31(seed + 5.0)) * 0.3; |
| +добавлено | spawn(int(f0.z), pos, vel, f3.y, f3.z * clamp(s * 2.0, 0.5, 1.5), seed); |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | return false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | ivec2 px = ivec2(gl_FragCoord.xy); |
| +добавлено | int idx = px.y * PW + px.x; |
| +добавлено | vec4 s0 = texelFetch(uS0, px, 0); |
| +добавлено | vec4 s1 = texelFetch(uS1, px, 0); |
| +добавлено | bool dead = s0.w >= s1.w; |
| +добавлено | if (dead) { |
| +добавлено | o0 = vec4(0.0, -1000.0, 0.0, 1e9); o1 = vec4(0.0, 0.0, 0.0, 1.0); o2 = vec4(0.0, 0.0, -1e4, 0.0); |
| +добавлено | if (!tryEmit(idx)) tryField(idx); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | // a texel re-allocated by the ring this frame restarts even if still alive (pool full: oldest die) |
| +добавлено | if (tryEmit(idx)) return; |
| +добавлено | |
| +добавлено | vec4 s2 = texelFetch(uS2, px, 0); |
| +добавлено | int kind = int(s2.x); |
| +добавлено | float sizeScale = fract(s2.x) * 10.0; |
| +добавлено | vec4 k0 = kindTexel(kind, 0), k1 = kindTexel(kind, 1), k2 = kindTexel(kind, 2), k6 = kindTexel(kind, 6); |
| +добавлено | vec4 k8 = kindTexel(kind, 8); |
| +добавлено | float dt = uSimDt; |
| +добавлено | vec3 pos = s0.xyz, vel = s1.xyz; |
| +добавлено | float age = s0.w + dt, life = s1.w, t = age / life; |
| +добавлено | float kill = 0.0; |
| +добавлено | |
| +добавлено | vec3 acc = vec3(0.0, k0.z * (1.0 - 0.6 * t) - k0.y, 0.0); |
| +добавлено | if (k0.w != 0.0) acc += curl3(pos * k1.x + vec3(0.0, uTime * 0.05, 0.0) + s2.y * 0.01) * k0.w; |
| +добавлено | if (k1.y != 0.0) acc += forceAccel(pos, vel, kill) * k1.y; |
| +добавлено | vel += acc * dt; |
| +добавлено | vel *= exp(-k0.x * dt); |
| +добавлено | vec3 np = pos + vel * dt; |
| +добавлено | |
| +добавлено | // collision with the arena (floor, rim, pillars, dummies, dynamic capsules) |
| +добавлено | float custom = s2.w, collide = s2.z; |
| +добавлено | if (k1.z >= 0.0) { |
| +добавлено | float rad = max(mix(k2.z, k2.w, t) * sizeScale * 0.5, 0.01); |
| +добавлено | float d = arenaSDF(np); |
| +добавлено | if (d < rad) { |
| +добавлено | vec3 n = arenaNormal(np); |
| +добавлено | np += n * (rad - d); |
| +добавлено | float vn = dot(vel, n); |
| +добавлено | if (vn < 0.0) { |
| +добавлено | vec3 vt = vel - n * vn; |
| +добавлено | vel = vt * (1.0 - k1.w) - n * vn * k1.z; |
| +добавлено | } |
| +добавлено | collide = uTime; |
| +добавлено | int flags = int(k6.w); |
| +добавлено | if ((flags & 2) != 0) kill = 1.0; |
| +добавлено | if (k6.z > 0.5) { // morph into another kind, keeping position and the bounce |
| +добавлено | int m = int(k6.z) - 1; |
| +добавлено | vec4 m2 = kindTexel(m, 2); |
| +добавлено | kind = m; age = 0.0; |
| +добавлено | life = mix(m2.x, m2.y, hash11(s2.y * 3.7)); |
| +добавлено | } |
| +добавлено | // debris: remember when it came to rest (its spin freezes there) |
| +добавлено | if (custom <= 0.0 && dot(vel, vel) < 0.04 && k6.x > 2.5) custom = age; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | // orbit hook: keep a Kepler-ish disk tidy (accretion), uses force 'orbit' for speed |
| +добавлено | if (kill > 0.5) age = life; |
| +добавлено | o0 = vec4(np, age); |
| +добавлено | o1 = vec4(vel, life); |
| +добавлено | o2 = vec4(float(kind) + sizeScale * 0.1, s2.y, collide, custom); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- glow: velocity-stretched additive quads, full res --------------------------------- |
| +добавлено | const GLOW_VERT = (W) => /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | ${COMMON_GLSL} |
| +добавлено | ${NOISE_GLSL} |
| +добавлено | ${STATE_GLSL(W)} |
| +добавлено | ${INDEX_GLSL} |
| +добавлено | ${LOOK_GLSL} |
| +добавлено | out vec2 vUv; |
| +добавлено | out vec3 vColor; |
| +добавлено | out float vSoft; |
| +добавлено | void main() { |
| +добавлено | int idx = particleIndex(gl_InstanceID); |
| +добавлено | ivec2 px = texelOf(idx); |
| +добавлено | vec4 s0 = texelFetch(uS0, px, 0), s1 = texelFetch(uS1, px, 0); |
| +добавлено | gl_Position = vec4(2.0, 2.0, 2.0, 1.0); |
| +добавлено | vColor = vec3(0.0); |
| +добавлено | if (s0.w >= s1.w) return; |
| +добавлено | vec4 s2 = texelFetch(uS2, px, 0); |
| +добавлено | int kind = int(s2.x); |
| +добавлено | float t = s0.w / s1.w; |
| +добавлено | Look l = particleLook(kind, t, fract(s2.x) * 10.0); |
| +добавлено | vec4 k3 = kindTexel(kind, 3); |
| +добавлено | vec3 headV = (viewMatrix * vec4(s0.xyz, 1.0)).xyz; |
| +добавлено | vec3 tailV = (viewMatrix * vec4(s0.xyz - s1.xyz * k3.x, 1.0)).xyz; |
| +добавлено | float viewZ = max(-headV.z, 0.05); |
| +добавлено | float pxWorld = 2.0 * viewZ / (projectionMatrix[1][1] * uResolution.y); |
| +добавлено | float size = l.size, w = max(size, 1.5 * pxWorld); |
| +добавлено | float aa = size / w; // Humus phone-wire AA: keep energy when clamped to 1.5 px |
| +добавлено | vec2 axis = tailV.xy - headV.xy; |
| +добавлено | float len = length(axis); |
| +добавлено | vec2 dir = len > 1e-4 ? axis / len : vec2(1.0, 0.0); |
| +добавлено | vec2 perp = vec2(-dir.y, dir.x); |
| +добавлено | // quad: x in [-1, 1] spans head (-1) .. tail (+1) plus caps, y across |
| +добавлено | vec2 off = dir * (position.x < 0.0 ? -w : len + w) + perp * position.y * w; |
| +добавлено | vec3 pv = headV + vec3(off, 0.0); |
| +добавлено | gl_Position = projectionMatrix * vec4(pv, 1.0); |
| +добавлено | vUv = vec2(position.x < 0.0 ? -1.0 : 1.0, position.y); |
| +добавлено | vSoft = len / (len + 2.0 * w); // how much of the quad is the stretched body |
| +добавлено | float nearFade = smoothstep(0.3, 1.2, viewZ); |
| +добавлено | // stretching spreads the same energy over a longer streak (motion-blur conservation) |
| +добавлено | float fk = kindTexel(kind, 10).x, ph = s2.y * 97.0 + s0.w * mix(9.0, 23.0, fract(s2.y * 13.7)); |
| +добавлено | vColor = l.color * l.emissive * l.alpha * aa * nearFade * (2.0 * w / (len + 2.0 * w)) * (1.0 - fk * (0.5 + 0.5 * sin(ph) * sin(ph * 0.37 + 1.3))); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const GLOW_FRAG = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | in vec2 vUv; |
| +добавлено | in vec3 vColor; |
| +добавлено | in float vSoft; |
| +добавлено | out vec4 fragColor; |
| +добавлено | void main() { |
| +добавлено | // capsule falloff: distance from the centre segment in quad units |
| +добавлено | float x = vUv.x * 0.5 + 0.5; // 0 head .. 1 tail |
| +добавлено | float ends = 1.0 - vSoft; |
| +добавлено | float dx = x < ends * 0.5 ? (ends * 0.5 - x) / max(ends * 0.5, 1e-3) : x > 1.0 - ends * 0.5 ? (x - 1.0 + ends * 0.5) / max(ends * 0.5, 1e-3) : 0.0; |
| +добавлено | float d2 = dx * dx + vUv.y * vUv.y; |
| +добавлено | float core = exp(-d2 * 4.0); |
| +добавлено | float tailFade = mix(1.0, 0.35, x); // brighter at the head |
| +добавлено | fragColor = vec4(vColor * core * tailFade, 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- media: spherical billboards into the half-res WBOIT pass --------------------------- |
| +добавлено | const MEDIA_VERT = (W) => FX_VERT_HEAD + /* glsl */` |
| +добавлено | ${COMMON_GLSL} |
| +добавлено | ${NOISE_GLSL} |
| +добавлено | ${ARENA_GLSL} |
| +добавлено | ${LIGHTS_GLSL} |
| +добавлено | ${STATE_GLSL(W)} |
| +добавлено | ${INDEX_GLSL} |
| +добавлено | ${LOOK_GLSL} |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform vec3 uAmbient; |
| +добавлено | out vec2 vUv; |
| +добавлено | out vec3 vSun; |
| +добавлено | out vec3 vAmb; |
| +добавлено | out vec3 vSunL; |
| +добавлено | out vec3 vUpL; |
| +добавлено | out vec3 vEmit; |
| +добавлено | out float vAlpha; |
| +добавлено | out float vViewZ; |
| +добавлено | out float vRadius; |
| +добавлено | out float vDensity; |
| +добавлено | out float vErode; |
| +добавлено | out float vDistort; |
| +добавлено | out vec3 vNoise; |
| +добавлено | void main() { |
| +добавлено | int idx = particleIndex(gl_InstanceID); |
| +добавлено | ivec2 px = texelOf(idx); |
| +добавлено | vec4 s0 = texelFetch(uS0, px, 0), s1 = texelFetch(uS1, px, 0); |
| +добавлено | gl_Position = vec4(2.0, 2.0, 2.0, 1.0); |
| +добавлено | vAlpha = 0.0; |
| +добавлено | if (s0.w >= s1.w) return; |
| +добавлено | vec4 s2 = texelFetch(uS2, px, 0); |
| +добавлено | int kind = int(s2.x); |
| +добавлено | float t = s0.w / s1.w; |
| +добавлено | Look l = particleLook(kind, t, fract(s2.x) * 10.0); |
| +добавлено | vec4 k6 = kindTexel(kind, 6), k7 = kindTexel(kind, 7), k9 = kindTexel(kind, 9); |
| +добавлено | vec3 cv = (viewMatrix * vec4(s0.xyz, 1.0)).xyz; |
| +добавлено | float viewZ = -cv.z; |
| +добавлено | if (viewZ < 0.05) return; |
| +добавлено | // overdraw guard: never wider than 12% of the screen height |
| +добавлено | float maxR = 0.12 * viewZ / projectionMatrix[1][1]; |
| +добавлено | float r = min(l.size * 0.5, maxR); |
| +добавлено | float spin = s2.y + s0.w * kindTexel(kind, 8).z; |
| +добавлено | vec2 c = vec2(cos(spin), sin(spin)); |
| +добавлено | vec2 q = mat2(c.x, -c.y, c.y, c.x) * position.xy; |
| +добавлено | gl_Position = projectionMatrix * vec4(cv + vec3(q * r, 0.0), 1.0); |
| +добавлено | vUv = position.xy; |
| +добавлено | vViewZ = viewZ; |
| +добавлено | vRadius = r; |
| +добавлено | vDensity = k7.z; |
| +добавлено | vErode = kindTexel(kind, 9).z * t; // erosion grows with age |
| +добавлено | vDistort = k7.w * l.alpha; |
| +добавлено | vNoise = s0.xyz * 0.35 + s2.y; |
| +добавлено | bool absorbing = (int(k6.w) & 1) != 0; |
| +добавлено | float smoke = absorbing ? 1.0 : l.smoke; |
| +добавлено | // lighting for the scattering part: sun with forward scattering, sky, spell lights |
| +добавлено | gLightNoShadow = true; |
| +добавлено | vec3 v = normalize(cameraPosition - s0.xyz); |
| +добавлено | float g = 0.35; |
| +добавлено | // flames glow; what scatters light is their soot, never their own blackbody colour |
| +добавлено | vec3 albedo = l.emissive > 0.0 ? vec3(k7.y) : mix(l.color, vec3(k7.y), smoke); |
| +добавлено | if (absorbing) albedo = l.color; |
| +добавлено | vSun = albedo * uSunColor * hgPhase(dot(uSunDir, -v), g) * 4.0 * PI * 0.6; |
| +добавлено | vAmb = albedo * (uAmbient * 1.4 + spellLightScatter(s0.xyz, v, g) * k9.x); |
| +добавлено | // sun and up in the sprite's own frame (view space turned back by the spin), so the fragment |
| +добавлено | // can shade the billboard as the sphere it stands for |
| +добавлено | vec3 sv = mat3(viewMatrix) * uSunDir, up = mat3(viewMatrix) * vec3(0.0, 1.0, 0.0); |
| +добавлено | mat2 unspin = mat2(c.x, c.y, -c.y, c.x); |
| +добавлено | vSunL = vec3(unspin * sv.xy, sv.z); |
| +добавлено | vUpL = vec3(unspin * up.xy, up.z); |
| +добавлено | // emission fades as fire turns to smoke |
| +добавлено | vEmit = (l.emissive > 0.0 && !absorbing) ? l.color * l.emissive * (1.0 - smoke) : vec3(0.0); |
| +добавлено | vAlpha = l.alpha; |
| +добавлено | // pure emitters (flames before they smoke) are mostly glow, little occlusion |
| +добавлено | vAlpha *= mix(0.25 + 0.75 * smoke, 1.0, step(l.emissive, 0.0)); |
| +добавлено | vAlpha *= smoothstep(0.2, 1.0, viewZ); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const MEDIA_FRAG = (W) => FX_FRAG_HEAD + /* glsl */` |
| +добавлено | ${COMMON_GLSL} |
| +добавлено | ${NOISE_GLSL} |
| +добавлено | ${FX_OUT_GLSL} |
| +добавлено | in vec2 vUv; |
| +добавлено | in vec3 vSun; |
| +добавлено | in vec3 vAmb; |
| +добавлено | in vec3 vSunL; |
| +добавлено | in vec3 vUpL; |
| +добавлено | in vec3 vEmit; |
| +добавлено | in float vAlpha; |
| +добавлено | in float vViewZ; |
| +добавлено | in float vRadius; |
| +добавлено | in float vDensity; |
| +добавлено | in float vErode; |
| +добавлено | in float vDistort; |
| +добавлено | in vec3 vNoise; |
| +добавлено | void main() { |
| +добавлено | if (vAlpha <= 0.001) discard; |
| +добавлено | float r2 = dot(vUv, vUv); |
| +добавлено | if (r2 >= 1.0) discard; |
| +добавлено | // spherical billboard (Umenhoffer et al. 2006): visible thickness of a sphere, cut by the scene |
| +добавлено | float h = sqrt(1.0 - r2) * vRadius; |
| +добавлено | float sceneZ = sceneViewZ(); |
| +добавлено | float thick = clamp(min(vViewZ + h, sceneZ) - max(vViewZ - h, uNearFar.x), 0.0, 2.0 * h); |
| +добавлено | // eroded by world-space noise so a sprite reads as a lumpy volume; a finer octave rags the edges |
| +добавлено | float n = noise3(vNoise + vec3(vUv * 0.42, 0.0)) * 0.72 + noise3(vNoise * 2.7 + vec3(vUv * 1.1, 0.0)) * 0.28; |
| +добавлено | float er = smoothstep(vErode, vErode + 0.35, n * (1.15 - r2 * 0.6)); |
| +добавлено | // billows and gaps from the first frame of a puff's life, not only once it erodes |
| +добавлено | float b = smoothstep(0.22, 0.62, n); |
| +добавлено | float a = (1.0 - exp(-vDensity * thick * (0.35 + 0.65 * b))) * er * vAlpha; |
| +добавлено | // shading: a dense puff is a lit sphere with a dark side, a dark core against the sun and billows |
| +добавлено | // that shadow each other (noise denser towards the sun = in shadow, one extra tap); thin wisps |
| +добавлено | // scatter evenly. Normalised so a front-lit puff keeps about its old mean brightness. |
| +добавлено | vec3 N = vec3(vUv, sqrt(1.0 - r2)); |
| +добавлено | float dense = 1.0 - exp(-vDensity * vRadius * 2.0); |
| +добавлено | float ns = noise3(vNoise + vec3((vUv + vSunL.xy * 0.3) * 0.42, 0.0)); |
| +добавлено | float self = clamp(0.5 + (n - ns) * 4.5, 0.0, 1.0); |
| +добавлено | float lam = clamp((dot(N, vSunL) + 0.35) / 1.35, 0.0, 1.0); |
| +добавлено | float through = exp(-vDensity * thick); |
| +добавлено | float sunShade = mix(through, lam, clamp(vSunL.z * 0.5 + 0.5, 0.0, 1.0)) * mix(1.0, self, 0.85) * 2.2; |
| +добавлено | float ambShade = (0.65 + 0.35 * dot(N, vUpL)) * (0.5 + 0.5 * sqrt(r2)) * 1.7; |
| +добавлено | vec3 vLit = vSun * mix(1.0, sunShade, dense) + vAmb * mix(1.0, ambShade, dense); |
| +добавлено | vec2 dist = vDistort * (vec2(noise3(vNoise * 1.7 + uTime * 0.6), noise3(vNoise.zxy * 1.7 - uTime * 0.6)) - 0.5) * 0.02 * (1.0 - r2); |
| +добавлено | // fire is hottest deep in a billow: thin edges and gaps run redder and much dimmer |
| +добавлено | float core = b * (1.0 - r2); |
| +добавлено | vec3 emit = vEmit * mix(vec3(0.5, 0.2, 0.08), vec3(1.5, 1.35, 1.2), core * core); |
| +добавлено | fxOut(vLit, a, emit * a * 2.0, dist, vViewZ); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- painting the ground field where paint kinds collided this frame -------------------- |
| +добавлено | const PAINT_VERT = (W) => /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | uniform float uTime; |
| +добавлено | uniform vec4 uGroundRect; |
| +добавлено | ${STATE_GLSL(W)} |
| +добавлено | ${INDEX_GLSL} |
| +добавлено | out vec4 vA; |
| +добавлено | out vec4 vB; |
| +добавлено | void main() { |
| +добавлено | int idx = particleIndex(gl_VertexID); |
| +добавлено | ivec2 px = texelOf(idx); |
| +добавлено | vec4 s0 = texelFetch(uS0, px, 0), s2 = texelFetch(uS2, px, 0); |
| +добавлено | gl_Position = vec4(2.0, 2.0, 2.0, 1.0); |
| +добавлено | gl_PointSize = 1.0; |
| +добавлено | vA = vB = vec4(0.0); |
| +добавлено | if (s2.z != uTime) return; // collided this frame (the sim wrote exactly this uniform) |
| +добавлено | int kind = int(s2.x); |
| +добавлено | vec4 k6 = kindTexel(kind, 6), k9 = kindTexel(kind, 9); |
| +добавлено | int ch = int(k6.y) - 1; |
| +добавлено | if (ch < 0) return; |
| +добавлено | vec2 uv = (s0.xz - uGroundRect.xy) * uGroundRect.w; |
| +добавлено | gl_Position = vec4(uv * 2.0 - 1.0, 0.0, 1.0); |
| +добавлено | gl_PointSize = 3.0; |
| +добавлено | float amt = kindTexel(kind, 9).w; |
| +добавлено | if (ch < 4) vA[ch] = amt; else vB[ch - 4] = amt; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const PAINT_FRAG = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | in vec4 vA; |
| +добавлено | in vec4 vB; |
| +добавлено | layout(location = 0) out vec4 gA; |
| +добавлено | layout(location = 1) out vec4 gB; |
| +добавлено | void main() { |
| +добавлено | float f = 1.0 - length(gl_PointCoord * 2.0 - 1.0); |
| +добавлено | if (f <= 0.0) discard; |
| +добавлено | gA = vA * f; gB = vB * f; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- geometry for debris variants ----------------------------------------------------- |
| +добавлено | function rockGeometry() { |
| +добавлено | const g = new THREE.IcosahedronGeometry(0.5, 1); |
| +добавлено | const p = g.attributes.position; |
| +добавлено | for (let i = 0; i < p.count; i++) { |
| +добавлено | const x = p.getX(i), y = p.getY(i), z = p.getZ(i); |
| +добавлено | const n = 0.75 + 0.35 * Math.abs(Math.sin(x * 9.1 + y * 4.3) * Math.cos(z * 7.7 - x * 2.1)); |
| +добавлено | p.setXYZ(i, x * n, y * n * 0.8, z * n); |
| +добавлено | } |
| +добавлено | g.computeVertexNormals(); |
| +добавлено | return g; // polyhedra are already non-indexed, so the normals are faceted |
| +добавлено | } |
| +добавлено | function shardGeometry() { |
| +добавлено | // hexagonal ice shard: prism with a pointed tip, flat facets |
| +добавлено | const g = new THREE.CylinderGeometry(0.0, 0.22, 1, 6, 1, false); |
| +добавлено | g.translate(0, 0.25, 0); |
| +добавлено | const tail = new THREE.CylinderGeometry(0.22, 0.12, 0.3, 6, 1, false); |
| +добавлено | tail.translate(0, -0.4, 0); |
| +добавлено | const merged = mergeTwo(g.toNonIndexed(), tail.toNonIndexed()); |
| +добавлено | merged.computeVertexNormals(); |
| +добавлено | return merged; |
| +добавлено | } |
| +добавлено | function leafGeometry() { |
| +добавлено | const g = new THREE.PlaneGeometry(1, 0.6, 2, 1); |
| +добавлено | const p = g.attributes.position; |
| +добавлено | for (let i = 0; i < p.count; i++) p.setZ(i, Math.abs(p.getX(i)) * 0.25); |
| +добавлено | g.computeVertexNormals(); |
| +добавлено | return g.toNonIndexed(); |
| +добавлено | } |
| +добавлено | function mergeTwo(a, b) { |
| +добавлено | const out = new THREE.BufferGeometry(); |
| +добавлено | for (const name of ['position', 'normal', 'uv']) { |
| +добавлено | const A = a.attributes[name], B = b.attributes[name]; |
| +добавлено | if (!A || !B) continue; |
| +добавлено | const arr = new Float32Array(A.array.length + B.array.length); |
| +добавлено | arr.set(A.array); arr.set(B.array, A.array.length); |
| +добавлено | out.setAttribute(name, new THREE.BufferAttribute(arr, A.itemSize)); |
| +добавлено | } |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- JS ------------------------------------------------------------------------------ |
| +добавлено | function colorArr(c) { const k = new THREE.Color(c); return [k.r, k.g, k.b]; } |
| +добавлено | |
| +добавлено | export class Particles { |
| +добавлено | constructor(renderer, { ground = null } = {}) { |
| +добавлено | this.renderer = renderer; |
| +добавлено | this.ground = ground; |
| +добавлено | [this.W, this.H] = Q.particles; |
| +добавлено | this.kinds = []; // { name, def, id } |
| +добавлено | this.kindIndex = new Map(); |
| +добавлено | this.fieldDefs = []; // { kind, style, count, wa, wb, threshold, rate, lifeScale, sizeScale, up } |
| +добавлено | this.kindData = new Float32Array(KW * MAX_KINDS * 4); |
| +добавлено | this.kindTex = new THREE.DataTexture(this.kindData, KW, MAX_KINDS, THREE.RGBAFormat, THREE.FloatType); |
| +добавлено | this.kindTex.magFilter = this.kindTex.minFilter = THREE.NearestFilter; |
| +добавлено | this.emitData = new Float32Array(REC_W * MAX_REC * 4); |
| +добавлено | this.emitTex = new THREE.DataTexture(this.emitData, REC_W, MAX_REC, THREE.RGBAFormat, THREE.FloatType); |
| +добавлено | this.emitTex.magFilter = this.emitTex.minFilter = THREE.NearestFilter; |
| +добавлено | this.fieldData = new Float32Array(4 * MAX_FIELD * 4); |
| +добавлено | this.fieldTex = new THREE.DataTexture(this.fieldData, 4, MAX_FIELD, THREE.RGBAFormat, THREE.FloatType); |
| +добавлено | this.fieldTex.magFilter = this.fieldTex.minFilter = THREE.NearestFilter; |
| +добавлено | this.recCount = 0; |
| +добавлено | this.built = false; |
| +добавлено | this.time = 0; |
| +добавлено | this.alive = 0; |
| +добавлено | this.seed = 1; |
| +добавлено | this.glow = this.media = this.debris = null; // meshes after build() |
| +добавлено | } |
| +добавлено | |
| +добавлено | // seeded LCG so ?shot / ?bench frames repeat exactly |
| +добавлено | rand() { this.seed = (Math.imul(this.seed, 1664525) + 1013904223) >>> 0; return this.seed / 4294967296; } |
| +добавлено | reseed(n) { this.seed = n >>> 0 || 1; } |
| +добавлено | |
| +добавлено | // --- authoring (spell create() at load) --- |
| +добавлено | addKind(name, def) { |
| +добавлено | if (this.kindIndex.has(name)) return this.kindIndex.get(name); |
| +добавлено | if (this.kinds.length >= MAX_KINDS) throw new Error('particle kinds full'); |
| +добавлено | const id = this.kinds.length; |
| +добавлено | // media is lit smoke/dust/mist unless it says it glows (or is a blackbody flame) |
| +добавлено | const lit = def.style === 'media' && !def.temp && !def.absorbing ? { emissive: 0 } : null; |
| +добавлено | const k = { name, id, def: { ...KIND_DEFAULTS, ...lit, ...def } }; |
| +добавлено | this.kinds.push(k); |
| +добавлено | this.kindIndex.set(name, id); |
| +добавлено | return id; |
| +добавлено | } |
| +добавлено | kind(name) { return this.kindIndex.get(name); } |
| +добавлено | |
| +добавлено | // live slider edits: no recompile, just texels |
| +добавлено | setKind(id, patch) { |
| +добавлено | const k = this.kinds[typeof id === 'string' ? this.kindIndex.get(id) : id]; |
| +добавлено | Object.assign(k.def, patch); |
| +добавлено | if (this.built) { this.writeKind(k); this.kindTex.needsUpdate = true; } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // GPU-driven emission from the ground field: weights on (heat, char, wet, frost) and |
| +добавлено | // (crack, acid, corruption, glow), minus threshold, times rate = spawn chance per slot per second |
| +добавлено | fieldEmitter(kind, { slots = 1024, a = [0, 0, 0, 0], b = [0, 0, 0, 0], threshold = 0.2, rate = 2, lifeScale = 1, sizeScale = 1, up = 0.5 } = {}) { |
| +добавлено | const id = typeof kind === 'string' ? this.kindIndex.get(kind) : kind; |
| +добавлено | this.fieldDefs.push({ kind: id, count: Math.max(64, Math.round(slots * Q.emission)), wa: a, wb: b, threshold, rate, lifeScale, sizeScale, up }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | writeKind(k) { |
| +добавлено | const d = k.def, o = k.id * KW * 4, D = this.kindData; |
| +добавлено | const [ca, cb] = [colorArr(d.color[0]), colorArr(d.color[1] ?? d.color[0])]; |
| +добавлено | const style = STYLES.indexOf(d.style); |
| +добавлено | const paint = d.paints ? PAINT_CHANNELS.indexOf(d.paints) + 1 : 0; |
| +добавлено | const morph = d.morph != null ? (typeof d.morph === 'string' ? this.kindIndex.get(d.morph) : d.morph) + 1 : 0; |
| +добавлено | const flags = (d.absorbing ? 1 : 0) | (d.killOnCollide ? 2 : 0) | (d.orbit ? 4 : 0); |
| +добавлено | D.set([ |
| +добавлено | d.drag, d.gravity, d.buoyancy, d.curl, |
| +добавлено | d.curlScale, d.forceResponse, d.restitution, d.friction, |
| +добавлено | d.life[0], d.life[1], d.size[0], d.size[1] ?? d.size[0], |
| +добавлено | d.stretch, d.emissive, d.temp ? d.temp[0] : 0, d.temp ? d.temp[1] ?? d.temp[0] : 0, |
| +добавлено | ...ca, d.alpha[0], |
| +добавлено | ...cb, d.alpha[1] ?? d.alpha[0], |
| +добавлено | // debris is 3 + variant / 10 (the sim tests > 2.5, the debris VS reads the variant) |
| +добавлено | style === 2 ? 3 + MESHES.indexOf(d.mesh) * 0.1 : style, paint, morph, flags, |
| +добавлено | d.toSmokeAt, d.smokeAlbedo, d.density, d.distortion, |
| +добавлено | d.fadeIn, d.fadeOut, d.spin, d.sizePow, |
| +добавлено | d.lightResponse, d.softness, d.erosion, d.paintAmount, |
| +добавлено | d.flicker, 0, 0, 0, // glow only: 0..1 per-particle twinkle (embers) |
| +добавлено | ], o); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- build once every spell has registered --- |
| +добавлено | build() { |
| +добавлено | const { W, H } = this; |
| +добавлено | for (const k of this.kinds) this.writeKind(k); |
| +добавлено | this.kindTex.needsUpdate = true; |
| +добавлено | |
| +добавлено | // row ranges: debris rows sized to Q.debris, the rest split glow 55% / media 45% |
| +добавлено | const debrisRows = Math.max(1, Math.ceil(Q.debris / W)); |
| +добавлено | const rest = H - debrisRows; |
| +добавлено | const glowRows = Math.round(rest * 0.55), mediaRows = rest - glowRows; |
| +добавлено | const rows = { glow: [0, glowRows], media: [glowRows, mediaRows], debris: [glowRows + mediaRows, debrisRows] }; |
| +добавлено | this.style = {}; |
| +добавлено | for (const s of STYLES) { |
| +добавлено | const [r0, nr] = rows[s]; |
| +добавлено | this.style[s] = { start: r0 * W, count: nr * W, field: 0, cursor: 0, log: new Float64Array(LOG_N * 3), head: 0, tail: 0, base: 0, window: 0 }; |
| +добавлено | } |
| +добавлено | // field blocks at the start of their style's range |
| +добавлено | let fi = 0; |
| +добавлено | for (const fd of this.fieldDefs) { |
| +добавлено | const st = this.style[this.kinds[fd.kind].def.style]; |
| +добавлено | const count = Math.min(fd.count, Math.floor(st.count / 4)); |
| +добавлено | const o = fi * 4 * 4; |
| +добавлено | this.fieldData.set([st.start + st.field, count, fd.kind, fd.threshold, ...fd.wa, ...fd.wb, fd.rate, fd.lifeScale, fd.sizeScale, fd.up], o); |
| +добавлено | st.field += count; |
| +добавлено | fi++; |
| +добавлено | } |
| +добавлено | this.fieldCount = fi; |
| +добавлено | this.fieldTex.needsUpdate = true; |
| +добавлено | |
| +добавлено | const rtOpts = { type: THREE.FloatType, format: THREE.RGBAFormat, minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, depthBuffer: false, generateMipmaps: false, count: 3 }; |
| +добавлено | this.rt = [new THREE.WebGLRenderTarget(W, H, rtOpts), new THREE.WebGLRenderTarget(W, H, rtOpts)]; |
| +добавлено | this.cur = 0; |
| +добавлено | |
| +добавлено | const stateU = { uS0: { value: null }, uS1: { value: null }, uS2: { value: null }, uKinds: { value: this.kindTex } }; |
| +добавлено | this.stateU = stateU; |
| +добавлено | this.spans = Array.from({ length: 6 }, () => new THREE.Vector2()); |
| +добавлено | this.sim = new FullscreenQuad(new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: FULLSCREEN_VERT, fragmentShader: SIM_FRAG(W), |
| +добавлено | uniforms: { |
| +добавлено | ...U, ...stateU, |
| +добавлено | uEmitTex: { value: this.emitTex }, uEmitCount: { value: 0 }, uSpan: { value: this.spans }, uSpanCount: { value: 0 }, |
| +добавлено | uFieldTex: { value: this.fieldTex }, uFieldCount: { value: this.fieldCount }, uSimDt: { value: 1 / 60 }, |
| +добавлено | }, |
| +добавлено | depthTest: false, depthWrite: false, |
| +добавлено | })); |
| +добавлено | // initialise every texel dead: one sim step with nothing to emit |
| +добавлено | this.clearState(); |
| +добавлено | |
| +добавлено | const quad = new THREE.InstancedBufferGeometry(); |
| +добавлено | quad.setAttribute('position', new THREE.Float32BufferAttribute([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0], 3)); |
| +добавлено | quad.setIndex([0, 1, 2, 0, 2, 3]); |
| +добавлено | const styleU = (s) => ({ |
| +добавлено | uStyleStart: { value: this.style[s].start }, uStyleCount: { value: this.style[s].count }, |
| +добавлено | uFieldCount: { value: this.style[s].field }, uRingBase: { value: 0 }, |
| +добавлено | }); |
| +добавлено | |
| +добавлено | // glow (lines scene) |
| +добавлено | const gq = quad.clone(); |
| +добавлено | this.glow = new THREE.Mesh(gq, new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: GLOW_VERT(W), fragmentShader: GLOW_FRAG, |
| +добавлено | uniforms: { ...U, ...stateU, ...styleU('glow') }, ...LINES_BLENDING, |
| +добавлено | })); |
| +добавлено | this.glow.frustumCulled = false; |
| +добавлено | this.glow.renderOrder = 10; |
| +добавлено | this.glow.layers.enable(1); // shows in the floor reflection |
| +добавлено | |
| +добавлено | // media (fx scene) |
| +добавлено | const mq = quad.clone(); |
| +добавлено | this.media = new THREE.Mesh(mq, new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: MEDIA_VERT(W), fragmentShader: MEDIA_FRAG(W), |
| +добавлено | uniforms: { ...U, ...stateU, ...styleU('media') }, ...FX_BLENDING, |
| +добавлено | })); |
| +добавлено | this.media.frustumCulled = false; |
| +добавлено | |
| +добавлено | // debris (opaque scene): one mesh per variant, each skips instances of other variants |
| +добавлено | const debrisU = styleU('debris'); // shared by the three variant materials |
| +добавлено | this.debris = MESHES.map((variant, vi) => { |
| +добавлено | const src = variant === 'rock' ? rockGeometry() : variant === 'shard' ? shardGeometry() : leafGeometry(); |
| +добавлено | const g = new THREE.InstancedBufferGeometry(); |
| +добавлено | for (const n of ['position', 'normal', 'uv']) if (src.attributes[n]) g.setAttribute(n, src.attributes[n]); |
| +добавлено | g.instanceCount = 0; |
| +добавлено | const mat = debrisMaterial(W, stateU, debrisU, vi, variant); |
| +добавлено | mat.userData.u = debrisU; |
| +добавлено | const m = new THREE.Mesh(g, mat); |
| +добавлено | m.frustumCulled = false; |
| +добавлено | m.layers.enable(1); |
| +добавлено | return m; |
| +добавлено | }); |
| +добавлено | |
| +добавлено | // paint into the ground field: one Points draw per style window |
| +добавлено | this.paint = []; |
| +добавлено | if (this.ground?.paintScene) { |
| +добавлено | for (const s of STYLES) { |
| +добавлено | // the shader reads no attributes; three clamps the draw to position.count, so size it |
| +добавлено | const g = new THREE.BufferGeometry(); |
| +добавлено | g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(this.style[s].count), 1)); |
| +добавлено | g.setDrawRange(0, 0); |
| +добавлено | g.boundingSphere = new THREE.Sphere(); // three sorts by it; computing it from a 1-wide attribute gives NaN |
| +добавлено | const m = new THREE.Points(g, new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: PAINT_VERT(W), fragmentShader: PAINT_FRAG, |
| +добавлено | uniforms: { uTime: U.uTime, uGroundRect: U.uGroundRect, ...stateU, ...styleU(s) }, |
| +добавлено | depthTest: false, depthWrite: false, transparent: true, blending: THREE.AdditiveBlending, |
| +добавлено | })); |
| +добавлено | m.frustumCulled = false; |
| +добавлено | m.userData.style = s; |
| +добавлено | this.ground.paintScene.add(m); |
| +добавлено | this.paint.push(m); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | this.built = true; |
| +добавлено | this.bindState(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | clearState() { |
| +добавлено | this.recCount = 0; |
| +добавлено | this.sim.material.uniforms.uEmitCount.value = 0; |
| +добавлено | this.sim.material.uniforms.uSpanCount.value = 0; |
| +добавлено | this.sim.material.uniforms.uFieldCount.value = 0; |
| +добавлено | const r = this.renderer; |
| +добавлено | // the textures start as zero: age 0 >= life 0 counts as dead |
| +добавлено | for (const rt of this.rt) { r.setRenderTarget(rt); r.setClearColor(0x000000, 0); r.clear(true, false, false); } |
| +добавлено | r.setRenderTarget(null); |
| +добавлено | for (const s of STYLES) Object.assign(this.style?.[s] ?? {}, { cursor: 0, head: 0, tail: 0, base: 0, window: 0 }); |
| +добавлено | this.sim.material.uniforms.uFieldCount.value = this.fieldCount ?? 0; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- emitters: reusable handles so continuous emission allocates nothing --- |
| +добавлено | emitter(kind, opts = {}) { |
| +добавлено | const id = typeof kind === 'string' ? this.kindIndex.get(kind) : kind; |
| +добавлено | if (id === undefined) throw new Error(`unknown particle kind ${kind}`); |
| +добавлено | const p = this; |
| +добавлено | return { |
| +добавлено | kind: id, shape: SHAPES[opts.shape ?? 'sphere'], pos: new THREE.Vector3(), radius: opts.radius ?? 0.1, |
| +добавлено | vel: new THREE.Vector3(), spread: opts.spread ?? 0, p: new THREE.Vector3(), radial: opts.radial ?? 0, |
| +добавлено | size: opts.size ?? 1, life: opts.life ?? 1, cone: opts.cone ?? 0.4, acc: 0, |
| +добавлено | burst(count) { p.emit(this, count); }, |
| +добавлено | // continuous: fractional accumulator so low rates still emit |
| +добавлено | rate(perSecond, dt) { |
| +добавлено | this.acc += perSecond * dt * Q.emission * Q.auto.emission; |
| +добавлено | const n = Math.floor(this.acc); |
| +добавлено | if (n > 0) { this.acc -= n; p.emit(this, n, true); } |
| +добавлено | }, |
| +добавлено | setShape(name) { this.shape = SHAPES[name]; return this; }, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | emit(e, count, prescaled = false) { |
| +добавлено | if (!this.built) return; |
| +добавлено | const st = this.style[this.kinds[e.kind].def.style]; |
| +добавлено | const ring = st.count - st.field; |
| +добавлено | let n = prescaled ? count : Math.round(count * Q.emission * Q.auto.emission); |
| +добавлено | n = Math.min(n, ring); |
| +добавлено | if (n <= 0) return; |
| +добавлено | const def = this.kinds[e.kind].def, life = def.life[1] * e.life; |
| +добавлено | // the ground field only simulates (and accepts paint) where it was touched: cover the reach |
| +добавлено | const mk = typeof def.morph === 'string' ? this.kindIndex.get(def.morph) : def.morph; |
| +добавлено | if ((def.paints || this.kinds[mk]?.def.paints) && this.ground?.touch) { |
| +добавлено | const reach = Math.min(8, e.radius + 1 + 0.6 * life * (e.spread + e.vel.length())); |
| +добавлено | this.ground.touch(e.pos.x, e.pos.z, reach, life); |
| +добавлено | } |
| +добавлено | let start = st.cursor; |
| +добавлено | while (n > 0 && this.recCount < MAX_REC) { |
| +добавлено | const take = Math.min(n, ring - start); |
| +добавлено | const o = this.recCount * REC_W * 4, D = this.emitData; |
| +добавлено | D[o] = st.start + st.field + start; D[o + 1] = take; D[o + 2] = e.kind; D[o + 3] = e.shape; |
| +добавлено | D[o + 4] = e.pos.x; D[o + 5] = e.pos.y; D[o + 6] = e.pos.z; D[o + 7] = e.radius; |
| +добавлено | D[o + 8] = e.vel.x; D[o + 9] = e.vel.y; D[o + 10] = e.vel.z; D[o + 11] = e.spread; |
| +добавлено | D[o + 12] = e.p.x; D[o + 13] = e.p.y; D[o + 14] = e.p.z; D[o + 15] = this.rand(); |
| +добавлено | D[o + 16] = e.radial; D[o + 17] = e.size; D[o + 18] = e.life; D[o + 19] = e.cone; |
| +добавлено | this.recCount++; |
| +добавлено | // emission log (ring): entries expire in order, the oldest live one is the draw window base |
| +добавлено | const h = st.head % LOG_N * 3; |
| +добавлено | st.log[h] = start; st.log[h + 1] = take; st.log[h + 2] = this.time + life; |
| +добавлено | st.head++; |
| +добавлено | if (st.head - st.tail > LOG_N) st.tail++; |
| +добавлено | start = (start + take) % ring; |
| +добавлено | n -= take; |
| +добавлено | } |
| +добавлено | st.cursor = start; |
| +добавлено | } |
| +добавлено | |
| +добавлено | bindState() { |
| +добавлено | const s = this.rt[this.cur].textures; |
| +добавлено | this.stateU.uS0.value = s[0]; this.stateU.uS1.value = s[1]; this.stateU.uS2.value = s[2]; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // once per frame, before rendering. dt is the scaled sim step. |
| +добавлено | update(dt, time) { |
| +добавлено | if (!this.built) return; |
| +добавлено | this.time = time; |
| +добавлено | const u = this.sim.material.uniforms; |
| +добавлено | // spans this frame: per style, from the first record start to the cursor (wrapping) |
| +добавлено | let sc = 0; |
| +добавлено | for (const s of STYLES) this.style[s].first = -1; |
| +добавлено | for (let r = 0; r < this.recCount; r++) { |
| +добавлено | const o = r * REC_W * 4, st = this.style[this.kinds[this.emitData[o + 2]].def.style]; |
| +добавлено | if (st.first < 0) st.first = this.emitData[o]; |
| +добавлено | } |
| +добавлено | for (const s of STYLES) { |
| +добавлено | const st = this.style[s]; |
| +добавлено | if (st.first < 0) continue; |
| +добавлено | const ringStart = st.start + st.field, ring = st.count - st.field; |
| +добавлено | const a = st.first, b = ringStart + st.cursor; |
| +добавлено | if (b > a) this.spans[sc++].set(a, b); |
| +добавлено | else { this.spans[sc++].set(a, ringStart + ring); this.spans[sc++].set(ringStart, b === ringStart ? ringStart + ring : b); } |
| +добавлено | } |
| +добавлено | u.uSpanCount.value = sc; |
| +добавлено | u.uEmitCount.value = this.recCount; |
| +добавлено | if (this.recCount) this.emitTex.needsUpdate = true; |
| +добавлено | u.uSimDt.value = dt; |
| +добавлено | this.bindState(); // read the current state ... |
| +добавлено | this.cur ^= 1; |
| +добавлено | this.sim.render(this.renderer, this.rt[this.cur]); // ... write the other |
| +добавлено | this.bindState(); |
| +добавлено | this.recCount = 0; |
| +добавлено | |
| +добавлено | // live windows: drop expired log entries, base = oldest live start |
| +добавлено | this.alive = 0; |
| +добавлено | for (const s of STYLES) { |
| +добавлено | const st = this.style[s], ring = st.count - st.field, L = st.log; |
| +добавлено | while (st.tail < st.head && L[st.tail % LOG_N * 3 + 2] < time) st.tail++; |
| +добавлено | for (let j = st.tail; j < st.head; j++) this.alive += L[j % LOG_N * 3 + 1]; |
| +добавлено | const live = st.head > st.tail; |
| +добавлено | st.base = live ? L[st.tail % LOG_N * 3] : st.cursor; |
| +добавлено | st.window = live ? ((st.cursor - st.base + ring) % ring || ring) : 0; |
| +добавлено | this.setDraw(s, st.base, st.field + st.window); |
| +добавлено | } |
| +добавлено | this.alive = Math.min(this.alive, this.W * this.H); |
| +добавлено | } |
| +добавлено | |
| +добавлено | setDraw(s, base, n) { |
| +добавлено | const meshes = s === 'glow' ? [this.glow] : s === 'media' ? [this.media] : this.debris; |
| +добавлено | for (const m of meshes) { |
| +добавлено | m.geometry.instanceCount = n; |
| +добавлено | (m.material.uniforms ?? m.material.userData.u).uRingBase.value = base; |
| +добавлено | m.visible = n > 0; |
| +добавлено | } |
| +добавлено | for (const p of this.paint) if (p.userData.style === s) { |
| +добавлено | p.material.uniforms.uRingBase.value = base; |
| +добавлено | p.geometry.setDrawRange(0, n); |
| +добавлено | p.visible = n > 0; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // everything visible for one warm-up frame (shader variants are built at first draw) |
| +добавлено | warm(on) { |
| +добавлено | for (const s of STYLES) { |
| +добавлено | const st = this.style[s]; |
| +добавлено | if (on) this.setDraw(s, 0, 1); else this.setDraw(s, st.base, st.field + st.window); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | function debrisMaterial(W, stateU, styleU, variant, name) { |
| +добавлено | const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: name === 'shard' ? 0.08 : 0.85, metalness: 0, side: name === 'leaf' ? THREE.DoubleSide : THREE.FrontSide }); |
| +добавлено | mat.onBeforeCompile = (sh) => { |
| +добавлено | Object.assign(sh.uniforms, U, stateU, styleU, { uVariant: { value: variant } }); |
| +добавлено | sh.vertexShader = sh.vertexShader |
| +добавлено | .replace('#include <common>', `#include <common> |
| +добавлено | ${STATE_GLSL(W)} |
| +добавлено | ${INDEX_GLSL} |
| +добавлено | uniform float uVariant; |
| +добавлено | varying vec3 vKindColor; |
| +добавлено | varying vec3 vKindEmit; |
| +добавлено | varying float vRough; |
| +добавлено | mat3 axisAngle(vec3 a, float t) { |
| +добавлено | float c = cos(t), s = sin(t), C = 1.0 - c; |
| +добавлено | return mat3(c + a.x*a.x*C, a.y*a.x*C + a.z*s, a.z*a.x*C - a.y*s, |
| +добавлено | a.x*a.y*C - a.z*s, c + a.y*a.y*C, a.z*a.y*C + a.x*s, |
| +добавлено | a.x*a.z*C + a.y*s, a.y*a.z*C - a.x*s, c + a.z*a.z*C); |
| +добавлено | } |
| +добавлено | vec3 hash3(float p) { vec3 p3 = fract(vec3(p) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xxy + p3.yzz) * p3.zyx); } |
| +добавлено | mat3 gRot; vec3 gPos; float gScale; bool gDead; |
| +добавлено | void debrisSetup() { |
| +добавлено | int idx = particleIndex(gl_InstanceID); |
| +добавлено | ivec2 px = texelOf(idx); |
| +добавлено | vec4 s0 = texelFetch(uS0, px, 0), s1 = texelFetch(uS1, px, 0), s2 = texelFetch(uS2, px, 0); |
| +добавлено | int kind = int(s2.x); |
| +добавлено | vec4 k2 = kindTexel(kind, 2), k4 = kindTexel(kind, 4), k5 = kindTexel(kind, 5), k6 = kindTexel(kind, 6), k8 = kindTexel(kind, 8); |
| +добавлено | float t = s0.w / max(s1.w, 1e-4); |
| +добавлено | gDead = s0.w >= s1.w || abs(fract(k6.x) * 10.0 - uVariant) > 0.5; |
| +добавлено | vec3 h = hash3(s2.y); |
| +добавлено | vec3 ax = normalize(h - 0.5 + 1e-4); |
| +добавлено | float spinT = s2.w > 0.0 ? s2.w : s0.w; |
| +добавлено | gRot = axisAngle(ax, h.x * 6.283 + k8.z * spinT); |
| +добавлено | float fade = 1.0 - smoothstep(1.0 - max(k8.y, 1e-3), 1.0, t); |
| +добавлено | gScale = mix(k2.z, k2.w, t) * fract(s2.x) * 10.0 * (0.6 + 0.8 * h.y) * mix(0.0, 1.0, fade) * smoothstep(0.0, 0.03, s0.w + 0.01); |
| +добавлено | gPos = s0.xyz; |
| +добавлено | vKindColor = k4.rgb * (0.75 + 0.5 * h.z); |
| +добавлено | vKindEmit = k5.rgb * pow(1.0 - t, 2.0); |
| +добавлено | vRough = k5.a; |
| +добавлено | }`) |
| +добавлено | .replace('#include <beginnormal_vertex>', `debrisSetup(); |
| +добавлено | vec3 objectNormal = gRot * normal; |
| +добавлено | #ifdef USE_TANGENT |
| +добавлено | vec3 objectTangent = vec3(tangent.xyz); |
| +добавлено | #endif`) |
| +добавлено | .replace('#include <begin_vertex>', `vec3 transformed = gDead ? vec3(0.0, -1000.0, 0.0) : gRot * position * gScale + gPos;`); |
| +добавлено | sh.fragmentShader = sh.fragmentShader |
| +добавлено | .replace('#include <common>', `#include <common> |
| +добавлено | ${COMMON_GLSL} |
| +добавлено | ${WORLD_GLSL} |
| +добавлено | ${LIGHTS_GLSL} |
| +добавлено | varying vec3 vKindColor; |
| +добавлено | varying vec3 vKindEmit; |
| +добавлено | varying float vRough;`) |
| +добавлено | .replace('#include <lights_fragment_end>', `#include <lights_fragment_end> |
| +добавлено | { |
| +добавлено | // spell lights in world space (view-space normal/position rotated back) |
| +добавлено | vec3 wN = normalize((vec4(normal, 0.0) * viewMatrix).xyz); |
| +добавлено | vec3 wP = cameraPosition + (vec4(-vViewPosition, 0.0) * viewMatrix).xyz; |
| +добавлено | vec3 sd, ss; |
| +добавлено | spellLightPBR(wP, wN, normalize(cameraPosition - wP), material.roughness, material.specularColor, material.diffuseColor, sd, ss); |
| +добавлено | reflectedLight.directDiffuse += sd; |
| +добавлено | reflectedLight.directSpecular += ss; |
| +добавлено | }`) |
| +добавлено | .replace('#include <color_fragment>', `#include <color_fragment> |
| +добавлено | diffuseColor.rgb *= vKindColor;`) |
| +добавлено | .replace('#include <roughnessmap_fragment>', `float roughnessFactor = vRough > 0.0 ? vRough : roughness;`) |
| +добавлено | .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment> |
| +добавлено | totalEmissiveRadiance += vKindEmit;`); |
| +добавлено | }; |
| +добавлено | return mat; |
| +добавлено | } |
| +добавлено | // Shared optics for every refract-pass material (metaballs, ice, pool surface). These draw into |
| +добавлено | // the MSAA HDR target right after the opaque scene and sample its resolve (UW's water pass): |
| +добавлено | // uSceneColor = opaque linear HDR, uSceneDepth = its [0,1] depth. |
| +добавлено | // |
| +добавлено | // Needs COMMON_GLSL first (uResolution, uNearFar, linearDepth) and three's ShaderMaterial prefix |
| +добавлено | // (viewMatrix). Declares projectionMatrix (three's fragment prefix only has viewMatrix and |
| +добавлено | // cameraPosition; three still fills it), uSceneColor, uSceneDepth and uSkyCube: don't redeclare |
| +добавлено | // them; pass { ...U, own } so the values are shared. |
| +добавлено | // |
| +добавлено | // Units: metres, linear radiance, absorption in 1/m, cosines of unit vectors. |
| +добавлено | export const REFRACT_GLSL = /* glsl */` |
| +добавлено | uniform mat4 projectionMatrix; |
| +добавлено | uniform sampler2D uSceneColor; |
| +добавлено | uniform highp sampler2D uSceneDepth; |
| +добавлено | uniform samplerCube uSkyCube; |
| +добавлено | |
| +добавлено | // Schlick. cosTheta = dot(n, v); f0 = 0.02 for water and ice (IOR ~1.33) |
| +добавлено | float fresnel(float cosTheta, float f0) { |
| +добавлено | float m = 1.0 - clamp(cosTheta, 0.0, 1.0), m2 = m * m; |
| +добавлено | return f0 + (1.0 - f0) * m2 * m2 * m; |
| +добавлено | } |
| +добавлено | // rough surfaces stop short of a white rim at grazing: F90 drops with roughness (Lagarde 2014, |
| +добавлено | // as UW's ocean: F90 = 1 - 0.7 sqrt(alpha), alpha = roughness^2) |
| +добавлено | float fresnelRough(float cosTheta, float f0, float roughness) { |
| +добавлено | float f90 = max(1.0 - 0.7 * roughness, f0); |
| +добавлено | float m = 1.0 - clamp(cosTheta, 0.0, 1.0), m2 = m * m; |
| +добавлено | return f0 + (f90 - f0) * m2 * m2 * m; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // transmittance after dist metres of a medium with absorption (1/m) per channel |
| +добавлено | vec3 beerLambert(vec3 absorption, float dist) { return exp(-absorption * dist); } |
| +добавлено | |
| +добавлено | // sky cube radiance along r. The cube is plain mipmapped (not convolved): a mip texel spans |
| +добавлено | // ~2^lod / size of a face, so the GGX lobe width alpha maps to lod = log2(alpha * size * 0.64). |
| +добавлено | // The cube's lower hemisphere already holds the lit ground (sky.js). |
| +добавлено | vec3 envReflect(vec3 r, float roughness) { |
| +добавлено | float size = float(textureSize(uSkyCube, 0).x); |
| +добавлено | return textureLod(uSkyCube, r, log2(max(roughness * roughness * size * 0.64, 1.0))).rgb; |
| +добавлено | } |
| +добавлено | |
| +добавлено | float refrViewZ(vec3 p) { return -(viewMatrix * vec4(p, 1.0)).z; } |
| +добавлено | vec2 refrUV(vec3 p) { vec4 c = projectionMatrix * viewMatrix * vec4(p, 1.0); return c.xy / c.w * 0.5 + 0.5; } |
| +добавлено | |
| +добавлено | // Scene seen through a surface at worldPos (normal n, v = to camera): the screen lookup moves to |
| +добавлено | // where the refracted ray is after 'thickness' metres (pass the medium thickness, scaled up for a |
| +добавлено | // stronger lens). If that lookup lands on something in front of the surface (an object edge), it |
| +добавлено | // falls back smoothly to the straight-through lookup, as UW's water does, so edges get no |
| +добавлено | // outline. behind = metres (view z) from the surface to the opaque scene behind the lookup. |
| +добавлено | vec3 sceneRefract(vec3 worldPos, vec3 n, vec3 v, float ior, float thickness, out float behind) { |
| +добавлено | vec2 px = 1.0 / uResolution; |
| +добавлено | vec2 uv0 = gl_FragCoord.xy * px; |
| +добавлено | vec3 rd = refract(-v, n, 1.0 / ior); |
| +добавлено | vec2 uv = clamp(refrUV(worldPos + rd * thickness), px, 1.0 - px); |
| +добавлено | float zs = refrViewZ(worldPos); |
| +добавлено | float z0 = linearDepth(textureLod(uSceneDepth, uv0, 0.0).r); |
| +добавлено | float z1 = linearDepth(textureLod(uSceneDepth, uv, 0.0).r); |
| +добавлено | float keep = smoothstep(zs - 0.3, zs + 0.3, z1); |
| +добавлено | behind = max(mix(z0, z1, keep) - zs, 0.0); |
| +добавлено | return textureLod(uSceneColor, mix(uv0, uv, keep), 0.0).rgb; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { U, COMMON_GLSL, FX_VERT_HEAD, FX_FRAG_HEAD, FX_OUT_GLSL, FX_BLENDING, LINES_BLENDING } from './common.js'; |
| +добавлено | |
| +добавлено | // Instanced camera-facing strips (PLAN 2.5 "Ribbons and bolts"). One draw per material for every |
| +добавлено | // ribbon it owns; nothing is allocated after construction. Strips wind either way depending on |
| +добавлено | // the path direction, so every strip material is DoubleSide. |
| +добавлено | // TrailRibbons history ribbons: a points x max float texture of head positions, a ring per row |
| +добавлено | // AnalyticRibbons stateless: the centreline is user GLSL evaluated per vertex |
| +добавлено | // Bolts.js builds on STRIP_GLSL too. |
| +добавлено | // |
| +добавлено | // Distortion amounts everywhere are metres of apparent displacement at the strip's depth, so a far |
| +добавлено | // effect bends the background less than a near one. |
| +добавлено | |
| +добавлено | // Needs projectionMatrix, viewMatrix and cameraPosition (three's prefix, or FX_VERT_HEAD). |
| +добавлено | export const STRIP_GLSL = /* glsl */` |
| +добавлено | // Humus "phone-wire" AA: a strip is never drawn thinner than 1.5 px; the width it lacks comes back |
| +добавлено | // as intensity (aa = trueWidth / clampedWidth), so thin wires fade out instead of breaking into dashes. |
| +добавлено | // Returns the world half width to expand by. |
| +добавлено | float wireHalfWidth(float width, float viewZ, float pxPerM, out float aa) { |
| +добавлено | float px = width * pxPerM / max(viewZ, 1e-3); |
| +добавлено | float clamped = max(px, 1.5); |
| +добавлено | aa = px / clamped; |
| +добавлено | return 0.5 * width * clamped / max(px, 1e-6); |
| +добавлено | } |
| +добавлено | // pixels per metre at view depth 1, for a target resY pixels tall |
| +добавлено | float pxPerMetre(float resY) { return 0.5 * resY * projectionMatrix[1][1]; } |
| +добавлено | // unit side vector of a strip through p with tangent t, facing the camera |
| +добавлено | vec3 stripSide(vec3 p, vec3 t) { |
| +добавлено | vec3 s = cross(t, p - cameraPosition); |
| +добавлено | float l = length(s); |
| +добавлено | return l > 1e-7 ? s / l : vec3(1.0, 0.0, 0.0); |
| +добавлено | } |
| +добавлено | // screen-UV offset of 1 m of apparent displacement along world dir at p (dir ~ perpendicular to the view ray) |
| +добавлено | vec2 distortPerMetre(vec3 p, vec3 dir, float viewZ, vec2 res) { |
| +добавлено | mat4 vp = projectionMatrix * viewMatrix; |
| +добавлено | vec4 a = vp * vec4(p, 1.0), b = vp * vec4(p + dir * 0.01 * viewZ, 1.0); |
| +добавлено | vec2 px = (b.xy / b.w - a.xy / a.w) * res; |
| +добавлено | vec2 d = dot(px, px) > 1e-12 ? normalize(px) : vec2(1.0, 0.0); |
| +добавлено | float h = 0.5 * projectionMatrix[1][1] / max(viewZ, 1e-3); // metres -> fraction of screen height |
| +добавлено | return d * vec2(h * res.y / res.x, h); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // dead instances / strands: every vertex at one point outside the clip volume |
| +добавлено | const COLLAPSE = 'gl_Position = vec4(2.0, 2.0, 2.0, 1.0);'; |
| +добавлено | |
| +добавлено | // (count + 1) x 2 vertex strip; position = (x, side, z) with x from xOf(i) |
| +добавлено | function stripIndex(index, base, segments) { |
| +добавлено | for (let i = 0; i < segments; i++) { |
| +добавлено | const a = base + i * 2; |
| +добавлено | index.push(a, a + 1, a + 2, a + 1, a + 3, a + 2); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // write 4 floats, report whether anything changed (dirty tracking without allocations) |
| +добавлено | export function put4(arr, o, x, y, z, w) { |
| +добавлено | if (arr[o] === x && arr[o + 1] === y && arr[o + 2] === z && arr[o + 3] === w) return false; |
| +добавлено | arr[o] = x; arr[o + 1] = y; arr[o + 2] = z; arr[o + 3] = w; |
| +добавлено | return true; |
| +добавлено | } |
| +добавлено | const put4v = (arr, o, v) => put4(arr, o, v.x, v.y, v.z, v.w); |
| +добавлено | |
| +добавлено | export function instanced(geo, name, count, size = 4) { |
| +добавлено | const attr = new THREE.InstancedBufferAttribute(new Float32Array(count * size), size); |
| +добавлено | attr.setUsage(THREE.DynamicDrawUsage); |
| +добавлено | geo.setAttribute(name, attr); |
| +добавлено | return attr; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- history ribbons --------------------------------------------------------------------- |
| +добавлено | |
| +добавлено | const TRAIL_VERT = /* glsl */` |
| +добавлено | uniform highp sampler2D uTrailTex; // x = point slot (ring), y = trail row; xyz pos, w push time |
| +добавлено | uniform float uTrailTime; |
| +добавлено | in vec4 aTrail; // row, head slot, point count, fade time |
| +добавлено | in vec4 aLook; // width, glow (fx width multiplier), taper, distortion (m) |
| +добавлено | in vec4 aColor; // rgb * intensity, glow intensity (fraction of the core's) |
| +добавлено | out vec2 vUv; // along (0 head .. 1 tail), across (-1..1) |
| +добавлено | out vec3 vColor; |
| +добавлено | out float vViewZ; |
| +добавлено | out vec2 vDist; |
| +добавлено | |
| +добавлено | vec4 trailPoint(int row, int head, int i, int P) { return texelFetch(uTrailTex, ivec2((head - i + P) % P, row), 0); } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | int n = int(aTrail.z); |
| +добавлено | vColor = vec3(0.0); vUv = vec2(0.0); vViewZ = 1.0; vDist = vec2(0.0); |
| +добавлено | if (n < 2) { ${COLLAPSE} return; } |
| +добавлено | int P = textureSize(uTrailTex, 0).x, row = int(aTrail.x), head = int(aTrail.y); |
| +добавлено | int i = min(int(position.x), n - 1); |
| +добавлено | vec4 c = trailPoint(row, head, i, P); |
| +добавлено | vec3 tangent = trailPoint(row, head, max(i - 1, 0), P).xyz - trailPoint(row, head, min(i + 1, n - 1), P).xyz; |
| +добавлено | float u = float(i) / float(n - 1); |
| +добавлено | // past the last point the strip folds onto it with zero width (zero-area triangles) |
| +добавлено | float alive = position.x > float(n - 1) ? 0.0 : 1.0; |
| +добавлено | float fade = clamp(1.0 - (uTrailTime - c.w) / max(aTrail.w, 1e-3), 0.0, 1.0); |
| +добавлено | fade *= fade; |
| +добавлено | vec4 view = viewMatrix * vec4(c.xyz, 1.0); |
| +добавлено | vViewZ = -view.z; |
| +добавлено | vec3 side = stripSide(c.xyz, tangent); |
| +добавлено | float width = aLook.x * mix(1.0, 1.0 - u, aLook.z) * alive, aa; |
| +добавлено | #ifdef TRAIL_FX |
| +добавлено | // the wide glow would end in a square cap at the head: fade it in over the first two points |
| +добавлено | float cap = smoothstep(0.0, 2.0, float(i)); |
| +добавлено | float hw = wireHalfWidth(width * aLook.y * mix(0.4, 1.0, cap), vViewZ, pxPerMetre(uFxResolution.y), aa); |
| +добавлено | vColor = aColor.rgb * aColor.a * fade * aa * cap; |
| +добавлено | vDist = distortPerMetre(c.xyz, side, vViewZ, uFxResolution) * aLook.w * fade; |
| +добавлено | #else |
| +добавлено | float hw = wireHalfWidth(width, vViewZ, pxPerMetre(uResolution.y), aa); |
| +добавлено | vColor = aColor.rgb * fade * aa; |
| +добавлено | #endif |
| +добавлено | vUv = vec2(u, position.y); |
| +добавлено | gl_Position = projectionMatrix * viewMatrix * vec4(c.xyz + side * position.y * hw, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const TRAIL_LINES_FRAG = /* glsl */` |
| +добавлено | in vec2 vUv; |
| +добавлено | in vec3 vColor; |
| +добавлено | out vec4 fragColor; |
| +добавлено | void main() { |
| +добавлено | float v = 1.0 - vUv.y * vUv.y; |
| +добавлено | fragColor = vec4(vColor * v * v, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const TRAIL_FX_FRAG = /* glsl */` |
| +добавлено | in vec2 vUv; |
| +добавлено | in vec3 vColor; |
| +добавлено | in float vViewZ; |
| +добавлено | in vec2 vDist; |
| +добавлено | void main() { |
| +добавлено | float v = vUv.y; |
| +добавлено | float g = max(exp(-4.0 * v * v) - 0.0183, 0.0); // gaussian, zero at the strip edge |
| +добавлено | // derivative-of-gaussian profile: the centreline acts as a cylindrical lens (pushes outward) |
| +добавлено | vec2 dist = vDist * (v * exp(-3.0 * v * v) * 2.33); |
| +добавлено | fxOut(vec3(0.0), 0.0, vColor * g * softFade(vViewZ, 0.4), dist, vViewZ); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // per-trail look, reset on acquire. spacing: metres between committed points (points * spacing |
| +добавлено | // caps the trail's length; fadeTime its duration) |
| +добавлено | const TRAIL_DEFAULTS = { width: 0.06, intensity: 4, glow: 6, glowIntensity: 0.3, distortion: 0, taper: 1, fadeTime: 0.4, spacing: 0.08 }; |
| +добавлено | |
| +добавлено | export class TrailRibbons { |
| +добавлено | constructor({ max = 64, points = 48 } = {}) { |
| +добавлено | this.max = max; |
| +добавлено | this.points = points; |
| +добавлено | this.time = 0; |
| +добавлено | this.data = new Float32Array(points * max * 4); |
| +добавлено | const tex = this.texture = new THREE.DataTexture(this.data, points, max, THREE.RGBAFormat, THREE.FloatType); |
| +добавлено | tex.minFilter = tex.magFilter = THREE.NearestFilter; |
| +добавлено | tex.needsUpdate = true; |
| +добавлено | // one texel per push; preallocated so pushing into texture.updateRanges allocates nothing |
| +добавлено | this._ranges = Array.from({ length: max * 4 }, () => ({ start: 0, count: 0 })); |
| +добавлено | this._nRanges = 0; |
| +добавлено | this._full = false; |
| +добавлено | |
| +добавлено | const geo = new THREE.InstancedBufferGeometry(); |
| +добавлено | const pos = [], index = []; |
| +добавлено | for (let i = 0; i < points; i++) pos.push(i, -1, 0, i, 1, 0); |
| +добавлено | stripIndex(index, 0, points - 1); |
| +добавлено | geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); |
| +добавлено | geo.setIndex(index); |
| +добавлено | this.aTrail = instanced(geo, 'aTrail', max); |
| +добавлено | this.aLook = instanced(geo, 'aLook', max); |
| +добавлено | this.aColor = instanced(geo, 'aColor', max); |
| +добавлено | geo.instanceCount = 0; |
| +добавлено | this.geometry = geo; |
| +добавлено | |
| +добавлено | this.uniforms = { ...U, uTrailTex: { value: tex }, uTrailTime: { value: 0 } }; |
| +добавлено | this.lines = new THREE.Mesh(geo, new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms: this.uniforms, ...LINES_BLENDING, side: THREE.DoubleSide, |
| +добавлено | vertexShader: COMMON_GLSL + STRIP_GLSL + TRAIL_VERT, fragmentShader: TRAIL_LINES_FRAG, |
| +добавлено | })); |
| +добавлено | this.fx = new THREE.Mesh(geo, new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms: this.uniforms, ...FX_BLENDING, side: THREE.DoubleSide, defines: { TRAIL_FX: 1 }, |
| +добавлено | vertexShader: FX_VERT_HEAD + COMMON_GLSL + STRIP_GLSL + TRAIL_VERT, |
| +добавлено | fragmentShader: FX_FRAG_HEAD + COMMON_GLSL + FX_OUT_GLSL + TRAIL_FX_FRAG, |
| +добавлено | })); |
| +добавлено | this.lines.frustumCulled = this.fx.frustumCulled = false; |
| +добавлено | this.lines.visible = this.fx.visible = false; |
| +добавлено | |
| +добавлено | this.trails = Array.from({ length: max }, (_, row) => { |
| +добавлено | const owner = this; |
| +добавлено | return { |
| +добавлено | row, active: false, released: false, head: 0, count: 0, lastPush: 0, |
| +добавлено | last: new THREE.Vector3(), color: new THREE.Color(1, 1, 1), ...TRAIL_DEFAULTS, |
| +добавлено | // the newest point follows pos; a new point is committed once it is `spacing` from the last |
| +добавлено | push(p) { |
| +добавлено | if (this.count > 0 && this.last.distanceToSquared(p) >= this.spacing * this.spacing) { |
| +добавлено | this.head = (this.head + 1) % owner.points; |
| +добавлено | this.count = Math.min(this.count + 1, owner.points); |
| +добавлено | this.last.copy(p); |
| +добавлено | } else if (this.count === 0) { |
| +добавлено | this.count = 1; |
| +добавлено | this.last.copy(p); |
| +добавлено | } |
| +добавлено | owner._write(this.row, this.head, p); |
| +добавлено | this.lastPush = owner.time; |
| +добавлено | }, |
| +добавлено | release() { this.released = true; }, |
| +добавлено | }; |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // released trails keep drawing until their newest point has faded (fadeTime), then free |
| +добавлено | acquire() { |
| +добавлено | for (const t of this.trails) { |
| +добавлено | if (t.active) continue; |
| +добавлено | Object.assign(t, TRAIL_DEFAULTS); |
| +добавлено | t.active = true; t.released = false; t.head = 0; t.count = 0; |
| +добавлено | t.color.setRGB(1, 1, 1); |
| +добавлено | return t; |
| +добавлено | } |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | _write(row, slot, p) { |
| +добавлено | const i = row * this.points + slot, o = i * 4, d = this.data; |
| +добавлено | d[o] = p.x; d[o + 1] = p.y; d[o + 2] = p.z; d[o + 3] = this.time; |
| +добавлено | if (this._nRanges < this._ranges.length) { |
| +добавлено | const r = this._ranges[this._nRanges++]; |
| +добавлено | r.start = o; r.count = 4; |
| +добавлено | } else this._full = true; |
| +добавлено | } |
| +добавлено | |
| +добавлено | update(dt) { |
| +добавлено | this.time += dt; |
| +добавлено | this.uniforms.uTrailTime.value = this.time; |
| +добавлено | const A = this.aTrail.array, B = this.aLook.array, C = this.aColor.array; |
| +добавлено | let n = 0; |
| +добавлено | for (const t of this.trails) { |
| +добавлено | if (!t.active) continue; |
| +добавлено | if (t.released && this.time - t.lastPush > t.fadeTime) { t.active = false; continue; } |
| +добавлено | const o = n * 4, I = t.intensity; |
| +добавлено | A[o] = t.row; A[o + 1] = t.head; A[o + 2] = t.count; A[o + 3] = t.fadeTime; |
| +добавлено | B[o] = t.width; B[o + 1] = t.glow; B[o + 2] = t.taper; B[o + 3] = t.distortion; |
| +добавлено | C[o] = t.color.r * I; C[o + 1] = t.color.g * I; C[o + 2] = t.color.b * I; C[o + 3] = t.glowIntensity; |
| +добавлено | n++; |
| +добавлено | } |
| +добавлено | this.geometry.instanceCount = n; |
| +добавлено | this.lines.visible = this.fx.visible = n > 0; |
| +добавлено | if (n) this.aTrail.needsUpdate = this.aLook.needsUpdate = this.aColor.needsUpdate = true; |
| +добавлено | |
| +добавлено | // texel uploads: only what was pushed. Ranges still queued from a frame that never drew mean |
| +добавлено | // the GPU copy is behind, so send the whole texture once (48 KB at 64 x 48). |
| +добавлено | const tex = this.texture; |
| +добавлено | if (tex.updateRanges.length) this._full = true; |
| +добавлено | if (this._full) { |
| +добавлено | tex.updateRanges.length = 0; |
| +добавлено | tex.needsUpdate = true; |
| +добавлено | } else if (this._nRanges) { |
| +добавлено | for (let i = 0; i < this._nRanges; i++) tex.updateRanges.push(this._ranges[i]); |
| +добавлено | tex.needsUpdate = true; |
| +добавлено | } |
| +добавлено | this._full = false; |
| +добавлено | this._nRanges = 0; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- analytic ribbons ------------------------------------------------------------------ |
| +добавлено | |
| +добавлено | // The default shade: a soft additive core in the ribbon's colour. |
| +добавлено | const DEFAULT_SHADE = /* glsl */` |
| +добавлено | vec3 ribbonShade(RibbonFrag r, out vec3 media, out float alpha, out float distortion) { |
| +добавлено | media = vec3(0.0); alpha = 0.0; distortion = 0.0; |
| +добавлено | float v = 1.0 - r.uv.y * r.uv.y; |
| +добавлено | return r.color * v * v; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const ANALYTIC_HEAD = /* glsl */` |
| +добавлено | uniform float uSegments; |
| +добавлено | struct RibbonFrag { |
| +добавлено | vec2 uv; // x along 0..1, y across -1..1 |
| +добавлено | vec4 p0, p1, p2, p3; |
| +добавлено | vec3 color; // colour * intensity |
| +добавлено | float viewZ; |
| +добавлено | }; |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const ANALYTIC_VERT = /* glsl */` |
| +добавлено | in vec4 aP0; |
| +добавлено | in vec4 aP1; |
| +добавлено | in vec4 aP2; |
| +добавлено | in vec4 aP3; |
| +добавлено | in vec4 aColor; // rgb * intensity, on |
| +добавлено | out vec2 vUv; |
| +добавлено | out float vViewZ; |
| +добавлено | out float vAA; |
| +добавлено | out vec2 vDist; |
| +добавлено | flat out vec4 vP0; |
| +добавлено | flat out vec4 vP1; |
| +добавлено | flat out vec4 vP2; |
| +добавлено | flat out vec4 vP3; |
| +добавлено | flat out vec3 vColor; |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vUv = vec2(0.0); vViewZ = 1.0; vAA = 0.0; vDist = vec2(0.0); |
| +добавлено | vP0 = aP0; vP1 = aP1; vP2 = aP2; vP3 = aP3; vColor = aColor.rgb; |
| +добавлено | if (aColor.a <= 0.0) { ${COLLAPSE} return; } |
| +добавлено | float t = position.x, w, w2; |
| +добавлено | vec3 p = ribbonPath(t, aP0, aP1, aP2, aP3, w); |
| +добавлено | float h = 0.5 / uSegments; |
| +добавлено | vec3 tangent = ribbonPath(min(t + h, 1.0), aP0, aP1, aP2, aP3, w2) - ribbonPath(max(t - h, 0.0), aP0, aP1, aP2, aP3, w2); |
| +добавлено | vec3 side = stripSide(p, tangent); |
| +добавлено | vViewZ = -(viewMatrix * vec4(p, 1.0)).z; |
| +добавлено | #ifdef RIBBON_FX |
| +добавлено | float hw = wireHalfWidth(w, vViewZ, pxPerMetre(uFxResolution.y), vAA); |
| +добавлено | vDist = distortPerMetre(p, side, vViewZ, uFxResolution); |
| +добавлено | #else |
| +добавлено | float hw = wireHalfWidth(w, vViewZ, pxPerMetre(uResolution.y), vAA); |
| +добавлено | #endif |
| +добавлено | vUv = vec2(t, position.y); |
| +добавлено | gl_Position = projectionMatrix * viewMatrix * vec4(p + side * position.y * hw, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const ANALYTIC_LINES_FRAG = /* glsl */` |
| +добавлено | in vec2 vUv; |
| +добавлено | in float vViewZ; |
| +добавлено | in float vAA; |
| +добавлено | flat in vec4 vP0; |
| +добавлено | flat in vec4 vP1; |
| +добавлено | flat in vec4 vP2; |
| +добавлено | flat in vec4 vP3; |
| +добавлено | flat in vec3 vColor; |
| +добавлено | out vec4 fragColor; |
| +добавлено | void main() { |
| +добавлено | vec3 media = vec3(0.0); float alpha = 0.0, distortion = 0.0; |
| +добавлено | vec3 e = ribbonShade(RibbonFrag(vUv, vP0, vP1, vP2, vP3, vColor, vViewZ), media, alpha, distortion); |
| +добавлено | fragColor = vec4(e * vAA, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const ANALYTIC_FX_FRAG = /* glsl */` |
| +добавлено | in vec2 vUv; |
| +добавлено | in float vViewZ; |
| +добавлено | in float vAA; |
| +добавлено | in vec2 vDist; |
| +добавлено | flat in vec4 vP0; |
| +добавлено | flat in vec4 vP1; |
| +добавлено | flat in vec4 vP2; |
| +добавлено | flat in vec4 vP3; |
| +добавлено | flat in vec3 vColor; |
| +добавлено | void main() { |
| +добавлено | vec3 media = vec3(0.0); float alpha = 0.0, distortion = 0.0; |
| +добавлено | vec3 e = ribbonShade(RibbonFrag(vUv, vP0, vP1, vP2, vP3, vColor, vViewZ), media, alpha, distortion); |
| +добавлено | float s = softFade(vViewZ, 0.3) * vAA; |
| +добавлено | fxOut(media, alpha * s, e * s, vDist * distortion * s, vViewZ); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // pathGLSL: vec3 ribbonPath(float t, vec4 p0, vec4 p1, vec4 p2, vec4 p3, out float width) t 0..1 |
| +добавлено | // shadeGLSL: vec3 ribbonShade(RibbonFrag r, out vec3 media, out float alpha, out float distortion) |
| +добавлено | // returns emission; media/alpha (WBOIT coverage) and distortion only count for target 'fx'. |
| +добавлено | // distortion: signed metres along the +uv.y side; make it odd in uv.y (e.g. uv.y * exp(-3 uv.y^2)) |
| +добавлено | // to push the background away from the centreline. |
| +добавлено | // Either may declare its own uniforms (pass them in `uniforms`). |
| +добавлено | export class AnalyticRibbons { |
| +добавлено | constructor({ max = 16, segments = 64, pathGLSL, shadeGLSL = DEFAULT_SHADE, target = 'lines', uniforms = {} }) { |
| +добавлено | this.max = max; |
| +добавлено | const geo = new THREE.InstancedBufferGeometry(); |
| +добавлено | const pos = [], index = []; |
| +добавлено | for (let i = 0; i <= segments; i++) pos.push(i / segments, -1, 0, i / segments, 1, 0); |
| +добавлено | stripIndex(index, 0, segments); |
| +добавлено | geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); |
| +добавлено | geo.setIndex(index); |
| +добавлено | this.attrs = ['aP0', 'aP1', 'aP2', 'aP3', 'aColor'].map((n) => instanced(geo, n, max)); |
| +добавлено | geo.instanceCount = 0; |
| +добавлено | this.geometry = geo; |
| +добавлено | this.uniforms = { ...U, ...uniforms, uSegments: { value: segments } }; |
| +добавлено | const head = COMMON_GLSL + STRIP_GLSL + ANALYTIC_HEAD + pathGLSL; |
| +добавлено | const material = target === 'fx' |
| +добавлено | ? new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms: this.uniforms, ...FX_BLENDING, side: THREE.DoubleSide, defines: { RIBBON_FX: 1 }, |
| +добавлено | vertexShader: FX_VERT_HEAD + head + ANALYTIC_VERT, |
| +добавлено | fragmentShader: FX_FRAG_HEAD + COMMON_GLSL + FX_OUT_GLSL + ANALYTIC_HEAD + shadeGLSL + ANALYTIC_FX_FRAG, |
| +добавлено | }) |
| +добавлено | : new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms: this.uniforms, ...LINES_BLENDING, side: THREE.DoubleSide, |
| +добавлено | vertexShader: head + ANALYTIC_VERT, fragmentShader: COMMON_GLSL + ANALYTIC_HEAD + shadeGLSL + ANALYTIC_LINES_FRAG, |
| +добавлено | }); |
| +добавлено | this.mesh = new THREE.Mesh(geo, material); |
| +добавлено | this.mesh.frustumCulled = false; |
| +добавлено | this.mesh.visible = false; |
| +добавлено | this.ribbons = Array.from({ length: max }, (_, index) => ({ |
| +добавлено | index, active: false, |
| +добавлено | p0: new THREE.Vector4(), p1: new THREE.Vector4(), p2: new THREE.Vector4(), p3: new THREE.Vector4(), |
| +добавлено | color: new THREE.Color(1, 1, 1), intensity: 1, |
| +добавлено | release() { this.active = false; }, |
| +добавлено | })); |
| +добавлено | } |
| +добавлено | |
| +добавлено | acquire() { |
| +добавлено | for (const r of this.ribbons) { |
| +добавлено | if (r.active) continue; |
| +добавлено | r.active = true; r.intensity = 1; r.color.setRGB(1, 1, 1); |
| +добавлено | r.p0.set(0, 0, 0, 0); r.p1.set(0, 0, 0, 0); r.p2.set(0, 0, 0, 0); r.p3.set(0, 0, 0, 0); |
| +добавлено | return r; |
| +добавлено | } |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // copy handle fields into the instance attributes; upload only if something changed |
| +добавлено | update() { |
| +добавлено | let top = 0, dirty = false; |
| +добавлено | const X = this.attrs, a0 = X[0], a1 = X[1], a2 = X[2], a3 = X[3], ac = X[4]; |
| +добавлено | for (const r of this.ribbons) { |
| +добавлено | const o = r.index * 4, on = r.active && r.intensity > 0; |
| +добавлено | if (on) top = r.index + 1; |
| +добавлено | dirty = put4(ac.array, o, r.color.r * r.intensity, r.color.g * r.intensity, r.color.b * r.intensity, on ? 1 : 0) || dirty; |
| +добавлено | if (!on) continue; |
| +добавлено | dirty = put4v(a0.array, o, r.p0) || dirty; |
| +добавлено | dirty = put4v(a1.array, o, r.p1) || dirty; |
| +добавлено | dirty = put4v(a2.array, o, r.p2) || dirty; |
| +добавлено | dirty = put4v(a3.array, o, r.p3) || dirty; |
| +добавлено | } |
| +добавлено | if (dirty) for (const a of this.attrs) a.needsUpdate = true; |
| +добавлено | this.geometry.instanceCount = top; |
| +добавлено | this.mesh.visible = top > 0; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { U, COMMON_GLSL, FX_VERT_HEAD, FX_FRAG_HEAD, FX_OUT_GLSL, FX_BLENDING } from './common.js'; |
| +добавлено | import { instanced } from './Ribbons.js'; |
| +добавлено | |
| +добавлено | // Expanding shock shells and ground rings in the fx pass: a radial screen-space distortion |
| +добавлено | // proportional to how much shell the view ray crosses (so the rim reads as a lens), plus optional |
| +добавлено | // emission. Fire and forget: spawn() and the pool (16, one instanced draw) ages them out. |
| +добавлено | // sphere: camera-facing quad perpendicular to the view axis, sized to the shell's silhouette cone; |
| +добавлено | // the profile is the exact chord through the shell, normalised to 1 at its peak (rho = inner radius) |
| +добавлено | // ground: a flat quad hugging pos.y; ring profile with a sharp leading edge and a soft wake |
| +добавлено | // Radius follows a blast-wave curve r0 + (r1 - r0) x^0.4 (Sedov-Taylor r ~ t^0.4); emission decays |
| +добавлено | // as (1 - x)^3 (a flash), distortion as (1 - x)^1.5 after a 5% attack. distortion is metres of |
| +добавлено | // apparent displacement at the shell's depth. |
| +добавлено | |
| +добавлено | const VERT = /* glsl */` |
| +добавлено | in vec4 aS0; // centre, ground |
| +добавлено | in vec4 aS1; // radius, thickness, progress (< 0: dead), - |
| +добавлено | in vec4 aS2; // emission rgb, distortion (m), envelopes applied |
| +добавлено | out vec3 vWorld; |
| +добавлено | out float vViewZ; |
| +добавлено | flat out vec4 vS0; |
| +добавлено | flat out vec4 vS1; |
| +добавлено | flat out vec4 vS2; |
| +добавлено | flat out vec2 vCentre; // projected centre, fx pixels |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vS0 = aS0; vS1 = aS1; vS2 = aS2; vWorld = vec3(0.0); vViewZ = 1.0; vCentre = vec2(0.0); |
| +добавлено | vec3 c = aS0.xyz; |
| +добавлено | float R = aS1.x + 0.75 * aS1.y; |
| +добавлено | vec3 toC = c - cameraPosition; |
| +добавлено | float D = length(toC); |
| +добавлено | // ponytail: a camera inside a sphere shell just loses it (ground rings still draw) |
| +добавлено | if (aS1.z < 0.0 || (aS0.w < 0.5 && D < R * 1.05)) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; } |
| +добавлено | vec3 p; |
| +добавлено | if (aS0.w > 0.5) p = c + vec3(position.x * R, 0.03, position.y * R); |
| +добавлено | else { |
| +добавлено | vec3 f = toC / D, r = normalize(cross(f, abs(f.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0))), u = cross(r, f); |
| +добавлено | p = c + (r * position.x + u * position.y) * (R / sqrt(1.0 - (R / D) * (R / D))); |
| +добавлено | } |
| +добавлено | vWorld = p; |
| +добавлено | vec4 cc = projectionMatrix * viewMatrix * vec4(c, 1.0); |
| +добавлено | vCentre = (cc.xy / cc.w * 0.5 + 0.5) * uFxResolution; |
| +добавлено | vec4 view = viewMatrix * vec4(p, 1.0); |
| +добавлено | vViewZ = -view.z; |
| +добавлено | gl_Position = projectionMatrix * view; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const FRAG = /* glsl */` |
| +добавлено | uniform mat4 projectionMatrix; |
| +добавлено | in vec3 vWorld; |
| +добавлено | in float vViewZ; |
| +добавлено | flat in vec4 vS0; |
| +добавлено | flat in vec4 vS1; |
| +добавлено | flat in vec4 vS2; |
| +добавлено | flat in vec2 vCentre; |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vec3 c = vS0.xyz; |
| +добавлено | float r = vS1.x, th = vS1.y, prof; |
| +добавлено | if (vS0.w > 0.5) { |
| +добавлено | // sharp leading edge, soft wake behind it |
| +добавлено | float x = (length(vWorld.xz - c.xz) - r) / (0.5 * th); |
| +добавлено | prof = exp(-x * x * (x > 0.0 ? 6.0 : 0.8)); |
| +добавлено | } else { |
| +добавлено | vec3 rd = normalize(vWorld - cameraPosition), oc = c - cameraPosition; |
| +добавлено | float tc = dot(oc, rd), rho2 = max(dot(oc, oc) - tc * tc, 0.0); |
| +добавлено | float ro = r + 0.5 * th, ri = max(r - 0.5 * th, 0.0); |
| +добавлено | float chord = sqrt(max(ro * ro - rho2, 0.0)) - sqrt(max(ri * ri - rho2, 0.0)); |
| +добавлено | prof = chord / sqrt(max(ro * ro - ri * ri, 1e-6)); |
| +добавлено | } |
| +добавлено | if (prof < 1e-3) discard; |
| +добавлено | vec2 dir = gl_FragCoord.xy - vCentre; |
| +добавлено | dir = dot(dir, dir) > 1e-6 ? normalize(dir) : vec2(0.0); |
| +добавлено | float h = 0.5 * projectionMatrix[1][1] / max(vViewZ, 1e-3); |
| +добавлено | float s = softFade(vViewZ, 0.3) * prof; |
| +добавлено | // sample nearer the centre: the background bulges outward under the rim |
| +добавлено | vec2 dist = -dir * vec2(h * uFxResolution.y / uFxResolution.x, h) * vS2.w * s; |
| +добавлено | // emission hugs the rim (seen through, the shell's two walls would otherwise glow as a dome) |
| +добавлено | float p2 = prof * prof; |
| +добавлено | fxOut(vec3(0.0), 0.0, vS2.rgb * p2 * p2 * softFade(vViewZ, 0.3), dist, vViewZ); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export class Shockwaves { |
| +добавлено | constructor({ max = 16 } = {}) { |
| +добавлено | const geo = new THREE.InstancedBufferGeometry(); |
| +добавлено | geo.setAttribute('position', new THREE.Float32BufferAttribute([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0], 3)); |
| +добавлено | geo.setIndex([0, 1, 2, 0, 2, 3]); |
| +добавлено | this.attrs = ['aS0', 'aS1', 'aS2'].map((n) => instanced(geo, n, max)); |
| +добавлено | geo.instanceCount = 0; |
| +добавлено | this.geometry = geo; |
| +добавлено | this.uniforms = { ...U }; |
| +добавлено | this.mesh = new THREE.Mesh(geo, new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms: this.uniforms, ...FX_BLENDING, side: THREE.DoubleSide, |
| +добавлено | vertexShader: FX_VERT_HEAD + COMMON_GLSL + VERT, |
| +добавлено | fragmentShader: FX_FRAG_HEAD + COMMON_GLSL + FX_OUT_GLSL + FRAG, |
| +добавлено | })); |
| +добавлено | this.mesh.frustumCulled = false; |
| +добавлено | this.mesh.visible = false; |
| +добавлено | this.slots = Array.from({ length: max }, (_, index) => ({ |
| +добавлено | index, active: false, age: 0, |
| +добавлено | pos: new THREE.Vector3(), radius0: 0.2, radius1: 6, duration: 0.6, thickness: 0.6, |
| +добавлено | distortion: 0.12, color: new THREE.Color(1, 1, 1), intensity: 0, ground: false, |
| +добавлено | })); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // pos: Vector3, color: THREE.Color (both copied). Full pool: the most advanced wave is replaced. |
| +добавлено | spawn({ pos, radius0 = 0.2, radius1 = 6, duration = 0.6, thickness = 0.6, distortion = 0.12, color, intensity = 0, ground = false }) { |
| +добавлено | let s = this.slots[0]; |
| +добавлено | for (const x of this.slots) { |
| +добавлено | if (!x.active) { s = x; break; } |
| +добавлено | if (x.age / x.duration > s.age / s.duration) s = x; |
| +добавлено | } |
| +добавлено | s.pos.copy(pos); |
| +добавлено | Object.assign(s, { active: true, age: 0, radius0, radius1, duration, thickness, distortion, intensity, ground }); |
| +добавлено | if (color) s.color.copy(color); else s.color.setRGB(1, 1, 1); |
| +добавлено | return s; |
| +добавлено | } |
| +добавлено | |
| +добавлено | update(dt) { |
| +добавлено | const a0 = this.attrs[0].array, a1 = this.attrs[1].array, a2 = this.attrs[2].array; |
| +добавлено | let top = 0; |
| +добавлено | for (const s of this.slots) { |
| +добавлено | const o = s.index * 4; |
| +добавлено | if (s.active) { |
| +добавлено | s.age += dt; |
| +добавлено | if (s.age >= s.duration) s.active = false; |
| +добавлено | } |
| +добавлено | if (!s.active) { a1[o + 2] = -1; continue; } |
| +добавлено | top = s.index + 1; |
| +добавлено | const x = s.age / s.duration, k = 1 - x; |
| +добавлено | const e = s.intensity * k * k * k, d = s.distortion * Math.pow(k, 1.5) * Math.min(1, x / 0.05); |
| +добавлено | a0[o] = s.pos.x; a0[o + 1] = s.pos.y; a0[o + 2] = s.pos.z; a0[o + 3] = s.ground ? 1 : 0; |
| +добавлено | a1[o] = s.radius0 + (s.radius1 - s.radius0) * Math.pow(x, 0.4); a1[o + 1] = s.thickness * (0.5 + 0.5 * x); a1[o + 2] = x; |
| +добавлено | a2[o] = s.color.r * e; a2[o + 1] = s.color.g * e; a2[o + 2] = s.color.b * e; a2[o + 3] = d; |
| +добавлено | } |
| +добавлено | for (const a of this.attrs) a.needsUpdate = true; |
| +добавлено | this.geometry.instanceCount = top; |
| +добавлено | this.mesh.visible = top > 0; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { U, COMMON_GLSL, LINES_BLENDING, lights } from './common.js'; |
| +добавлено | import { instanced, put4 } from './Ribbons.js'; |
| +добавлено | |
| +добавлено | // Procedural SDF sigil circles (PLAN 3 Light "Judgment", Arcane). Everything is distance fields |
| +добавлено | // on a plane quad, full-res additive in the lines scene: concentric rings, a rotating band of runes |
| +добавлено | // (12 glyphs built from segments and arcs), a star polygon drawn as one pen stroke per closed |
| +добавлено | // path, ticks / sunburst / spiral arms per style, and a halo from the union distance. Lines are |
| +добавлено | // box-filtered with fwidth and never drawn thinner than ~0.6 px: below that their energy is |
| +добавлено | // scaled down instead (Persson's phone-wire AA), so a far sigil dims rather than shimmers. |
| +добавлено | // Reveal is arc length: rings sweep in clockwise (seen from the normal side), runes flash on as |
| +добавлено | // the pen passes them, then the star strokes, then the core. One instanced draw for all sigils. |
| +добавлено | // Look (Doctor Strange mandala / burning-filament reference): every stroke is a white-hot filament |
| +добавлено | // inside a saturated sheath, with hot knots of energy streaming round the circle and a halo whose |
| +добавлено | // red falls off slower than its blue (dispersion). Grinder sparks spit off the outer ring as |
| +добавлено | // velocity streaks (void sucks them inwards). Each visible sigil also borrows a spell light: a |
| +добавлено | // rune-ring cookie under a floor sigil, a point light in front of an upright one, so the burning |
| +добавлено | // strokes light the floor, pillars and dummies around them. |
| +добавлено | |
| +добавлено | // Needs COMMON_GLSL (PI, hash11). q: plane coords with |q| = 1 on the outer ring; px: pixel |
| +добавлено | // footprint in the same units (fwidth; pass a constant like 0.02 for a soft cookie). style 0 holy, |
| +добавлено | // 1 arcane, 2 void. Returns x line coverage (energy-normalised), y halo, z reveal-front sparkle. |
| +добавлено | export const SIGIL_GLSL = /* glsl */` |
| +добавлено | float sgSat(float x) { return clamp(x, 0.0, 1.0); } |
| +добавлено | float sgSeg(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0)); } |
| +добавлено | float sgCircle(vec2 p, vec2 c, float r) { return abs(length(p - c) - r); } |
| +добавлено | // arc of radius r about c, from angle a0 (radians, from +x towards +y) over da |
| +добавлено | float sgArc(vec2 p, vec2 c, float r, float a0, float da) { |
| +добавлено | vec2 q = p - c; |
| +добавлено | if (mod(atan(q.y, q.x) - a0, 2.0 * PI) < da) return abs(length(q) - r); |
| +добавлено | return min(length(q - r * vec2(cos(a0), sin(a0))), length(q - r * vec2(cos(a0 + da), sin(a0 + da)))); |
| +добавлено | } |
| +добавлено | // 12 runes (futhark-like, own shapes). Cell x in [-0.5, 0.5], y in [-1, 1]; distance to the strokes. |
| +добавлено | float sigilGlyph(int id, vec2 p) { |
| +добавлено | float d = 1e3; |
| +добавлено | #define S(ax, ay, bx, by) d = min(d, sgSeg(p, vec2(ax, ay), vec2(bx, by))) |
| +добавлено | switch (id) { |
| +добавлено | case 0: S(-0.25, -0.9, -0.25, 0.9); S(-0.25, 0.15, 0.35, 0.6); S(-0.25, -0.35, 0.35, 0.1); break; |
| +добавлено | case 1: S(0.0, -0.9, 0.0, 0.9); S(0.0, 0.9, -0.38, 0.45); S(0.0, 0.9, 0.38, 0.45); break; |
| +добавлено | case 2: S(0.0, 0.85, 0.4, 0.0); S(0.4, 0.0, 0.0, -0.85); S(0.0, -0.85, -0.4, 0.0); S(-0.4, 0.0, 0.0, 0.85); break; |
| +добавлено | case 3: S(0.0, -0.9, 0.0, 0.9); d = min(d, sgCircle(p, vec2(0.0, 0.3), 0.28)); break; |
| +добавлено | case 4: S(-0.3, 0.85, 0.3, 0.3); S(0.3, 0.3, -0.3, -0.3); S(-0.3, -0.3, 0.3, -0.85); break; |
| +добавлено | case 5: S(0.0, -0.9, 0.0, 0.9); S(0.0, 0.2, -0.4, 0.8); S(0.0, 0.2, 0.4, 0.8); break; |
| +добавлено | case 6: d = sgArc(p, vec2(0.12, 0.0), 0.55, 0.5 * PI, PI); d = min(d, sgCircle(p, vec2(0.12, 0.0), 0.08)); break; |
| +добавлено | case 7: S(-0.35, -0.9, -0.35, 0.9); S(0.35, -0.9, 0.35, 0.9); S(-0.35, 0.3, 0.35, -0.3); break; |
| +добавлено | case 8: S(-0.4, -0.8, -0.4, 0.8); S(0.4, -0.8, 0.4, 0.8); S(-0.4, 0.8, 0.4, -0.8); S(-0.4, -0.8, 0.4, 0.8); break; |
| +добавлено | case 9: d = sgCircle(p, vec2(0.0), 0.42); S(0.0, -0.8, 0.0, 0.8); S(-0.42, 0.0, 0.42, 0.0); break; |
| +добавлено | case 10: S(0.0, 0.85, 0.38, 0.35); S(0.38, 0.35, 0.0, -0.15); S(0.0, -0.15, -0.38, 0.35); S(-0.38, 0.35, 0.0, 0.85); |
| +добавлено | S(-0.25, 0.18, 0.35, -0.9); S(0.25, 0.18, -0.35, -0.9); break; |
| +добавлено | default: S(0.35, 0.8, -0.3, 0.0); S(-0.3, 0.0, 0.35, -0.8); S(0.05, 0.0, 0.42, 0.0); break; |
| +добавлено | } |
| +добавлено | #undef S |
| +добавлено | return d; |
| +добавлено | } |
| +добавлено | |
| +добавлено | float gSgPx; // pixel footprint for the helpers below |
| +добавлено | float gSgCore; // set by sigilPattern: white-hot inner filament coverage (energy-normalised) |
| +добавлено | float gSgDist; // set by sigilPattern: distance to the nearest revealed stroke (plane units) |
| +добавлено | // smooth periodic value noise: period in cells |
| +добавлено | float sgNoise(float x, float period) { |
| +добавлено | float i = floor(x), f = fract(x); |
| +добавлено | f = f * f * (3.0 - 2.0 * f); |
| +добавлено | return mix(hash11(mod(i, period) + 0.37), hash11(mod(i + 1.0, period) + 0.37), f); |
| +добавлено | } |
| +добавлено | // add one stroke: d distance, w half width, k brightness (0 = not revealed). acc.z: the inner 35% |
| +добавлено | // of the stroke, the incandescent core (also never thinner than ~0.5 px, energy-scaled instead) |
| +добавлено | void sgLine(float d, float w, float k, inout vec3 acc) { |
| +добавлено | if (k <= 0.0) return; |
| +добавлено | float we = max(w, gSgPx * 0.6); |
| +добавлено | acc.x = max(acc.x, sgSat((we - d) / gSgPx + 0.5) * (w / we) * k); |
| +добавлено | acc.y = min(acc.y, d); |
| +добавлено | float wc = 0.35 * w, wce = max(wc, gSgPx * 0.5); |
| +добавлено | acc.z = max(acc.z, sgSat((wce - d) / gSgPx + 0.5) * (wc / wce) * k); |
| +добавлено | } |
| +добавлено | // grinder sparks thrown off the outer ring: one per angular slot and cycle (~30% of slots fire), |
| +добавлено | // born on the ring, flying out (dir 1) or in (dir -1), slanted along the spin, as short streaks |
| +добавлено | float sgSparks(float r, float cw, float time, float seed, float dir) { |
| +добавлено | const float n = 96.0; |
| +добавлено | float a = cw * n, cell = floor(a); |
| +добавлено | vec4 h = hash41(cell * 1.618 + seed * 7.31); |
| +добавлено | float t = time / (0.3 + 0.45 * h.x) + h.y * 17.0; |
| +добавлено | float ph = fract(t); |
| +добавлено | if (hash11(floor(t) * 3.17 + cell * 0.71 + seed) > 0.3) return 0.0; |
| +добавлено | float v = (r - 1.0) * dir - 0.004 - ph * (0.03 + 0.07 * h.z); // radial: 0 at the spark head |
| +добавлено | float u = (fract(a) - 0.5 - (h.w - 0.5) * 0.5) * 6.2832 * r / n + v * 0.6; // tangential, slanted |
| +добавлено | float len = 0.012 + 0.03 * ph; // the streak grows as it speeds up |
| +добавлено | float d = length(vec2(u, max(v, 0.0) + max(-v - len, 0.0))); |
| +добавлено | float w = 0.0022, we = max(w, gSgPx * 0.6); |
| +добавлено | float k = 1.0 - ph; |
| +добавлено | return sgSat((we - d) / gSgPx + 0.5) * (w / we) * k * k * 2.5; |
| +добавлено | } |
| +добавлено | // clockwise sweep mask: visible where cw < p (p >= 1: whole ring, no seam) |
| +добавлено | float sgSweep(float p, float cw, float r) { return p >= 1.0 ? 1.0 : sgSat((p - cw) * 6.2832 * r / gSgPx + 0.5); } |
| +добавлено | vec2 sgPolar(float r, float cw) { float a = cw * 6.2832; return r * vec2(sin(a), -cos(a)); } |
| +добавлено | float sgPen(vec2 q, float r, float p) { |
| +добавлено | if (p <= 0.0 || p >= 1.0) return 0.0; |
| +добавлено | vec2 e = q - sgPolar(r, p); |
| +добавлено | return exp(-dot(e, e) * 2500.0); |
| +добавлено | } |
| +добавлено | // ring drawn clockwise from north up to p: a true arc SDF (round caps, seamless halo) |
| +добавлено | void sgRing(vec2 q, float r, float cw, float R, float w, float p, float k, inout vec3 acc, inout float front) { |
| +добавлено | if (p <= 0.0) return; |
| +добавлено | float d = p >= 1.0 || cw <= p ? abs(r - R) : min(length(q - vec2(0.0, -R)), length(q - sgPolar(R, p))); |
| +добавлено | sgLine(d, w, k, acc); |
| +добавлено | front += sgPen(q, R, p); |
| +добавлено | } |
| +добавлено | // rune band: n cells centred on radius rc, half height hh; rotates with rot (radians) |
| +добавлено | void sgRunes(float r, float cw, float rot, float n, float rc, float hh, float seed, float p, float time, float glitch, inout vec3 acc) { |
| +добавлено | if (abs(r - rc) > hh * 1.3) return; |
| +добавлено | float a = fract(cw + rot / 6.2832) * n; |
| +добавлено | float cell = floor(a); |
| +добавлено | vec2 g = vec2((fract(a) - 0.5) * (6.2832 * rc / n) / hh, (r - rc) / hh); |
| +добавлено | int id = int(hash11(cell * 7.31 + seed * 13.7) * 12.0); |
| +добавлено | float at = (cell + 0.5) / n; // where the pen passes this rune |
| +добавлено | float on = sgSat((p - at) * n * 2.0 + 0.5); |
| +добавлено | float flash = 1.0 + 1.5 * exp(-max(p - at, 0.0) * n * 1.2) * on; |
| +добавлено | float pulse = 0.75 + 0.5 * pow(0.5 + 0.5 * sin(time * 2.2 - cell * 0.9), 6.0); |
| +добавлено | if (glitch > 0.0) pulse *= step(0.12, hash11(cell + floor(time * 9.0) * 3.1)); // void: runes drop out |
| +добавлено | sgLine(sigilGlyph(id, g) * hh, 0.07 * hh, on * flash * pulse, acc); |
| +добавлено | } |
| +добавлено | // star polygon {n/k} on radius R, g closed strokes, each drawn chord after chord as p goes 0 -> 1 |
| +добавлено | void sgStar(vec2 q, float R, int n, int k, int g, float rot, float p, float w, inout vec3 acc, inout float front) { |
| +добавлено | if (p <= 0.0 || dot(q, q) > (R + 0.03) * (R + 0.03)) return; |
| +добавлено | int per = n / g; |
| +добавлено | float st = 6.2832 * float(k) / float(n); |
| +добавлено | mat2 step_ = mat2(cos(st), sin(st), -sin(st), cos(st)); // one chord further round |
| +добавлено | for (int s = 0; s < g; s++) { |
| +добавлено | float a0 = rot + 6.2832 * float(s) / float(n); |
| +добавлено | vec2 A = R * vec2(sin(a0), -cos(a0)); |
| +добавлено | for (int m = 0; m < per; m++) { |
| +добавлено | float cp = sgSat(p * float(per) - float(m)); |
| +добавлено | if (cp <= 0.0) break; |
| +добавлено | vec2 B = step_ * A; |
| +добавлено | vec2 E = mix(A, B, cp); |
| +добавлено | sgLine(sgSeg(q, A, E), w, 1.0, acc); |
| +добавлено | if (cp < 1.0) front += exp(-dot(q - E, q - E) * 2500.0); |
| +добавлено | A = B; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | // n radial strokes from r0 to r1 (every major-th one longer by ext) |
| +добавлено | void sgSpokes(float r, float cw, float rot, float n, float r0, float r1, float major, float ext, float w, float k, inout vec3 acc) { |
| +добавлено | float a = fract(cw + rot / 6.2832) * n; |
| +добавлено | float i = floor(a + 0.5); |
| +добавлено | float lo = mod(i, major) < 0.5 ? r0 - ext : r0; |
| +добавлено | float t = (a - i) * 6.2832 * r / n; |
| +добавлено | sgLine(length(vec2(t, max(max(lo - r, r - r1), 0.0))), w, k, acc); |
| +добавлено | } |
| +добавлено | |
| +добавлено | vec3 sigilPattern(vec2 q, float px, int style, float reveal, float rot, float seed, float time) { |
| +добавлено | gSgPx = max(px, 1e-4); |
| +добавлено | float r = length(q); |
| +добавлено | float cw = fract(atan(q.x, -q.y) / 6.2832); // 0 at "north", clockwise seen from the normal side |
| +добавлено | float pO = sgSat(reveal / 0.35), pR = sgSat((reveal - 0.12) / 0.45), pI = sgSat((reveal - 0.3) / 0.35); |
| +добавлено | float pS = sgSat((reveal - 0.42) / 0.4), pC = sgSat((reveal - 0.7) / 0.3); |
| +добавлено | vec3 acc = vec3(0.0, 1e3, 0.0); |
| +добавлено | float front = 0.0; |
| +добавлено | if (style == 2 ? (r > 0.86 && r < 1.01) : r > 0.99) front += sgSparks(r, cw, time, seed, style == 2 ? -1.0 : 1.0) * pO; |
| +добавлено | // energy running round the rings |
| +добавлено | float shimmer = 0.85 + 0.3 * sin(cw * 56.5 + r * 30.0 - time * 3.0) * sin(cw * 31.4 - time * 1.7); |
| +добавлено | if (style == 0) { // holy: double ring, runes, ticks, hexagram, sunburst |
| +добавлено | sgRing(q, r, cw, 1.0, 0.010, pO, shimmer, acc, front); |
| +добавлено | sgRing(q, r, cw, 0.965, 0.0035, pO, 1.0, acc, front); |
| +добавлено | sgRing(q, r, cw, 0.82, 0.004, pR, 1.0, acc, front); |
| +добавлено | sgRunes(r, cw, rot, 16.0, 0.89, 0.042, seed, pR, time, 0.0, acc); |
| +добавлено | if (r > 0.77 && r < 0.815) sgSpokes(r, cw, rot, 72.0, 0.79, 0.81, 6.0, 0.012, 0.0022, sgSweep(pR, cw, 0.8), acc); |
| +добавлено | sgRing(q, r, cw, 0.76, 0.003, pI, 1.0, acc, front); |
| +добавлено | sgStar(q, 0.76, 6, 2, 2, -rot * 0.6, pS, 0.0045, acc, front); |
| +добавлено | sgRing(q, r, cw, 0.38, 0.004, pI, 1.0, acc, front); |
| +добавлено | if (r < 0.36) sgSpokes(r, cw, -rot * 0.6, 24.0, 0.17, 0.33, 2.0, -0.06, 0.003, pC, acc); |
| +добавлено | sgRing(q, r, cw, 0.12, 0.006, pC, 1.0, acc, front); |
| +добавлено | sgLine(max(r - 0.03, 0.0), 0.006, pC, acc); |
| +добавлено | } else if (style == 1) { // arcane: dashed counter ring, two rune bands, heptagram |
| +добавлено | sgRing(q, r, cw, 1.0, 0.009, pO, shimmer, acc, front); |
| +добавлено | float dash = step(fract(cw * 48.0 - time * 0.12), 0.6); |
| +добавлено | sgLine(abs(r - 0.972), 0.0035, sgSweep(pO, cw, 0.972) * dash, acc); |
| +добавлено | sgRing(q, r, cw, 0.94, 0.003, pR, 1.0, acc, front); |
| +добавлено | sgRing(q, r, cw, 0.83, 0.004, pR, 1.0, acc, front); |
| +добавлено | sgRunes(r, cw, rot, 20.0, 0.885, 0.038, seed, pR, time, 0.0, acc); |
| +добавлено | sgRing(q, r, cw, 0.8, 0.003, pI, 1.0, acc, front); |
| +добавлено | sgStar(q, 0.8, 7, 2, 1, -rot * 0.5, pS, 0.004, acc, front); |
| +добавлено | sgRing(q, r, cw, 0.5, 0.004, pI, 1.0, acc, front); |
| +добавлено | sgRing(q, r, cw, 0.42, 0.0025, pC, 1.0, acc, front); |
| +добавлено | sgRunes(r, cw, -rot * 1.4, 8.0, 0.36, 0.05, seed + 3.0, pC, time, 0.0, acc); |
| +добавлено | sgRing(q, r, cw, 0.3, 0.0025, pC, 1.0, acc, front); |
| +добавлено | sgStar(q, 0.2, 4, 1, 1, rot, pC, 0.004, acc, front); |
| +добавлено | sgLine(max(r - 0.025, 0.0), 0.006, pC, acc); |
| +добавлено | } else { // void: broken ring, glitching runes, octagram, inward spiral arms |
| +добавлено | float gap = step(sin(cw * 31.4159 + rot * 3.0), 0.82); |
| +добавлено | sgLine(abs(r - 1.0), 0.011, sgSweep(pO, cw, 1.0) * gap * shimmer, acc); |
| +добавлено | front += sgPen(q, 1.0, pO); |
| +добавлено | sgRing(q, r, cw, 0.95, 0.003, pO, 1.0, acc, front); |
| +добавлено | sgRing(q, r, cw, 0.81, 0.004, pR, 1.0, acc, front); |
| +добавлено | sgRunes(r, cw, rot, 12.0, 0.88, 0.046, seed, pR, time, 1.0, acc); |
| +добавлено | sgStar(q, 0.78, 8, 3, 1, -rot * 0.4, pS, 0.004, acc, front); |
| +добавлено | if (r > 0.1 && r < 0.66) { |
| +добавлено | // 5 logarithmic arms (theta = 2.2 ln r), turning inwards; distance across the arm |
| +добавлено | float arms = 5.0, k = 2.2; |
| +добавлено | float ph = fract(cw - k * log(r) / 6.2832 + time * 0.08 + rot / 6.2832) * arms; |
| +добавлено | float d = abs(fract(ph) - 0.5) * 6.2832 * r / arms / sqrt(1.0 + k * k); |
| +добавлено | sgLine(d, 0.0035 * smoothstep(0.1, 0.25, r) * smoothstep(0.66, 0.45, r), pI, acc); |
| +добавлено | } |
| +добавлено | sgRing(q, r, cw, 0.3, 0.003, pI, 1.0, acc, front); |
| +добавлено | sgRing(q, r, cw, 0.1, 0.008, pC, 1.4, acc, front); |
| +добавлено | } |
| +добавлено | // hot knots of energy streaming round the circle (two periodic octaves along the angle, drifting |
| +добавлено | // opposite ways) and a slow whole-sigil flicker: the strokes burn unevenly, never a flat colour |
| +добавлено | float flow = sgNoise(cw * 24.0 - time * 1.7 + seed, 24.0) * 0.65 + sgNoise(cw * 80.0 + time * 4.1 + r * 13.0 + seed, 80.0) * 0.35; |
| +добавлено | float energy = (0.45 + 1.15 * flow * flow) * (0.9 + 0.2 * sgNoise(time * 7.0 + seed * 3.0, 4096.0)); |
| +добавлено | gSgCore = acc.z * energy; |
| +добавлено | gSgDist = acc.y; |
| +добавлено | // halo from the union distance + a wide glow hugging the outer ring + faint inner fill |
| +добавлено | float halo = (exp(-acc.y / 0.012) * 0.3 + exp(-acc.y / 0.05) * 0.07) * step(acc.y, 1e2); |
| +добавлено | halo += 0.12 * exp(-abs(r - 1.0) / 0.04) * pO; |
| +добавлено | return vec3(acc.x * mix(1.0, energy, 0.75), halo * mix(1.0, energy, 0.5), front); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const VERT = /* glsl */` |
| +добавлено | in vec4 aPos; // centre, radius (m) |
| +добавлено | in vec4 aNrm; // plane normal, rotation (rad) |
| +добавлено | in vec4 aCol; // linear colour x intensity, reveal |
| +добавлено | in vec4 aSty; // style, seed, -, - |
| +добавлено | out vec2 vQ; |
| +добавлено | flat out vec4 vCol; |
| +добавлено | flat out vec4 vSty; |
| +добавлено | flat out float vRot; |
| +добавлено | void main() { |
| +добавлено | mat3 B = basisFrom(normalize(aNrm.xyz)); |
| +добавлено | vec2 c = position.xy * 1.1; // room for the outer glow (it is ~1% by r = 1.1) |
| +добавлено | vec3 wp = aPos.xyz + (B[0] * c.x + B[1] * c.y) * aPos.w + B[2] * 0.015; |
| +добавлено | vQ = c; |
| +добавлено | vCol = aCol; vSty = aSty; vRot = aNrm.w; |
| +добавлено | gl_Position = aPos.w > 0.0 ? projectionMatrix * viewMatrix * vec4(wp, 1.0) : vec4(2.0, 2.0, 2.0, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const FRAG = /* glsl */` |
| +добавлено | in vec2 vQ; |
| +добавлено | flat in vec4 vCol; |
| +добавлено | flat in vec4 vSty; |
| +добавлено | flat in float vRot; |
| +добавлено | out vec4 fragColor; |
| +добавлено | void main() { |
| +добавлено | float r = length(vQ); |
| +добавлено | if (r > 1.1) discard; |
| +добавлено | float px = length(fwidth(vQ)) * 0.7071; |
| +добавлено | vec3 s = sigilPattern(vQ, px, int(vSty.x + 0.5), vCol.a, vRot, vSty.y, uTime); |
| +добавлено | // most of the disc is empty: no blend into the 4x MSAA target where nothing shows |
| +добавлено | if (s.x + s.y + s.z < 0.003) discard; |
| +добавлено | vec3 c = vCol.rgb; |
| +добавлено | float peak = max(c.r, max(c.g, c.b)); |
| +добавлено | // plasma layering: white-hot filament core, saturated sheath, then a deeper-hued halo whose red |
| +добавлено | // spreads wider than its blue (dispersion fringe); pen front and sparks burn white |
| +добавлено | vec3 deep = c * c / max(peak, 1e-4); |
| +добавлено | vec3 disp = exp(min(gSgDist, 0.15) / 0.04 * vec3(0.3, 0.0, -0.3)); |
| +добавлено | vec3 col = vec3(peak) * gSgCore * 2.2 + mix(c, vec3(peak), 0.12) * s.x * 1.1 |
| +добавлено | + mix(c, deep, 0.45) * s.y * disp + vec3(peak) * s.z * 1.5; |
| +добавлено | if (uDebug > 0.5 && uDebug < 1.5) col = vec3(0.04, 0.012, 0.004); // overdraw view |
| +добавлено | fragColor = vec4(col, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const STYLES = { holy: 0, arcane: 1, void: 2 }; |
| +добавлено | const STYLE_COLORS = { holy: [1.0, 0.72, 0.3], arcane: [0.55, 0.32, 1.0], void: [0.62, 0.12, 1.0] }; |
| +добавлено | const DEFAULTS = { radius: 1.5, intensity: 4, reveal: 1, rotation: 0, style: 'holy', seed: 0 }; |
| +добавлено | // light borrowed per visible sigil: intensity = LIGHT_GAIN x sigil intensity x radius (bigger and |
| +добавлено | // brighter circles throw more light), range ~2 radii |
| +добавлено | const LIGHT_GAIN = 1.6; |
| +добавлено | let seedState = 12345; // deterministic default seeds (callers normally pass their cast's) |
| +добавлено | |
| +добавлено | export class Sigils { |
| +добавлено | constructor({ max = 8 } = {}) { |
| +добавлено | this.max = max; |
| +добавлено | const geo = new THREE.InstancedBufferGeometry(); |
| +добавлено | geo.setAttribute('position', new THREE.Float32BufferAttribute([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0], 3)); |
| +добавлено | geo.setIndex([0, 1, 2, 0, 2, 3]); |
| +добавлено | this.attrs = ['aPos', 'aNrm', 'aCol', 'aSty'].map((n) => instanced(geo, n, max)); |
| +добавлено | this._arrays = this.attrs.map((a) => a.array); |
| +добавлено | geo.instanceCount = 0; |
| +добавлено | this.geometry = geo; |
| +добавлено | this.uniforms = { ...U }; |
| +добавлено | this.mesh = new THREE.Mesh(geo, new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms: this.uniforms, ...LINES_BLENDING, side: THREE.DoubleSide, |
| +добавлено | polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2, |
| +добавлено | vertexShader: COMMON_GLSL + VERT, fragmentShader: COMMON_GLSL + SIGIL_GLSL + FRAG, |
| +добавлено | })); |
| +добавлено | this.mesh.frustumCulled = false; |
| +добавлено | this.mesh.visible = false; |
| +добавлено | this.sigils = Array.from({ length: max }, (_, index) => ({ |
| +добавлено | index, active: false, ...DEFAULTS, |
| +добавлено | pos: new THREE.Vector3(), normal: new THREE.Vector3(0, 1, 0), color: new THREE.Color(), light: null, |
| +добавлено | release() { this.active = false; }, |
| +добавлено | })); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // pos/normal: Vector3, color: Color (copied). Live fields: pos, normal, radius, color, intensity, |
| +добавлено | // reveal (0..1), rotation (rad), style, seed. Returns null when all are live. |
| +добавлено | acquire(opts = {}) { |
| +добавлено | for (const h of this.sigils) { |
| +добавлено | if (h.active) continue; |
| +добавлено | Object.assign(h, DEFAULTS); |
| +добавлено | h.normal.set(0, 1, 0); |
| +добавлено | seedState = (Math.imul(seedState, 1664525) + 1013904223) >>> 0; |
| +добавлено | h.seed = seedState % 1000; |
| +добавлено | const style = opts.style ?? 'holy'; |
| +добавлено | h.color.setRGB(...(STYLE_COLORS[style] ?? STYLE_COLORS.holy)); |
| +добавлено | for (const k in opts) { |
| +добавлено | const v = opts[k]; |
| +добавлено | if (v && (v.isVector3 || v.isColor)) h[k].copy(v); else h[k] = v; |
| +добавлено | } |
| +добавлено | h.active = true; |
| +добавлено | return h; |
| +добавлено | } |
| +добавлено | return null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | update() { |
| +добавлено | let n = 0, dirty = false; |
| +добавлено | const X = this._arrays, P = X[0], N = X[1], C = X[2], S = X[3]; |
| +добавлено | for (const h of this.sigils) { |
| +добавлено | const on = h.active && h.intensity > 0 && h.reveal > 0; |
| +добавлено | this.light(h, on); |
| +добавлено | if (!on) continue; |
| +добавлено | const o = n * 4, k = h.intensity; |
| +добавлено | dirty = put4(P, o, h.pos.x, h.pos.y, h.pos.z, h.radius) || dirty; |
| +добавлено | dirty = put4(N, o, h.normal.x, h.normal.y, h.normal.z, h.rotation) || dirty; |
| +добавлено | dirty = put4(C, o, h.color.r * k, h.color.g * k, h.color.b * k, h.reveal) || dirty; |
| +добавлено | dirty = put4(S, o, STYLES[h.style] ?? 0, h.seed, 0, 0) || dirty; |
| +добавлено | n++; |
| +добавлено | } |
| +добавлено | if (dirty || n !== this.geometry.instanceCount) for (const a of this.attrs) a.needsUpdate = true; |
| +добавлено | this.geometry.instanceCount = n; |
| +добавлено | this.mesh.visible = n > 0; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // the burning strokes light what is near them (pool handle per visible sigil, none when the pool |
| +добавлено | // is full). Floor sigil: rune-ring cookie (common.js pattern 2, ring at r = 1) from just above |
| +добавлено | // its centre, so the floor glows under the strokes. Upright sigil: a point light in front of it. |
| +добавлено | light(h, on) { |
| +добавлено | if (!on) { if (h.light) { h.light.release(); h.light = null; } return; } |
| +добавлено | const L = h.light ?? (h.light = lights.acquire()); |
| +добавлено | if (!L) return; |
| +добавлено | const floor = h.normal.y > 0.7, R = h.radius, t = U.uTime.value; |
| +добавлено | L.type = floor ? 2 : 0; |
| +добавлено | L.pos.copy(h.pos).addScaledVector(h.normal, (floor ? 0.3 : 0.2) * R); |
| +добавлено | L.range = 2.2 * R + 1.5; |
| +добавлено | L.color.copy(h.color); |
| +добавлено | L.cookie[0] = floor ? 2 : 0; L.cookie[1] = 1 / Math.max(R, 1e-3); L.cookie[2] = h.rotation; |
| +добавлено | const flicker = 0.9 + 0.1 * Math.sin(t * 23 + h.seed) * Math.sin(t * 7.3 + h.seed * 0.37); |
| +добавлено | L.intensity = LIGHT_GAIN * h.intensity * Math.min(1, h.reveal * 1.5) * R * flicker; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { U, COMMON_GLSL, NOISE_GLSL, WORLD_GLSL, LIGHTS_GLSL, IMPACTS_GLSL, occluders } from './common.js'; |
| +добавлено | import { instanced, put4 } from './Ribbons.js'; |
| +добавлено | |
| +добавлено | // Erupting spikes (PLAN 3 Earth "Upheaval", Ice "Frost Nova"). Geometry is generated once at load: |
| +добавлено | // 4 rock variants (~380 triangles: stacked strata layers with ledges, faceted sides, a fractured |
| +добавлено | // top) and 4 ice variants (hexagonal crystal clusters, flat facets). All variants of a material sit |
| +добавлено | // in one vertex buffer and every instance collapses the triangles of the other three to zero area, |
| +добавлено | // so each material is ONE instanced draw (8 spikes x 4 variants x ~1.1k vertices is nothing; a |
| +добавлено | // draw per variant would be 4x the state changes). |
| +добавлено | // |
| +добавлено | // Rock: MeshStandardMaterial + onBeforeCompile in the opaque scene. Strata, a few straight |
| +добавлено | // fractures, derivative bump, spell lights, impacts (scorch / frost / magma) and per-spike heat -> |
| +добавлено | // blackbody glow deep in the fractures and on the broken face towards the source (hot basalt after a |
| +добавлено | // blast, a lava-crust breakout: the outer surface is cooled dark rock). |
| +добавлено | // Ice: ShaderMaterial in the refract scene, sampling the resolved opaque HDR. Each crystal is a |
| +добавлено | // convex polytope (6 side planes, 6 tip planes, base) whose planes travel as flat per-vertex |
| +добавлено | // attributes, so the refracted ray's exit distance is exact (analytic thickness), the exit face |
| +добавлено | // refracts a second time (or totally internally reflects), and the distance to the nearest edge |
| +добавлено | // drives the frost. |
| +добавлено | // |
| +добавлено | // Rise: ease-out-back out of the ground over `rise` s after `delay`; crumble after `life` s: sinks, |
| +добавлено | // shrinks, tilts and fades with alpha-to-coverage (dithered so 4x MSAA gives more than 5 levels). |
| +добавлено | // Each spike is a capsule occluder (kind 2) from the start of its rise until it starts crumbling. |
| +добавлено | |
| +добавлено | const UP = new THREE.Vector3(0, 1, 0); |
| +добавлено | |
| +добавлено | function lcg(seed) { |
| +добавлено | let s = (seed >>> 0) || 1; |
| +добавлено | return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 4294967296); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- rock geometry ------------------------------------------------------------------------ |
| +добавлено | // unit space: base ring around y = 0 (buried down to -0.25), tip near y = 1, base radius ~1. |
| +добавлено | function rockVariant(seed) { |
| +добавлено | const rand = lcg(seed * 7919 + 13); |
| +добавлено | const sides = 7 + ((rand() * 3) | 0); |
| +добавлено | const layers = 7 + ((rand() * 2) | 0); |
| +добавлено | const tipY = 0.84 + rand() * 0.08; |
| +добавлено | const ang = Array.from({ length: sides }, (_, i) => ((i + (rand() - 0.5) * 0.55) / sides) * Math.PI * 2); |
| +добавлено | const bulge = Array.from({ length: sides }, () => 0.86 + rand() * 0.26); // per-side: vertical facets |
| +добавлено | const prof = (y) => 0.1 + 0.9 * Math.pow(Math.max(1 - Math.max(y, 0) / 1.02, 0), 0.9); |
| +добавлено | const bounds = [-0.25]; |
| +добавлено | for (let l = 1; l < layers; l++) bounds.push(tipY * Math.pow(l / layers, 0.85) + (rand() - 0.5) * 0.03); |
| +добавлено | bounds.push(tipY); |
| +добавлено | |
| +добавлено | const rings = []; // { pts: [x, y, z][], layer, seam } ; seam rings start a ledge band |
| +добавлено | for (let l = 0; l < layers; l++) { |
| +добавлено | const ox = (rand() - 0.5) * 0.12, oz = (rand() - 0.5) * 0.12, k = 0.9 + rand() * 0.2, tw = (rand() - 0.5) * 0.12; |
| +добавлено | const lr = rand(); |
| +добавлено | const y0 = bounds[l] + (l ? 0.006 : 0), y1 = bounds[l + 1]; |
| +добавлено | for (const [f, jit] of [[0, 0.04], [0.5, 0.1], [1, 0.04]]) { |
| +добавлено | const y = y0 + (y1 - y0) * f; |
| +добавлено | const r = prof(y) * k; |
| +добавлено | rings.push({ |
| +добавлено | layer: lr, seam: f === 0 && l > 0, |
| +добавлено | pts: ang.map((a, i) => { |
| +добавлено | const rr = r * bulge[i] * (1 + (rand() - 0.5) * jit * 2); |
| +добавлено | return [Math.cos(a + tw) * rr + ox * r, y, Math.sin(a + tw) * rr + oz * r]; |
| +добавлено | }), |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | // fractured top: apex off-centre, then everything above an oblique plane is flattened onto it |
| +добавлено | const top = rings[rings.length - 1]; |
| +добавлено | const apex = [top.pts[0][0] * 0.2 + (rand() - 0.5) * 0.08, tipY + 0.08 + rand() * 0.1, top.pts[0][2] * 0.2 + (rand() - 0.5) * 0.08]; |
| +добавлено | const cn = new THREE.Vector3((rand() - 0.5) * 1.2, 1, (rand() - 0.5) * 1.2).normalize(); |
| +добавлено | const cut = tipY + 0.02 + rand() * 0.04; |
| +добавлено | const flatten = (p) => { |
| +добавлено | const d = (p[0] * cn.x + (p[1] - cut) * cn.y + p[2] * cn.z); |
| +добавлено | return d > 0 ? [p[0] - cn.x * d, p[1] - cn.y * d, p[2] - cn.z * d] : p; |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const pos = [], rock = []; |
| +добавлено | const tri = (a, b, c, layer, seam) => { |
| +добавлено | pos.push(...flatten(a), ...flatten(b), ...flatten(c)); |
| +добавлено | for (let i = 0; i < 3; i++) rock.push(layer, seam); |
| +добавлено | }; |
| +добавлено | for (let r = 0; r < rings.length - 1; r++) { |
| +добавлено | const A = rings[r], B = rings[r + 1]; |
| +добавлено | const seam = B.seam ? 1 : 0, layer = seam ? A.layer : B.layer; |
| +добавлено | for (let i = 0; i < sides; i++) { |
| +добавлено | const j = (i + 1) % sides; |
| +добавлено | tri(A.pts[i], B.pts[j], A.pts[j], layer, seam); |
| +добавлено | tri(A.pts[i], B.pts[i], B.pts[j], layer, seam); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | for (let i = 0; i < sides; i++) tri(top.pts[i], apex, top.pts[(i + 1) % sides], top.layer, 0); |
| +добавлено | return { pos, rock }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- ice geometry ------------------------------------------------------------------------- |
| +добавлено | // hexagonal prisms with pyramidal tips; per vertex the crystal's planes: c0 = (base, apothem), |
| +добавлено | // c1 = (axis, prism length), c2 = (side reference normal, tip length), all in unit space |
| +добавлено | function iceVariant(seed) { |
| +добавлено | const rand = lcg(seed * 104729 + 7); |
| +добавлено | const crystals = []; |
| +добавлено | const tiltMain = new THREE.Vector3((rand() - 0.5) * 0.18, 1, (rand() - 0.5) * 0.18).normalize(); |
| +добавлено | crystals.push({ b: new THREE.Vector3(0, -0.25, 0), a: tiltMain, w: 0.3 + rand() * 0.06, L: 0.98 - rand() * 0.06, T: 0.24 + rand() * 0.1 }); |
| +добавлено | const n = 4 + ((rand() * 3) | 0); |
| +добавлено | for (let i = 0; i < n; i++) { |
| +добавлено | const az = ((i + rand() * 0.6) / n) * Math.PI * 2, tilt = 0.35 + rand() * 0.45; |
| +добавлено | const a = new THREE.Vector3(Math.cos(az) * Math.sin(tilt), Math.cos(tilt), Math.sin(az) * Math.sin(tilt)); |
| +добавлено | const r0 = 0.25 + rand() * 0.25; |
| +добавлено | const w = 0.1 + rand() * 0.12; |
| +добавлено | crystals.push({ b: new THREE.Vector3(Math.cos(az) * r0, -0.25, Math.sin(az) * r0), a, w, L: 0.25 + rand() * 0.4 + w, T: w * (0.9 + rand() * 0.9) }); |
| +добавлено | } |
| +добавлено | const pos = [], c0 = [], c1 = [], c2 = []; |
| +добавлено | const s = new THREE.Vector3(), u = new THREE.Vector3(), v = new THREE.Vector3(); |
| +добавлено | for (const c of crystals) { |
| +добавлено | s.set(rand() - 0.5, rand() - 0.5, rand() - 0.5).cross(c.a).normalize(); // any perpendicular, random spin |
| +добавлено | u.crossVectors(c.a, s); |
| +добавлено | const R = c.w / Math.cos(Math.PI / 6); // circumradius |
| +добавлено | const ring = (h) => Array.from({ length: 6 }, (_, k) => { |
| +добавлено | const t = (k - 0.5) * Math.PI / 3; // corners halfway between the side normals |
| +добавлено | return v.copy(c.b).addScaledVector(c.a, h).addScaledVector(s, Math.cos(t) * R).addScaledVector(u, Math.sin(t) * R).toArray(); |
| +добавлено | }); |
| +добавлено | const lo = ring(0), hi = ring(c.L), apex = v.copy(c.b).addScaledVector(c.a, c.L + c.T).toArray(); |
| +добавлено | const tri = (p, q, r) => { |
| +добавлено | pos.push(...p, ...q, ...r); |
| +добавлено | for (let i = 0; i < 3; i++) { |
| +добавлено | c0.push(c.b.x, c.b.y, c.b.z, c.w); c1.push(c.a.x, c.a.y, c.a.z, c.L); c2.push(s.x, s.y, s.z, c.T); |
| +добавлено | } |
| +добавлено | }; |
| +добавлено | for (let k = 0; k < 6; k++) { |
| +добавлено | const j = (k + 1) % 6; |
| +добавлено | // winding: outward normals (n_k between corner k and k+1 ... see ring()) |
| +добавлено | tri(lo[k], lo[j], hi[j]); |
| +добавлено | tri(lo[k], hi[j], hi[k]); |
| +добавлено | tri(hi[k], hi[j], apex); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return { pos, c0, c1, c2 }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // all variants of one material in one buffer, + aVariant; flat normals from the triangles |
| +добавлено | function merged(variants, extra) { |
| +добавлено | const g = new THREE.InstancedBufferGeometry(); |
| +добавлено | const pos = variants.flatMap((v) => v.pos); |
| +добавлено | const variant = variants.flatMap((v, i) => new Array(v.pos.length / 3).fill(i)); |
| +добавлено | g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); |
| +добавлено | g.setAttribute('aVariant', new THREE.Float32BufferAttribute(variant, 1)); |
| +добавлено | for (const [name, size] of extra) g.setAttribute(name, new THREE.Float32BufferAttribute(variants.flatMap((v) => v[name]), size)); |
| +добавлено | g.computeVertexNormals(); // non-indexed -> face normals (both builders wind outward, CCW) |
| +добавлено | return g; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- shared GLSL -------------------------------------------------------------------------- |
| +добавлено | // per-instance: 3 affine rows, (variant, heat, fade, seed), (radius, height, front, glow) |
| +добавлено | const INSTANCE_VERT = /* glsl */` |
| +добавлено | attribute float aVariant; |
| +добавлено | attribute vec4 aM0; |
| +добавлено | attribute vec4 aM1; |
| +добавлено | attribute vec4 aM2; |
| +добавлено | attribute vec4 aSpike; |
| +добавлено | attribute vec4 aSize; |
| +добавлено | mat4 spikeMatrix() { return transpose(mat4(aM0, aM1, aM2, vec4(0.0, 0.0, 0.0, 1.0))); } |
| +добавлено | // inverse-transpose for rotation x scale matrices (three's instancing trick) |
| +добавлено | vec3 spikeNormal(mat3 m, vec3 n) { return m * (n / vec3(dot(m[0], m[0]), dot(m[1], m[1]), dot(m[2], m[2]))); } |
| +добавлено | bool spikeOther() { return abs(aVariant - aSpike.x) > 0.5; } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // --- rock material -------------------------------------------------------------------------- |
| +добавлено | const ROCK_FRAG_PARS = COMMON_GLSL + NOISE_GLSL + WORLD_GLSL + LIGHTS_GLSL + IMPACTS_GLSL + /* glsl */` |
| +добавлено | varying vec3 vObj; // object space in metres, unrotated and unanimated (texture space) |
| +добавлено | varying vec2 vRock; // layer random, seam (ledge band) |
| +добавлено | varying vec4 vSpikeP; // variant, heat, fade, seed |
| +добавлено | varying vec4 vSizeP; // radius, height, -, - |
| +добавлено | varying vec3 vLean; // the spike's axis in world space (rims lean away from what threw them up) |
| +добавлено | uniform vec4 uRockLook; // strata contrast, vein width, heat glow scale, bump |
| +добавлено | uniform vec4 uSpikeOpts; // x rock receives capsule shadows, y ice does |
| +добавлено | float gBump; float gHeat; float gVein; float gStrata; float gHalo; float gDirt; float gFace; float gGlow; |
| +добавлено | uniform vec3 uRockDust; // dust settled on ledges and caked on the foot |
| +добавлено | // zero crossings of the fbm form a closed vein network; fwidth keeps them ~constant in pixels, and |
| +добавлено | // thin lines are scaled back so their coverage (and glow) is conserved instead of sparkling |
| +добавлено | float vein(float n, float w) { float fw = fwidth(n); return (1.0 - smoothstep(w, w + fw * 1.5, abs(n - 0.5))) * w / (w + 0.75 * fw); } |
| +добавлено | // one through-going fracture: a plane through the spike (mostly vertical, random strike), slightly |
| +добавлено | // jagged, limited to a patch of the plane and tapering to its tips. x: coverage, y: metres to it, |
| +добавлено | // z: taper (0 at the tips) |
| +добавлено | vec3 fracture(vec3 o, vec3 h, vec3 h2, float jag, float R, float H) { |
| +добавлено | float th = h2.x * 6.2831853; |
| +добавлено | vec3 n = normalize(vec3(cos(th), (h2.y - 0.5) * 0.7, sin(th))); |
| +добавлено | vec3 q = o - vec3((h.x - 0.5) * 0.9 * R, (0.2 + 0.55 * h.y) * H, (h.z - 0.5) * 0.9 * R); |
| +добавлено | float d = dot(q, n) + jag; |
| +добавлено | float L = (0.22 + 0.33 * h2.z) * H; |
| +добавлено | float taper = clamp(1.0 - dot(q - n * dot(q, n), q - n * dot(q, n)) / (L * L), 0.0, 1.0); |
| +добавлено | float w = 0.004 + 0.012 * taper * taper; |
| +добавлено | float fw = fwidth(d); |
| +добавлено | return vec3((1.0 - smoothstep(w * 0.3, w + fw, abs(d))) * w / (w + 0.75 * fw) * step(0.0, taper - 0.02), abs(d), taper); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const ROCK_ALBEDO = /* glsl */` |
| +добавлено | { |
| +добавлено | vec3 o = vObj + vSpikeP.w * vec3(3.7, 1.3, 5.1); |
| +добавлено | vec4 nA = noise3v(o * 0.33); |
| +добавлено | vec4 nB = noise3v(o * 1.1 + 0.37); |
| +добавлено | vec4 nC = noise3v(o * 3.4 + 0.71); // grain: pits, crystals, fine roughness |
| +добавлено | // strata: horizontal bands warped by low noise, thinner bright laminae inside the bright bands |
| +добавлено | float b = vObj.y * 4.5 + (nA.r - 0.5) * 0.7 + vRock.x * 2.0; |
| +добавлено | float s = fract(b); |
| +добавлено | gStrata = smoothstep(0.62, 0.68, s) * (1.0 - smoothstep(0.84, 0.9, s)) * smoothstep(0.3, 0.55, nA.b); |
| +добавлено | float lam = smoothstep(0.8, 0.92, fract(vObj.y * 17.0 + nB.r * 0.8)) * 0.35; |
| +добавлено | vec3 basalt = vec3(0.04, 0.038, 0.036) * (0.7 + 0.6 * nB.r) * (0.85 + 0.3 * vRock.x) * (0.8 + 0.4 * nC.g); |
| +добавлено | vec3 strata = vec3(0.12, 0.1, 0.08) * (0.8 + 0.4 * nA.g) * (0.85 + 0.3 * nC.b); |
| +добавлено | vec3 albedo = mix(basalt, strata, clamp((gStrata + lam) * uRockLook.x, 0.0, 1.0)); |
| +добавлено | // world-space decals: scorch darkens, frost whitens up-facing faces, magma heats the veins |
| +добавлено | vec3 wPos = cameraPosition + (vec4(-vViewPosition, 0.0) * viewMatrix).xyz; |
| +добавлено | vec4 wa, wb; vec3 gc; |
| +добавлено | impactWeights(wPos, wa, wb, gc); |
| +добавлено | albedo *= 1.0 - 0.7 * clamp(wa.x, 0.0, 1.0); |
| +добавлено | vec3 wN = normalize((vec4(vNormal, 0.0) * viewMatrix).xyz); |
| +добавлено | // it came up out of the ground: dust caked on the foot, settled on up-facing ledges (sunlit, pale), |
| +добавлено | // darker in the pits |
| +добавлено | float hu = vObj.y / max(vSizeP.y, 0.01); |
| +добавлено | float dirt = max(1.0 - smoothstep(0.02, 0.18 + 0.2 * nA.b, hu), smoothstep(0.45, 0.85, wN.y) * smoothstep(0.4, 0.62, nB.g + 0.1 * nC.r) * 0.75); |
| +добавлено | dirt *= 1.0 - 0.85 * smoothstep(0.05, 0.35, vSpikeP.y); // thrown up hot: soot, no settled dust |
| +добавлено | albedo *= 1.0 - 0.55 * smoothstep(0.1, 0.6, vSpikeP.y); |
| +добавлено | albedo = mix(albedo, uRockDust * (0.7 + 0.6 * nC.r), dirt); |
| +добавлено | albedo *= 0.75 + 0.25 * smoothstep(0.25, 0.6, nC.a); |
| +добавлено | albedo = mix(albedo, vec3(0.7, 0.8, 0.9), clamp(wa.y, 0.0, 1.0) * smoothstep(-0.2, 0.6, wN.y) * smoothstep(0.35, 0.6, nB.g)); |
| +добавлено | gHeat = clamp(vSpikeP.y + wa.w, 0.0, 1.0); |
| +добавлено | // three straight-ish fractures through the spike (glowing deep inside when hot, a dull-red rim that |
| +добавлено | // cools to dark within a few centimetres), fine dark cracks (albedo only), broken ledge seams |
| +добавлено | // (dark; hot only on the face towards the source) |
| +добавлено | float crack = vein(nB.r, uRockLook.y * 0.35); |
| +добавлено | float sd = mod(vSpikeP.w, 4093.0), jag = (nB.r - 0.5) * 0.016 + (nC.g - 0.5) * 0.006; |
| +добавлено | // (hottest where the fracture is widest and low down, nearer the heat; cooler towards its tips) |
| +добавлено | float warm = 1.0 - 0.65 * smoothstep(0.1, 0.9, hu); |
| +добавлено | gVein = 0.0; gHalo = 0.0; gGlow = 0.0; |
| +добавлено | for (int k = 0; k < 3; k++) { |
| +добавлено | vec3 hk = hash33(vec3(sd, float(k), 3.1)); |
| +добавлено | vec3 f = fracture(vObj, hk, hash33(vec3(sd, float(k), 8.7)), jag, vSizeP.x, vSizeP.y) * (k < 2 || hk.y > 0.5 ? 1.0 : 0.0); |
| +добавлено | gVein = max(gVein, f.x); |
| +добавлено | gGlow = max(gGlow, f.x * f.z * warm); |
| +добавлено | gHalo = max(gHalo, exp(-f.y / 0.02) * f.z * warm); |
| +добавлено | } |
| +добавлено | // the broken face towards the source (the side the spike leans away from), lower part: hot rock |
| +добавлено | // under a crust that has started to skin over in patches |
| +добавлено | vec2 lean = vLean.xz / max(length(vLean), 1e-4); |
| +добавлено | float face = smoothstep(0.2, 0.75, dot(normalize(wN.xz + 1e-5), -lean / max(length(lean), 1e-4))) * smoothstep(0.1, 0.35, length(lean)) * smoothstep(0.15, 0.5, length(wN.xz)); |
| +добавлено | gFace = face * (1.0 - smoothstep(0.0, 0.22, hu + (nB.g - 0.5) * 0.15)) * smoothstep(0.45, 0.75, nB.r + (nC.r - 0.5) * 0.3); |
| +добавлено | albedo *= 1.0 - 0.6 * face * smoothstep(0.1, 0.5, vSpikeP.y); // the fresh hot face: dark, unweathered basalt |
| +добавлено | float seam = vRock.y * smoothstep(0.45, 0.7, nA.g); |
| +добавлено | gVein = max(gVein, seam * face); |
| +добавлено | gGlow = max(gGlow, seam * face * warm * 0.6); |
| +добавлено | gBump = (nB.r * 0.45 + nA.r * 0.3 + nC.r * 0.25) - gVein * 0.6 - crack * 0.2 + gStrata * 0.15; |
| +добавлено | gDirt = dirt; |
| +добавлено | diffuseColor.rgb = albedo * (1.0 - max(max(gVein, seam) * 0.75, max(crack * 0.3, gHalo * 0.25))); |
| +добавлено | // crumble: alpha-to-coverage, dithered so 4 samples give a smooth fade |
| +добавлено | float fade = vSpikeP.z; |
| +добавлено | diffuseColor.a = fade >= 1.0 ? 1.0 : clamp(fade + (ign(gl_FragCoord.xy) - 0.5) * 0.25, 0.0, 1.0); |
| +добавлено | if (diffuseColor.a < 0.01) discard; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // Mikkelsen 2010 surface-gradient bump from screen derivatives (three's perturbNormalArb idea) |
| +добавлено | const ROCK_BUMP = /* glsl */` |
| +добавлено | { |
| +добавлено | vec3 dpdx = dFdx(-vViewPosition), dpdy = dFdy(-vViewPosition); |
| +добавлено | float dhx = dFdx(gBump), dhy = dFdy(gBump); |
| +добавлено | vec3 r1 = cross(dpdy, normal), r2 = cross(normal, dpdx); |
| +добавлено | float det = dot(dpdx, r1); |
| +добавлено | vec3 grad = sign(det) * (dhx * r1 + dhy * r2) * uRockLook.w * 0.02; |
| +добавлено | normal = normalize(abs(det) * normal - grad); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const ROCK_EMIT = /* glsl */` |
| +добавлено | { |
| +добавлено | // heat: deep in the fractures at the blackbody colour of ~800..1500 K, a dull-red rim beside them, |
| +добавлено | // the broken face below them; the crust itself only near full heat |
| +добавлено | float T = mix(800.0, 1500.0, gHeat); |
| +добавлено | float h2 = gHeat * gHeat; |
| +добавлено | totalEmissiveRadiance += (blackbody(T) * gGlow * h2 * 10.0 |
| +добавлено | + blackbody(T * 0.7) * (gHalo * h2 * 0.9 + gFace * h2 * 0.35 + smoothstep(0.85, 1.0, gHeat) * 0.05)) * uRockLook.z; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const SPELL_LIGHTS = /* glsl */` |
| +добавлено | { |
| +добавлено | gLightNoShadow = uSpikeOpts.x < 0.5; |
| +добавлено | vec3 wN = normalize((vec4(normal, 0.0) * viewMatrix).xyz); |
| +добавлено | vec3 wP = cameraPosition + (vec4(-vViewPosition, 0.0) * viewMatrix).xyz; |
| +добавлено | vec3 sd, ss; |
| +добавлено | spellLightPBR(wP, wN, normalize(cameraPosition - wP), material.roughness, material.specularColor, material.diffuseColor, sd, ss); |
| +добавлено | reflectedLight.directDiffuse += sd; |
| +добавлено | reflectedLight.directSpecular += ss; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | function rockMaterial(own) { |
| +добавлено | const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.85, metalness: 0, alphaToCoverage: true }); |
| +добавлено | mat.onBeforeCompile = (sh) => { |
| +добавлено | Object.assign(sh.uniforms, U, own); |
| +добавлено | sh.vertexShader = sh.vertexShader |
| +добавлено | .replace('#include <common>', `#include <common> |
| +добавлено | ${INSTANCE_VERT} |
| +добавлено | attribute vec2 aRock; |
| +добавлено | varying vec3 vObj; |
| +добавлено | varying vec2 vRock; |
| +добавлено | varying vec4 vSpikeP; |
| +добавлено | varying vec4 vSizeP; |
| +добавлено | varying vec3 vLean; |
| +добавлено | mat4 gM;`) |
| +добавлено | .replace('#include <beginnormal_vertex>', `gM = spikeMatrix(); |
| +добавлено | vec3 objectNormal = spikeNormal(mat3(gM), normal);`) |
| +добавлено | .replace('#include <begin_vertex>', `vec3 transformed = spikeOther() ? vec3(0.0) : (gM * vec4(position, 1.0)).xyz; |
| +добавлено | vObj = position * vec3(aSize.x, aSize.y, aSize.x); |
| +добавлено | vRock = aRock; vSpikeP = aSpike; vSizeP = aSize; vLean = mat3(gM) * vec3(0.0, 1.0, 0.0);`); |
| +добавлено | sh.fragmentShader = sh.fragmentShader |
| +добавлено | .replace('#include <common>', '#include <common>\n' + ROCK_FRAG_PARS) |
| +добавлено | .replace('#include <color_fragment>', '#include <color_fragment>\n' + ROCK_ALBEDO) |
| +добавлено | .replace('#include <roughnessmap_fragment>', 'float roughnessFactor = mix(mix(0.88, 0.62, gStrata) - gVein * 0.25, 0.97, gDirt);') |
| +добавлено | .replace('#include <normal_fragment_maps>', '#include <normal_fragment_maps>\n' + ROCK_BUMP) |
| +добавлено | .replace('#include <emissivemap_fragment>', '#include <emissivemap_fragment>\n' + ROCK_EMIT) |
| +добавлено | .replace('#include <lights_fragment_end>', '#include <lights_fragment_end>\n' + SPELL_LIGHTS); |
| +добавлено | }; |
| +добавлено | mat.customProgramCacheKey = () => 'ue-spike-rock'; |
| +добавлено | return mat; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- ice material --------------------------------------------------------------------------- |
| +добавлено | const ICE_VERT = INSTANCE_VERT + /* glsl */` |
| +добавлено | attribute vec4 c0; |
| +добавлено | attribute vec4 c1; |
| +добавлено | attribute vec4 c2; |
| +добавлено | out vec3 vWorld; |
| +добавлено | out vec3 vN; |
| +добавлено | out vec3 vLocal; |
| +добавлено | flat out vec4 vC0; |
| +добавлено | flat out vec4 vC1; |
| +добавлено | flat out vec4 vC2; |
| +добавлено | flat out vec3 vInv0; |
| +добавлено | flat out vec3 vInv1; |
| +добавлено | flat out vec3 vInv2; |
| +добавлено | flat out vec4 vSpikeP; |
| +добавлено | flat out vec4 vSizeP; |
| +добавлено | void main() { |
| +добавлено | mat4 M = modelMatrix * spikeMatrix(); |
| +добавлено | mat3 L = mat3(M); |
| +добавлено | vec4 wp = M * vec4(position, 1.0); |
| +добавлено | vWorld = wp.xyz; |
| +добавлено | vN = normalize(spikeNormal(L, normal)); |
| +добавлено | vLocal = position; |
| +добавлено | mat3 inv = inverse(L); |
| +добавлено | vInv0 = inv[0]; vInv1 = inv[1]; vInv2 = inv[2]; |
| +добавлено | vC0 = c0; vC1 = c1; vC2 = c2; |
| +добавлено | vSpikeP = aSpike; vSizeP = aSize; |
| +добавлено | gl_Position = spikeOther() ? vec4(2.0, 2.0, 2.0, 1.0) : projectionMatrix * viewMatrix * wp; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const ICE_FRAG = COMMON_GLSL + NOISE_GLSL + WORLD_GLSL + LIGHTS_GLSL + /* glsl */` |
| +добавлено | uniform mat4 projectionMatrix; // three only declares it in the vertex stage |
| +добавлено | uniform highp sampler2D uSceneColor; |
| +добавлено | uniform highp sampler2D uSceneDepth; |
| +добавлено | uniform samplerCube uSkyCube; |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform vec3 uAmbient; |
| +добавлено | uniform vec3 uIceAbsorb; // Beer-Lambert sigma per metre (red highest -> cyan) |
| +добавлено | uniform vec4 uIceLook; // ior, frost, interior, glints |
| +добавлено | uniform vec3 uIceGlow; // growth-front emission (linear HDR) |
| +добавлено | uniform vec4 uSpikeOpts; // x rock receives capsule shadows, y ice does |
| +добавлено | in vec3 vWorld; |
| +добавлено | in vec3 vN; |
| +добавлено | in vec3 vLocal; |
| +добавлено | flat in vec4 vC0; |
| +добавлено | flat in vec4 vC1; |
| +добавлено | flat in vec4 vC2; |
| +добавлено | flat in vec3 vInv0; |
| +добавлено | flat in vec3 vInv1; |
| +добавлено | flat in vec3 vInv2; |
| +добавлено | flat in vec4 vSpikeP; |
| +добавлено | flat in vec4 vSizeP; |
| +добавлено | out vec4 fragColor; |
| +добавлено | |
| +добавлено | // half-space dot(p, N) <= off: nearest exit along d, and the two largest signed distances (the |
| +добавлено | // fragment's own face ~0 and the nearest other face = distance to the nearest edge) |
| +добавлено | void icePlane(vec3 N, float off, vec3 o, vec3 d, inout float tMin, inout vec3 nExit, inout float s1, inout float s2) { |
| +добавлено | float dn = dot(d, N), sd = dot(o, N) - off; |
| +добавлено | if (dn > 1e-5) { float t = -sd / dn; if (t < tMin) { tMin = t; nExit = N; } } |
| +добавлено | if (sd > s1) { s2 = s1; s1 = sd; } else if (sd > s2) s2 = sd; |
| +добавлено | } |
| +добавлено | float crystalExit(vec3 o, vec3 d, out vec3 nExit, out float edge) { |
| +добавлено | vec3 b = vC0.xyz, a = vC1.xyz, s = vC2.xyz, u = cross(a, s); |
| +добавлено | float w = vC0.w, L = vC1.w, T = vC2.w; |
| +добавлено | vec3 apex = b + a * (L + T); |
| +добавлено | float tMin = 1e3, s1 = -1e3, s2 = -1e3, il = inversesqrt(T * T + w * w); |
| +добавлено | nExit = a; |
| +добавлено | vec2 cs = vec2(1.0, 0.0); // side k at k x 60 degrees, rotated by recurrence (no trig) |
| +добавлено | for (int k = 0; k < 6; k++) { |
| +добавлено | vec3 n = cs.x * s + cs.y * u; |
| +добавлено | icePlane(n, dot(b, n) + w, o, d, tMin, nExit, s1, s2); |
| +добавлено | vec3 m = (n * T + a * w) * il; |
| +добавлено | icePlane(m, dot(apex, m), o, d, tMin, nExit, s1, s2); |
| +добавлено | cs = vec2(cs.x * 0.5 - cs.y * 0.8660254, cs.y * 0.5 + cs.x * 0.8660254); |
| +добавлено | } |
| +добавлено | icePlane(-a, -dot(b, a), o, d, tMin, nExit, s1, s2); |
| +добавлено | edge = -s2; |
| +добавлено | return clamp(tMin, 0.0, 4.0); |
| +добавлено | } |
| +добавлено | vec2 toUV(vec3 p) { vec4 c = projectionMatrix * viewMatrix * vec4(p, 1.0); return c.xy / c.w * 0.5 + 0.5; } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vec3 N = normalize(vN); |
| +добавлено | vec3 V = normalize(cameraPosition - vWorld); |
| +добавлено | float NoV = max(dot(N, V), 1e-3); |
| +добавлено | float ior = uIceLook.x; |
| +добавлено | mat3 inv = mat3(vInv0, vInv1, vInv2); |
| +добавлено | vec3 size = vec3(vSizeP.x, vSizeP.y, vSizeP.x); |
| +добавлено | float hf = vLocal.y; // 0 at the ground, ~1 at the main tip |
| +добавлено | |
| +добавлено | // --- through the crystal: enter, exact convex exit, refract out (or TIR) ----------------- |
| +добавлено | vec3 R = refract(-V, N, 1.0 / ior); |
| +добавлено | vec3 nL, ld = inv * R; |
| +добавлено | float edge; |
| +добавлено | float thick = crystalExit(vLocal, ld, nL, edge); |
| +добавлено | vec3 nX = normalize(nL * inv); // exit face normal in world space (inverse transpose) |
| +добавлено | vec3 R2 = refract(R, -nX, ior); |
| +добавлено | float tir = dot(R2, R2) < 1e-4 ? 1.0 : 0.0; |
| +добавлено | if (tir > 0.5) R2 = reflect(R, nX); |
| +добавлено | vec3 pExit = vWorld + R * thick; |
| +добавлено | |
| +добавлено | vec2 uv = gl_FragCoord.xy / uResolution; |
| +добавлено | float iceZ = linearDepth(gl_FragCoord.z); |
| +добавлено | float sceneZ = linearDepth(texture(uSceneDepth, uv).r); |
| +добавлено | float behind = clamp(sceneZ - iceZ, 0.2, 3.0); |
| +добавлено | vec2 ruv = clamp(toUV(pExit + R2 * behind * 0.5), 0.002, 0.998); |
| +добавлено | // the bent ray landed on something in front of the ice: fall back to the straight view (UW) |
| +добавлено | float rZ = linearDepth(texture(uSceneDepth, ruv).r); |
| +добавлено | ruv = mix(uv, ruv, smoothstep(iceZ - 0.05, iceZ + 0.25, rZ)); |
| +добавлено | vec3 bg = textureLod(uSceneColor, ruv, 0.0).rgb; |
| +добавлено | float path = thick + tir * vSizeP.x * 0.6; // TIR: one more trip through the body |
| +добавлено | vec3 Tr = exp(-uIceAbsorb * path); |
| +добавлено | |
| +добавлено | // --- light: spell lights (GGX on the flat facet), sun, sky ------------------------------- |
| +добавлено | vec3 sd, ss; |
| +добавлено | gLightNoShadow = uSpikeOpts.y < 0.5; // capsule shadows per ice pixel cost more than they show |
| +добавлено | spellLightPBR(vWorld, N, V, 0.04, vec3(0.018), vec3(1.0), sd, ss); |
| +добавлено | float NoL = max(dot(N, uSunDir), 0.0); |
| +добавлено | vec3 H = normalize(uSunDir + V); |
| +добавлено | float a = 0.0016; // GGX alpha for roughness 0.04 |
| +добавлено | float sunSpec = spellD_GGX(max(dot(N, H), 0.0), a) * spellV_Smith(NoV, NoL, a) * NoL * PI; |
| +добавлено | vec3 irr = uAmbient + uSunColor * NoL + sd; // diffuse radiance factor for white, this facet |
| +добавлено | vec3 irrOmni = uAmbient + uSunColor * 0.5 + sd; // light scattered inside (one light loop only) |
| +добавлено | |
| +добавлено | // --- fake interior: 3 taps along the refracted ray read as bubbles, veils and cracks ----- |
| +добавлено | float seedOff = vSpikeP.w * 0.13; |
| +добавлено | float scat = 0.0; |
| +добавлено | vec3 ldS = ld * size; // object-space metres per metre of path |
| +добавлено | for (int i = 1; i <= 3; i++) { |
| +добавлено | float f = float(i) * 0.25; |
| +добавлено | vec3 q = vLocal * size + ldS * thick * f; |
| +добавлено | vec4 n = noise3v(q * 0.42 + seedOff); |
| +добавлено | float veil = smoothstep(0.6, 0.95, n.r) * 0.35; |
| +добавлено | float bubble = smoothstep(0.84, 0.95, n.a) * 1.6; |
| +добавлено | float crack = smoothstep(0.03, 0.0, abs(n.g - 0.55)) * smoothstep(0.3, 0.6, n.r) * 1.4; |
| +добавлено | scat += (veil + bubble + crack) * exp(-uIceAbsorb.r * thick * f); |
| +добавлено | } |
| +добавлено | scat *= uIceLook.z / 3.0; |
| +добавлено | |
| +добавлено | // --- frost: rough white on edges, at the base and in noisy patches ------------------------ |
| +добавлено | // (edge band scales with the crystal: thin crystals keep clear faces) |
| +добавлено | vec4 fn = noise3v(vLocal * size * 1.7 + seedOff); |
| +добавлено | float ew = vC0.w * 0.07; // edge distance spans 0 .. 0.5 apothem across a face |
| +добавлено | vec4 fe = noise3v(vLocal * size * 5.0 + seedOff); // rime grows unevenly along the edges |
| +добавлено | float ewl = ew * (0.2 + 1.8 * fe.r * fe.r); |
| +добавлено | float frost = smoothstep(ewl, ewl * 0.15, edge - (fe.g - 0.5) * ew * 0.8); |
| +добавлено | frost = max(frost, smoothstep(0.12, 0.0, hf + (fn.g - 0.5) * 0.12)); |
| +добавлено | frost = max(frost, smoothstep(0.84, 0.97, fn.b) * 0.3); |
| +добавлено | // growth front: everything above it is still forming (milky, glowing), a bright band on it |
| +добавлено | float front = vSizeP.z, glow = vSizeP.w; |
| +добавлено | float above = smoothstep(front - 0.02, front + 0.02, hf) * glow; |
| +добавлено | frost = clamp(max(frost, above) * uIceLook.y, 0.0, 1.0); |
| +добавлено | |
| +добавлено | // --- compose ------------------------------------------------------------------------------ |
| +добавлено | float F = 0.018 + 0.982 * pow(1.0 - NoV, 5.0); |
| +добавлено | vec3 refl = textureLod(uSkyCube, reflect(-V, N), 0.0).rgb; |
| +добавлено | // transmitted background + cyan in-scatter of the column (UW's water body) + interior features |
| +добавлено | vec3 inscat = vec3(0.04, 0.34, 0.62) * irrOmni * 0.5; |
| +добавлено | vec3 body = bg * Tr + inscat * (1.0 - Tr) + vec3(0.8, 0.92, 1.0) * irrOmni * scat * 0.2; |
| +добавлено | body += tir * inscat * 0.4; |
| +добавлено | vec3 col = body * (1.0 - F) + (refl * F + ss + uSunColor * F * sunSpec) * (1.0 - frost * 0.8); |
| +добавлено | vec3 frostCol = vec3(0.82, 0.9, 1.0) * irr; |
| +добавлено | col = mix(col, frostCol, frost * 0.85); |
| +добавлено | |
| +добавлено | // glints: tiny random facets whose hash changes with the view direction and time (they flick |
| +добавлено | // on and off as you orbit, like real ice), lit by whatever reaches this face; faded when sub-pixel |
| +добавлено | vec3 gq = vLocal * size * 26.0; |
| +добавлено | vec3 cell = floor(gq); |
| +добавлено | vec3 gh = hash33(cell + floor(V * 5.0) * 17.0); |
| +добавлено | float tw = pow(0.5 + 0.5 * sin(uTime * 7.0 + gh.y * 60.0), 6.0); |
| +добавлено | float spot = smoothstep(0.35, 0.0, length(fract(gq) - 0.5 - (gh - 0.5) * 0.4)); |
| +добавлено | float px = length(fwidth(gq)); |
| +добавлено | float glint = step(0.93, gh.x) * spot * tw * smoothstep(1.2, 0.4, px) * (0.4 + frost); |
| +добавлено | col += glint * (irr * 6.0 + ss * 0.5) * uIceLook.w; |
| +добавлено | |
| +добавлено | float band = exp(-abs(hf - front) * 26.0) * glow; |
| +добавлено | col += uIceGlow * (band * 3.0 + above * 0.35); |
| +добавлено | |
| +добавлено | float fade = vSpikeP.z; |
| +добавлено | float alpha = fade >= 1.0 ? 1.0 : clamp(fade + (ign(gl_FragCoord.xy) - 0.5) * 0.25, 0.0, 1.0); |
| +добавлено | if (alpha < 0.01) discard; |
| +добавлено | fragColor = vec4(col, alpha); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // --- spikes --------------------------------------------------------------------------------- |
| +добавлено | const DEFAULTS = { height: 2, radius: 0.4, material: 'rock', delay: 0, rise: 0.15, life: 4, crumble: 0.6, heat: 0, seed: 0 }; |
| +добавлено | const _m = new THREE.Matrix4(), _q = new THREE.Quaternion(), _qy = new THREE.Quaternion(), _qt = new THREE.Quaternion(); |
| +добавлено | const _p = new THREE.Vector3(), _s = new THREE.Vector3(), _ax = new THREE.Vector3(), _v = new THREE.Vector3(); |
| +добавлено | const easeOutBack = (x) => { const c1 = 1.70158, c3 = c1 + 1, y = x - 1; return 1 + c3 * y * y * y + c1 * y * y; }; |
| +добавлено | const smooth = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); }; |
| +добавлено | |
| +добавлено | export class Spikes { |
| +добавлено | constructor({ max = 48 } = {}) { |
| +добавлено | this.max = max; |
| +добавлено | this.uniforms = { |
| +добавлено | ...U, |
| +добавлено | uRockLook: { value: new THREE.Vector4(1, 0.022, 1, 1) }, // strata contrast, vein width, heat glow, bump |
| +добавлено | uRockDust: { value: new THREE.Color(0.15, 0.13, 0.11) }, |
| +добавлено | uIceAbsorb: { value: new THREE.Vector3(2.6, 0.75, 0.3) }, |
| +добавлено | uIceLook: { value: new THREE.Vector4(1.31, 1, 1, 1) }, // ior, frost, interior, glints |
| +добавлено | uIceGlow: { value: new THREE.Vector3(0.6, 1.6, 2.6) }, |
| +добавлено | // receive capsule shadows (rock, ice): off by default, each costs ~2 texel fetches per capsule |
| +добавлено | // per shadowed light per pixel (0.2 ms for 8 spikes on a 3060); a uniform, so tiers can flip it |
| +добавлено | uSpikeOpts: { value: new THREE.Vector4(0, 0, 0, 0) }, |
| +добавлено | }; |
| +добавлено | const rockGeo = merged([0, 1, 2, 3].map(rockVariant), [['rock', 2]]); |
| +добавлено | rockGeo.setAttribute('aRock', rockGeo.attributes.rock); |
| +добавлено | rockGeo.deleteAttribute('rock'); |
| +добавлено | const iceGeo = merged([0, 1, 2, 3].map(iceVariant), [['c0', 4], ['c1', 4], ['c2', 4]]); |
| +добавлено | this.triangles = { rock: rockGeo.attributes.position.count / 12, ice: iceGeo.attributes.position.count / 12 }; // per variant |
| +добавлено | |
| +добавлено | this.kinds = {}; |
| +добавлено | for (const [name, geo] of [['rock', rockGeo], ['ice', iceGeo]]) { |
| +добавлено | const attrs = ['aM0', 'aM1', 'aM2', 'aSpike', 'aSize'].map((n) => instanced(geo, n, max)); |
| +добавлено | geo.instanceCount = 0; |
| +добавлено | const mat = name === 'rock' ? rockMaterial(this.uniforms) : new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, uniforms: this.uniforms, vertexShader: ICE_VERT, fragmentShader: ICE_FRAG, |
| +добавлено | alphaToCoverage: true, |
| +добавлено | }); |
| +добавлено | const mesh = new THREE.Mesh(geo, mat); |
| +добавлено | mesh.frustumCulled = false; |
| +добавлено | mesh.visible = false; |
| +добавлено | this.kinds[name] = { mesh, geo, attrs, arrays: attrs.map((a) => a.array), count: 0 }; |
| +добавлено | } |
| +добавлено | // rock first in the opaque pass: early-Z then skips the floor under every spike |
| +добавлено | this.kinds.rock.mesh.renderOrder = -1; |
| +добавлено | this.opaque = new THREE.Group(); |
| +добавлено | this.opaque.add(this.kinds.rock.mesh); |
| +добавлено | this.refract = new THREE.Group(); |
| +добавлено | this.refract.add(this.kinds.ice.mesh); |
| +добавлено | |
| +добавлено | this.spikes = Array.from({ length: max }, (_, index) => ({ |
| +добавлено | index, active: false, ...DEFAULTS, |
| +добавлено | pos: new THREE.Vector3(), dir: new THREE.Vector3(0, 1, 0), |
| +добавлено | age: 0, state: 'waiting', // waiting | rising | standing | crumbling |
| +добавлено | emerge: 0, fade: 1, |
| +добавлено | matrix: new THREE.Matrix4(), // current instance transform (unit spike -> world) |
| +добавлено | capsule: { a: new THREE.Vector3(), b: new THREE.Vector3(), radius: 0 }, // current, even if not registered |
| +добавлено | occluder: null, |
| +добавлено | // current tip (world); pos is the base on the ground, for debris |
| +добавлено | top(out) { return out.set(0, 1.02, 0).applyMatrix4(this.matrix); }, |
| +добавлено | release() { this.active = false; this.occluder?.release(); this.occluder = null; }, |
| +добавлено | })); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // pos/dir: Vector3 (copied, dir normalised). Returns null when all `max` are live. |
| +добавлено | spawn(opts = {}) { |
| +добавлено | let h = null; |
| +добавлено | for (const s of this.spikes) if (!s.active) { h = s; break; } |
| +добавлено | if (!h) return null; |
| +добавлено | Object.assign(h, DEFAULTS); |
| +добавлено | h.dir.set(0, 1, 0); |
| +добавлено | h.seed = (Math.random() * 16777216) | 0; |
| +добавлено | for (const k in opts) { |
| +добавлено | const v = opts[k]; |
| +добавлено | if (v && v.isVector3) h[k].copy(v); else h[k] = v; |
| +добавлено | } |
| +добавлено | h.dir.normalize(); |
| +добавлено | h.age = 0; h.state = 'waiting'; h.emerge = 0; h.fade = 1; |
| +добавлено | h.occluder?.release(); h.occluder = null; |
| +добавлено | h.active = true; |
| +добавлено | this._pose(h, -h.height, 0.75, 1, 0); // sunk: capsule data valid before the rise |
| +добавлено | return h; |
| +добавлено | } |
| +добавлено | |
| +добавлено | _pose(h, offset, radial, axial, tilt) { |
| +добавлено | const yaw = ((h.seed * 0.6180339887) % 1) * Math.PI * 2; |
| +добавлено | _qy.setFromAxisAngle(UP, yaw); |
| +добавлено | _q.setFromUnitVectors(UP, h.dir); |
| +добавлено | if (tilt) { |
| +добавлено | _ax.set(Math.cos(h.seed), 0, Math.sin(h.seed)); |
| +добавлено | _q.multiply(_qt.setFromAxisAngle(_ax, tilt)); |
| +добавлено | } |
| +добавлено | _q.multiply(_qy); |
| +добавлено | _p.copy(h.pos).addScaledVector(h.dir, offset); |
| +добавлено | _s.set(h.radius * radial, h.height * axial, h.radius * radial); |
| +добавлено | h.matrix.compose(_p, _q, _s); |
| +добавлено | const c = h.capsule; |
| +добавлено | c.a.set(0, 0.1, 0).applyMatrix4(h.matrix); |
| +добавлено | c.b.set(0, 0.78, 0).applyMatrix4(h.matrix); |
| +добавлено | c.radius = h.radius * radial * 0.5; |
| +добавлено | } |
| +добавлено | |
| +добавлено | update(dt) { |
| +добавлено | let dirty = false; |
| +добавлено | this.kinds.rock.count = this.kinds.ice.count = 0; |
| +добавлено | for (const h of this.spikes) { |
| +добавлено | if (!h.active) continue; |
| +добавлено | h.age += dt; |
| +добавлено | const t = h.age - h.delay; |
| +добавлено | if (t < 0) { h.state = 'waiting'; continue; } |
| +добавлено | if (t >= h.life + h.crumble) { h.release(); continue; } |
| +добавлено | const ice = h.material === 'ice'; |
| +добавлено | let offset, radial = 1, axial = 1, tilt = 0; |
| +добавлено | if (t < h.life) { |
| +добавлено | const u = Math.min(1, t / Math.max(h.rise, 1e-3)); |
| +добавлено | h.state = u < 1 ? 'rising' : 'standing'; |
| +добавлено | h.emerge = easeOutBack(u); |
| +добавлено | offset = (h.emerge - 1) * h.height; |
| +добавлено | radial = 0.75 + 0.25 * Math.min(h.emerge, 1); |
| +добавлено | h.fade = 1; |
| +добавлено | if (!h.occluder) h.occluder = occluders.add(h.capsule.a, h.capsule.b, h.capsule.radius, 2); |
| +добавлено | } else { |
| +добавлено | if (h.state !== 'crumbling') { h.occluder?.release(); h.occluder = null; } |
| +добавлено | h.state = 'crumbling'; |
| +добавлено | const v = (t - h.life) / Math.max(h.crumble, 1e-3); |
| +добавлено | offset = -v * v * h.height * (ice ? 0.25 : 0.55); |
| +добавлено | radial = 1 - (ice ? 0.45 : 0.3) * v; |
| +добавлено | axial = 1 - (ice ? 0.35 : 0.2) * v; |
| +добавлено | tilt = (ice ? 0.05 : 0.22) * v * v; |
| +добавлено | h.fade = 1 - smooth(ice ? 0.1 : 0.25, 1, v); |
| +добавлено | } |
| +добавлено | this._pose(h, offset, radial, axial, tilt); |
| +добавлено | if (h.occluder) { h.occluder.a.copy(h.capsule.a); h.occluder.b.copy(h.capsule.b); h.occluder.radius = h.capsule.radius; } |
| +добавлено | |
| +добавлено | // ice: the growth front sweeps base -> tip over ~4x the rise, its glow dies with it |
| +добавлено | const fu = ice ? Math.min(1, t / Math.max(h.rise * 4, 0.3)) : 1; |
| +добавлено | const K = this.kinds[ice ? 'ice' : 'rock'], X = K.arrays, o = K.count * 4, e = h.matrix.elements; |
| +добавлено | dirty = put4(X[0], o, e[0], e[4], e[8], e[12]) || dirty; |
| +добавлено | dirty = put4(X[1], o, e[1], e[5], e[9], e[13]) || dirty; |
| +добавлено | dirty = put4(X[2], o, e[2], e[6], e[10], e[14]) || dirty; |
| +добавлено | dirty = put4(X[3], o, h.seed & 3, h.heat, h.fade, (h.seed % 997) / 997) || dirty; |
| +добавлено | dirty = put4(X[4], o, h.radius, h.height, fu * 1.3 - 0.05, ice ? 1 - smooth(0.75, 1, fu) : 0) || dirty; |
| +добавлено | K.count++; |
| +добавлено | } |
| +добавлено | for (let i = 0; i < 2; i++) { |
| +добавлено | const K = i ? this.kinds.ice : this.kinds.rock; |
| +добавлено | K.geo.instanceCount = K.count; |
| +добавлено | K.mesh.visible = K.count > 0; |
| +добавлено | if (K.count && dirty) for (const a of K.attrs) { a.clearUpdateRanges(); a.addUpdateRange(0, K.count * 4); a.needsUpdate = true; } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | get live() { return this.kinds.rock.count + this.kinds.ice.count; } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { U, COMMON_GLSL, NOISE_GLSL, ARENA_GLSL, LIGHTS_GLSL, FX_VERT_HEAD, FX_FRAG_HEAD, FX_OUT_GLSL, FX_BLENDING } from './common.js'; |
| +добавлено | import { Q } from '../engine/quality.js'; |
| +добавлено | |
| +добавлено | // Raymarched hero volumes (PLAN 2.5 "Volumes"). Each volume is a proxy mesh in the fx scene whose |
| +добавлено | // BACK faces are drawn (so the camera can be inside) with the depth test off (a back face behind the |
| +добавлено | // floor must not hide the part of the volume in front of it); the shader intersects the true shape |
| +добавлено | // analytically and marches from entry to min(exit, scene depth). |
| +добавлено | // |
| +добавлено | // Spells supply the medium: |
| +добавлено | // void volumeSample(vec3 pw, vec3 pl, out float sigma, out vec3 albedo, out vec3 emission) |
| +добавлено | // pw world position, pl local position (-1..1 over the shape's half extents) |
| +добавлено | // sigma extinction (1/m) |
| +добавлено | // albedo single-scattering albedo |
| +добавлено | // emission emitted radiance per metre (HDR); integrated as T * E * (1 - exp(-sigma dt)) / sigma |
| +добавлено | // with COMMON, NOISE (noise3/fbm3/blackbody), ARENA and LIGHTS GLSL available, plus the uniforms |
| +добавлено | // below (uVolScale etc.). |
| +добавлено | // |
| +добавлено | // Integration is per-slab energy conserving (Hillaire 2015). Lighting per occupied sample: |
| +добавлено | // sun HG phase (g), shadowed by ONE extra density tap towards the sun (optical depth = |
| +добавлено | // trapezoid over the tap), plus a 0.25-strength wide lobe standing in for multiple |
| +добавлено | // scattering (after Wrenninge's octaves) |
| +добавлено | // ambient uAmbient, dimmed by the sun tap's optical depth |
| +добавлено | // spells spellLightScatter (no capsule shadows: gLightNoShadow), all attenuated by one tap |
| +добавлено | // towards the brightest spell light (light 0; packWorld sorts brightest first), so smoke |
| +добавлено | // over a fireball is lit from below and dark on top |
| +добавлено | // Lighting is evaluated on every 2nd occupied sample and held in between (it varies much more |
| +добавлено | // slowly than density); the two shadow taps alternate, so each refreshes every 4th sample. That |
| +добавлено | // keeps the march at ~1.5 density evaluations per step. Samples with zero albedo (pure fire, soot) |
| +добавлено | // skip lighting entirely. |
| +добавлено | // Step count = clamp(radiusPx / 5, 8, min(maxSteps, Q.volumeSteps * Q.auto.steps)), radiusPx in |
| +добавлено | // FX-target pixels, set per frame by update(). Samples are combined as trapezoid slabs (sigma, |
| +добавлено | // albedo and emission averaged over each slab's two ends), which removes the step banding; there is |
| +добавлено | // NO per-pixel jitter: at half res without TAA any jitter turns into a fixed dither pattern ("grid of |
| +добавлено | // dots") on high-frequency media. gVolDt (this ray's step) lets volumeSample fade noise octaves the |
| +добавлено | // march can't resolve. |
| +добавлено | |
| +добавлено | // Every lookup in a march is LOD 0 (the noise, curl and blackbody textures have no mips anyway): |
| +добавлено | // implicit-gradient samples inside the data-dependent loop make ANGLE's HLSL compiler (FXC) unroll |
| +добавлено | // or restructure it, which costs seconds of compile and a slower shader. Volume GLSL may only call |
| +добавлено | // texture(sampler, coord) with two arguments. |
| +добавлено | const NO_GRADIENTS = '#define texture(s, p) textureLod(s, p, 0.0)\n'; |
| +добавлено | |
| +добавлено | const VOLUME_VERT = /* glsl */` |
| +добавлено | out vec3 vWorld; |
| +добавлено | void main() { |
| +добавлено | vec4 w = modelMatrix * vec4(position, 1.0); |
| +добавлено | vWorld = w.xyz; |
| +добавлено | gl_Position = projectionMatrix * viewMatrix * w; |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const VOLUME_HEAD = /* glsl */` |
| +добавлено | uniform vec3 uVolCenter; |
| +добавлено | uniform mat3 uVolRot; // world -> shape axes |
| +добавлено | uniform vec3 uVolScale; // half extents (m) |
| +добавлено | uniform float uVolSteps; |
| +добавлено | uniform vec4 uVolLight; // HG g, sun tap distance (m), ambient gain, sun gain |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform vec3 uAmbient; |
| +добавлено | in vec3 vWorld; |
| +добавлено | // this ray's step length (m), readable from volumeSample: fade noise octaves finer than ~2 steps |
| +добавлено | // (they can't be resolved and only turn into per-pixel grain) |
| +добавлено | float gVolDt = 0.1; |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // entry/exit distances along a unit ray in shape space (rotated, unscaled, so t is metres) |
| +добавлено | const SHAPES_GLSL = /* glsl */` |
| +добавлено | #if VOLUME_SHAPE == 0 |
| +добавлено | vec2 volumeHit(vec3 o, vec3 d) { // ellipsoid |
| +добавлено | vec3 oc = o / uVolScale, rd = d / uVolScale; |
| +добавлено | float a = dot(rd, rd), b = dot(oc, rd), c = dot(oc, oc) - 1.0; |
| +добавлено | float h = b * b - a * c; |
| +добавлено | if (h < 0.0) return vec2(1.0, -1.0); |
| +добавлено | h = sqrt(h); |
| +добавлено | return vec2(-b - h, -b + h) / a; |
| +добавлено | } |
| +добавлено | #elif VOLUME_SHAPE == 1 |
| +добавлено | vec2 volumeHit(vec3 o, vec3 d) { // box |
| +добавлено | vec3 dd = mix(d, vec3(1e-6), lessThan(abs(d), vec3(1e-6))); |
| +добавлено | vec3 m = 1.0 / dd, n = m * o, k = abs(m) * uVolScale; |
| +добавлено | vec3 t1 = -n - k, t2 = -n + k; |
| +добавлено | return vec2(max(max(t1.x, t1.y), t1.z), min(min(t2.x, t2.y), t2.z)); |
| +добавлено | } |
| +добавлено | #else |
| +добавлено | // capsule along y: radius uVolScale.x, half length uVolScale.y including the caps. |
| +добавлено | // Near hit after Inigo Quilez (MIT); the far hit is the near hit of the reversed ray. |
| +добавлено | float capsuleNear(vec3 ro, vec3 rd, float hy, float ra) { |
| +добавлено | vec3 ba = vec3(0.0, 2.0 * hy, 0.0), oa = ro - vec3(0.0, -hy, 0.0); |
| +добавлено | float baba = dot(ba, ba), bard = dot(ba, rd), baoa = dot(ba, oa), rdoa = dot(rd, oa), oaoa = dot(oa, oa); |
| +добавлено | float a = baba - bard * bard, b = baba * rdoa - baoa * bard, c = baba * oaoa - baoa * baoa - ra * ra * baba; |
| +добавлено | float h = b * b - a * c; |
| +добавлено | if (h >= 0.0) { |
| +добавлено | float t = (-b - sqrt(h)) / a; |
| +добавлено | float y = baoa + t * bard; |
| +добавлено | if (y > 0.0 && y < baba) return t; |
| +добавлено | vec3 oc = y <= 0.0 ? oa : ro - vec3(0.0, hy, 0.0); |
| +добавлено | b = dot(rd, oc); c = dot(oc, oc) - ra * ra; h = b * b - c; |
| +добавлено | if (h > 0.0) return -b - sqrt(h); |
| +добавлено | } |
| +добавлено | return -1.0; |
| +добавлено | } |
| +добавлено | vec2 volumeHit(vec3 o, vec3 d) { |
| +добавлено | float ra = uVolScale.x, hy = max(uVolScale.y - ra, 1e-4); |
| +добавлено | float far = length(o) + 2.0 * (uVolScale.y + ra); |
| +добавлено | float tb = capsuleNear(o + d * far, -d, hy, ra); |
| +добавлено | if (tb < 0.0) return vec2(1.0, -1.0); |
| +добавлено | vec3 q = o; q.y -= clamp(q.y, -hy, hy); |
| +добавлено | return vec2(dot(q, q) < ra * ra ? 0.0 : capsuleNear(o, d, hy, ra), far - tb); |
| +добавлено | } |
| +добавлено | #endif |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const VOLUME_MAIN = /* glsl */` |
| +добавлено | void main() { |
| +добавлено | gLightNoShadow = true; |
| +добавлено | vec3 rd = normalize(vWorld - cameraPosition); |
| +добавлено | vec3 o = uVolRot * (cameraPosition - uVolCenter), d = uVolRot * rd; |
| +добавлено | vec2 hit = volumeHit(o, d); |
| +добавлено | float cosV = dot(rd, -vec3(viewMatrix[0][2], viewMatrix[1][2], viewMatrix[2][2])); |
| +добавлено | float t0 = max(hit.x, 0.0), t1 = min(hit.y, sceneViewZ() / cosV); |
| +добавлено | if (t1 <= t0) discard; |
| +добавлено | int steps = int(uVolSteps); |
| +добавлено | float dt = (t1 - t0) / float(steps); |
| +добавлено | gVolDt = dt; |
| +добавлено | // samples sit at t0 + (i + j) dt; slabs run between them (trapezoid), plus a j dt slab in |
| +добавлено | // front of the first sample and a (1 - j) dt one behind the last, so [t0, t1] is covered exactly |
| +добавлено | const float j = 0.5; |
| +добавлено | float t = t0 + dt * j, len = dt * j; |
| +добавлено | float tap = uVolLight.y; |
| +добавлено | vec3 tapS = uVolRot * uSunDir * tap; |
| +добавлено | float sunPhase = hgPhase(dot(uSunDir, rd), uVolLight.x) * 4.0 * PI; |
| +добавлено | vec3 sun = uSunColor * uVolLight.w * sunPhase, amb = uAmbient * uVolLight.z; |
| +добавлено | vec3 scat = vec3(0.0), emit = vec3(0.0), Lin = vec3(0.0); |
| +добавлено | float T = 1.0, zSum = 0.0, wSum = 0.0, odSun = 0.0, odL = 0.0, s2; |
| +добавлено | vec3 a2, e2; |
| +добавлено | float sP = 0.0; vec3 aP = vec3(0.0), eP = vec3(0.0); // previous sample |
| +добавлено | bool hasLight = uWorldCounts.x > 0.5; |
| +добавлено | int lit = 0; |
| +добавлено | for (int i = 0; i <= 64; i++) { |
| +добавлено | if (i > steps || T < 0.01) break; |
| +добавлено | float sigma = sP; vec3 albedo = aP, e = eP; |
| +добавлено | if (i < steps) { |
| +добавлено | vec3 ps = o + d * t, pw = cameraPosition + rd * t; |
| +добавлено | volumeSample(pw, ps / uVolScale, sigma, albedo, e); |
| +добавлено | if (sigma > 1e-4) { |
| +добавлено | // lighting on every 2nd occupied sample, held in between; the shadow taps alternate between |
| +добавлено | // the sun and the brightest spell light (packWorld sorts it first), both on the first sample |
| +добавлено | int k = lit & 3; |
| +добавлено | if ((k & 1) == 0 && max(albedo.r, max(albedo.g, albedo.b)) > 1e-3) { |
| +добавлено | if (k == 0) { |
| +добавлено | volumeSample(pw + uSunDir * tap, (ps + tapS) / uVolScale, s2, a2, e2); |
| +добавлено | odSun = (sigma + s2) * tap; |
| +добавлено | } |
| +добавлено | if (hasLight && (k == 2 || lit == 0)) { |
| +добавлено | SpellLight L0 = spellLight(0); |
| +добавлено | vec3 lp = L0.type == 1 ? closestOnSegment(L0.pos, L0.end, pw) : L0.pos, ld = lp - pw; |
| +добавлено | float ll = length(ld), dl = min(tap, ll * 0.5); // never tap past the light itself |
| +добавлено | ld *= dl / max(ll, 1e-4); |
| +добавлено | volumeSample(pw + ld, (ps + uVolRot * ld) / uVolScale, s2, a2, e2); |
| +добавлено | odL = (sigma + s2) * dl; |
| +добавлено | } |
| +добавлено | Lin = sun * (exp(-odSun) + 0.25 * exp(-0.25 * odSun)) + amb * mix(0.35, 1.0, exp(-0.5 * odSun)) |
| +добавлено | + spellLightScatter(pw, -rd, uVolLight.x) * (exp(-odL) + 0.25 * exp(-0.25 * odL)); |
| +добавлено | } |
| +добавлено | lit++; |
| +добавлено | } |
| +добавлено | } else len = dt * (1.0 - j); |
| +добавлено | // trapezoid slab: the mean of its two end samples, so a density edge between two samples |
| +добавлено | // contributes in proportion to where it falls (rectangle slabs turn it into contour bands) |
| +добавлено | float sg = i == 0 ? sigma : 0.5 * (sigma + sP); |
| +добавлено | vec3 eg = i == 0 ? e : 0.5 * (e + eP), ag = i == 0 ? albedo : 0.5 * (albedo + aP); |
| +добавлено | sP = sigma; aP = albedo; eP = e; |
| +добавлено | if (sg > 1e-4) { |
| +добавлено | float Tr = exp(-sg * len), a = T * (1.0 - Tr); |
| +добавлено | scat += a * ag * Lin; |
| +добавлено | emit += a * eg / sg; |
| +добавлено | zSum += a * (t - 0.5 * len); wSum += a; |
| +добавлено | T *= Tr; |
| +добавлено | } else emit += T * eg * len; |
| +добавлено | t += dt; len = dt; |
| +добавлено | } |
| +добавлено | float alpha = 1.0 - T; |
| +добавлено | if (alpha < 0.002 && dot(emit, emit) < 1e-6) discard; |
| +добавлено | float z = (wSum > 0.0 ? zSum / wSum : t0) * cosV; |
| +добавлено | fxOut(scat / max(alpha, 1e-4), alpha, emit, vec2(0.0), z); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const SHAPES = { sphere: 0, box: 1, capsule: 2 }; |
| +добавлено | |
| +добавлено | // icosphere scaled so its faces (not just its vertices) enclose the unit sphere |
| +добавлено | function sphereProxy() { |
| +добавлено | const g = new THREE.IcosahedronGeometry(1, 2), p = g.attributes.position; |
| +добавлено | const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3(), n = new THREE.Vector3(); |
| +добавлено | let inner = 1; |
| +добавлено | for (let i = 0; i < p.count; i += 3) { |
| +добавлено | a.fromBufferAttribute(p, i); b.fromBufferAttribute(p, i + 1); c.fromBufferAttribute(p, i + 2); |
| +добавлено | n.subVectors(c, b).cross(a.clone().sub(b)).normalize(); |
| +добавлено | inner = Math.min(inner, Math.abs(n.dot(a))); |
| +добавлено | } |
| +добавлено | return g.scale(1.01 / inner, 1.01 / inner, 1.01 / inner); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const _p = new THREE.Vector3(), _q = new THREE.Quaternion(), _s = new THREE.Vector3(), _m = new THREE.Matrix4(); |
| +добавлено | |
| +добавлено | export class Volumes { |
| +добавлено | constructor() { |
| +добавлено | this.group = new THREE.Group(); // add once to the fx scene |
| +добавлено | this.list = []; |
| +добавлено | this.proxies = { sphere: sphereProxy(), box: new THREE.BoxGeometry(2, 2, 2) }; |
| +добавлено | this.proxies.capsule = this.proxies.box; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // At load only (one program per call). Returns a plain handle; set its fields each frame. |
| +добавлено | add({ shape = 'sphere', glsl, uniforms = {}, maxSteps = 32 }) { |
| +добавлено | const own = { |
| +добавлено | uVolCenter: { value: new THREE.Vector3() }, uVolRot: { value: new THREE.Matrix3() }, |
| +добавлено | uVolScale: { value: new THREE.Vector3(1, 1, 1) }, uVolSteps: { value: 8 }, |
| +добавлено | uVolLight: { value: new THREE.Vector4(0.3, 0.3, 1, 1) }, |
| +добавлено | }; |
| +добавлено | const material = new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, defines: { VOLUME_SHAPE: SHAPES[shape] }, |
| +добавлено | uniforms: { ...U, ...own, ...uniforms }, ...FX_BLENDING, depthTest: false, side: THREE.BackSide, |
| +добавлено | vertexShader: FX_VERT_HEAD + VOLUME_VERT, |
| +добавлено | fragmentShader: FX_FRAG_HEAD + NO_GRADIENTS + COMMON_GLSL + NOISE_GLSL + ARENA_GLSL + LIGHTS_GLSL + FX_OUT_GLSL |
| +добавлено | + VOLUME_HEAD + SHAPES_GLSL + glsl + VOLUME_MAIN, |
| +добавлено | }); |
| +добавлено | const mesh = new THREE.Mesh(this.proxies[shape], material); |
| +добавлено | mesh.visible = false; |
| +добавлено | this.group.add(mesh); |
| +добавлено | const h = { |
| +добавлено | mesh, position: mesh.position, scale: mesh.scale, quaternion: mesh.quaternion, uniforms: material.uniforms, |
| +добавлено | visible: false, maxSteps, |
| +добавлено | g: 0.3, // HG asymmetry (sun and spell lights) |
| +добавлено | shadowTap: 0.3, // sun-shadow tap distance, fraction of the smallest half extent |
| +добавлено | ambient: 1, sun: 1, |
| +добавлено | }; |
| +добавлено | this.list.push(h); |
| +добавлено | return h; |
| +добавлено | } |
| +добавлено | |
| +добавлено | update(camera) { |
| +добавлено | const cap = Math.max(4, Math.floor(Math.min(Q.volumeSteps * Q.auto.steps, 64))); |
| +добавлено | const pxPerM = 0.5 * U.uFxResolution.value.y * camera.projectionMatrix.elements[5]; |
| +добавлено | for (const h of this.list) { |
| +добавлено | const m = h.mesh, u = h.uniforms; |
| +добавлено | m.visible = h.visible; |
| +добавлено | if (!h.visible) continue; |
| +добавлено | m.updateMatrixWorld(); |
| +добавлено | m.matrixWorld.decompose(_p, _q, _s); |
| +добавлено | u.uVolCenter.value.copy(_p); |
| +добавлено | u.uVolScale.value.copy(_s); |
| +добавлено | u.uVolRot.value.setFromMatrix4(_m.makeRotationFromQuaternion(_q.invert())); |
| +добавлено | u.uVolLight.value.set(h.g, h.shadowTap * Math.min(_s.x, _s.y, _s.z), h.ambient, h.sun); |
| +добавлено | const r = Math.max(_s.x, _s.y, _s.z), dist = _p.distanceTo(camera.position); |
| +добавлено | const px = dist > r ? r * pxPerM / dist : Infinity; |
| +добавлено | u.uVolSteps.value = Math.min(h.maxSteps, cap, Math.max(8, Math.ceil(px / 5))); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | // ── АДАПТЕР (наша правка): земля арены заменена рельефом мира Ultra-Water. ── |
| +добавлено | import { islandHeight as groundHeight } from '../../uw/scene/islandHeight.js'; |
| +добавлено | |
| +добавлено | // The shared world every spell, sim and material sees. One file so the GLSL and its JS mirror |
| +добавлено | // stay side by side: |
| +добавлено | // - ARENA: the fixed layout (floor, rim wall, pillars, dummies, pool, caster focus) |
| +добавлено | // - U: uniforms shared by reference across every material ({ ...U, own uniforms }) |
| +добавлено | // - the world texture: lights, forces, impacts and capsule occluders packed into one 64x4 |
| +добавлено | // RGBA32F DataTexture, uploaded once per frame and read with texelFetch (no uniform-array |
| +добавлено | // limits, no per-material uploads) |
| +добавлено | // - GLSL chunks to read all of the above, and arenaSDF()/arenaRaycast() mirrored in JS |
| +добавлено | // |
| +добавлено | // Conventions: metres, y up, floor at y = 0, linear HDR. Spells never touch the texture; |
| +добавлено | // they hold handles from lights/forces/impacts/occluders and set plain fields. |
| +добавлено | |
| +добавлено | // --- arena layout ------------------------------------------------------------------- |
| +добавлено | const pillarAngles = Array.from({ length: 8 }, (_, i) => (i + 0.5) * Math.PI / 4); |
| +добавлено | export const ARENA = { |
| +добавлено | // ── АДАПТЕР (наша правка): арены-коробки у нас нет. ── |
| +добавлено | // Заклинания читают radius как границу мира (ветер: `R > ARENA.radius - 0.8`), |
| +добавлено | // поэтому границу уводим далеко; стену, колонны и манекены убираем. |
| +добавлено | radius: 100000, |
| +добавлено | wallThickness: 0.0, |
| +добавлено | wallHeight: 0.0, |
| +добавлено | pillarRing: 14, |
| +добавлено | pillarRadius: 0.6, |
| +добавлено | pillarHeight: 0, |
| +добавлено | pillars: [], |
| +добавлено | focus: new THREE.Vector3(0, 1.6, 12), // caster's focus orb, on a pedestal |
| +добавлено | pedestal: { pos: new THREE.Vector3(0, 0, 12), radius: 0.35, height: 1.15 }, |
| +добавлено | dummies: [], // цели — наши враги (см. src/world/spells.ts) |
| +добавлено | dummyRadius: 0.35, // capsule (x, 0.35, z) -> (x, 1.55, z) |
| +добавлено | dummyHeight: 1.9, |
| +добавлено | pool: { center: new THREE.Vector2(9.75, 0), half: new THREE.Vector2(2.25, 4.5), depth: 0.15, water: -0.03 }, |
| +добавлено | ground: { min: new THREE.Vector2(-20, -20), size: 40 }, // ground field covers this square |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // --- shared uniforms ---------------------------------------------------------------- |
| +добавлено | export const WORLD_W = 64; |
| +добавлено | export const MAX_LIGHTS = 16, MAX_FORCES = 16, MAX_IMPACTS = 16, MAX_OCCLUDERS = 32; |
| +добавлено | const worldData = new Float32Array(WORLD_W * 4 * 4); |
| +добавлено | const worldTex = new THREE.DataTexture(worldData, WORLD_W, 4, THREE.RGBAFormat, THREE.FloatType); |
| +добавлено | worldTex.magFilter = worldTex.minFilter = THREE.NearestFilter; |
| +добавлено | worldTex.needsUpdate = true; |
| +добавлено | |
| +добавлено | const placeholder3D = new THREE.Data3DTexture(new Uint8Array([128, 128, 128, 128]), 1, 1, 1); |
| +добавлено | placeholder3D.needsUpdate = true; |
| +добавлено | const placeholder2D = new THREE.DataTexture(new Uint8Array([0, 0, 0, 0]), 1, 1); |
| +добавлено | placeholder2D.needsUpdate = true; |
| +добавлено | |
| +добавлено | export const U = { |
| +добавлено | uTime: { value: 0 }, // seconds, scaled by time scale, wraps at 3600 |
| +добавлено | uDt: { value: 1 / 60 }, |
| +добавлено | uFrame: { value: 0 }, |
| +добавлено | uWorld: { value: worldTex }, |
| +добавлено | uWorldCounts: { value: new THREE.Vector4() }, // lights, forces, impacts, occluders |
| +добавлено | uNoise3D: { value: placeholder3D }, // noise.js: 128^3 RGBA8 tileable (r perlin-worley fbm, gba worley f2/f4/f8) |
| +добавлено | uCurl3D: { value: placeholder3D }, // noise.js: 64^3 RGBA8 tileable curl, rgb = curl * 0.5 + 0.5 |
| +добавлено | uBlackbody: { value: placeholder2D },// noise.js: 256x1 RGBA16F, see blackbody() below for the mapping |
| +добавлено | uGroundA: { value: placeholder2D }, // GroundField: heat, char, wet, frost |
| +добавлено | uGroundB: { value: placeholder2D }, // GroundField: crack, acid, corruption, glow |
| +добавлено | uGroundRect: { value: new THREE.Vector4(ARENA.ground.min.x, ARENA.ground.min.y, ARENA.ground.size, 1 / ARENA.ground.size) }, |
| +добавлено | uSceneDepth: { value: null }, // full-res resolved depth (DepthTexture, [0,1] non-linear) |
| +добавлено | uSceneColor: { value: null }, // resolved opaque HDR (refraction) |
| +добавлено | uResolution: { value: new THREE.Vector2(1, 1) }, |
| +добавлено | uFxResolution: { value: new THREE.Vector2(1, 1) }, |
| +добавлено | uNearFar: { value: new THREE.Vector2(0.1, 400) }, |
| +добавлено | uSunDir: { value: new THREE.Vector3(0, 1, 0) }, |
| +добавлено | uSunColor: { value: new THREE.Vector3(1, 1, 1) }, // radiance scale, as UW's sky.sunColor |
| +добавлено | uAmbient: { value: new THREE.Vector3(0.1, 0.1, 0.12) }, // average sky irradiance / pi, for particles |
| +добавлено | uSkyCube: { value: null }, |
| +добавлено | uDebug: { value: 0 }, // debug view id (0 = off), read by FX materials for overdraw |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // --- GLSL --------------------------------------------------------------------------- |
| +добавлено | const f = (x) => x.toFixed(4); |
| +добавлено | |
| +добавлено | export const COMMON_GLSL = /* glsl */` |
| +добавлено | #ifndef PI |
| +добавлено | #define PI 3.14159265359 |
| +добавлено | #endif |
| +добавлено | uniform float uTime; |
| +добавлено | uniform float uDt; |
| +добавлено | uniform float uFrame; |
| +добавлено | uniform vec2 uResolution; |
| +добавлено | uniform vec2 uFxResolution; |
| +добавлено | uniform vec2 uNearFar; |
| +добавлено | uniform float uDebug; |
| +добавлено | // Hash without Sine (Dave Hoskins, MIT) |
| +добавлено | float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); } |
| +добавлено | float hash12(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); } |
| +добавлено | vec2 hash21(float p) { vec3 p3 = fract(vec3(p) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); } |
| +добавлено | vec3 hash31(float p) { vec3 p3 = fract(vec3(p) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xxy + p3.yzz) * p3.zyx); } |
| +добавлено | vec3 hash33(vec3 p3) { p3 = fract(p3 * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yxz + 33.33); return fract((p3.xxy + p3.yxx) * p3.zyx); } |
| +добавлено | vec4 hash41(float p) { vec4 p4 = fract(vec4(p) * vec4(0.1031, 0.1030, 0.0973, 0.1099)); p4 += dot(p4, p4.wzxy + 33.33); return fract((p4.xxyz + p4.yzzw) * p4.zywx); } |
| +добавлено | // interleaved gradient noise (Jimenez 2014), rotated per frame |
| +добавлено | float ign(vec2 px) { px += 5.588238 * mod(uFrame, 64.0); return fract(52.9829189 * fract(dot(px, vec2(0.06711056, 0.00583715)))); } |
| +добавлено | float linearDepth(float d) { return uNearFar.x * uNearFar.y / (uNearFar.y - d * (uNearFar.y - uNearFar.x)); } |
| +добавлено | vec3 randomInSphere(vec3 r) { float z = r.x * 2.0 - 1.0, a = r.y * 2.0 * PI; float s = sqrt(1.0 - z * z); return vec3(s * cos(a), z, s * sin(a)) * pow(r.z, 1.0 / 3.0); } |
| +добавлено | vec3 randomOnSphere(vec2 r) { float z = r.x * 2.0 - 1.0, a = r.y * 2.0 * PI; float s = sqrt(1.0 - z * z); return vec3(s * cos(a), z, s * sin(a)); } |
| +добавлено | mat3 basisFrom(vec3 n) { vec3 t = abs(n.y) < 0.99 ? normalize(cross(n, vec3(0, 1, 0))) : vec3(1, 0, 0); return mat3(t, cross(t, n), n); } |
| +добавлено | float hgPhase(float mu, float g) { float g2 = g * g; return (1.0 - g2) / (4.0 * PI * pow(1.0 + g2 - 2.0 * g * mu, 1.5)); } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | export const NOISE_GLSL = /* glsl */` |
| +добавлено | uniform highp sampler3D uNoise3D; |
| +добавлено | uniform highp sampler3D uCurl3D; |
| +добавлено | uniform sampler2D uBlackbody; |
| +добавлено | // p in tile units (one tile = one repeat of the texture) |
| +добавлено | vec4 noise3v(vec3 p) { return texture(uNoise3D, p); } |
| +добавлено | float noise3(vec3 p) { return texture(uNoise3D, p).r; } |
| +добавлено | float worley3(vec3 p) { return texture(uNoise3D, p).g; } |
| +добавлено | vec3 curl3(vec3 p) { return texture(uCurl3D, p).rgb * 2.0 - 1.0; } |
| +добавлено | // two-octave fbm from the baked fbm channel (already 4 octaves deep) |
| +добавлено | float fbm3(vec3 p) { return texture(uNoise3D, p).r * 0.7 + texture(uNoise3D, p * 2.63 + 0.37).r * 0.3; } |
| +добавлено | // Blackbody chromaticity in linear sRGB, normalised to luminance 1. u = log(K / 500) / log(40), |
| +добавлено | // i.e. 500 K .. 20000 K logarithmically. Intensity is a separate artist curve. |
| +добавлено | vec3 blackbody(float kelvin) { return texture(uBlackbody, vec2(clamp(log(kelvin / 500.0) / log(40.0), 0.0, 1.0), 0.5)).rgb; } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | export const WORLD_GLSL = /* glsl */` |
| +добавлено | uniform highp sampler2D uWorld; |
| +добавлено | uniform vec4 uWorldCounts; |
| +добавлено | vec4 worldTexel(int row, int i) { return texelFetch(uWorld, ivec2(i, row), 0); } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // floor (pool recess), rim wall ring, then every capsule in the occluder list |
| +добавлено | export const ARENA_GLSL = WORLD_GLSL + /* glsl */` |
| +добавлено | float sdCapsule(vec3 p, vec3 a, vec3 b, float r) { |
| +добавлено | vec3 pa = p - a, ba = b - a; |
| +добавлено | float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-6), 0.0, 1.0); |
| +добавлено | return length(pa - ba * h) - r; |
| +добавлено | } |
| +добавлено | float arenaStatic(vec3 p) { |
| +добавлено | vec2 pq = abs(p.xz - vec2(${f(ARENA.pool.center.x)}, ${f(ARENA.pool.center.y)})); |
| +добавлено | float floorY = (pq.x < ${f(ARENA.pool.half.x)} && pq.y < ${f(ARENA.pool.half.y)}) ? ${f(ARENA.pool.water)} : 0.0; |
| +добавлено | float d = p.y - floorY; |
| +добавлено | vec2 q = vec2(abs(length(p.xz) - ${f(ARENA.radius + ARENA.wallThickness / 2)}) - ${f(ARENA.wallThickness / 2)}, |
| +добавлено | abs(p.y - ${f(ARENA.wallHeight / 2)}) - ${f(ARENA.wallHeight / 2)}); |
| +добавлено | return min(d, length(max(q, 0.0)) + min(max(q.x, q.y), 0.0)); |
| +добавлено | } |
| +добавлено | float arenaSDF(vec3 p) { |
| +добавлено | float d = arenaStatic(p); |
| +добавлено | int n = int(uWorldCounts.w); |
| +добавлено | for (int i = 0; i < ${MAX_OCCLUDERS}; i++) { |
| +добавлено | if (i >= n) break; |
| +добавлено | vec4 a = worldTexel(3, i * 2), b = worldTexel(3, i * 2 + 1); |
| +добавлено | d = min(d, sdCapsule(p, a.xyz, b.xyz, a.w)); |
| +добавлено | } |
| +добавлено | return d; |
| +добавлено | } |
| +добавлено | vec3 arenaNormal(vec3 p) { |
| +добавлено | const vec2 e = vec2(0.01, 0.0); |
| +добавлено | return normalize(vec3(arenaSDF(p + e.xyy) - arenaSDF(p - e.xyy), arenaSDF(p + e.yxy) - arenaSDF(p - e.yxy), arenaSDF(p + e.yyx) - arenaSDF(p - e.yyx))); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // Spell lights: point (type 0), line (1, segment pos -> end), cookie (2, point light with a |
| +добавлено | // projected pattern: cookie.x = 1 caustic, 2 rune ring; cookie.y scale, cookie.z rotation). |
| +добавлено | // Karis 2013 windowed inverse-square falloff; line lights use the representative point. The |
| +добавлено | // first lights flagged shadow (the CPU keeps at most Q.shadowLights of them) get analytic |
| +добавлено | // capsule shadows from the occluder list (UE4 capsule shadows), penumbra growing with distance. |
| +добавлено | export const LIGHTS_GLSL = /* glsl */` |
| +добавлено | bool gLightNoShadow = false; // set true in volume/media shaders: capsule shadows per step cost too much |
| +добавлено | struct SpellLight { vec3 pos; float range; vec3 color; int type; vec3 end; float shadow; vec4 cookie; }; |
| +добавлено | SpellLight spellLight(int i) { |
| +добавлено | vec4 a = worldTexel(0, i * 4), b = worldTexel(0, i * 4 + 1), c = worldTexel(0, i * 4 + 2), d = worldTexel(0, i * 4 + 3); |
| +добавлено | return SpellLight(a.xyz, a.w, b.rgb, int(b.a), c.xyz, c.w, d); |
| +добавлено | } |
| +добавлено | float lightFalloff(float d, float range) { |
| +добавлено | float x = d / range; x *= x; x *= x; |
| +добавлено | float w = clamp(1.0 - x, 0.0, 1.0); |
| +добавлено | return w * w / (d * d + 1.0); |
| +добавлено | } |
| +добавлено | vec3 closestOnSegment(vec3 a, vec3 b, vec3 p) { |
| +добавлено | vec3 ab = b - a; |
| +добавлено | return a + ab * clamp(dot(p - a, ab) / max(dot(ab, ab), 1e-6), 0.0, 1.0); |
| +добавлено | } |
| +добавлено | // closest point on segment a-b to the ray o + t*r (t >= 0) |
| +добавлено | vec3 closestOnSegmentToRay(vec3 a, vec3 b, vec3 o, vec3 r) { |
| +добавлено | vec3 ab = b - a, ao = a - o; |
| +добавлено | float abr = dot(ab, r), abab = dot(ab, ab); |
| +добавлено | float t = (dot(ao, r) * abr - dot(ao, ab)) / max(abab - abr * abr, 1e-5); |
| +добавлено | return a + ab * clamp(t, 0.0, 1.0); |
| +добавлено | } |
| +добавлено | // distance between segments p1-q1 and p2-q2; s = parameter on the first (Ericson 5.1.9) |
| +добавлено | float segSegDist(vec3 p1, vec3 q1, vec3 p2, vec3 q2, out float s) { |
| +добавлено | vec3 d1 = q1 - p1, d2 = q2 - p2, r = p1 - p2; |
| +добавлено | float a = dot(d1, d1), e = dot(d2, d2), f = dot(d2, r), c = dot(d1, r), b = dot(d1, d2); |
| +добавлено | float denom = a * e - b * b; |
| +добавлено | s = denom > 1e-6 ? clamp((b * f - c * e) / denom, 0.0, 1.0) : 0.0; |
| +добавлено | float t = (b * s + f) / max(e, 1e-6); |
| +добавлено | if (t < 0.0) { t = 0.0; s = clamp(-c / max(a, 1e-6), 0.0, 1.0); } |
| +добавлено | else if (t > 1.0) { t = 1.0; s = clamp((b - c) / max(a, 1e-6), 0.0, 1.0); } |
| +добавлено | return length(p1 + d1 * s - (p2 + d2 * t)); |
| +добавлено | } |
| +добавлено | float capsuleShadow(vec3 p, vec3 lp) { |
| +добавлено | vec3 dir = lp - p; |
| +добавлено | float len = length(dir); |
| +добавлено | p += dir * min(0.15 / max(len, 1e-3), 0.5); // start off the surface (own capsule) |
| +добавлено | float vis = 1.0; |
| +добавлено | int n = int(uWorldCounts.w); |
| +добавлено | for (int i = 0; i < ${MAX_OCCLUDERS}; i++) { |
| +добавлено | if (i >= n) break; |
| +добавлено | vec4 a = worldTexel(3, i * 2), b = worldTexel(3, i * 2 + 1); |
| +добавлено | if (abs(b.w - 3.0) < 0.5) continue; // shields are glass: they collide but cast no shadow |
| +добавлено | // bounding-sphere reject first: most capsules are nowhere near this shadow ray |
| +добавлено | vec3 m = 0.5 * (a.xyz + b.xyz), q = closestOnSegment(p, lp, m) - m; |
| +добавлено | float R = 0.5 * length(b.xyz - a.xyz) + a.w + 0.04 + 0.18 * len; |
| +добавлено | if (dot(q, q) > R * R) continue; |
| +добавлено | float s, d = segSegDist(p, lp, a.xyz, b.xyz, s); |
| +добавлено | float pen = 0.04 + 0.18 * s * len; |
| +добавлено | vis *= smoothstep(a.w - pen * 0.5, a.w + pen, d); |
| +добавлено | } |
| +добавлено | return vis; |
| +добавлено | } |
| +добавлено | float lightCookie(SpellLight L, vec3 p) { |
| +добавлено | if (L.cookie.x < 0.5) return 1.0; |
| +добавлено | vec2 q = (p.xz - L.pos.xz) * L.cookie.y; |
| +добавлено | float c = cos(L.cookie.z), s = sin(L.cookie.z); |
| +добавлено | q = mat2(c, -s, s, c) * q; |
| +добавлено | if (L.cookie.x < 1.5) { // caustic: folded sines, cheap and shimmering |
| +добавлено | vec2 w = q * 3.0 + vec2(sin(q.y * 2.1 + uTime * 1.3), cos(q.x * 1.7 - uTime * 1.1)); |
| +добавлено | float k = abs(sin(w.x) * sin(w.y)); |
| +добавлено | return 0.35 + 2.2 * pow(1.0 - k, 6.0); |
| +добавлено | } |
| +добавлено | float r = length(q); // rune ring |
| +добавлено | float ring = smoothstep(0.06, 0.0, abs(r - 1.0)) + smoothstep(0.04, 0.0, abs(r - 0.78)); |
| +добавлено | float spokes = smoothstep(0.92, 1.0, abs(cos(atan(q.y, q.x) * 6.0))) * step(r, 1.0) * step(0.78, r); |
| +добавлено | return 0.2 + 3.0 * clamp(ring + spokes, 0.0, 1.0); |
| +добавлено | } |
| +добавлено | // light vector + radiance arriving at p from light i (no BRDF). For line lights the point used |
| +добавлено | // is the closest one to the reflection ray r for specular (pass r) or to p for diffuse (r = 0). |
| +добавлено | vec3 spellLightRaw(SpellLight L, vec3 p, vec3 r, out vec3 l, out vec3 lp) { |
| +добавлено | lp = L.pos; |
| +добавлено | if (L.type == 1) lp = dot(r, r) > 0.0 ? closestOnSegmentToRay(L.pos, L.end, p, r) : closestOnSegment(L.pos, L.end, p); |
| +добавлено | vec3 d = lp - p; |
| +добавлено | float dist = length(d); |
| +добавлено | l = d / max(dist, 1e-4); |
| +добавлено | vec3 c = L.color * lightFalloff(dist, L.range); |
| +добавлено | if (L.type == 2) c *= lightCookie(L, p); |
| +добавлено | return c; |
| +добавлено | } |
| +добавлено | // shadow only where the light actually arrives (outside its range the falloff is exactly 0) |
| +добавлено | float spellLightShadow(SpellLight L, vec3 p, vec3 lp, vec3 c) { |
| +добавлено | return (L.shadow > 0.5 && !gLightNoShadow && dot(c, c) > 0.0) ? capsuleShadow(p, lp) : 1.0; |
| +добавлено | } |
| +добавлено | vec3 spellLightIncoming(SpellLight L, vec3 p, vec3 r, out vec3 l) { |
| +добавлено | vec3 lp, c = spellLightRaw(L, p, r, l, lp); |
| +добавлено | return c * spellLightShadow(L, p, lp, c); |
| +добавлено | } |
| +добавлено | // sum of spell-light irradiance / pi on a surface (n) or, with n = 0, omnidirectional (media) |
| +добавлено | vec3 spellLightDiffuse(vec3 p, vec3 n) { |
| +добавлено | vec3 sum = vec3(0.0), l; |
| +добавлено | int count = int(uWorldCounts.x); |
| +добавлено | for (int i = 0; i < ${MAX_LIGHTS}; i++) { |
| +добавлено | if (i >= count) break; |
| +добавлено | vec3 c = spellLightIncoming(spellLight(i), p, vec3(0.0), l); |
| +добавлено | sum += c * (dot(n, n) > 0.0 ? max(dot(n, l), 0.0) : 0.5); |
| +добавлено | } |
| +добавлено | return sum; |
| +добавлено | } |
| +добавлено | // in-scatter for media / volumes: Henyey-Greenstein phase towards the viewer (v = to camera) |
| +добавлено | vec3 spellLightScatter(vec3 p, vec3 v, float g) { |
| +добавлено | vec3 sum = vec3(0.0), l; |
| +добавлено | int count = int(uWorldCounts.x); |
| +добавлено | for (int i = 0; i < ${MAX_LIGHTS}; i++) { |
| +добавлено | if (i >= count) break; |
| +добавлено | vec3 c = spellLightIncoming(spellLight(i), p, vec3(0.0), l); |
| +добавлено | sum += c * hgPhase(dot(l, -v), g) * 4.0 * PI; |
| +добавлено | } |
| +добавлено | return sum; |
| +добавлено | } |
| +добавлено | float spellD_GGX(float nh, float a) { float a2 = a * a; float d = nh * nh * (a2 - 1.0) + 1.0; return a2 / (PI * d * d); } |
| +добавлено | float spellV_Smith(float nv, float nl, float a) { return 0.5 / mix(2.0 * nl * nv, nl + nv, a); } |
| +добавлено | // GGX + Lambert from every spell light; diffuse and specular returned apart (radiance) |
| +добавлено | void spellLightPBR(vec3 p, vec3 n, vec3 v, float roughness, vec3 f0, vec3 diffColor, out vec3 diffuse, out vec3 specular) { |
| +добавлено | diffuse = vec3(0.0); specular = vec3(0.0); |
| +добавлено | float a = max(roughness * roughness, 0.002); |
| +добавлено | float nv = max(dot(n, v), 1e-4); |
| +добавлено | vec3 r = reflect(-v, n), l; |
| +добавлено | int count = int(uWorldCounts.x); |
| +добавлено | for (int i = 0; i < ${MAX_LIGHTS}; i++) { |
| +добавлено | if (i >= count) break; |
| +добавлено | SpellLight L = spellLight(i); |
| +добавлено | vec3 lp, cd = spellLightRaw(L, p, vec3(0.0), l, lp); |
| +добавлено | if (dot(cd, cd) == 0.0) continue; |
| +добавлено | float sh = spellLightShadow(L, p, lp, cd); // one shadow per light: the specular point reuses it |
| +добавлено | cd *= sh; |
| +добавлено | diffuse += cd * diffColor * max(dot(n, l), 0.0) / PI; |
| +добавлено | vec3 cs = L.type == 1 ? spellLightRaw(L, p, r, l, lp) * sh : cd; |
| +добавлено | vec3 h = normalize(l + v); |
| +добавлено | float nl = max(dot(n, l), 0.0), nh = max(dot(n, h), 0.0), vh = max(dot(v, h), 0.0); |
| +добавлено | vec3 F = f0 + (1.0 - f0) * pow(1.0 - vh, 5.0); |
| +добавлено | float aL = L.type == 1 ? min(a + 0.25 / max(2.0 * distance(lp, p), 0.25), 1.0) : a; // line lights are ~0.25 m tubes, not hard streaks |
| +добавлено | specular += cs * F * (spellD_GGX(nh, aL) * spellV_Smith(nv, nl, aL) * nl) * (a / aL); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // Forces act on every particle (scaled by its kind's force response) and warp fire volumes. |
| +добавлено | // 0 wind t2.xyz dir, t1 = (speed m/s, gustiness, coupling, -) |
| +добавлено | // 1 vortex pos = base, t2.xyz axis, t1 = (core R, circulation G, updraft W, inflow), t2.w height |
| +добавлено | // 2 attractor t1 = (strength, softening, kill radius, range) (negative strength repels) |
| +добавлено | // 3 orbit Kepler disk: t2.xyz axis, t1 = (GM, inner, outer, coupling) |
| +добавлено | // 4 shock expanding shell: t1 = (radius, thickness, impulse, -) |
| +добавлено | // 5 push cone gust: t2.xyz dir, t1 = (speed, radius, length, coupling) |
| +добавлено | export const FORCES_GLSL = /* glsl */` |
| +добавлено | vec3 forceAccel(vec3 p, vec3 v, inout float kill) { |
| +добавлено | vec3 acc = vec3(0.0); |
| +добавлено | int n = int(uWorldCounts.y); |
| +добавлено | for (int i = 0; i < ${MAX_FORCES}; i++) { |
| +добавлено | if (i >= n) break; |
| +добавлено | vec4 a = worldTexel(1, i * 4), k = worldTexel(1, i * 4 + 1), b = worldTexel(1, i * 4 + 2); |
| +добавлено | int type = int(a.w); |
| +добавлено | vec3 d = p - a.xyz; |
| +добавлено | if (type == 0) { |
| +добавлено | float gust = 1.0 + k.y * sin(uTime * 1.7 + dot(p, vec3(0.13, 0.05, 0.11))) * sin(uTime * 0.53 + p.x * 0.07); |
| +добавлено | acc += (b.xyz * k.x * gust - v) * k.z; |
| +добавлено | } else if (type == 1) { |
| +добавлено | vec3 ax = b.xyz; |
| +добавлено | float h = dot(d, ax); |
| +добавлено | vec3 radial = d - ax * h; |
| +добавлено | float r = length(radial); |
| +добавлено | if (h > -0.5 && h < b.w && r < k.x * 6.0) { |
| +добавлено | vec3 er = radial / max(r, 1e-3), et = cross(ax, er); |
| +добавлено | float vt = r < k.x ? k.y / (2.0 * PI) * r / (k.x * k.x) : k.y / (2.0 * PI * r); |
| +добавлено | float up = k.z * exp(-r * r / (k.x * k.x * 2.0)); |
| +добавлено | vec3 target = et * vt + ax * up - er * k.w * smoothstep(k.x * 6.0, k.x, r) * (1.0 - smoothstep(0.0, 2.0, h) * 0.6); |
| +добавлено | acc += (target - v) * 3.0 * smoothstep(k.x * 6.0, k.x * 3.0, r); |
| +добавлено | } |
| +добавлено | } else if (type == 2) { |
| +добавлено | float r2 = dot(d, d); |
| +добавлено | if (r2 < k.w * k.w) { |
| +добавлено | acc -= normalize(d) * k.x / (r2 + k.y * k.y); |
| +добавлено | if (r2 < k.z * k.z) kill = 1.0; |
| +добавлено | } |
| +добавлено | } else if (type == 3) { |
| +добавлено | vec3 ax = b.xyz; |
| +добавлено | float h = dot(d, ax); |
| +добавлено | vec3 radial = d - ax * h; |
| +добавлено | float r = length(radial); |
| +добавлено | if (r > k.y * 0.5 && r < k.z) { |
| +добавлено | vec3 et = cross(ax, radial / r); |
| +добавлено | vec3 target = et * sqrt(k.x / r) - ax * h * 4.0; |
| +добавлено | acc += (target - v) * k.w; |
| +добавлено | } |
| +добавлено | if (r < k.y) kill = max(kill, step(abs(h), 0.5)); |
| +добавлено | } else if (type == 4) { |
| +добавлено | float r = length(d); |
| +добавлено | float shell = 1.0 - clamp(abs(r - k.x) / max(k.y, 1e-3), 0.0, 1.0); |
| +добавлено | acc += d / max(r, 1e-3) * k.z * shell; |
| +добавлено | } else if (type == 5) { |
| +добавлено | float along = dot(d, b.xyz); |
| +добавлено | float off = length(d - b.xyz * along); |
| +добавлено | if (along > -0.5 && along < k.z && off < k.y) acc += (b.xyz * k.x - v) * k.w * (1.0 - off / k.y); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return acc; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // Spherical "volume decals" for surfaces: weights per impact type at p (amount x falloff x fade). |
| +добавлено | // A: x scorch/heat, y frost, z wet, w magma glow. B: x acid, y holy glow, z corruption, w electric. |
| +добавлено | // Each impact also carries a colour (t2.rgb) for the glow types. |
| +добавлено | export const IMPACTS_GLSL = /* glsl */` |
| +добавлено | void impactWeights(vec3 p, out vec4 wa, out vec4 wb, out vec3 glowColor) { |
| +добавлено | wa = vec4(0.0); wb = vec4(0.0); glowColor = vec3(0.0); |
| +добавлено | int n = int(uWorldCounts.z); |
| +добавлено | for (int i = 0; i < ${MAX_IMPACTS}; i++) { |
| +добавлено | if (i >= n) break; |
| +добавлено | vec4 a = worldTexel(2, i * 4), b = worldTexel(2, i * 4 + 1), c = worldTexel(2, i * 4 + 2); |
| +добавлено | float w = b.z * smoothstep(1.0, 0.55, length(p - a.xyz) / a.w); |
| +добавлено | if (w <= 0.0) continue; |
| +добавлено | int t = int(b.x); |
| +добавлено | if (t < 4) wa[t] += w; else wb[t - 4] += w; |
| +добавлено | glowColor += c.rgb * w; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | export const GROUND_GLSL = /* glsl */` |
| +добавлено | uniform sampler2D uGroundA; |
| +добавлено | uniform sampler2D uGroundB; |
| +добавлено | uniform vec4 uGroundRect; // min x, min z, size, 1 / size |
| +добавлено | vec2 groundUV(vec2 xz) { return (xz - uGroundRect.xy) * uGroundRect.w; } |
| +добавлено | vec4 groundA(vec2 xz) { return texture(uGroundA, groundUV(xz)); } // heat, char, wet, frost |
| +добавлено | vec4 groundB(vec2 xz) { return texture(uGroundB, groundUV(xz)); } // crack, acid, corruption, glow |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // --- FX pass (half-res MRT, weighted-blended OIT; McGuire & Bavoil 2013) ------------- |
| +добавлено | // Every FX-pass material is a RawShaderMaterial (GLSL3) using FX_VERT_HEAD / FX_FRAG_HEAD and |
| +добавлено | // ...FX_BLENDING, and ends with fxOut(). One blend state for the three attachments: |
| +добавлено | // 0 media (w*c*a, a) -> rgb sum, alpha = revealage product |
| +добавлено | // 1 weight (w*a, distortion.xy, a) |
| +добавлено | // 2 emission (rgb, 0) -> additive, never occluded by media unless the composite says so |
| +добавлено | export const FX_BLENDING = { |
| +добавлено | transparent: true, depthWrite: false, depthTest: true, |
| +добавлено | blending: THREE.CustomBlending, |
| +добавлено | blendEquation: THREE.AddEquation, blendSrc: THREE.OneFactor, blendDst: THREE.OneFactor, |
| +добавлено | blendEquationAlpha: THREE.AddEquation, blendSrcAlpha: THREE.ZeroFactor, blendDstAlpha: THREE.OneMinusSrcAlphaFactor, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | export const FX_VERT_HEAD = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | uniform mat4 modelMatrix; |
| +добавлено | uniform mat4 modelViewMatrix; |
| +добавлено | uniform mat4 projectionMatrix; |
| +добавлено | uniform mat4 viewMatrix; |
| +добавлено | uniform vec3 cameraPosition; |
| +добавлено | in vec3 position; |
| +добавлено | `; |
| +добавлено | |
| +добавлено | export const FX_FRAG_HEAD = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | precision highp sampler2D; |
| +добавлено | uniform mat4 viewMatrix; |
| +добавлено | uniform vec3 cameraPosition; |
| +добавлено | uniform highp sampler2D uSceneDepth; |
| +добавлено | layout(location = 0) out vec4 fxMedia; |
| +добавлено | layout(location = 1) out vec4 fxWeight; |
| +добавлено | layout(location = 2) out vec4 fxEmit; |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // needs COMMON_GLSL. viewZ positive distance along the view axis. |
| +добавлено | export const FX_OUT_GLSL = /* glsl */` |
| +добавлено | // full-res scene depth under this half-res fragment (nearest of the 2x2 would be ideal; the |
| +добавлено | // prepass already made the FX depth the farthest, this is the soft-fade reference) |
| +добавлено | // farthest depth of this half-res pixel's full-res block, the same value the depth prepass |
| +добавлено | // wrote: soft fade and volume clipping must agree with the depth test, or smoke gaps open |
| +добавлено | // along every silhouette when the composite picks the far tap there |
| +добавлено | float sceneViewZ() { |
| +добавлено | ivec2 b = ivec2(floor(floor(gl_FragCoord.xy) * uResolution / uFxResolution)); |
| +добавлено | ivec2 m = ivec2(uResolution) - 1; |
| +добавлено | float d = texelFetch(uSceneDepth, min(b, m), 0).r; |
| +добавлено | d = max(d, texelFetch(uSceneDepth, min(b + ivec2(1, 0), m), 0).r); |
| +добавлено | d = max(d, texelFetch(uSceneDepth, min(b + ivec2(0, 1), m), 0).r); |
| +добавлено | d = max(d, texelFetch(uSceneDepth, min(b + ivec2(1, 1), m), 0).r); |
| +добавлено | return linearDepth(d); |
| +добавлено | } |
| +добавлено | float softFade(float viewZ, float dist) { return clamp((sceneViewZ() - viewZ) / dist, 0.0, 1.0); } |
| +добавлено | float wboitWeight(float viewZ, float a) { |
| +добавлено | return a * clamp(10.0 / (1e-5 + pow(viewZ / 10.0, 2.0) + pow(viewZ / 200.0, 6.0)), 0.01, 30.0); |
| +добавлено | } |
| +добавлено | // col: lit media colour, a: coverage, emit: additive HDR emission, dist: screen-space UV offset |
| +добавлено | void fxOut(vec3 col, float a, vec3 emit, vec2 dist, float viewZ) { |
| +добавлено | a = clamp(a, 0.0, 0.999); // 0.995 let a bright HDR sky print through opaque soot |
| +добавлено | if (uDebug > 0.5 && uDebug < 1.5) { fxMedia = vec4(0.0, 0.0, 0.0, 0.0); fxWeight = vec4(0.0); fxEmit = vec4(0.04, 0.012, 0.004, 0.0); return; } |
| +добавлено | float w = wboitWeight(viewZ, a); |
| +добавлено | fxMedia = vec4(col * a * w, a); |
| +добавлено | fxWeight = vec4(a * w, dist, a); |
| +добавлено | fxEmit = vec4(emit, 0.0); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // full-res additive emissive (sparks, motes, bolt cores, sigils) into the HDR target. Pure |
| +добавлено | // ONE/ONE on rgb whatever alpha the shader writes (three's AdditiveBlending scales by src alpha), |
| +добавлено | // destination alpha kept (the planar reflection uses alpha as its 'something drawn' mask). |
| +добавлено | export const LINES_BLENDING = { |
| +добавлено | transparent: true, depthWrite: false, depthTest: true, |
| +добавлено | blending: THREE.CustomBlending, |
| +добавлено | blendEquation: THREE.AddEquation, blendSrc: THREE.OneFactor, blendDst: THREE.OneFactor, |
| +добавлено | blendEquationAlpha: THREE.AddEquation, blendSrcAlpha: THREE.ZeroFactor, blendDstAlpha: THREE.OneFactor, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // --- JS side: pools packed into the world texture ------------------------------------- |
| +добавлено | function makePool(n, init) { |
| +добавлено | const items = Array.from({ length: n }, (_, i) => ({ index: i, active: false, ...init() })); |
| +добавлено | return { |
| +добавлено | items, |
| +добавлено | acquire() { |
| +добавлено | const it = items.find((x) => !x.active); |
| +добавлено | if (!it) return null; |
| +добавлено | Object.assign(it, init(), { active: true }); |
| +добавлено | return it; |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // light: pos, range, color (linear), intensity, type 0 point / 1 line / 2 cookie, end (line), |
| +добавлено | // shadow (wants capsule shadows), cookie [pattern, scale, rotation, 0] |
| +добавлено | export const lights = makePool(MAX_LIGHTS, () => ({ |
| +добавлено | pos: new THREE.Vector3(), range: 8, color: new THREE.Color(1, 1, 1), intensity: 0, type: 0, |
| +добавлено | end: new THREE.Vector3(), shadow: false, cookie: [0, 1, 0, 0], |
| +добавлено | release() { this.active = false; }, |
| +добавлено | })); |
| +добавлено | |
| +добавлено | export const forces = makePool(MAX_FORCES, () => ({ |
| +добавлено | pos: new THREE.Vector3(), type: 0, p: [0, 0, 0, 0], dir: new THREE.Vector3(0, 1, 0), w: 0, |
| +добавлено | release() { this.active = false; }, |
| +добавлено | })); |
| +добавлено | |
| +добавлено | // impacts fade on their own: amount * (1 - age / life), oldest replaced when full |
| +добавлено | const IMPACT_TYPES = { scorch: 0, frost: 1, wet: 2, magma: 3, acid: 4, holy: 5, corruption: 6, electric: 7 }; |
| +добавлено | const impactList = Array.from({ length: MAX_IMPACTS }, () => ({ pos: new THREE.Vector3(), radius: 1, type: 0, age: 1e9, life: 1, amount: 0, color: new THREE.Color() })); |
| +добавлено | const DEFAULT_IMPACT = new THREE.Color(1, 0.4, 0.1); |
| +добавлено | export const impacts = { |
| +добавлено | types: IMPACT_TYPES, |
| +добавлено | add(type, pos, radius, amount = 1, life = 6, color = null) { |
| +добавлено | let it = impactList[0]; |
| +добавлено | for (const x of impactList) if (x.age / x.life > it.age / it.life) it = x; |
| +добавлено | it.pos.copy(pos); it.radius = radius; it.type = typeof type === 'string' ? IMPACT_TYPES[type] : type; |
| +добавлено | it.amount = amount; it.life = life; it.age = 0; |
| +добавлено | it.color.copy(color ?? DEFAULT_IMPACT); |
| +добавлено | return it; |
| +добавлено | }, |
| +добавлено | clear() { for (const x of impactList) x.age = 1e9; }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // capsules (a, b, radius); static ones are added once by the arena, dynamic ones (spikes, |
| +добавлено | // shields) are acquired and released. kind: 0 stone, 1 dummy, 2 spike, 3 shield, 4 pedestal |
| +добавлено | const occluderList = []; |
| +добавлено | export const occluders = { |
| +добавлено | list: occluderList, |
| +добавлено | add(a, b, radius, kind = 0) { |
| +добавлено | if (occluderList.length >= MAX_OCCLUDERS) return null; |
| +добавлено | const o = { a: a.clone(), b: b.clone(), radius, kind, release() { const i = occluderList.indexOf(o); if (i >= 0) occluderList.splice(i, 1); } }; |
| +добавлено | occluderList.push(o); |
| +добавлено | return o; |
| +добавлено | }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // The CPU keeps at most `maxLights` lights and `maxShadowed` shadowed ones (the brightest). |
| +добавлено | const lightOrder = []; |
| +добавлено | export function packWorld(dt, { maxLights = MAX_LIGHTS, maxShadowed = 4 } = {}) { |
| +добавлено | const d = worldData; |
| +добавлено | d.fill(0); |
| +добавлено | // lights, brightest first so a tier cut drops the dim ones |
| +добавлено | lightOrder.length = 0; |
| +добавлено | for (const l of lights.items) if (l.active && l.intensity > 1e-3) lightOrder.push(l); |
| +добавлено | lightOrder.sort((a, b) => b.intensity * b.range - a.intensity * a.range); |
| +добавлено | const nl = Math.min(lightOrder.length, maxLights); |
| +добавлено | let shadowed = 0; |
| +добавлено | for (let i = 0; i < nl; i++) { |
| +добавлено | const l = lightOrder[i], o = (0 * WORLD_W + i * 4) * 4; |
| +добавлено | const sh = l.shadow && shadowed < maxShadowed ? (shadowed++, 1) : 0; |
| +добавлено | d.set([l.pos.x, l.pos.y, l.pos.z, l.range, l.color.r * l.intensity, l.color.g * l.intensity, l.color.b * l.intensity, l.type, |
| +добавлено | l.end.x, l.end.y, l.end.z, sh, l.cookie[0], l.cookie[1], l.cookie[2], l.cookie[3]], o); |
| +добавлено | } |
| +добавлено | let nf = 0; |
| +добавлено | for (const fo of forces.items) { |
| +добавлено | if (!fo.active) continue; |
| +добавлено | const o = (1 * WORLD_W + nf * 4) * 4; |
| +добавлено | d.set([fo.pos.x, fo.pos.y, fo.pos.z, fo.type, fo.p[0], fo.p[1], fo.p[2], fo.p[3], fo.dir.x, fo.dir.y, fo.dir.z, fo.w], o); |
| +добавлено | nf++; |
| +добавлено | } |
| +добавлено | let ni = 0; |
| +добавлено | for (const it of impactList) { |
| +добавлено | it.age += dt; |
| +добавлено | if (it.age >= it.life) continue; |
| +добавлено | const o = (2 * WORLD_W + ni * 4) * 4; |
| +добавлено | const fade = 1 - it.age / it.life; |
| +добавлено | d.set([it.pos.x, it.pos.y, it.pos.z, it.radius, it.type, it.age, it.amount * fade * fade, 0, it.color.r, it.color.g, it.color.b, 0], o); |
| +добавлено | ni++; |
| +добавлено | } |
| +добавлено | const no = occluderList.length; |
| +добавлено | for (let i = 0; i < no; i++) { |
| +добавлено | const c = occluderList[i], o = (3 * WORLD_W + i * 2) * 4; |
| +добавлено | d.set([c.a.x, c.a.y, c.a.z, c.radius, c.b.x, c.b.y, c.b.z, c.kind], o); |
| +добавлено | } |
| +добавлено | U.uWorldCounts.value.set(nl, nf, ni, no); |
| +добавлено | worldTex.needsUpdate = true; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- JS mirror of arenaSDF (click targeting, projectile impacts, spawn placement) ----- |
| +добавлено | const _pa = new THREE.Vector3(), _ba = new THREE.Vector3(); |
| +добавлено | function sdCapsule(p, a, b, r) { |
| +добавлено | _pa.subVectors(p, a); _ba.subVectors(b, a); |
| +добавлено | const h = Math.min(1, Math.max(0, _pa.dot(_ba) / Math.max(_ba.dot(_ba), 1e-6))); |
| +добавлено | return _pa.addScaledVector(_ba, -h).length() - r; |
| +добавлено | } |
| +добавлено | export function arenaStatic(p) { |
| +добавлено | // ── АДАПТЕР (наша правка): вместо пола арены и бортика — рельеф острова. ── |
| +добавлено | return p.y - groundHeight(p.x, p.z); |
| +добавлено | } |
| +добавлено | export function arenaSDF(p) { |
| +добавлено | let d = arenaStatic(p); |
| +добавлено | for (const c of occluderList) d = Math.min(d, sdCapsule(p, c.a, c.b, c.radius)); |
| +добавлено | return d; |
| +добавлено | } |
| +добавлено | const _rp = new THREE.Vector3(); |
| +добавлено | // sphere trace; returns distance along dir or -1 |
| +добавлено | export function arenaRaycast(origin, dir, maxDist = 200) { |
| +добавлено | let t = 0; |
| +добавлено | for (let i = 0; i < 256 && t < maxDist; i++) { |
| +добавлено | const d = arenaSDF(_rp.copy(origin).addScaledVector(dir, t)); |
| +добавлено | if (d < 0.002) return t; |
| +добавлено | t += Math.max(d, 0.01); |
| +добавлено | } |
| +добавлено | return -1; |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { FullscreenQuad, rawPass } from '../engine/fullscreen.js'; |
| +добавлено | import { U } from './common.js'; |
| +добавлено | |
| +добавлено | // Procedural noise, baked on the GPU at load (no assets): |
| +добавлено | // noise3D N^3 RGBA8, tileable on all axes. r = Perlin-Worley fbm (Schneider 2015: Perlin fbm |
| +добавлено | // dilated by Worley fbm), g/b/a = inverted Worley F1 fbm at base frequencies 2/4/8. |
| +добавлено | // curl3D 64^3 RGBA8, tileable. rgb = curl * 0.5 + 0.5 of a 3-field gradient-noise vector |
| +добавлено | // potential (Bridson et al. 2007), divergence-free by construction. |
| +добавлено | // blackbody 256x1 RGBA16F, CPU: Planck x Wyman-Sloan-Shirley 2013 CIE fit -> linear sRGB, Y = 1. |
| +добавлено | // Sampling contract: NOISE_GLSL in common.js. |
| +добавлено | |
| +добавлено | const HASH = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | in vec2 vUv; |
| +добавлено | uniform float uZ; |
| +добавлено | // always 1. Loop bounds read it so ANGLE's D3D compiler (FXC) can't unroll the 27-cell |
| +добавлено | // searches into megabytes of HLSL: unrolled, these two bakes spend ~300 ms compiling. |
| +добавлено | uniform int uOne; |
| +добавлено | out vec4 outColor; |
| +добавлено | // pcg3d (Jarzynski & Olano 2020): cheap and free of lattice artefacts |
| +добавлено | uvec3 pcg3d(uvec3 v) { |
| +добавлено | v = v * 1664525u + 1013904223u; |
| +добавлено | v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y; |
| +добавлено | v ^= v >> 16u; |
| +добавлено | v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y; |
| +добавлено | return v; |
| +добавлено | } |
| +добавлено | // lattice point -> hash, wrapped at period P so every octave tiles the unit cube. c is always |
| +добавлено | // within one period of [0, P), so a select replaces two integer modulos per component. |
| +добавлено | uvec3 hashL(ivec3 c, int P, uint seed) { |
| +добавлено | c += P * (ivec3(lessThan(c, ivec3(0))) - ivec3(greaterThanEqual(c, ivec3(P)))); |
| +добавлено | return pcg3d(uvec3(c) + seed * uvec3(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u)); |
| +добавлено | } |
| +добавлено | vec3 hash3(ivec3 c, int P, uint seed) { return vec3(hashL(c, P, seed) >> 8u) * (1.0 / 16777216.0); } |
| +добавлено | // inverted Worley F1: 1 at feature points, ~0 on cell borders. x in cells (= p * P) |
| +добавлено | float worley(vec3 x, int P, uint seed) { |
| +добавлено | ivec3 i = ivec3(floor(x)); |
| +добавлено | vec3 f = fract(x); |
| +добавлено | float d = 8.0; |
| +добавлено | for (int z = -uOne; z <= uOne; z++) for (int y = -uOne; y <= uOne; y++) for (int k = -uOne; k <= uOne; k++) { |
| +добавлено | ivec3 o = ivec3(k, y, z); |
| +добавлено | vec3 r = vec3(o) + hash3(i + o, P, seed) - f; |
| +добавлено | d = min(d, dot(r, r)); |
| +добавлено | } |
| +добавлено | return 1.0 - clamp(sqrt(d), 0.0, 1.0); |
| +добавлено | } |
| +добавлено | // quintic gradient noise, ~[-1, 1]; corners in a loop (one inlined hash instead of eight) |
| +добавлено | float gnoise(vec3 x, int P, uint seed) { |
| +добавлено | ivec3 i = ivec3(floor(x)); |
| +добавлено | vec3 f = fract(x), u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0); |
| +добавлено | float v = 0.0; |
| +добавлено | for (int c = 0; c < 8 * uOne; c++) { |
| +добавлено | ivec3 o = ivec3(c & 1, (c >> 1) & 1, c >> 2); |
| +добавлено | vec3 s = mix(1.0 - u, u, vec3(o)); |
| +добавлено | v += s.x * s.y * s.z * dot(hash3(i + o, P, seed) * 2.0 - 1.0, f - vec3(o)); |
| +добавлено | } |
| +добавлено | return v; |
| +добавлено | } |
| +добавлено | // gradients (d/dx) of three independent gradient-noise fields at once, as mat3 columns. One |
| +добавлено | // hash per corner carries all three gradients (10 bits per component). |
| +добавлено | mat3 gnoiseGrad3(vec3 x, int P, uint seed) { |
| +добавлено | ivec3 i = ivec3(floor(x)); |
| +добавлено | vec3 f = fract(x), u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0), du = 30.0 * f * f * (f * (f - 2.0) + 1.0); |
| +добавлено | mat3 J = mat3(0.0); |
| +добавлено | for (int c = 0; c < 8 * uOne; c++) { |
| +добавлено | ivec3 o = ivec3(c & 1, (c >> 1) & 1, c >> 2); |
| +добавлено | vec3 fo = f - vec3(o), s = mix(1.0 - u, u, vec3(o)), ds = mix(-du, du, vec3(o)); |
| +добавлено | float w = s.x * s.y * s.z; |
| +добавлено | vec3 dw = vec3(ds.x * s.y * s.z, s.x * ds.y * s.z, s.x * s.y * ds.z); |
| +добавлено | uvec3 h = hashL(i + o, P, seed); |
| +добавлено | vec3 g0 = vec3((h >> 22u) & 1023u) / 511.5 - 1.0, g1 = vec3((h >> 12u) & 1023u) / 511.5 - 1.0, g2 = vec3((h >> 2u) & 1023u) / 511.5 - 1.0; |
| +добавлено | J[0] += w * g0 + dot(g0, fo) * dw; |
| +добавлено | J[1] += w * g1 + dot(g1, fo) * dw; |
| +добавлено | J[2] += w * g2 + dot(g2, fo) * dw; |
| +добавлено | } |
| +добавлено | return J; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // Ranges measured from a readback histogram of the raw fbm (dev/fields.js "noise stats"): |
| +добавлено | // stretch the 1st..99th percentile to 0..1 so volume thresholds have the whole byte range. |
| +добавлено | const NOISE_FRAG = HASH + /* glsl */` |
| +добавлено | float stretch(float x, float lo, float hi) { return clamp((x - lo) / (hi - lo), 0.0, 1.0); } |
| +добавлено | void main() { |
| +добавлено | vec3 p = vec3(vUv, uZ); |
| +добавлено | float pf = 0.0, amp = 1.0; |
| +добавлено | for (int o = 0; o < 5 * uOne; o++) { pf += gnoise(p * float(4 << o), 4 << o, 7u) * amp; amp *= 0.5; } |
| +добавлено | float perlin = clamp(pf * 0.5 + 0.5, 0.0, 1.0); |
| +добавлено | // Worley octaves at 2, 4, 8, 16, 32 cells; channel c is the fbm starting at octave c with |
| +добавлено | // weights 0.625 / 0.25 / 0.125 (Schneider 2015), so g/b/a share octaves like his detail noise |
| +добавлено | vec3 gba = vec3(0.0); |
| +добавлено | for (int o = 0; o < 5 * uOne; o++) { |
| +добавлено | vec3 k = float(o) - vec3(0.0, 1.0, 2.0); |
| +добавлено | vec3 wt = 0.625 * step(abs(k), vec3(0.5)) + 0.25 * step(abs(k - 1.0), vec3(0.5)) + 0.125 * step(abs(k - 2.0), vec3(0.5)); |
| +добавлено | gba += wt * worley(p * float(2 << o), 2 << o, uint(o + 1)); |
| +добавлено | } |
| +добавлено | // dilate Perlin by the low Worley fbm: remap(perlin, 0, 1, worley, 1) -> billowy, round cells |
| +добавлено | float pw = gba.y + perlin * (1.0 - gba.y); |
| +добавлено | outColor = vec4(stretch(pw, PW_LO, PW_HI), stretch(gba.x, W_LO, W_HI), stretch(gba.y, W_LO, W_HI), stretch(gba.z, W_LO, W_HI)); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // vector potential = three gradient-noise fbms; octave amplitudes fall faster than 1/f so the |
| +добавлено | // big swirls dominate and the fine octaves only roughen them |
| +добавлено | const CURL_FRAG = HASH + /* glsl */` |
| +добавлено | void main() { |
| +добавлено | vec3 p = vec3(vUv, uZ); |
| +добавлено | mat3 J = mat3(0.0); // column k = grad of potential k |
| +добавлено | float amp = 1.0; |
| +добавлено | for (int o = 0; o < 3 * uOne; o++) { |
| +добавлено | J += gnoiseGrad3(p * float(4 << o), 4 << o, 11u) * amp; // d/dp = d/dx * P; amplitude 1/P -> amp |
| +добавлено | amp *= 0.6; |
| +добавлено | } |
| +добавлено | vec3 curl = vec3(J[2].y - J[1].z, J[0].z - J[2].x, J[1].x - J[0].y) * CURL_SCALE; |
| +добавлено | outColor = vec4(curl * 0.5 + 0.5, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // calibration knobs, from dev/fields.js "noise stats" (1st / 99th percentiles of the raw sums; |
| +добавлено | // curl scale puts the mean |curl| at 0.5) |
| +добавлено | export const NOISE_TUNING = { PW_LO: 0.53, PW_HI: 0.90, W_LO: 0.21, W_HI: 0.75, CURL_SCALE: 0.37 }; |
| +добавлено | |
| +добавлено | const defines = (keys) => Object.fromEntries(keys.map((k) => [k, NOISE_TUNING[k].toFixed(4)])); |
| +добавлено | |
| +добавлено | // material + mesh for one 3D bake; compiled up front so both programs build in parallel |
| +добавлено | // (KHR_parallel_shader_compile) while the first one is already drawing |
| +добавлено | function bakePass(renderer, frag, keys) { |
| +добавлено | const mat = rawPass(frag, { uZ: { value: 0 }, uOne: { value: 1 } }, { defines: defines(keys) }); |
| +добавлено | const quad = new FullscreenQuad(mat); |
| +добавлено | renderer.compile(quad.mesh, bakeCam); |
| +добавлено | return quad; |
| +добавлено | } |
| +добавлено | const bakeCam = new THREE.Camera(); |
| +добавлено | |
| +добавлено | function bake3D(renderer, quad, size) { |
| +добавлено | const rt = new THREE.WebGL3DRenderTarget(size, size, size, { |
| +добавлено | type: THREE.UnsignedByteType, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | wrapS: THREE.RepeatWrapping, wrapT: THREE.RepeatWrapping, depthBuffer: false, generateMipmaps: false, |
| +добавлено | }); |
| +добавлено | rt.texture.wrapR = THREE.RepeatWrapping; |
| +добавлено | const mat = quad.material; |
| +добавлено | const gl = renderer.getContext(), px = new Uint8Array(4); |
| +добавлено | const t0 = performance.now(); |
| +добавлено | for (let z = 0; z < size; z++) { |
| +добавлено | mat.uniforms.uZ.value = (z + 0.5) / size; |
| +добавлено | renderer.setRenderTarget(rt, z); |
| +добавлено | renderer.render(quad.mesh, bakeCam); |
| +добавлено | if (z === 0) { gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); rt.compileMs = performance.now() - t0; } |
| +добавлено | } |
| +добавлено | gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); |
| +добавлено | rt.drawMs = performance.now() - t0 - rt.compileMs; |
| +добавлено | mat.dispose(); |
| +добавлено | return rt; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- blackbody (CPU) ------------------------------------------------------------------- |
| +добавлено | const LAMBDA0 = 360, LAMBDA_STEP = 5, LAMBDA_N = 95; // 360..830 nm |
| +добавлено | const cmf = new Float64Array(LAMBDA_N * 3); |
| +добавлено | { |
| +добавлено | // Wyman, Sloan & Shirley 2013, multi-lobe piecewise-Gaussian fit to CIE 1931 2-degree |
| +добавлено | const g = (x, mu, s1, s2) => { const t = (x - mu) / (x < mu ? s1 : s2); return Math.exp(-0.5 * t * t); }; |
| +добавлено | for (let i = 0; i < LAMBDA_N; i++) { |
| +добавлено | const l = LAMBDA0 + i * LAMBDA_STEP; |
| +добавлено | cmf[i * 3] = 1.056 * g(l, 599.8, 37.9, 31.0) + 0.362 * g(l, 442.0, 16.0, 26.7) - 0.065 * g(l, 501.1, 20.4, 26.2); |
| +добавлено | cmf[i * 3 + 1] = 0.821 * g(l, 568.8, 46.9, 40.5) + 0.286 * g(l, 530.9, 16.3, 31.1); |
| +добавлено | cmf[i * 3 + 2] = 1.217 * g(l, 437.0, 11.8, 36.0) + 0.681 * g(l, 459.0, 26.0, 13.8); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | // Planck spectrum against the CMFs -> XYZ / Y -> linear sRGB (D65), negatives clipped, |
| +добавлено | // then rescaled so Rec.709 luminance is exactly 1 again |
| +добавлено | function planckRGB(kelvin, out, o) { |
| +добавлено | const c2 = 1.4387769e7; // hc / k in nm K |
| +добавлено | let X = 0, Y = 0, Z = 0; |
| +добавлено | for (let i = 0; i < LAMBDA_N; i++) { |
| +добавлено | const l = LAMBDA0 + i * LAMBDA_STEP; |
| +добавлено | const b = 1 / (l ** 5 * (Math.exp(c2 / (l * kelvin)) - 1)); |
| +добавлено | X += b * cmf[i * 3]; Y += b * cmf[i * 3 + 1]; Z += b * cmf[i * 3 + 2]; |
| +добавлено | } |
| +добавлено | X /= Y; Z /= Y; Y = 1; |
| +добавлено | const r = Math.max(0, 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z); |
| +добавлено | const g = Math.max(0, -0.969266 * X + 1.8760108 * Y + 0.041556 * Z); |
| +добавлено | const b = Math.max(0, 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z); |
| +добавлено | const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b; |
| +добавлено | out[o] = r / lum; out[o + 1] = g / lum; out[o + 2] = b / lum; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const BB_N = 256; |
| +добавлено | const bbLUT = new Float32Array(BB_N * 3); // CPU copy, texel centres at u = (i + 0.5) / 256 |
| +добавлено | const kelvinAt = (u) => 500 * Math.pow(40, u); |
| +добавлено | for (let i = 0; i < BB_N; i++) planckRGB(kelvinAt((i + 0.5) / BB_N), bbLUT, i * 3); |
| +добавлено | |
| +добавлено | // same mapping and linear filtering as blackbody() in NOISE_GLSL (minus fp16 rounding) |
| +добавлено | export function blackbodyRGB(kelvin, outColor = new THREE.Color()) { |
| +добавлено | const u = Math.min(1, Math.max(0, Math.log(kelvin / 500) / Math.log(40))); |
| +добавлено | const x = Math.min(BB_N - 1, Math.max(0, u * BB_N - 0.5)); |
| +добавлено | const i = Math.min(BB_N - 2, Math.floor(x)), t = x - i, a = i * 3, b = a + 3; |
| +добавлено | return outColor.setRGB(bbLUT[a] + (bbLUT[b] - bbLUT[a]) * t, bbLUT[a + 1] + (bbLUT[b + 1] - bbLUT[a + 1]) * t, |
| +добавлено | bbLUT[a + 2] + (bbLUT[b + 2] - bbLUT[a + 2]) * t, THREE.LinearSRGBColorSpace); |
| +добавлено | } |
| +добавлено | |
| +добавлено | function makeBlackbodyTexture() { |
| +добавлено | const data = new Uint16Array(BB_N * 4); |
| +добавлено | for (let i = 0; i < BB_N; i++) { |
| +добавлено | for (let c = 0; c < 3; c++) data[i * 4 + c] = THREE.DataUtils.toHalfFloat(bbLUT[i * 3 + c]); |
| +добавлено | data[i * 4 + 3] = THREE.DataUtils.toHalfFloat(1); |
| +добавлено | } |
| +добавлено | const tex = new THREE.DataTexture(data, BB_N, 1, THREE.RGBAFormat, THREE.HalfFloatType); |
| +добавлено | tex.minFilter = tex.magFilter = THREE.LinearFilter; |
| +добавлено | tex.needsUpdate = true; |
| +добавлено | return tex; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // throws on failure; returns a one-line summary |
| +добавлено | export function blackbodySelfCheck() { |
| +добавлено | const assert = (ok, msg) => { if (!ok) throw new Error('blackbody self-check: ' + msg); }; |
| +добавлено | const c = new THREE.Color(); |
| +добавлено | const w = blackbodyRGB(6500, c).toArray(); |
| +добавлено | assert(Math.max(...w) / Math.min(...w) < 1.15, `6500 K not near white (${w.map((x) => x.toFixed(3))})`); |
| +добавлено | const o = blackbodyRGB(1900, new THREE.Color()).toArray(); |
| +добавлено | assert(o[0] > o[1] && o[1] > o[2], `1900 K not orange (${o.map((x) => x.toFixed(3))})`); |
| +добавлено | let prev = -1; |
| +добавлено | for (let i = 0; i < BB_N; i++) { |
| +добавлено | const r = bbLUT[i * 3], g = bbLUT[i * 3 + 1], b = bbLUT[i * 3 + 2]; |
| +добавлено | assert(Math.abs(0.2126 * r + 0.7152 * g + 0.0722 * b - 1) < 1e-6, `luminance != 1 at texel ${i}`); |
| +добавлено | const hue = (b + 1e-6) / (r + 1e-6); // blue/red rises monotonically with temperature |
| +добавлено | assert(hue >= prev, `hue not monotone at texel ${i}`); |
| +добавлено | prev = hue; |
| +добавлено | } |
| +добавлено | return `blackbody ok: 6500K (${w.map((x) => x.toFixed(3))}), 1900K (${o.map((x) => x.toFixed(3))})`; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- bake ------------------------------------------------------------------------------- |
| +добавлено | export function bakeNoise(renderer, { noiseSize = 128 } = {}) { |
| +добавлено | const t0 = performance.now(); |
| +добавлено | const prevTarget = renderer.getRenderTarget(); |
| +добавлено | const noisePass = bakePass(renderer, NOISE_FRAG, ['PW_LO', 'PW_HI', 'W_LO', 'W_HI']); |
| +добавлено | const curlPass = bakePass(renderer, CURL_FRAG, ['CURL_SCALE']); |
| +добавлено | const noise = bake3D(renderer, noisePass, noiseSize); |
| +добавлено | const curl = bake3D(renderer, curlPass, 64); |
| +добавлено | const blackbody = makeBlackbodyTexture(); |
| +добавлено | renderer.setRenderTarget(prevTarget); |
| +добавлено | // bake3D fenced each stage with a 1-texel read, so this is wall time to finished textures |
| +добавлено | const ms = performance.now() - t0; |
| +добавлено | U.uNoise3D.value = noise.texture; |
| +добавлено | U.uCurl3D.value = curl.texture; |
| +добавлено | U.uBlackbody.value = blackbody; |
| +добавлено | console.info(`noise bake: ${noiseSize}^3 noise + 64^3 curl + blackbody in ${ms.toFixed(1)} ms (waiting on compile ${(noise.compileMs + curl.compileMs).toFixed(1)}, draw noise ${noise.drawMs.toFixed(1)} curl ${curl.drawMs.toFixed(1)})`); |
| +добавлено | return { noise3D: noise.texture, curl3D: curl.texture, blackbody, ms, targets: [noise, curl] }; |
| +добавлено | } |
| +добавлено | <!doctype html> |
| +добавлено | <html lang="ru"><head><meta charset="UTF-8"><style>html,body{margin:0;height:100%;overflow:hidden;background:#000}canvas{display:block;width:100vw;height:100vh}</style></head> |
| +добавлено | <body><canvas id="c"></canvas><script type="module" src="/src/uwcheck.ts"></script></body></html> |
| +добавлено | MIT License |
| +добавлено | |
| +добавлено | Copyright (c) 2026 Humpalumps |
| +добавлено | |
| +добавлено | Permission is hereby granted, free of charge, to any person obtaining a copy |
| +добавлено | of this software and associated documentation files (the "Software"), to deal |
| +добавлено | in the Software without restriction, including without limitation the rights |
| +добавлено | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| +добавлено | copies of the Software, and to permit persons to whom the Software is |
| +добавлено | furnished to do so, subject to the following conditions: |
| +добавлено | |
| +добавлено | The above copyright notice and this permission notice shall be included in all |
| +добавлено | copies or substantial portions of the Software. |
| +добавлено | |
| +добавлено | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| +добавлено | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| +добавлено | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| +добавлено | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| +добавлено | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| +добавлено | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| +добавлено | SOFTWARE. |
| +добавлено | # Third-party notices |
| +добавлено | |
| +добавлено | Ultra Water is MIT licensed (see [LICENSE](LICENSE)). A few small pieces of its code are adapted from the MIT-licensed projects below. Their copyright notices are kept here, as their licences require. The MIT licence text that applies to each of them is at the end of this file. |
| +добавлено | |
| +добавлено | Runtime dependencies (three.js, lil-gui) are installed from npm and carry their own licences in `node_modules`. |
| +добавлено | |
| +добавлено | ## three.js |
| +добавлено | |
| +добавлено | - Source: https://github.com/mrdoob/three.js |
| +добавлено | - Used in: `src/scene/sky.js` (cloud layer, adapted from `Sky.js`) and `src/engine/PostFX.js` (AgX tone mapping, same maths as three's `AgXToneMapping` chunk. That chunk is itself based on Filament's AgX, which follows Blender's). |
| +добавлено | - Copyright © 2010-2026 three.js authors |
| +добавлено | - MIT License |
| +добавлено | |
| +добавлено | ## Hash without Sine (Dave Hoskins) |
| +добавлено | |
| +добавлено | - Source: https://www.shadertoy.com/view/4djSRW |
| +добавлено | - Used in: `src/engine/PostFX.js` (`hash33`) and `src/scene/sky.js` (`gradient`) |
| +добавлено | - Copyright (c) 2014 David Hoskins |
| +добавлено | - MIT License |
| +добавлено | |
| +добавлено | ## UnrealEngineSkyAtmosphere (Sébastien Hillaire) |
| +добавлено | |
| +добавлено | - Source: https://github.com/sebh/UnrealEngineSkyAtmosphere |
| +добавлено | - Used in: `src/scene/atmosphere.js`, which follows the structure of this reference implementation of Hillaire 2020, "A Scalable and Production Ready Sky and Atmosphere Rendering Technique". |
| +добавлено | - Copyright (c) 2020 Epic Games, Inc. |
| +добавлено | - MIT License |
| +добавлено | |
| +добавлено | ## MIT License |
| +добавлено | |
| +добавлено | Permission is hereby granted, free of charge, to any person obtaining a copy |
| +добавлено | of this software and associated documentation files (the "Software"), to deal |
| +добавлено | in the Software without restriction, including without limitation the rights |
| +добавлено | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| +добавлено | copies of the Software, and to permit persons to whom the Software is |
| +добавлено | furnished to do so, subject to the following conditions: |
| +добавлено | |
| +добавлено | The above copyright notice and this permission notice shall be included in all |
| +добавлено | copies or substantial portions of the Software. |
| +добавлено | |
| +добавлено | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| +добавлено | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| +добавлено | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| +добавлено | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| +добавлено | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| +добавлено | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| +добавлено | SOFTWARE. |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | |
| +добавлено | // Mirror camera about the y=0 plane with an oblique near plane (Lengyel), rendering |
| +добавлено | // into a half-res target cleared to alpha 0 so the water falls back to the sky cube |
| +добавлено | // wherever nothing was drawn. Same math as three's Reflector, minus the mesh. |
| +добавлено | const normal = new THREE.Vector3(0, 1, 0); |
| +добавлено | const camPos = new THREE.Vector3(); |
| +добавлено | const lookAt = new THREE.Vector3(); |
| +добавлено | const target = new THREE.Vector3(); |
| +добавлено | const rot = new THREE.Matrix4(); |
| +добавлено | const plane = new THREE.Plane(); |
| +добавлено | const clip = new THREE.Vector4(); |
| +добавлено | const q = new THREE.Vector4(); |
| +добавлено | |
| +добавлено | export class PlanarReflection { |
| +добавлено | constructor(layer = 1) { |
| +добавлено | this.camera = new THREE.PerspectiveCamera(); |
| +добавлено | this.camera.layers.set(layer); |
| +добавлено | this.textureMatrix = new THREE.Matrix4(); |
| +добавлено | // mipmapped: the water blurs it by its roughness |
| +добавлено | this.target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter }); |
| +добавлено | this.scale = 0.5; |
| +добавлено | } |
| +добавлено | |
| +добавлено | setSize(w, h) { this.target.setSize(Math.max(1, Math.floor(w * this.scale)), Math.max(1, Math.floor(h * this.scale))); } |
| +добавлено | |
| +добавлено | render(renderer, scene, camera) { |
| +добавлено | const rc = this.camera; |
| +добавлено | camPos.setFromMatrixPosition(camera.matrixWorld); |
| +добавлено | rot.extractRotation(camera.matrixWorld); |
| +добавлено | lookAt.set(0, 0, -1).applyMatrix4(rot).add(camPos); |
| +добавлено | target.set(lookAt.x, -lookAt.y, lookAt.z); |
| +добавлено | rc.position.set(camPos.x, -camPos.y, camPos.z); |
| +добавлено | rc.up.set(0, 1, 0).applyMatrix4(rot).reflect(normal); |
| +добавлено | rc.lookAt(target); |
| +добавлено | rc.far = camera.far; |
| +добавлено | rc.updateMatrixWorld(); |
| +добавлено | rc.projectionMatrix.copy(camera.projectionMatrix); |
| +добавлено | |
| +добавлено | this.textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1) |
| +добавлено | .multiply(rc.projectionMatrix).multiply(rc.matrixWorldInverse); |
| +добавлено | |
| +добавлено | plane.setFromNormalAndCoplanarPoint(normal, target.set(0, 0, 0)).applyMatrix4(rc.matrixWorldInverse); |
| +добавлено | clip.set(plane.normal.x, plane.normal.y, plane.normal.z, plane.constant); |
| +добавлено | const p = rc.projectionMatrix.elements; |
| +добавлено | q.set((Math.sign(clip.x) + p[8]) / p[0], (Math.sign(clip.y) + p[9]) / p[5], -1, (1 + p[10]) / p[14]); |
| +добавлено | clip.multiplyScalar(2 / clip.dot(q)); |
| +добавлено | p[2] = clip.x; p[6] = clip.y; p[10] = clip.z + 1; p[14] = clip.w; |
| +добавлено | rc.projectionMatrixInverse.copy(rc.projectionMatrix).invert(); |
| +добавлено | |
| +добавлено | renderer.setRenderTarget(this.target); |
| +добавлено | renderer.setClearColor(0x000000, 0); |
| +добавлено | renderer.clear(true, true, false); |
| +добавлено | renderer.render(scene, rc); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | |
| +добавлено | const LEVELS = 6; |
| +добавлено | const METER = 32; // auto-exposure metering target is METER x METER |
| +добавлено | |
| +добавлено | const VERT = /* glsl */` |
| +добавлено | in vec3 position; |
| +добавлено | out vec2 vUv; |
| +добавлено | void main() { |
| +добавлено | vUv = position.xy * 0.5 + 0.5; |
| +добавлено | gl_Position = vec4(position.xy, 0.0, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const HEAD = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp sampler2D; |
| +добавлено | in vec2 vUv; |
| +добавлено | out vec4 fragColor; |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // 13-tap dual-filter downsample (CoD AW). With PREFILTER: clamp + soft knee per tap, Karis-weighted groups. |
| +добавлено | const DOWN = /* glsl */` |
| +добавлено | uniform sampler2D tSrc; |
| +добавлено | uniform vec2 uTexel; // source texel size |
| +добавлено | #ifdef PREFILTER |
| +добавлено | uniform vec4 uCurve; // threshold-knee, 2*knee, 0.25/knee, threshold |
| +добавлено | uniform float uClamp; |
| +добавлено | #endif |
| +добавлено | |
| +добавлено | float luma(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); } |
| +добавлено | |
| +добавлено | vec3 tap(vec2 o) { |
| +добавлено | vec3 c = texture(tSrc, vUv + o * uTexel).rgb; |
| +добавлено | #ifdef PREFILTER |
| +добавлено | c = max(c, 0.0); // negatives (and NaN on most GPUs) -> 0 |
| +добавлено | float l = max(luma(c), 1e-4); |
| +добавлено | c *= min(1.0, uClamp / l); |
| +добавлено | l = min(l, uClamp); |
| +добавлено | float q = clamp(l - uCurve.x, 0.0, uCurve.y); |
| +добавлено | c *= max(uCurve.z * q * q, l - uCurve.w) / l; |
| +добавлено | #endif |
| +добавлено | return c; |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vec3 a = tap(vec2(-2.0, 2.0)), b = tap(vec2(0.0, 2.0)), c = tap(vec2(2.0, 2.0)); |
| +добавлено | vec3 d = tap(vec2(-2.0, 0.0)), e = tap(vec2(0.0, 0.0)), f = tap(vec2(2.0, 0.0)); |
| +добавлено | vec3 g = tap(vec2(-2.0, -2.0)), h = tap(vec2(0.0, -2.0)), i = tap(vec2(2.0, -2.0)); |
| +добавлено | vec3 j = tap(vec2(-1.0, 1.0)), k = tap(vec2(1.0, 1.0)), l = tap(vec2(-1.0, -1.0)), m = tap(vec2(1.0, -1.0)); |
| +добавлено | vec3 g0 = (a + b + d + e) * 0.25, g1 = (b + c + e + f) * 0.25; |
| +добавлено | vec3 g2 = (d + e + g + h) * 0.25, g3 = (e + f + h + i) * 0.25; |
| +добавлено | vec3 g4 = (j + k + l + m) * 0.25; |
| +добавлено | #ifdef PREFILTER |
| +добавлено | float w0 = 0.125 / (1.0 + luma(g0)), w1 = 0.125 / (1.0 + luma(g1)); |
| +добавлено | float w2 = 0.125 / (1.0 + luma(g2)), w3 = 0.125 / (1.0 + luma(g3)); |
| +добавлено | float w4 = 0.5 / (1.0 + luma(g4)); |
| +добавлено | vec3 r = (g0 * w0 + g1 * w1 + g2 * w2 + g3 * w3 + g4 * w4) / (w0 + w1 + w2 + w3 + w4); |
| +добавлено | #else |
| +добавлено | vec3 r = g4 * 0.5 + (g0 + g1 + g2 + g3) * 0.125; |
| +добавлено | #endif |
| +добавлено | fragColor = vec4(r, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // 9-tap tent upsample; blended additively onto the finer level. |
| +добавлено | const UP = /* glsl */` |
| +добавлено | uniform sampler2D tSrc; |
| +добавлено | uniform vec2 uTexel; // source (coarser) texel size |
| +добавлено | void main() { |
| +добавлено | vec4 d = uTexel.xyxy * vec4(1.0, 1.0, -1.0, 0.0); |
| +добавлено | vec3 s = texture(tSrc, vUv - d.xy).rgb + texture(tSrc, vUv - d.wy).rgb * 2.0 + texture(tSrc, vUv - d.zy).rgb |
| +добавлено | + texture(tSrc, vUv + d.zw).rgb * 2.0 + texture(tSrc, vUv).rgb * 4.0 + texture(tSrc, vUv + d.xw).rgb * 2.0 |
| +добавлено | + texture(tSrc, vUv + d.zy).rgb + texture(tSrc, vUv + d.wy).rgb * 2.0 + texture(tSrc, vUv + d.xy).rgb; |
| +добавлено | fragColor = vec4(s * (1.0 / 16.0), 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // Auto-exposure 1/2: HDR -> METERxMETER of log2(luminance). 4x4 bilinear taps per texel over its footprint, |
| +добавлено | // the grid jittered per frame (the temporal filter averages it out). Luminance is clamped to [1e-4, 64] |
| +добавлено | // before the log so the sun disc / glints can't pump exposure; the mean is taken in log space anyway. |
| +добавлено | const METER_FRAG = /* glsl */` |
| +добавлено | uniform sampler2D tSrc; |
| +добавлено | uniform vec2 uJitter; // [0,1)^2 |
| +добавлено | void main() { |
| +добавлено | float s = 0.0; |
| +добавлено | for (int j = 0; j < 4; j++) for (int i = 0; i < 4; i++) { |
| +добавлено | vec2 o = (vec2(float(i), float(j)) + uJitter) * 0.25 - 0.5; |
| +добавлено | vec3 c = max(texture(tSrc, vUv + o * ${(1 / METER).toFixed(8)}).rgb, 0.0); |
| +добавлено | s += log2(clamp(dot(c, vec3(0.2126, 0.7152, 0.0722)), 1e-4, 64.0)); |
| +добавлено | } |
| +добавлено | fragColor = vec4(s * (1.0 / 16.0), 0.0, 0.0, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // Auto-exposure 2/2: METERxMETER -> 1x1 mean (16x16 bilinear taps, each = 2x2 texels), then temporal |
| +добавлено | // adaptation in log2 space, ping-pong with the previous 1x1 state. r = adapted log2(avg luminance). |
| +добавлено | const ADAPT_FRAG = /* glsl */` |
| +добавлено | uniform sampler2D tSrc; // metering target, linear filtered |
| +добавлено | uniform sampler2D tPrev; // previous 1x1 state |
| +добавлено | uniform vec2 uK; // blend factor when scene brightens (x) / darkens (y); 1 = snap |
| +добавлено | uniform vec2 uRange; // allowed log2 luminance range (from min/max exposure) |
| +добавлено | void main() { |
| +добавлено | float sum = 0.0; |
| +добавлено | for (int j = 0; j < 16; j++) for (int i = 0; i < 16; i++) |
| +добавлено | sum += texture(tSrc, (vec2(float(i), float(j)) + 0.5) * (1.0 / 16.0)).r; |
| +добавлено | float t = clamp(sum * (1.0 / 256.0), uRange.x, uRange.y); |
| +добавлено | float prev = texelFetch(tPrev, ivec2(0), 0).r; |
| +добавлено | float k = t > prev ? uK.x : uK.y; |
| +добавлено | float s = k >= 1.0 ? t : prev + (t - prev) * k; |
| +добавлено | if (isnan(s)) s = t; |
| +добавлено | fragColor = vec4(s, 0.0, 0.0, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // Same math as three's AgXToneMapping chunk (Filament/Blender AgX, iolite contrast approx). |
| +добавлено | const COMP = /* glsl */` |
| +добавлено | uniform sampler2D tHdr; |
| +добавлено | uniform sampler2D tBloom; |
| +добавлено | uniform sampler2D tExp; // 1x1 adapted log2 average luminance |
| +добавлено | uniform float uExposure; // exposure compensation (auto) or absolute exposure |
| +добавлено | uniform float uAuto; // 1 = auto exposure |
| +добавлено | uniform vec3 uExpo; // keyValue, minExposure, maxExposure |
| +добавлено | uniform float uBloom; |
| +добавлено | uniform vec2 uLook; // AgX look: power (contrast), saturation |
| +добавлено | uniform float uFrame; // 0..255, dither seed |
| +добавлено | uniform float uDroplets; // 0..1 |
| +добавлено | uniform float uTime; // seconds, wraps at 4096 |
| +добавлено | uniform float uAspect; // width / height |
| +добавлено | uniform float uResY; // height in pixels |
| +добавлено | |
| +добавлено | const mat3 SRGB_TO_REC2020 = mat3( |
| +добавлено | vec3(0.6274, 0.0691, 0.0164), vec3(0.3293, 0.9195, 0.0880), vec3(0.0433, 0.0113, 0.8956)); |
| +добавлено | const mat3 REC2020_TO_SRGB = mat3( |
| +добавлено | vec3(1.6605, -0.1246, -0.0182), vec3(-0.5876, 1.1329, -0.1006), vec3(-0.0728, -0.0083, 1.1187)); |
| +добавлено | const mat3 AGX_INSET = mat3( |
| +добавлено | vec3(0.856627153315983, 0.137318972929847, 0.11189821299995), |
| +добавлено | vec3(0.0951212405381588, 0.761241990602591, 0.0767994186031903), |
| +добавлено | vec3(0.0482516061458583, 0.101439036467562, 0.811302368396859)); |
| +добавлено | const mat3 AGX_OUTSET = mat3( |
| +добавлено | vec3(1.1271005818144368, -0.1413297634984383, -0.14132976349843826), |
| +добавлено | vec3(-0.11060664309660323, 1.157823702216272, -0.11060664309660294), |
| +добавлено | vec3(-0.016493938717834573, -0.016493938717834257, 1.2519364065950405)); |
| +добавлено | const float AGX_MIN_EV = -12.47393; |
| +добавлено | const float AGX_MAX_EV = 4.026069; |
| +добавлено | |
| +добавлено | vec3 agxContrast(vec3 x) { |
| +добавлено | vec3 x2 = x * x, x4 = x2 * x2; |
| +добавлено | return 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; |
| +добавлено | } |
| +добавлено | |
| +добавлено | vec3 agx(vec3 c) { |
| +добавлено | c = AGX_INSET * (SRGB_TO_REC2020 * c); |
| +добавлено | c = clamp((log2(max(c, 1e-10)) - AGX_MIN_EV) / (AGX_MAX_EV - AGX_MIN_EV), 0.0, 1.0); |
| +добавлено | c = agxContrast(c); |
| +добавлено | // AgX "punchy"-style look in the encoded domain |
| +добавлено | c = pow(max(c, 0.0), vec3(uLook.x)); |
| +добавлено | float l = dot(c, vec3(0.2126, 0.7152, 0.0722)); |
| +добавлено | c = l + uLook.y * (c - l); |
| +добавлено | c = AGX_OUTSET * c; |
| +добавлено | return clamp(REC2020_TO_SRGB * pow(max(c, 0.0), vec3(2.2)), 0.0, 1.0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // Dave Hoskins hash without sine |
| +добавлено | vec3 hash33(vec3 p) { |
| +добавлено | p = fract(p * vec3(0.1031, 0.1030, 0.0973)); |
| +добавлено | p += dot(p, p.yxz + 33.33); |
| +добавлено | return fract((p.xxy + p.yxx) * p.zyx); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // ---- lens droplets (only evaluated when uDroplets > 0) ----------------------------------------- |
| +добавлено | // All lengths are in screen-height units (p = vUv * vec2(aspect, 1)). Each drop is a tiny lens: the |
| +добавлено | // image under it is sampled from the mirrored side of its centre, sample = centre - (K-1) * d, so it |
| +добавлено | // looks inverted and slightly magnified, with a faint dark rim. |
| +добавлено | const float DROP_K = 1.8; |
| +добавлено | |
| +добавлено | // d: pixel - drop centre, r: radius. Returns (uv offset, darkening). |
| +добавлено | vec3 lensDrop(vec2 d, float r) { |
| +добавлено | float dist = length(d); |
| +добавлено | float cov = clamp((r - dist) * uResY + 0.5, 0.0, 1.0); // 1px AA |
| +добавлено | if (cov <= 0.0) return vec3(0.0); |
| +добавлено | return vec3(-d * DROP_K * cov, 0.22 * smoothstep(0.6, 1.0, dist / r) * cov); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // One drop (at most) per grid cell, kept inside its cell so only the own cell is tested. |
| +добавлено | vec3 dropLayer(vec2 p, float scale, float density, float seed) { |
| +добавлено | vec2 q = p * scale + seed * 17.31; |
| +добавлено | vec2 id = floor(q); |
| +добавлено | vec3 h = hash33(vec3(id, seed)), g = hash33(vec3(id + 57.0, seed)); |
| +добавлено | if (h.x > density) return vec3(0.0); |
| +добавлено | float fade = clamp((uDroplets - g.x * 0.8) * 6.0, 0.0, 1.0); // drops dry up one by one (order = g.x) |
| +добавлено | float rf = mix(0.10, 0.24, h.y * h.y); // radius, cell units |
| +добавлено | vec2 c = rf + vec2(h.z, g.y) * (1.0 - 2.0 * rf); |
| +добавлено | return lensDrop((fract(q) - c) / scale, rf * fade / scale); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // A drop sliding down the lens, leaving a thin wet trail above it. speed in cycles/s. |
| +добавлено | // Head enters above the screen and leaves below with its trail fully off-screen, so the wrap never pops. |
| +добавлено | vec3 streak(vec2 p, float id, float speed, float amp) { |
| +добавлено | const float R = 0.016, L = 0.45, W = 0.0035; |
| +добавлено | float u = uTime * speed + id * 0.37; |
| +добавлено | float cyc = mod(floor(u), 128.0), f = fract(u); |
| +добавлено | f += 0.012 * sin(f * 47.0); // stick-slip |
| +добавлено | vec3 h = hash33(vec3(id, cyc, 5.1)); |
| +добавлено | float x0 = (0.08 + 0.84 * h.x) * uAspect; |
| +добавлено | float hy = mix(1.0 + R, -R - L, f); |
| +добавлено | float hx = x0 + 0.006 * sin(hy * 14.0 + h.y * 6.28); |
| +добавлено | vec3 o = lensDrop(p - vec2(hx, hy), R * amp); |
| +добавлено | float ty = p.y - hy; |
| +добавлено | if (ty > 0.0 && ty < L) { |
| +добавлено | float a = smoothstep(0.0, 0.03, ty) * (1.0 - ty / L) * amp; |
| +добавлено | float tx = (p.x - x0 - 0.006 * sin(p.y * 14.0 + h.y * 6.28)) / W; |
| +добавлено | float cov = clamp((1.0 - abs(tx)) * W * uResY + 0.5, 0.0, 1.0) * a; |
| +добавлено | o += vec3(-tx * W * DROP_K * cov, 0.0, 0.12 * smoothstep(0.5, 1.0, abs(tx)) * cov); |
| +добавлено | } |
| +добавлено | return o; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // Returns (uv offset, darkening). |
| +добавлено | vec3 droplets() { |
| +добавлено | vec2 p = vUv * vec2(uAspect, 1.0); |
| +добавлено | float sa = smoothstep(0.0, 0.4, uDroplets); |
| +добавлено | vec3 a = dropLayer(p, 6.0, 0.30, 0.0) + dropLayer(p, 10.0, 0.20, 1.0) + dropLayer(p, 17.0, 0.06, 2.0) |
| +добавлено | + streak(p, 0.0, 0.0625, sa) + streak(p, 1.0, 0.03125, sa); |
| +добавлено | return vec3(a.xy / vec2(uAspect, 1.0), min(a.z, 0.5)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | float ex = uExposure; |
| +добавлено | if (uAuto > 0.5) ex *= clamp(uExpo.x * exp2(-texelFetch(tExp, ivec2(0), 0).r), uExpo.y, uExpo.z); |
| +добавлено | |
| +добавлено | vec2 uv = vUv; |
| +добавлено | float dark = 0.0; |
| +добавлено | if (uDroplets > 0.001) { |
| +добавлено | vec3 dr = droplets(); |
| +добавлено | uv += dr.xy; |
| +добавлено | dark = dr.z; |
| +добавлено | } |
| +добавлено | |
| +добавлено | vec3 c = (texture(tHdr, uv).rgb + texture(tBloom, uv).rgb * uBloom) * (ex * (1.0 - dark)); |
| +добавлено | vec2 d = (vUv - 0.5) * 1.41421356; // |d|^2 = 1 at corners |
| +добавлено | c = agx(c) * (1.0 - 0.08 * dot(d, d)); |
| +добавлено | vec3 o = mix(pow(c, vec3(1.0 / 2.4)) * 1.055 - 0.055, c * 12.92, vec3(lessThanEqual(c, vec3(0.0031308)))); |
| +добавлено | |
| +добавлено | // TPDF dither, +-1/255, after sRGB encoding and before the 8-bit store |
| +добавлено | vec3 n = hash33(vec3(gl_FragCoord.xy, uFrame)) + hash33(vec3(gl_FragCoord.xy, uFrame + 17.0)); |
| +добавлено | fragColor = vec4(o + (n - 1.0) * (1.0 / 255.0), 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const mk = (frag, uniforms, defines = {}, extra = {}) => new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: VERT, fragmentShader: HEAD + frag, |
| +добавлено | uniforms, defines, depthTest: false, depthWrite: false, ...extra, |
| +добавлено | }); |
| +добавлено | |
| +добавлено | export class PostFX { |
| +добавлено | params = { |
| +добавлено | // Exposure. autoExposure: `exposure` is a multiplier on the metered exposure (exposure compensation, 1 = neutral). |
| +добавлено | // !autoExposure: `exposure` is the absolute exposure, as before. |
| +добавлено | exposure: 1.0, |
| +добавлено | autoExposure: true, |
| +добавлено | // Metered exposure = keyValue / (log-average scene luminance). 0.18 puts the scene's geometric mean at |
| +добавлено | // middle grey, which this AgX look maps to ~0.46 sRGB. Tune: ~0.12 moodier/darker, ~0.3 airy/bright. |
| +добавлено | keyValue: 0.18, |
| +добавлено | adaptUp: 2.5, // adaptation rate (1/s) when the scene gets brighter (exposure falls); ~0.4 s time constant |
| +добавлено | adaptDown: 1.0, // rate (1/s) when the scene gets darker (exposure rises); ~1 s time constant |
| +добавлено | minExposure: 0.05, // metered exposure clamp (linear multipliers, ~ -4.3 .. +4.3 EV around 1) |
| +добавлено | maxExposure: 20.0, |
| +добавлено | bloomStrength: 0.06, bloomThreshold: 1.0, bloomClamp: 64.0, contrast: 1.12, saturation: 1.3, |
| +добавлено | droplets: 0.0, // 0..1 lens water droplets; 0 costs nothing |
| +добавлено | }; |
| +добавлено | |
| +добавлено | constructor(renderer) { |
| +добавлено | this.renderer = renderer; |
| +добавлено | |
| +добавлено | this.geometry = new THREE.BufferGeometry(); |
| +добавлено | this.geometry.setAttribute('position', new THREE.Float32BufferAttribute([-1, -1, 0, 3, -1, 0, -1, 3, 0], 3)); |
| +добавлено | this.mesh = new THREE.Mesh(this.geometry); |
| +добавлено | this.mesh.frustumCulled = false; |
| +добавлено | this.camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1); |
| +добавлено | |
| +добавлено | const src = () => ({ tSrc: { value: null }, uTexel: { value: null } }); |
| +добавлено | this.matPre = mk(DOWN, { ...src(), uCurve: { value: new THREE.Vector4() }, uClamp: { value: 64 } }, { PREFILTER: 1 }); |
| +добавлено | this.matDown = mk(DOWN, src()); |
| +добавлено | this.matUp = mk(UP, src(), {}, { |
| +добавлено | blending: THREE.CustomBlending, blendEquation: THREE.AddEquation, |
| +добавлено | blendSrc: THREE.OneFactor, blendDst: THREE.OneFactor, |
| +добавлено | }); |
| +добавлено | this.matMeter = mk(METER_FRAG, { tSrc: { value: null }, uJitter: { value: new THREE.Vector2() } }); |
| +добавлено | this.matAdapt = mk(ADAPT_FRAG, { |
| +добавлено | tSrc: { value: null }, tPrev: { value: null }, uK: { value: new THREE.Vector2(1, 1) }, uRange: { value: new THREE.Vector2(-8, 4) }, |
| +добавлено | }); |
| +добавлено | this.matComp = mk(COMP, { |
| +добавлено | tHdr: { value: null }, tBloom: { value: null }, tExp: { value: null }, uExposure: { value: 1 }, uAuto: { value: 1 }, |
| +добавлено | uExpo: { value: new THREE.Vector3(0.18, 0.05, 20) }, uBloom: { value: 0 }, uLook: { value: new THREE.Vector2(1, 1) }, |
| +добавлено | uFrame: { value: 0 }, uDroplets: { value: 0 }, uTime: { value: 0 }, uAspect: { value: 1 }, uResY: { value: 1 }, |
| +добавлено | }); |
| +добавлено | |
| +добавлено | // levels[i] is 1/2^(i+1) of the input; texel[0] is the HDR input, texel[i+1] is levels[i] |
| +добавлено | this.levels = []; |
| +добавлено | this.texel = [new THREE.Vector2()]; |
| +добавлено | for (let i = 0; i < LEVELS; i++) { |
| +добавлено | this.levels.push(new THREE.WebGLRenderTarget(1, 1, { |
| +добавлено | type: THREE.HalfFloatType, format: THREE.RGBAFormat, |
| +добавлено | minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | wrapS: THREE.ClampToEdgeWrapping, wrapT: THREE.ClampToEdgeWrapping, |
| +добавлено | depthBuffer: false, stencilBuffer: false, generateMipmaps: false, |
| +добавлено | })); |
| +добавлено | this.texel.push(new THREE.Vector2()); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // auto exposure: METERxMETER log-luminance target, then a 1x1 float ping-pong holding the adapted value |
| +добавлено | this.meterRT = new THREE.WebGLRenderTarget(METER, METER, { |
| +добавлено | type: THREE.HalfFloatType, format: THREE.RGBAFormat, |
| +добавлено | minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | depthBuffer: false, stencilBuffer: false, generateMipmaps: false, |
| +добавлено | }); |
| +добавлено | const f32 = renderer.extensions.has('EXT_color_buffer_float'); |
| +добавлено | this.adapt = [0, 1].map(() => new THREE.WebGLRenderTarget(1, 1, { |
| +добавлено | type: f32 ? THREE.FloatType : THREE.HalfFloatType, format: THREE.RGBAFormat, |
| +добавлено | minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, |
| +добавлено | depthBuffer: false, stencilBuffer: false, generateMipmaps: false, |
| +добавлено | })); |
| +добавлено | this._cur = 0; // adapt[_cur] holds the latest state |
| +добавлено | this._snap = true; // next metered frame replaces the state instead of easing to it |
| +добавлено | this._frame = 0; |
| +добавлено | this._time = 0; |
| +добавлено | |
| +добавлено | const size = renderer.getDrawingBufferSize(new THREE.Vector2()); |
| +добавлено | this.setSize(size.x, size.y); |
| +добавлено | } |
| +добавлено | |
| +добавлено | setSize(width, height) { |
| +добавлено | let w = Math.max(1, Math.floor(width)), h = Math.max(1, Math.floor(height)); |
| +добавлено | this.matComp.uniforms.uAspect.value = w / h; |
| +добавлено | this.matComp.uniforms.uResY.value = h; |
| +добавлено | this._snap = true; // new framebuffer: re-meter instantly |
| +добавлено | this.texel[0].set(1 / w, 1 / h); |
| +добавлено | for (let i = 0; i < LEVELS; i++) { |
| +добавлено | w = Math.max(1, Math.floor(w / 2)); |
| +добавлено | h = Math.max(1, Math.floor(h / 2)); |
| +добавлено | this.levels[i].setSize(w, h); |
| +добавлено | this.texel[i + 1].set(1 / w, 1 / h); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | _pass(mat, target) { |
| +добавлено | this.mesh.material = mat; |
| +добавлено | this.renderer.setRenderTarget(target); |
| +добавлено | this.renderer.render(this.mesh, this.camera); |
| +добавлено | } |
| +добавлено | |
| +добавлено | _blit(mat, src, texel, target) { |
| +добавлено | mat.uniforms.tSrc.value = src; |
| +добавлено | mat.uniforms.uTexel.value = texel; |
| +добавлено | this._pass(mat, target); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // Two tiny passes: HDR -> 32x32 log2 luminance -> 1x1 mean + temporal adaptation (all on the GPU). |
| +добавлено | _meterExposure(hdr, dt) { |
| +добавлено | const p = this.params, m = this.matMeter.uniforms, a = this.matAdapt.uniforms, f = this._frame; |
| +добавлено | m.tSrc.value = hdr; |
| +добавлено | m.uJitter.value.set((f * 0.7548776662466927) % 1, (f * 0.5698402909980532) % 1); // R2 sequence |
| +добавлено | this._pass(this.matMeter, this.meterRT); |
| +добавлено | |
| +добавлено | // keep the state inside the range the exposure clamp can actually show, so it never "winds up" |
| +добавлено | const key = Math.max(p.keyValue, 1e-4), lo = Math.max(Math.min(p.minExposure, p.maxExposure), 1e-4), hi = Math.max(p.minExposure, p.maxExposure, 1e-4); |
| +добавлено | a.tSrc.value = this.meterRT.texture; |
| +добавлено | a.tPrev.value = this.adapt[this._cur].texture; |
| +добавлено | a.uK.value.set(this._snap ? 1 : 1 - Math.exp(-dt * p.adaptUp), this._snap ? 1 : 1 - Math.exp(-dt * p.adaptDown)); |
| +добавлено | a.uRange.value.set(Math.log2(key / hi), Math.log2(key / lo)); |
| +добавлено | this._cur ^= 1; |
| +добавлено | this._pass(this.matAdapt, this.adapt[this._cur]); |
| +добавлено | this._snap = false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | render(hdrTexture, dt = 1 / 60) { |
| +добавлено | const r = this.renderer, p = this.params, L = this.levels, T = this.texel; |
| +добавлено | dt = dt > 0 ? Math.min(dt, 1) : 0; // also catches NaN |
| +добавлено | this._frame = (this._frame + 1) & 255; |
| +добавлено | this._time = (this._time + dt) % 4096; |
| +добавлено | |
| +добавлено | const prevTarget = r.getRenderTarget(), prevClear = r.autoClear, prevReset = r.info.autoReset; |
| +добавлено | r.autoClear = false; |
| +добавлено | r.info.autoReset = false; // keep scene stats; our passes would otherwise wipe them |
| +добавлено | |
| +добавлено | if (p.autoExposure) this._meterExposure(hdrTexture, dt); |
| +добавлено | else this._snap = true; // state goes stale while off: snap when it comes back |
| +добавлено | |
| +добавлено | const th = p.bloomThreshold, knee = Math.max(th * 0.5, 1e-4); |
| +добавлено | const pre = this.matPre.uniforms; |
| +добавлено | pre.uCurve.value.set(th - knee, 2 * knee, 0.25 / knee, th); |
| +добавлено | pre.uClamp.value = p.bloomClamp; |
| +добавлено | |
| +добавлено | if (p.bloomStrength > 0) { // off, the composite scales the stale chain by 0 |
| +добавлено | this._blit(this.matPre, hdrTexture, T[0], L[0]); |
| +добавлено | for (let i = 1; i < LEVELS; i++) this._blit(this.matDown, L[i - 1].texture, T[i], L[i]); |
| +добавлено | for (let i = LEVELS - 2; i >= 0; i--) this._blit(this.matUp, L[i + 1].texture, T[i + 2], L[i]); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const u = this.matComp.uniforms; |
| +добавлено | u.tHdr.value = hdrTexture; |
| +добавлено | u.tBloom.value = L[0].texture; |
| +добавлено | u.tExp.value = this.adapt[this._cur].texture; |
| +добавлено | u.uExposure.value = p.exposure; |
| +добавлено | u.uAuto.value = p.autoExposure ? 1 : 0; |
| +добавлено | u.uExpo.value.set(p.keyValue, Math.min(p.minExposure, p.maxExposure), Math.max(p.minExposure, p.maxExposure)); |
| +добавлено | u.uLook.value.set(p.contrast, p.saturation); |
| +добавлено | u.uBloom.value = p.bloomStrength; |
| +добавлено | u.uFrame.value = this._frame; |
| +добавлено | u.uDroplets.value = Math.min(Math.max(p.droplets, 0), 1); |
| +добавлено | u.uTime.value = this._time; |
| +добавлено | this._pass(this.matComp, null); |
| +добавлено | |
| +добавлено | r.setRenderTarget(prevTarget); |
| +добавлено | r.autoClear = prevClear; |
| +добавлено | r.info.autoReset = prevReset; |
| +добавлено | } |
| +добавлено | |
| +добавлено | dispose() { |
| +добавлено | for (const rt of this.levels) rt.dispose(); |
| +добавлено | this.meterRT.dispose(); |
| +добавлено | for (const rt of this.adapt) rt.dispose(); |
| +добавлено | for (const m of [this.matPre, this.matDown, this.matUp, this.matMeter, this.matAdapt, this.matComp]) m.dispose(); |
| +добавлено | this.geometry.dispose(); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | |
| +добавлено | // One big triangle covering the viewport; shared by every fullscreen pass. |
| +добавлено | const geometry = new THREE.BufferGeometry(); |
| +добавлено | geometry.setAttribute('position', new THREE.Float32BufferAttribute([-1, -1, 0, 3, -1, 0, -1, 3, 0], 3)); |
| +добавлено | const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1); |
| +добавлено | |
| +добавлено | export const FULLSCREEN_VERT = /* glsl */` |
| +добавлено | in vec3 position; |
| +добавлено | out vec2 vUv; |
| +добавлено | void main() { |
| +добавлено | vUv = position.xy * 0.5 + 0.5; |
| +добавлено | gl_Position = vec4(position.xy, 0.0, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export function rawPass(fragmentShader, uniforms = {}, extra = {}) { |
| +добавлено | return new THREE.RawShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, |
| +добавлено | vertexShader: FULLSCREEN_VERT, |
| +добавлено | fragmentShader, |
| +добавлено | uniforms, |
| +добавлено | depthTest: false, |
| +добавлено | depthWrite: false, |
| +добавлено | ...extra, |
| +добавлено | }); |
| +добавлено | } |
| +добавлено | |
| +добавлено | export class FullscreenQuad { |
| +добавлено | constructor(material) { |
| +добавлено | this.mesh = new THREE.Mesh(geometry, material); |
| +добавлено | this.mesh.frustumCulled = false; |
| +добавлено | } |
| +добавлено | get material() { return this.mesh.material; } |
| +добавлено | set material(m) { this.mesh.material = m; } |
| +добавлено | render(renderer, target) { |
| +добавлено | renderer.setRenderTarget(target); |
| +добавлено | renderer.render(this.mesh, camera); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | // GPU timings via EXT_disjoint_timer_query_webgl2. Queries can't nest, so each |
| +добавлено | // labelled section is begun/ended back-to-back; results arrive a few frames late. |
| +добавлено | export class GpuTimer { |
| +добавлено | constructor(gl) { |
| +добавлено | this.gl = gl; |
| +добавлено | this.ext = gl.getExtension('EXT_disjoint_timer_query_webgl2'); |
| +добавлено | this.pending = []; |
| +добавлено | this.current = null; |
| +добавлено | this.frame = null; |
| +добавлено | this.ms = {}; // smoothed ms per label |
| +добавлено | this.total = 0; // smoothed sum of all labels |
| +добавлено | } |
| +добавлено | |
| +добавлено | get available() { return !!this.ext; } |
| +добавлено | |
| +добавлено | beginFrame() { if (this.ext) this.frame = []; } |
| +добавлено | |
| +добавлено | begin(label) { |
| +добавлено | if (!this.ext || !this.frame) return; |
| +добавлено | this.end(); |
| +добавлено | const q = this.gl.createQuery(); |
| +добавлено | this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT, q); |
| +добавлено | this.current = { label, q }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | end() { |
| +добавлено | if (!this.current) return; |
| +добавлено | this.gl.endQuery(this.ext.TIME_ELAPSED_EXT); |
| +добавлено | this.frame.push(this.current); |
| +добавлено | this.current = null; |
| +добавлено | } |
| +добавлено | |
| +добавлено | endFrame() { |
| +добавлено | if (!this.ext || !this.frame) return; |
| +добавлено | this.end(); |
| +добавлено | this.pending.push(this.frame); |
| +добавлено | this.frame = null; |
| +добавлено | if (this.keep) return; // benchmark: keep everything for drain() |
| +добавлено | const gl = this.gl; |
| +добавлено | const disjoint = gl.getParameter(this.ext.GPU_DISJOINT_EXT); |
| +добавлено | while (this.pending.length) { |
| +добавлено | const f = this.pending[0]; |
| +добавлено | if (!gl.getQueryParameter(f[f.length - 1].q, gl.QUERY_RESULT_AVAILABLE)) break; |
| +добавлено | this.pending.shift(); |
| +добавлено | let sum = 0; |
| +добавлено | for (const { label, q } of f) { |
| +добавлено | const ms = gl.getQueryParameter(q, gl.QUERY_RESULT) / 1e6; |
| +добавлено | gl.deleteQuery(q); |
| +добавлено | if (disjoint) continue; |
| +добавлено | this.ms[label] = this.ms[label] === undefined ? ms : this.ms[label] * 0.95 + ms * 0.05; |
| +добавлено | sum += ms; |
| +добавлено | } |
| +добавлено | if (!disjoint) this.total = this.total ? this.total * 0.95 + sum * 0.05 : sum; |
| +добавлено | } |
| +добавлено | // ponytail: drop backlog if the GPU never reports (tab hidden etc.) |
| +добавлено | if (this.pending.length > 8) this.pending.splice(0, this.pending.length - 8).flat().forEach(({ q }) => gl.deleteQuery(q)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // read every pending query (call after a GPU fence) -> mean ms per label per frame |
| +добавлено | drain() { |
| +добавлено | const gl = this.gl, sums = {}; |
| +добавлено | const frames = this.pending.length; |
| +добавлено | for (const f of this.pending) for (const { label, q } of f) { |
| +добавлено | if (gl.getQueryParameter(q, gl.QUERY_RESULT_AVAILABLE)) sums[label] = (sums[label] || 0) + gl.getQueryParameter(q, gl.QUERY_RESULT) / 1e6; |
| +добавлено | gl.deleteQuery(q); |
| +добавлено | } |
| +добавлено | this.pending = []; |
| +добавлено | for (const k in sums) sums[k] /= frames; |
| +добавлено | return sums; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { FullscreenQuad, rawPass } from '../engine/fullscreen.js'; |
| +добавлено | |
| +добавлено | // Physically based atmosphere after Hillaire 2020, "A Scalable and Production Ready Sky and |
| +добавлено | // Atmosphere Rendering Technique" (sebh/UnrealEngineSkyAtmosphere): transmittance LUT, |
| +добавлено | // multiple-scattering LUT and a sky-view LUT for an observer at sea level. Everything is |
| +добавлено | // rebuilt in update() (well under a millisecond); nothing runs per frame. |
| +добавлено | // Distances in km. Radiance is relative to the sun illuminance uSunIllum (see sky.js). |
| +добавлено | |
| +добавлено | const RB = 6360, RT = 6460, OBS_H = 0.01; // ground, top of atmosphere, observer altitude (km) |
| +добавлено | const TRANS_W = 256, TRANS_H = 64, MS_RES = 32, SKY_W = 192, SKY_H = 108; |
| +добавлено | |
| +добавлено | // Earth defaults from sebh / Bruneton 2017 (per km at sea level). turbidity scales the aerosol |
| +добавлено | // density as turbidity^2: 1 = sebh/Bruneton (very clean, aerosol optical depth 0.005), |
| +добавлено | // 2 = clear maritime (default, ~0.02), 5 = ~0.13, 10 = heavy haze (~0.5). |
| +добавлено | // rayleigh scales the molecular density. |
| +добавлено | export function atmosphereCoefficients(p) { |
| +добавлено | const m = p.turbidity * p.turbidity; |
| +добавлено | return { |
| +добавлено | rayleigh: [5.802e-3, 13.558e-3, 33.1e-3].map((v) => v * p.rayleigh), |
| +добавлено | mieScattering: 3.996e-3 * m, |
| +добавлено | mieExtinction: 4.44e-3 * m, |
| +добавлено | ozone: [0.65e-3, 1.881e-3, 0.085e-3], |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- CPU mirror of the transmittance LUT integral (for the sun colour) ------------------ |
| +добавлено | function altitudeAt(h, mu, t) { |
| +добавлено | const q = h * (2 * RB + h) + t * (2 * (RB + h) * mu + t); |
| +добавлено | return q / (Math.sqrt(RB * RB + q) + RB); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // transmittance from altitude h (km) along zenith cosine mu to space, same quadrature as the LUT |
| +добавлено | export function transmittance(c, h, mu, out = [0, 0, 0]) { |
| +добавлено | const r = RB + h; |
| +добавлено | const d = Math.max(-r * mu + Math.sqrt(Math.max(r * r * (mu * mu - 1) + RT * RT, 0)), 0); |
| +добавлено | const od = [0, 0, 0]; |
| +добавлено | for (let i = 0; i < 40; i++) { |
| +добавлено | const a = Math.max(altitudeAt(h, mu, d * ((i + 0.5) / 40) ** 2), 0); |
| +добавлено | const w = (2 * i + 1) * d / 1600; |
| +добавлено | const dR = Math.exp(-a / 8) * w, dM = Math.exp(-a / 1.2) * w, dO = Math.max(0, 1 - Math.abs(a - 25) / 15) * w; |
| +добавлено | for (let k = 0; k < 3; k++) od[k] += c.rayleigh[k] * dR + c.mieExtinction * dM + c.ozone[k] * dO; |
| +добавлено | } |
| +добавлено | for (let k = 0; k < 3; k++) out[k] = Math.exp(-od[k]); |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | export const OBSERVER_ALTITUDE = OBS_H; |
| +добавлено | |
| +добавлено | // --- GLSL --------------------------------------------------------------------------------- |
| +добавлено | // Shared by the LUT passes and the cube bake: uniforms, medium, LUT parameterisations. |
| +добавлено | export const ATMOSPHERE_GLSL = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp sampler2D; |
| +добавлено | #define PI 3.14159265359 |
| +добавлено | const float RB = ${RB.toFixed(1)}, RT = ${RT.toFixed(1)}, OBS_H = ${OBS_H}; |
| +добавлено | const float H_TOP = ${Math.sqrt(RT * RT - RB * RB).toFixed(4)}; // sqrt(RT^2 - RB^2) |
| +добавлено | const float MIE_G = 0.8; |
| +добавлено | const float GROUND_ALBEDO = 0.1; |
| +добавлено | const vec2 SKY_RES = vec2(${SKY_W}.0, ${SKY_H}.0); |
| +добавлено | uniform vec3 uRayleigh; // Rayleigh scattering at sea level (1/km) |
| +добавлено | uniform vec2 uMie; // aerosol scattering, extinction at sea level (1/km) |
| +добавлено | uniform vec3 uOzone; // ozone absorption at the layer peak (1/km) |
| +добавлено | uniform float uSunIllum; // sun illuminance outside the atmosphere |
| +добавлено | uniform sampler2D uTransLut; |
| +добавлено | uniform sampler2D uMsLut; |
| +добавлено | uniform sampler2D uSkyView; |
| +добавлено | |
| +добавлено | vec2 toSub(vec2 u, vec2 n) { return u * (n - 1.0) / n + 0.5 / n; } |
| +добавлено | vec2 fromSub(vec2 u, vec2 n) { return (u - 0.5 / n) * n / (n - 1.0); } |
| +добавлено | |
| +добавлено | // altitude after travelling t along a ray from altitude h with zenith cosine mu; r = radius |
| +добавлено | float altAt(float h, float mu, float t, out float r) { |
| +добавлено | float q = h * (2.0 * RB + h) + t * (2.0 * (RB + h) * mu + t); // r^2 - RB^2 without cancellation |
| +добавлено | r = sqrt(RB * RB + q); |
| +добавлено | return q / (r + RB); |
| +добавлено | } |
| +добавлено | |
| +добавлено | struct Medium { vec3 ray; float mie; vec3 scat; vec3 ext; }; |
| +добавлено | Medium medium(float h) { |
| +добавлено | h = max(h, 0.0); |
| +добавлено | float dM = exp(-h / 1.2); |
| +добавлено | Medium m; |
| +добавлено | m.ray = uRayleigh * exp(-h / 8.0); |
| +добавлено | m.mie = uMie.x * dM; |
| +добавлено | m.scat = m.ray + m.mie; |
| +добавлено | m.ext = m.ray + uMie.y * dM + uOzone * max(0.0, 1.0 - abs(h - 25.0) / 15.0); // ozone: tent 10..40 km |
| +добавлено | return m; |
| +добавлено | } |
| +добавлено | |
| +добавлено | float distTop(float r, float mu) { return max(-r * mu + sqrt(max(r * r * (mu * mu - 1.0) + RT * RT, 0.0)), 0.0); } |
| +добавлено | |
| +добавлено | // Bruneton's transmittance parameterisation (covers the rays that miss the ground) |
| +добавлено | vec2 transUv(float h, float mu) { |
| +добавлено | float r = RB + h, rho = sqrt(max(h, 0.0) * (2.0 * RB + h)); |
| +добавлено | float dMin = RT - r, dMax = rho + H_TOP; |
| +добавлено | return vec2((distTop(r, mu) - dMin) / (dMax - dMin), rho / H_TOP); |
| +добавлено | } |
| +добавлено | vec3 transmittance(float h, float mu) { return textureLod(uTransLut, transUv(h, mu), 0.0).rgb; } |
| +добавлено | |
| +добавлено | // 0 where the planet hides the sun from altitude h (radius r) |
| +добавлено | float sunVisible(float h, float r, float muS) { return step(-sqrt(max(h, 0.0) * (2.0 * RB + h)) / r, muS); } |
| +добавлено | |
| +добавлено | // sky-view LUT, upper hemisphere only (the observer is at sea level): u = sqrt of the azimuth |
| +добавлено | // cosine to the sun, v = sqrt(elevation / 90deg) so texels crowd the horizon |
| +добавлено | vec3 skyView(vec3 d, vec3 sunDir) { |
| +добавлено | float v = sqrt(asin(clamp(d.y, 0.0, 1.0)) / (0.5 * PI)); |
| +добавлено | float cosPhi = dot(d.xz, sunDir.xz) * inversesqrt(max(dot(d.xz, d.xz) * dot(sunDir.xz, sunDir.xz), 1e-12)); |
| +добавлено | float u = sqrt(clamp(0.5 - 0.5 * cosPhi, 0.0, 1.0)); |
| +добавлено | return textureLod(uSkyView, toSub(vec2(u, v), SKY_RES), 0.0).rgb; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const PASS_IO = /* glsl */` |
| +добавлено | in vec2 vUv; |
| +добавлено | out vec4 fragColor; |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // in-scattered radiance (unit sun illuminance) along a ray from altitude h, zenith cosine mu, |
| +добавлено | // sun zenith cosine muS, view.sun = nu; n samples spaced quadratically, each segment integrated |
| +добавлено | // analytically (Frostbite 2015 energy-conserving step). MS_PASS: isotropic phase, no multiple-scattering |
| +добавлено | // input, plus the lit ground; fms returns the transfer integral of eq. 7. |
| +добавлено | const INTEGRATE = /* glsl */` |
| +добавлено | float rayleighPhase(float c) { return 0.0596831 * (1.0 + c * c); } |
| +добавлено | float miePhase(float c) { |
| +добавлено | float k = 1.0 + MIE_G * MIE_G - 2.0 * MIE_G * c; |
| +добавлено | return (1.0 - MIE_G * MIE_G) / (4.0 * PI * k * sqrt(k)); |
| +добавлено | } |
| +добавлено | vec3 multiScatter(float h, float muS) { |
| +добавлено | vec2 uv = clamp(vec2(muS * 0.5 + 0.5, h / (RT - RB)), 0.0, 1.0); |
| +добавлено | return textureLod(uMsLut, toSub(uv, vec2(${MS_RES}.0)), 0.0).rgb; |
| +добавлено | } |
| +добавлено | vec3 integrate(float h, float mu, float muS, float nu, int n, out vec3 fms) { |
| +добавлено | float r0 = RB + h; |
| +добавлено | float gd = r0 * r0 * (mu * mu - 1.0) + RB * RB; |
| +добавлено | bool ground = mu < 0.0 && gd >= 0.0; |
| +добавлено | float tMax = ground ? max(-r0 * mu - sqrt(gd), 0.0) : distTop(r0, mu); |
| +добавлено | #ifdef MS_PASS |
| +добавлено | float pR = 1.0 / (4.0 * PI), pM = pR; |
| +добавлено | #else |
| +добавлено | float pR = rayleighPhase(nu), pM = miePhase(nu); |
| +добавлено | #endif |
| +добавлено | vec3 L = vec3(0.0), T = vec3(1.0); |
| +добавлено | fms = vec3(0.0); |
| +добавлено | float k = tMax / float(n * n); |
| +добавлено | for (int i = 0; i < n; i++) { |
| +добавлено | float fi = float(i); |
| +добавлено | float t = k * (fi + 0.5) * (fi + 0.5), dt = k * (2.0 * fi + 1.0); |
| +добавлено | float r; |
| +добавлено | float ht = altAt(h, mu, t, r); |
| +добавлено | float muSt = clamp((r0 * muS + t * nu) / r, -1.0, 1.0); |
| +добавлено | Medium m = medium(ht); |
| +добавлено | vec3 S = transmittance(ht, muSt) * sunVisible(ht, r, muSt) * (m.ray * pR + m.mie * pM); |
| +добавлено | #ifndef MS_PASS |
| +добавлено | S += m.scat * multiScatter(ht, muSt); |
| +добавлено | #endif |
| +добавлено | vec3 Ts = exp(-m.ext * dt); |
| +добавлено | vec3 seg = (1.0 - Ts) / max(m.ext, vec3(1e-7)); |
| +добавлено | L += T * S * seg; |
| +добавлено | fms += T * m.scat * seg; |
| +добавлено | T *= Ts; |
| +добавлено | } |
| +добавлено | #ifdef MS_PASS |
| +добавлено | if (ground) { |
| +добавлено | float muSg = clamp((r0 * muS + tMax * nu) / RB, -1.0, 1.0); |
| +добавлено | L += T * transmittance(0.0, muSg) * max(muSg, 0.0) * (GROUND_ALBEDO / PI); |
| +добавлено | } |
| +добавлено | #endif |
| +добавлено | return L; |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const TRANS_FRAG = ATMOSPHERE_GLSL + PASS_IO + /* glsl */` |
| +добавлено | void main() { |
| +добавлено | float rho = H_TOP * vUv.y; |
| +добавлено | float r = sqrt(rho * rho + RB * RB), h = rho * rho / (r + RB); |
| +добавлено | float dMin = RT - r, d = mix(dMin, rho + H_TOP, vUv.x); |
| +добавлено | float mu = d <= 0.0 ? 1.0 : clamp((H_TOP * H_TOP - rho * rho - d * d) / (2.0 * r * d), -1.0, 1.0); |
| +добавлено | vec3 od = vec3(0.0); |
| +добавлено | for (int i = 0; i < 40; i++) { |
| +добавлено | float fi = float(i), rr; |
| +добавлено | od += medium(altAt(h, mu, d * (fi + 0.5) * (fi + 0.5) / 1600.0, rr)).ext * (2.0 * fi + 1.0); |
| +добавлено | } |
| +добавлено | fragColor = vec4(exp(-od * (d / 1600.0)), 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // Psi_ms (Hillaire eq. 10) for unit illuminance: 2nd-order radiance and transfer factor averaged |
| +добавлено | // over 64 directions, summed as the geometric series L2 / (1 - f_ms) |
| +добавлено | const MS_FRAG = '#define MS_PASS\n' + ATMOSPHERE_GLSL + PASS_IO + INTEGRATE + /* glsl */` |
| +добавлено | void main() { |
| +добавлено | vec2 uv = fromSub(vUv, vec2(${MS_RES}.0)); |
| +добавлено | float muS = uv.x * 2.0 - 1.0, h = max(uv.y * (RT - RB), OBS_H); |
| +добавлено | float sinS = sqrt(max(1.0 - muS * muS, 0.0)); |
| +добавлено | vec3 L = vec3(0.0), F = vec3(0.0), fms; |
| +добавлено | for (int j = 0; j < 8; j++) { |
| +добавлено | float mu = 1.0 - 2.0 * (float(j) + 0.5) / 8.0, sinV = sqrt(1.0 - mu * mu); |
| +добавлено | for (int i = 0; i < 8; i++) { |
| +добавлено | float nu = cos(2.0 * PI * (float(i) + 0.5) / 8.0) * sinV * sinS + mu * muS; |
| +добавлено | L += integrate(h, mu, muS, nu, 20, fms); |
| +добавлено | F += fms; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | fragColor = vec4((L / 64.0) / (1.0 - F / 64.0), 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const SKY_FRAG = ATMOSPHERE_GLSL + PASS_IO + INTEGRATE + /* glsl */` |
| +добавлено | uniform float uSunMu; |
| +добавлено | void main() { |
| +добавлено | vec2 uv = fromSub(vUv, SKY_RES); |
| +добавлено | float cosPhi = 1.0 - 2.0 * uv.x * uv.x, elev = 0.5 * PI * uv.y * uv.y; |
| +добавлено | float mu = sin(elev), cosE = cos(elev); |
| +добавлено | vec3 v = vec3(cosE * cosPhi, mu, cosE * sqrt(max(1.0 - cosPhi * cosPhi, 0.0))); |
| +добавлено | vec3 s = vec3(sqrt(max(1.0 - uSunMu * uSunMu, 0.0)), uSunMu, 0.0); |
| +добавлено | vec3 fms; |
| +добавлено | fragColor = vec4(integrate(OBS_H, mu, uSunMu, dot(v, s), 32, fms) * uSunIllum, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const lutTarget = (w, h) => new THREE.WebGLRenderTarget(w, h, { |
| +добавлено | type: THREE.HalfFloatType, depthBuffer: false, generateMipmaps: false, |
| +добавлено | minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | }); |
| +добавлено | |
| +добавлено | export class Atmosphere { |
| +добавлено | constructor() { |
| +добавлено | this.transRT = lutTarget(TRANS_W, TRANS_H); |
| +добавлено | this.msRT = lutTarget(MS_RES, MS_RES); |
| +добавлено | this.skyRT = lutTarget(SKY_W, SKY_H); |
| +добавлено | // shared by reference with every pass that includes ATMOSPHERE_GLSL |
| +добавлено | this.uniforms = { |
| +добавлено | uRayleigh: { value: new THREE.Vector3() }, |
| +добавлено | uMie: { value: new THREE.Vector2() }, |
| +добавлено | uOzone: { value: new THREE.Vector3() }, |
| +добавлено | uSunIllum: { value: 1 }, |
| +добавлено | uTransLut: { value: this.transRT.texture }, |
| +добавлено | uMsLut: { value: this.msRT.texture }, |
| +добавлено | uSkyView: { value: this.skyRT.texture }, |
| +добавлено | }; |
| +добавлено | // each pass only gets the LUTs it reads, never the one it renders into |
| +добавлено | const { uTransLut, uMsLut, uSkyView, ...medium } = this.uniforms; |
| +добавлено | this.transPass = new FullscreenQuad(rawPass(TRANS_FRAG, medium)); |
| +добавлено | this.msPass = new FullscreenQuad(rawPass(MS_FRAG, { ...medium, uTransLut })); |
| +добавлено | this.skyPass = new FullscreenQuad(rawPass(SKY_FRAG, { ...medium, uTransLut, uMsLut, uSunMu: { value: 0 } })); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // c: atmosphereCoefficients(); sunMu: sun zenith cosine; sunIllum: illuminance at the top |
| +добавлено | update(renderer, c, sunMu, sunIllum) { |
| +добавлено | const u = this.uniforms; |
| +добавлено | u.uRayleigh.value.fromArray(c.rayleigh); |
| +добавлено | u.uMie.value.set(c.mieScattering, c.mieExtinction); |
| +добавлено | u.uOzone.value.fromArray(c.ozone); |
| +добавлено | u.uSunIllum.value = sunIllum; |
| +добавлено | this.skyPass.material.uniforms.uSunMu.value = sunMu; |
| +добавлено | this.transPass.render(renderer, this.transRT); |
| +добавлено | this.msPass.render(renderer, this.msRT); |
| +добавлено | this.skyPass.render(renderer, this.skyRT); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js'; |
| +добавлено | |
| +добавлено | // Procedural ocean floaters: one vertex-coloured mesh per kind, origin ~ centre of mass, +y up. |
| +добавлено | // Physics lives elsewhere; each builder only returns geometry + buoyancy metadata. |
| +добавлено | export const FLOATER_KINDS = ['crate', 'barrel', 'buoy', 'boat']; |
| +добавлено | |
| +добавлено | const col = (hex, k = 1) => new THREE.Color(hex).multiplyScalar(k); |
| +добавлено | |
| +добавлено | function rng(seed) { // mulberry32 |
| +добавлено | return () => { |
| +добавлено | seed = (seed + 0x6d2b79f5) | 0; |
| +добавлено | let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); |
| +добавлено | t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; |
| +добавлено | return ((t ^ (t >>> 14)) >>> 0) / 4294967296; |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function colorAttr(n, colorAt) { |
| +добавлено | const a = new Float32Array(n * 3); |
| +добавлено | for (let i = 0; i < n; i++) { |
| +добавлено | const c = colorAt(i); |
| +добавлено | a[i * 3] = c.r; a[i * 3 + 1] = c.g; a[i * 3 + 2] = c.b; |
| +добавлено | } |
| +добавлено | return new THREE.BufferAttribute(a, 3); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const paint = (geo, c) => geo.setAttribute('color', colorAttr(geo.attributes.position.count, () => c)); |
| +добавлено | const box = (w, h, d, x, y, z, c) => paint(new THREE.BoxGeometry(w, h, d).translate(x, y, z), c); |
| +добавлено | |
| +добавлено | // volume of a revolved profile of (r, y) points (frustum sum) |
| +добавлено | function latheVolume(pts) { |
| +добавлено | let v = 0; |
| +добавлено | for (let i = 1; i < pts.length; i++) { |
| +добавлено | const a = pts[i - 1], b = pts[i]; |
| +добавлено | v += Math.PI * Math.abs(b.y - a.y) * (a.x * a.x + a.x * b.x + b.x * b.x) / 3; |
| +добавлено | } |
| +добавлено | return v; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // signed volume + centroid x of a closed, non-indexed triangle soup |
| +добавлено | function solid(geo) { |
| +добавлено | const p = geo.attributes.position, a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3(); |
| +добавлено | let vol = 0, cx = 0; |
| +добавлено | for (let i = 0; i < p.count; i += 3) { |
| +добавлено | a.fromBufferAttribute(p, i); b.fromBufferAttribute(p, i + 1); c.fromBufferAttribute(p, i + 2); |
| +добавлено | const sx = a.x + b.x + c.x, dv = a.dot(b.cross(c)) / 6; |
| +добавлено | vol += dv; cx += dv * sx / 4; |
| +добавлено | } |
| +добавлено | return { vol, cx: cx / vol }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function crate() { |
| +добавлено | const rnd = rng(11), S = 0.9, h = S / 2, T = 0.09, o = h - T / 2; |
| +добавлено | const inner = S - 2 * T, N = 5, pw = inner / N; |
| +добавлено | // dark core shows through the plank seams |
| +добавлено | const parts = [box(0.84, 0.84, 0.84, 0, 0, 0, col(0x2e2117))]; |
| +добавлено | for (let a = 0; a < 3; a++) for (const p of [-1, 1]) for (const q of [-1, 1]) { // 12 frame beams |
| +добавлено | const d = [T, T, T], c = [0, 0, 0]; |
| +добавлено | d[a] = S; c[(a + 1) % 3] = p * o; c[(a + 2) % 3] = q * o; |
| +добавлено | parts.push(box(...d, ...c, col(0x6e4d2f, 0.9 + 0.2 * rnd()))); |
| +добавлено | } |
| +добавлено | for (let n = 0; n < 3; n++) for (const s of [-1, 1]) { // 6 faces x 5 planks |
| +добавлено | const run = (n + 1) % 3, stack = (n + 2) % 3; |
| +добавлено | for (let i = 0; i < N; i++) { |
| +добавлено | const d = [0, 0, 0], c = [0, 0, 0]; |
| +добавлено | d[n] = 0.04; d[run] = inner + 0.06; d[stack] = pw - 0.008; |
| +добавлено | c[n] = s * (h - 0.04); c[stack] = (i + 0.5 - N / 2) * pw; |
| +добавлено | parts.push(box(...d, ...c, col(0xa87b4b, 0.85 + 0.3 * rnd()))); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const q = S / 4, samples = []; |
| +добавлено | for (const x of [-q, q]) for (const y of [-q, q]) for (const z of [-q, q]) samples.push(new THREE.Vector3(x, y, z)); |
| +добавлено | return { geo: mergeGeometries(parts), rough: 0.85, metal: 0, volume: S ** 3, density: 550, samples, cellHeight: S / 2 }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function barrel() { |
| +добавлено | const L = 0.95, Rm = 0.32, Re = 0.27, hoop = 0.012, SEG = 24; |
| +добавлено | const bands = [[-0.44, -0.375], [-0.22, -0.17], [-0.035, 0.035], [0.17, 0.22], [0.375, 0.44]]; |
| +добавлено | const inHoop = (y) => bands.some(([a, b]) => y > a && y < b); |
| +добавлено | // profile (r, y): parabolic bulge, hoops raised; paired points at band edges keep the steps crisp |
| +добавлено | const ys = []; |
| +добавлено | for (let i = 0; i <= 40; i++) ys.push(-L / 2 + L * i / 40); |
| +добавлено | for (const [a, b] of bands) ys.push(a - 0.0015, a + 0.0015, b - 0.0015, b + 0.0015); |
| +добавлено | ys.sort((a, b) => a - b); |
| +добавлено | const pts = ys.map((y) => new THREE.Vector2(Re + (Rm - Re) * (1 - (2 * y / L) ** 2) + (inHoop(y) ? hoop : 0), y)); |
| +добавлено | |
| +добавлено | const body = new THREE.LatheGeometry(pts, SEG); // vertex = radial * pts.length + profile |
| +добавлено | const rnd = rng(5), stave = Array.from({ length: SEG }, () => 0.85 + 0.3 * rnd()); |
| +добавлено | const paintRed = col(0x8d3b2d), steel = col(0x2a2d32), pos = body.attributes.position; |
| +добавлено | body.setAttribute('color', colorAttr(pos.count, (i) => |
| +добавлено | inHoop(pos.getY(i)) ? steel : paintRed.clone().multiplyScalar(stave[Math.floor(i / pts.length) % SEG]))); |
| +добавлено | body.rotateZ(Math.PI / 2); // axis -> local X |
| +добавлено | |
| +добавлено | const head = [col(0x9c7248), col(0x6f4e2f)]; // oak: lighter centre, darker rim |
| +добавлено | const caps = [-1, 1].map((s) => { |
| +добавлено | const g = new THREE.CircleGeometry(Re, SEG).rotateY(s * Math.PI / 2).translate(s * L / 2, 0, 0); |
| +добавлено | return g.setAttribute('color', colorAttr(g.attributes.position.count, (i) => head[i ? 1 : 0])); |
| +добавлено | }); |
| +добавлено | |
| +добавлено | // 4 along the axis x 2 half-discs (centroid of a half disc is 4r/3pi ~ 0.14 off-axis) |
| +добавлено | const samples = []; |
| +добавлено | for (const x of [-3 * L / 8, -L / 8, L / 8, 3 * L / 8]) for (const y of [-0.14, 0.14]) samples.push(new THREE.Vector3(x, y, 0)); |
| +добавлено | return { geo: mergeGeometries([body, ...caps]), rough: 0.7, metal: 0.1, volume: latheVolume(pts), density: 420, samples, cellHeight: Rm }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function buoy() { |
| +добавлено | const R = 0.5, rb = 0.1, off = 0.06, band = 0.11; // float radius, ballast stub radius, origin below float centre, half band height |
| +добавлено | const y0 = Math.sqrt(R * R - rb * rb), th0 = Math.asin(y0 / R); |
| +добавлено | const ys = []; |
| +добавлено | for (let i = 0; i <= 40; i++) ys.push(R * Math.sin(-th0 + 2 * th0 * i / 40)); |
| +добавлено | for (const e of [-band, band]) ys.push(e - 0.003, e + 0.003); |
| +добавлено | ys.sort((a, b) => a - b); |
| +добавлено | const pts = [ |
| +добавлено | new THREE.Vector2(0, -0.8), new THREE.Vector2(rb, -0.8), // lead ballast stub |
| +добавлено | ...ys.map((y) => new THREE.Vector2(Math.sqrt(R * R - y * y), y)), |
| +добавлено | new THREE.Vector2(rb, 0.56), new THREE.Vector2(0, 0.56), // mast collar |
| +добавлено | ]; |
| +добавлено | const red = col(0xc42a1e), white = col(0xe8e4d8), dark = col(0x2a2d32); |
| +добавлено | const float = new THREE.LatheGeometry(pts, 28); |
| +добавлено | const pos = float.attributes.position; |
| +добавлено | float.setAttribute('color', colorAttr(pos.count, (i) => { |
| +добавлено | const y = pos.getY(i); |
| +добавлено | return y < -y0 + 1e-4 || y > y0 - 1e-4 ? dark : Math.abs(y) <= band ? white : red; |
| +добавлено | })); |
| +добавлено | |
| +добавлено | const parts = [ |
| +добавлено | float, |
| +добавлено | paint(new THREE.CylinderGeometry(0.022, 0.028, 0.45, 8).translate(0, 0.775, 0), col(0x7b8087)), // mast |
| +добавлено | paint(new THREE.CylinderGeometry(0.1, 0.1, 0.016, 12).translate(0, 1.0, 0), dark), // cage floor |
| +добавлено | paint(new THREE.ConeGeometry(0.1, 0.15, 12).translate(0, 1.225, 0), red), // topmark |
| +добавлено | ]; |
| +добавлено | for (let i = 0; i < 4; i++) { // cage struts |
| +добавлено | const a = Math.PI / 4 + i * Math.PI / 2; |
| +добавлено | parts.push(paint(new THREE.CylinderGeometry(0.008, 0.008, 0.15, 4).translate(0.085 * Math.cos(a), 1.083, 0.085 * Math.sin(a)), dark)); |
| +добавлено | } |
| +добавлено | parts.forEach((g) => g.translate(0, off, 0)); |
| +добавлено | |
| +добавлено | const k = 0.19, samples = []; // octant centroids of the float sphere (3R/8) |
| +добавлено | for (const x of [-k, k]) for (const y of [-k, k]) for (const z of [-k, k]) samples.push(new THREE.Vector3(x, off + y, z)); |
| +добавлено | return { geo: mergeGeometries(parts), rough: 0.45, metal: 0.05, volume: latheVolume(pts), density: 300, samples, cellHeight: R }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function boat() { |
| +добавлено | const L = 3.6, HW = 0.65, SX = 24, SY = 5, SZ = 8; |
| +добавлено | // deformed segmented box: box coords (u, v, w) in [-0.5, 0.5] -> hull point (x along length, +x bow) |
| +добавлено | const hull = (u, v, w, o) => { |
| +добавлено | const t = u + 0.5, zn = Math.abs(2 * w), vv = v + 0.5; |
| +добавлено | // plan: squarish transom at 0.62 beam, full beam at t=0.4, pointed bow |
| +добавлено | const f = t < 0.4 ? 0.62 + 0.38 * Math.sin(t / 0.4 * Math.PI / 2) : Math.max(0.02, 1 - ((t - 0.4) / 0.6) ** 1.8); |
| +добавлено | const sb = Math.max(0, (t - 0.3) / 0.7), ss = Math.max(0, (0.3 - t) / 0.3); |
| +добавлено | const top = 0.4 + 0.22 * sb * sb + 0.05 * ss * ss; // sheer rises toward bow |
| +добавлено | const keel = -0.2 + 0.2 * Math.max(0, (t - 0.5) / 0.5) ** 1.6 + 0.05 * (1 - t) ** 2; // rocker |
| +добавлено | const bot = keel + 0.2 * zn ** 1.5; // rounded V |
| +добавлено | return o.set(u * L, bot + (top - bot) * vv, 2 * w * HW * f * (0.8 + 0.2 * vv)); // flared topsides |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const g = new THREE.BoxGeometry(1, 1, 1, SX, SY, SZ); |
| +добавлено | const pos = g.attributes.position, idx = g.index, orig = pos.array.slice(), p = new THREE.Vector3(); |
| +добавлено | for (let i = 0; i < pos.count; i++) { |
| +добавлено | hull(orig[i * 3], orig[i * 3 + 1], orig[i * 3 + 2], p); |
| +добавлено | pos.setXYZ(i, p.x, p.y, p.z); |
| +добавлено | } |
| +добавлено | g.computeVertexNormals(); |
| +добавлено | |
| +добавлено | // flat colour per triangle: rows of the box give the paint scheme, deck columns give planks |
| +добавлено | const rnd = rng(3); |
| +добавлено | const under = col(0x1c3e44), stripe = col(0x2a8f8c), white = col(0xe9e6dc), trim = col(0x4a3020); |
| +добавлено | const rows = [under, under, stripe, white, trim]; |
| +добавлено | const planks = Array.from({ length: SZ }, (_, k) => (k === 0 || k === SZ - 1 ? trim : col(0xb08655, 0.9 + 0.2 * rnd()))); |
| +добавлено | const tri = []; |
| +добавлено | for (const { start, count, materialIndex: face } of g.groups) { // px nx py ny pz nz |
| +добавлено | for (let i = start; i < start + count; i += 3) { |
| +добавлено | let v = 0, w = 0; |
| +добавлено | for (let k = 0; k < 3; k++) { const j = idx.getX(i + k); v += orig[j * 3 + 1]; w += orig[j * 3 + 2]; } |
| +добавлено | v = v / 3 + 0.5; w = w / 3 + 0.5; |
| +добавлено | tri[i / 3] = face === 3 ? under : face === 2 ? planks[Math.floor(w * SZ)] : rows[Math.floor(v * SY)]; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const hullGeo = g.toNonIndexed(); |
| +добавлено | hullGeo.setAttribute('color', colorAttr(hullGeo.attributes.position.count, (i) => tri[Math.floor(i / 3)])); |
| +добавлено | const { vol, cx } = solid(hullGeo); |
| +добавлено | |
| +добавлено | const parts = [hullGeo]; |
| +добавлено | for (const u of [-0.1, 0.12]) { // two thwarts resting on the deck |
| +добавлено | hull(u, 0.5, 0.5, p); |
| +добавлено | parts.push(box(0.26, 0.045, p.z * 2 * 0.76, p.x, p.y + 0.0125, 0, col(0xb58a58)).toNonIndexed()); |
| +добавлено | } |
| +добавлено | |
| +добавлено | const samples = []; |
| +добавлено | for (let i = 0; i < 4; i++) for (const v of [-0.25, 0.25]) for (const w of [-0.25, 0.25]) samples.push(hull((i + 0.5) / 4 - 0.5, v, w, new THREE.Vector3())); |
| +добавлено | const geo = mergeGeometries(parts).translate(-cx, 0, 0); // COM (along length) at origin |
| +добавлено | samples.forEach((s) => s.x -= cx); |
| +добавлено | return { geo, rough: 0.55, metal: 0, volume: vol, density: 280, samples, cellHeight: 0.3 }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | const BUILDERS = { crate, barrel, buoy, boat }; |
| +добавлено | |
| +добавлено | export function makeFloater(kind, patchMaterial) { |
| +добавлено | const build = BUILDERS[kind]; |
| +добавлено | if (!build) throw new Error(`unknown floater kind: ${kind}`); |
| +добавлено | const { geo, rough, metal, ...meta } = build(); |
| +добавлено | const material = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: rough, metalness: metal }); |
| +добавлено | patchMaterial(material); |
| +добавлено | const mesh = new THREE.Mesh(geo, material); |
| +добавлено | mesh.name = `floater-${kind}`; |
| +добавлено | mesh.castShadow = false; // floaters have their own shadow map (floaterShadow.js) |
| +добавлено | mesh.receiveShadow = true; |
| +добавлено | mesh.layers.enable(1); // planar reflection layer |
| +добавлено | geo.computeBoundingBox(); |
| +добавлено | const size = geo.boundingBox.getSize(new THREE.Vector3()); |
| +добавлено | return { kind, object: mesh, size, volume: meta.volume, density: meta.density, samples: meta.samples, cellHeight: meta.cellHeight }; |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | |
| +добавлено | // Sharp sun shadows of the floating props only: a depth map from an ortho sun camera |
| +добавлено | // fitted around the bodies every frame, so the big static sun map (terrain + rocks) is |
| +добавлено | // never re-rendered for them. Water, terrain, props and the underwater shafts all take |
| +добавлено | // it through floatShadow(). |
| +добавлено | export const FLOAT_SHADOW_GLSL = /* glsl */` |
| +добавлено | uniform highp sampler2DShadow uFloatShadow; |
| +добавлено | uniform mat4 uFloatShadowMatrix; |
| +добавлено | uniform float uFloatShadowBias; // depth units; 0 = no casters this frame |
| +добавлено | float floatShadow(vec3 p) { |
| +добавлено | if (uFloatShadowBias <= 0.0) return 1.0; |
| +добавлено | vec3 sc = (uFloatShadowMatrix * vec4(p, 1.0)).xyz; |
| +добавлено | if (any(lessThan(sc, vec3(0.0))) || any(greaterThan(sc, vec3(1.0)))) return 1.0; |
| +добавлено | return texture(uFloatShadow, vec3(sc.xy, sc.z - uFloatShadowBias)); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const _c = new THREE.Vector3(); |
| +добавлено | |
| +добавлено | export class FloaterShadow { |
| +добавлено | constructor(size = 1024) { |
| +добавлено | const depth = new THREE.DepthTexture(size, size, THREE.FloatType); |
| +добавлено | depth.compareFunction = THREE.LessEqualCompare; // hardware 2x2 PCF |
| +добавлено | depth.minFilter = depth.magFilter = THREE.LinearFilter; |
| +добавлено | this.target = new THREE.WebGLRenderTarget(size, size, { format: THREE.RedFormat, depthTexture: depth, generateMipmaps: false }); |
| +добавлено | this.camera = new THREE.OrthographicCamera(); |
| +добавлено | this.material = new THREE.MeshBasicMaterial({ colorWrite: false, side: THREE.DoubleSide }); |
| +добавлено | this.uniforms = { |
| +добавлено | uFloatShadow: { value: depth }, |
| +добавлено | uFloatShadowMatrix: { value: new THREE.Matrix4() }, |
| +добавлено | uFloatShadowBias: { value: 0 }, |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // root: a Scene holding only the floaters; bodies: [{ pos, radius }]; sunDir: towards the sun |
| +добавлено | update(renderer, root, bodies, sunDir) { |
| +добавлено | const u = this.uniforms; |
| +добавлено | // the depth texture gets its compare mode when first rendered; until then any |
| +добавлено | // shadow sampler bound to it fails the draw |
| +добавлено | if (!this.ready) { this.clear(renderer); this.ready = true; } |
| +добавлено | if (!bodies.length || sunDir.y <= 0.01) { u.uFloatShadowBias.value = 0; return; } |
| +добавлено | _c.set(0, 0, 0); |
| +добавлено | for (const b of bodies) _c.add(b.pos); |
| +добавлено | _c.divideScalar(bodies.length); |
| +добавлено | let r = 1; |
| +добавлено | for (const b of bodies) r = Math.max(r, b.pos.distanceTo(_c) + b.radius); |
| +добавлено | // receivers lie along the light rays behind the casters, so the xy footprint is just |
| +добавлено | // the casters'; depth runs far past them for the seabed under a low sun |
| +добавлено | const cam = this.camera; |
| +добавлено | cam.left = cam.bottom = -r; |
| +добавлено | cam.right = cam.top = r; |
| +добавлено | cam.near = 1; |
| +добавлено | cam.far = r + 3000; |
| +добавлено | cam.position.copy(_c).addScaledVector(sunDir, r + 20); |
| +добавлено | cam.lookAt(_c); |
| +добавлено | cam.updateProjectionMatrix(); |
| +добавлено | cam.updateMatrixWorld(); |
| +добавлено | u.uFloatShadowMatrix.value.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1) |
| +добавлено | .multiply(cam.projectionMatrix).multiply(cam.matrixWorldInverse); |
| +добавлено | u.uFloatShadowBias.value = 0.03 / (cam.far - cam.near); |
| +добавлено | |
| +добавлено | const prev = renderer.getRenderTarget(); |
| +добавлено | root.overrideMaterial = this.material; |
| +добавлено | renderer.setRenderTarget(this.target); |
| +добавлено | renderer.clear(false, true, false); |
| +добавлено | renderer.render(root, cam); |
| +добавлено | root.overrideMaterial = null; |
| +добавлено | renderer.setRenderTarget(prev); |
| +добавлено | } |
| +добавлено | |
| +добавлено | clear(renderer) { |
| +добавлено | const prev = renderer.getRenderTarget(); |
| +добавлено | renderer.setRenderTarget(this.target); |
| +добавлено | renderer.clear(false, true, false); |
| +добавлено | renderer.setRenderTarget(prev); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { makeFloater } from './floaterMeshes.js'; |
| +добавлено | |
| +добавлено | // Rigid bodies floating on the GPU ocean. Each body is split into sub-cells (the |
| +добавлено | // descriptor's sample points); every cell gets Archimedes buoyancy for its submerged |
| +добавлено | // fraction plus drag against the local water velocity, applied at the cell, so roll, |
| +добавлено | // pitch and bobbing all come out of the same forces. Water heights come from |
| +добавлено | // WaterQuery (1-3 frames late) and water velocity from their change over time. |
| +добавлено | const RHO = 1025, G = 9.81; |
| +добавлено | const SUBSTEP = 1 / 240; |
| +добавлено | const MAX_BODIES = 28; |
| +добавлено | |
| +добавлено | const _v = new THREE.Vector3(), _r = new THREE.Vector3(), _f = new THREE.Vector3(); |
| +добавлено | const _vp = new THREE.Vector3(), _t = new THREE.Vector3(), _m = new THREE.Matrix3(), _mt = new THREE.Matrix3(); |
| +добавлено | const _q = new THREE.Quaternion(), _w = new THREE.Vector3(), _c = new THREE.Vector3(), _m4 = new THREE.Matrix4(); |
| +добавлено | |
| +добавлено | class Body { |
| +добавлено | constructor(desc) { |
| +добавлено | this.desc = desc; |
| +добавлено | this.object = desc.object; |
| +добавлено | this.mass = desc.density * desc.volume; |
| +добавлено | const s = desc.size, m = this.mass; |
| +добавлено | // solid-box inertia; good enough for every prop shape here |
| +добавлено | this.invInertia = new THREE.Vector3( |
| +добавлено | 12 / (m * (s.y * s.y + s.z * s.z)), 12 / (m * (s.x * s.x + s.z * s.z)), 12 / (m * (s.x * s.x + s.y * s.y))); |
| +добавлено | this.pos = new THREE.Vector3(); |
| +добавлено | this.vel = new THREE.Vector3(); |
| +добавлено | this.quat = new THREE.Quaternion(); |
| +добавлено | this.angVel = new THREE.Vector3(); |
| +добавлено | this.radius = desc.size.length() / 2; |
| +добавлено | this.wet = false; |
| +добавлено | const n = desc.samples.length; |
| +добавлено | this.cellVolume = desc.volume / n; |
| +добавлено | this.cellMass = m / n; |
| +добавлено | this.world = desc.samples.map(() => new THREE.Vector3()); |
| +добавлено | // per sample: water height, water velocity (x, y, z), last displacement for velocity |
| +добавлено | this.water = new Float32Array(n * 4); |
| +добавлено | this.lastDisp = new Float32Array(n * 3).fill(NaN); |
| +добавлено | } |
| +добавлено | |
| +добавлено | place(pos, yaw) { |
| +добавлено | this.pos.copy(pos); |
| +добавлено | this.vel.set(0, 0, 0); |
| +добавлено | this.angVel.set(0, 0, 0); |
| +добавлено | this.quat.setFromAxisAngle(_v.set(0, 1, 0), yaw); |
| +добавлено | this.water.fill(0); |
| +добавлено | this.lastDisp.fill(NaN); |
| +добавлено | this.updateWorld(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | updateWorld() { |
| +добавлено | for (let i = 0; i < this.world.length; i++) this.world[i].copy(this.desc.samples[i]).applyQuaternion(this.quat).add(this.pos); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | export class Floaters { |
| +добавлено | constructor({ scene, heightAt, patchMaterial }) { |
| +добавлено | // own (nested) scene so the floater shadow map can render just these |
| +добавлено | this.scene = new THREE.Scene(); |
| +добавлено | scene.add(this.scene); |
| +добавлено | this.heightAt = heightAt; |
| +добавлено | this.patchMaterial = patchMaterial; |
| +добавлено | this.bodies = []; |
| +добавлено | this.layout = 0; // bumps whenever the sample layout changes |
| +добавлено | this.points = new Float32Array(1024); // xz pairs submitted to WaterQuery |
| +добавлено | this.count = 0; |
| +добавлено | this.params = { drag: 1.6, angularDrag: 0.8, buoyancy: 1 }; |
| +добавлено | this.time = 0; |
| +добавлено | this.impacts = []; // last few water entries: { x, z, t, amp, size } for ripple rings |
| +добавлено | } |
| +добавлено | |
| +добавлено | add(kind, pos, yaw = Math.random() * Math.PI * 2) { |
| +добавлено | if (this.bodies.length >= MAX_BODIES) { |
| +добавлено | const old = this.bodies.shift(); |
| +добавлено | this.scene.remove(old.object); |
| +добавлено | } |
| +добавлено | const b = new Body(makeFloater(kind, this.patchMaterial)); |
| +добавлено | b.place(pos, yaw); |
| +добавлено | this.scene.add(b.object); |
| +добавлено | this.bodies.push(b); |
| +добавлено | this.layout++; |
| +добавлено | return b; |
| +добавлено | } |
| +добавлено | |
| +добавлено | clear() { |
| +добавлено | for (const b of this.bodies) this.scene.remove(b.object); |
| +добавлено | this.bodies.length = 0; |
| +добавлено | this.layout++; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // a small flotsam field in front of a viewpoint |
| +добавлено | spawn(center, forward) { |
| +добавлено | this.clear(); |
| +добавлено | const f = _f.copy(forward).setY(0).normalize(), side = new THREE.Vector3(-f.z, 0, f.x); |
| +добавлено | const at = (ahead, across) => new THREE.Vector3().copy(center).addScaledVector(f, ahead).addScaledVector(side, across).setY(0.2); |
| +добавлено | this.add('boat', at(22, -4), Math.atan2(f.x, f.z) + 1.2); |
| +добавлено | this.add('buoy', at(38, 9)); |
| +добавлено | [[12, 3], [16, -9], [27, 6], [31, -1], [19, 12]].forEach(([a, c]) => this.add('crate', at(a, c))); |
| +добавлено | [[14, -2], [24, 14], [34, -8]].forEach(([a, c]) => this.add('barrel', at(a, c))); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // sample points for this frame's water query |
| +добавлено | collectPoints(extra) { |
| +добавлено | let k = 0; |
| +добавлено | for (const e of extra) { this.points[k++] = e.x; this.points[k++] = e.z; } |
| +добавлено | for (const b of this.bodies) for (const p of b.world) { this.points[k++] = p.x; this.points[k++] = p.z; } |
| +добавлено | this.count = k / 2; |
| +добавлено | return this.points; |
| +добавлено | } |
| +добавлено | |
| +добавлено | // consume a WaterQuery result (offset = number of non-body points submitted first) |
| +добавлено | ingest(query, offset) { |
| +добавлено | if (query.resultTag !== this.layout || query.resultTime === this.lastResultTime) return; |
| +добавлено | const dtR = this.lastResultTime === undefined ? 0 : query.resultTime - this.lastResultTime; |
| +добавлено | this.lastResultTime = query.resultTime; |
| +добавлено | const r = query.result; |
| +добавлено | let k = offset; |
| +добавлено | for (const b of this.bodies) { |
| +добавлено | for (let i = 0; i < b.world.length; i++, k++) { |
| +добавлено | if (k >= query.resultCount) return; |
| +добавлено | const h = r[k * 4], dx = r[k * 4 + 1], dz = r[k * 4 + 2]; |
| +добавлено | const w = b.water, ld = b.lastDisp; |
| +добавлено | w[i * 4] = h; |
| +добавлено | if (dtR > 1e-4 && !Number.isNaN(ld[i * 3])) { |
| +добавлено | // water velocity from the change in displacement at a fixed point. At steep |
| +добавлено | // fronts that overstates particle speed (the front sweeps past), so clamp to |
| +добавлено | // roughly the largest orbital speeds these waves have |
| +добавлено | const c = (v, m) => Math.max(-m, Math.min(m, v)); |
| +добавлено | w[i * 4 + 1] = c((dx - ld[i * 3]) / dtR, 3); |
| +добавлено | w[i * 4 + 2] = c((h - ld[i * 3 + 1]) / dtR, 0.8); |
| +добавлено | w[i * 4 + 3] = c((dz - ld[i * 3 + 2]) / dtR, 3); |
| +добавлено | } |
| +добавлено | ld[i * 3] = dx; ld[i * 3 + 1] = h; ld[i * 3 + 2] = dz; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | step(dt) { |
| +добавлено | dt = Math.min(dt, 1 / 20); |
| +добавлено | this.time += dt; |
| +добавлено | const steps = Math.max(1, Math.ceil(dt / SUBSTEP)), h = dt / steps; |
| +добавлено | for (let s = 0; s < steps; s++) for (const b of this.bodies) this.integrate(b, h); |
| +добавлено | for (const b of this.bodies) { |
| +добавлено | b.object.position.copy(b.pos); |
| +добавлено | b.object.quaternion.copy(b.quat); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | integrate(b, h) { |
| +добавлено | const P = this.params; |
| +добавлено | const force = _f.set(0, -b.mass * G, 0), torque = _t.set(0, 0, 0); |
| +добавлено | const cell = b.desc.cellHeight; |
| +добавлено | let wet = false; |
| +добавлено | b.updateWorld(); |
| +добавлено | for (let i = 0; i < b.world.length; i++) { |
| +добавлено | const p = b.world[i], w = b.water; |
| +добавлено | _r.subVectors(p, b.pos); |
| +добавлено | _vp.copy(b.angVel).cross(_r).add(b.vel); // velocity of this cell |
| +добавлено | const sub = THREE.MathUtils.clamp((w[i * 4] - p.y) / cell + 0.5, 0, 1); |
| +добавлено | if (sub > 0) { |
| +добавлено | wet = true; |
| +добавлено | _v.set(0, RHO * G * b.cellVolume * sub * P.buoyancy, 0); |
| +добавлено | // drag against the moving water (gives orbital bobbing and surf push) |
| +добавлено | const k = P.drag * b.cellMass * sub; |
| +добавлено | _v.x -= (_vp.x - w[i * 4 + 1]) * k; |
| +добавлено | _v.y -= (_vp.y - w[i * 4 + 2]) * k * 1.5; |
| +добавлено | _v.z -= (_vp.z - w[i * 4 + 3]) * k; |
| +добавлено | force.add(_v); |
| +добавлено | torque.add(_c.copy(_r).cross(_v)); |
| +добавлено | } |
| +добавлено | // beach / seabed contact: stiff spring + friction |
| +добавлено | const ground = this.heightAt(p.x, p.z); |
| +добавлено | const pen = ground - p.y; |
| +добавлено | if (pen > 0) { |
| +добавлено | const kN = b.cellMass * 900; |
| +добавлено | _v.set(-_vp.x * b.cellMass * 6, pen * kN - _vp.y * b.cellMass * 40, -_vp.z * b.cellMass * 6); |
| +добавлено | force.add(_v); |
| +добавлено | torque.add(_c.copy(_r).cross(_v)); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | // hitting the water fast: ripple rings (and a splash) sized by the body and speed |
| +добавлено | if (wet && !b.wet && b.vel.y < -1.5) { |
| +добавлено | const s = b.desc.size; |
| +добавлено | this.impacts.push({ x: b.pos.x, z: b.pos.z, t: this.time, amp: Math.min(0.35, 0.03 * -b.vel.y * Math.min(s.x, s.z)), size: Math.max(s.x, s.z) * 0.5 }); |
| +добавлено | if (this.impacts.length > 8) this.impacts.shift(); |
| +добавлено | } |
| +добавлено | b.wet = wet; |
| +добавлено | b.vel.addScaledVector(force, h / b.mass); |
| +добавлено | b.pos.addScaledVector(b.vel, h); |
| +добавлено | |
| +добавлено | // world inverse inertia = R diag(I^-1) R^T |
| +добавлено | _m.setFromMatrix4(_m4.makeRotationFromQuaternion(b.quat)); |
| +добавлено | _mt.copy(_m).transpose(); |
| +добавлено | _w.copy(torque).applyMatrix3(_mt).multiply(b.invInertia).applyMatrix3(_m); |
| +добавлено | b.angVel.addScaledVector(_w, h); |
| +добавлено | b.angVel.multiplyScalar(Math.exp(-P.angularDrag * h)); |
| +добавлено | const a = b.angVel.length(); |
| +добавлено | if (a > 1e-6) { |
| +добавлено | _q.setFromAxisAngle(_v.copy(b.angVel).divideScalar(a), a * h); |
| +добавлено | b.quat.premultiply(_q).normalize(); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import { fbm, ridged } from './noise.js'; |
| +добавлено | |
| +добавлено | // Island footprint in world units (metres). Terrain mesh and the shore heightmap share it. |
| +добавлено | export const ISLAND_SIZE = 2400; |
| +добавлено | |
| +добавлено | const smooth = (a, b, x) => { |
| +добавлено | const t = Math.min(1, Math.max(0, (x - a) / (b - a))); |
| +добавлено | return t * t * (3 - 2 * t); |
| +добавлено | }; |
| +добавлено | |
| +добавлено | // Height above sea level (y = 0). Coastline sits around r ~ 330 m, seabed falls to -42 m. |
| +добавлено | export function islandHeight(x, z) { |
| +добавлено | const warp = fbm(x * 0.0035 + 11.3, z * 0.0035 - 4.1, 4, 3); |
| +добавлено | const r = Math.hypot(x - 40 * warp, z + 30 * warp) * (1 + 0.32 * fbm(x * 0.003, z * 0.003, 3, 7)); |
| +добавлено | |
| +добавлено | let h = 62 * Math.exp(-((r / 190) ** 2)) + 15 * Math.exp(-((r / 430) ** 2)) - 10; |
| +добавлено | h -= 32 * smooth(380, 1100, r); |
| +добавлено | |
| +добавлено | // rocky ridges only on the mountain |
| +добавлено | const mountain = smooth(4, 40, h); |
| +добавлено | h += mountain * 26 * (ridged(x * 0.009, z * 0.009, 5, 1) - 0.45); |
| +добавлено | |
| +добавлено | // gentle beaches above the waterline, shallow turquoise shelf below it |
| +добавлено | if (h > 0 && h < 5) h *= 0.55 + 0.09 * h; |
| +добавлено | else if (h <= 0 && h > -14) h = -14 * Math.pow(-h / 14, 1.8); |
| +добавлено | |
| +добавлено | h += 1.2 * fbm(x * 0.05, z * 0.05, 3, 9) * smooth(-30, 2, h); |
| +добавлено | return h; |
| +добавлено | } |
| +добавлено | // Small seeded value-noise helpers for CPU-side terrain generation. |
| +добавлено | |
| +добавлено | function hash2(x, z, seed) { |
| +добавлено | let h = Math.imul(x, 374761393) ^ Math.imul(z, 668265263) ^ Math.imul(seed, 2147483647); |
| +добавлено | h = Math.imul(h ^ (h >>> 13), 1274126177); |
| +добавлено | return ((h ^ (h >>> 16)) >>> 0) / 4294967295; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function valueNoise(x, z, seed = 0) { |
| +добавлено | const xi = Math.floor(x), zi = Math.floor(z); |
| +добавлено | const xf = x - xi, zf = z - zi; |
| +добавлено | const u = xf * xf * (3 - 2 * xf), v = zf * zf * (3 - 2 * zf); |
| +добавлено | const a = hash2(xi, zi, seed), b = hash2(xi + 1, zi, seed); |
| +добавлено | const c = hash2(xi, zi + 1, seed), d = hash2(xi + 1, zi + 1, seed); |
| +добавлено | return (a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v) * 2 - 1; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function fbm(x, z, octaves = 5, seed = 0) { |
| +добавлено | let sum = 0, amp = 0.5, norm = 0; |
| +добавлено | for (let i = 0; i < octaves; i++) { |
| +добавлено | sum += amp * valueNoise(x, z, seed + i * 17); |
| +добавлено | norm += amp; |
| +добавлено | // rotate each octave to hide the lattice |
| +добавлено | const nx = 1.6 * x - 1.2 * z, nz = 1.2 * x + 1.6 * z; |
| +добавлено | x = nx; z = nz; amp *= 0.5; |
| +добавлено | } |
| +добавлено | return sum / norm; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function ridged(x, z, octaves = 5, seed = 0) { |
| +добавлено | let sum = 0, amp = 0.5, norm = 0; |
| +добавлено | for (let i = 0; i < octaves; i++) { |
| +добавлено | const n = 1 - Math.abs(valueNoise(x, z, seed + i * 31)); |
| +добавлено | sum += amp * n * n; |
| +добавлено | norm += amp; |
| +добавлено | const nx = 1.6 * x - 1.2 * z, nz = 1.2 * x + 1.6 * z; |
| +добавлено | x = nx; z = nz; amp *= 0.5; |
| +добавлено | } |
| +добавлено | return sum / norm; |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { FullscreenQuad, rawPass } from '../engine/fullscreen.js'; |
| +добавлено | import { Atmosphere, ATMOSPHERE_GLSL, OBSERVER_ALTITUDE, atmosphereCoefficients, transmittance } from './atmosphere.js'; |
| +добавлено | |
| +добавлено | // Hillaire 2020 atmosphere (atmosphere.js) + clouds baked into a mipmapped HDR cube whenever the |
| +добавлено | // sun or sky params change; nothing runs per frame. The cube is the background, the water's |
| +добавлено | // reflection/fog source and the terrain IBL. The sun disc is analytic (background shader + water |
| +добавлено | // specular), so it's left out of the cube; alpha holds the cloud transmittance (1 = clear) so the |
| +добавлено | // disc can hide behind clouds. |
| +добавлено | // |
| +добавлено | // Units: the sky is lit by sun illuminance pi * sunIntensity at the top of the atmosphere, i.e. the |
| +добавлено | // cube is radiance in the same units as sunColor (sunColor = E_sun,ground / pi, what main.js feeds |
| +добавлено | // the DirectionalLight as pi * sunColor). No extra scale: against the old Preetham cube the +Y face |
| +добавлено | // averages ~0.55x at 52 deg sun, ~1.2x at 22 deg and ~3x at 3.5 deg (Preetham's sky dims too fast |
| +добавлено | // near the horizon). |
| +добавлено | const CUBE_SIZE = 1024; |
| +добавлено | const CLOUD_H = 2.5; // cloud deck altitude for lighting / aerial perspective (km) |
| +добавлено | |
| +добавлено | const BG_VERT = /* glsl */` |
| +добавлено | out vec3 vDir; |
| +добавлено | void main() { |
| +добавлено | vDir = position; |
| +добавлено | vec4 p = projectionMatrix * mat4(mat3(viewMatrix)) * vec4(position, 1.0); |
| +добавлено | gl_Position = p.xyww; // far plane |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const BG_FRAG = /* glsl */` |
| +добавлено | uniform samplerCube uCube; |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | in vec3 vDir; |
| +добавлено | out vec4 fragColor; |
| +добавлено | void main() { |
| +добавлено | vec3 d = normalize(vDir); |
| +добавлено | vec4 sky = textureLod(uCube, vec3(d.x, max(d.y, 0.0), d.z), 0.0); |
| +добавлено | float c = dot(d, uSunDir); |
| +добавлено | // 0.27 deg disc with limb darkening, plus a tight glow; hidden by clouds (cube alpha) |
| +добавлено | float disc = smoothstep(0.999985, 0.999992, c) * (0.6 + 0.4 * smoothstep(0.999985, 1.0, c)); |
| +добавлено | vec3 col = sky.rgb + uSunColor * (disc * 900.0 + pow(max(c, 0.0), 2200.0) * 1.5) * step(0.0, d.y) * sky.a; |
| +добавлено | fragColor = vec4(col, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // One cube face per draw: GL cube-map texel -> world direction (three's cube render targets are |
| +добавлено | // sampled with plain world directions). |
| +добавлено | const CUBE_FRAG = ATMOSPHERE_GLSL + /* glsl */` |
| +добавлено | const float CLOUD_H = ${CLOUD_H.toFixed(2)}; |
| +добавлено | const vec3 WATER = vec3(0.02, 0.035, 0.045); // deep-water body reflectance for the lower hemisphere |
| +добавлено | uniform int uFace; |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform float uCloudCoverage; |
| +добавлено | in vec2 vUv; |
| +добавлено | out vec4 fragColor; |
| +добавлено | |
| +добавлено | vec3 faceDir(vec2 uv) { |
| +добавлено | vec2 c = uv * 2.0 - 1.0; |
| +добавлено | if (uFace == 0) return vec3(1.0, -c.y, -c.x); |
| +добавлено | if (uFace == 1) return vec3(-1.0, -c.y, c.x); |
| +добавлено | if (uFace == 2) return vec3(c.x, 1.0, c.y); |
| +добавлено | if (uFace == 3) return vec3(c.x, -1.0, -c.y); |
| +добавлено | if (uFace == 4) return vec3(c.x, -c.y, 1.0); |
| +добавлено | return vec3(-c.x, -c.y, -1.0); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // cloud layer ported from three's Sky.js (static: time = 0, its cloudScale/elevation/density) |
| +добавлено | vec2 gradient(vec2 i) { |
| +добавлено | vec3 p = fract(i.xyx * vec3(0.1031, 0.1030, 0.0973)); |
| +добавлено | p += dot(p, p.yzx + 33.33); |
| +добавлено | return fract((p.xx + p.yz) * p.zy) * 2.0 - 1.0; |
| +добавлено | } |
| +добавлено | float noise(vec2 p) { |
| +добавлено | vec2 i = floor(p), f = fract(p); |
| +добавлено | vec2 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0); |
| +добавлено | float a = dot(gradient(i), f); |
| +добавлено | float b = dot(gradient(i + vec2(1.0, 0.0)), f - vec2(1.0, 0.0)); |
| +добавлено | float c = dot(gradient(i + vec2(0.0, 1.0)), f - vec2(0.0, 1.0)); |
| +добавлено | float d = dot(gradient(i + vec2(1.0, 1.0)), f - vec2(1.0, 1.0)); |
| +добавлено | return mix(mix(a, b, u.x), mix(c, d, u.x), u.y) * 1.6; |
| +добавлено | } |
| +добавлено | float fbm(vec2 p) { |
| +добавлено | float s = 0.0, a = 1.0; |
| +добавлено | for (int i = 0; i < 4; i++) { s += a * noise(p); a *= 0.5; p *= 2.0; } |
| +добавлено | return s; |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vec3 d = normalize(faceDir(vUv)); |
| +добавлено | vec3 up = skyView(vec3(0.0, 1.0, 0.0), uSunDir); |
| +добавлено | if (d.y < 0.0) { |
| +добавлено | // below the horizon: sea, Fresnel between the mirrored sky and a dark water body |
| +добавлено | float F = 0.02 + 0.98 * pow(1.0 + d.y, 5.0); |
| +добавлено | vec3 body = WATER * (uSunColor * max(uSunDir.y, 0.0) + up); |
| +добавлено | fragColor = vec4(mix(body, skyView(vec3(d.x, -d.y, d.z), uSunDir), F), 1.0); |
| +добавлено | return; |
| +добавлено | } |
| +добавлено | vec3 col = skyView(d, uSunDir); |
| +добавлено | float vis = 1.0; |
| +добавлено | if (d.y > 1e-3 && uCloudCoverage > 0.0) { |
| +добавлено | vec2 p = d.xz / d.y * 0.396; // cloudScale 2e-4 * 1000 / mix(1, 0.1, cloudElevation 0.55) |
| +добавлено | float n = clamp(fbm(p) * 0.7 + 0.5, 0.0, 1.0); |
| +добавлено | float th = 1.0 - clamp(uCloudCoverage + noise(p * 0.3) * 0.222, 0.0, 1.0); // clear gaps / dense banks |
| +добавлено | float fade = smoothstep(0.0, 0.063, d.y); |
| +добавлено | float mask = smoothstep(th, th + 0.3, n) * fade; |
| +добавлено | float depth = max(0.0, n - th); |
| +добавлено | float beer = exp(-4.0 * depth); |
| +добавлено | float shade = mix(0.45, 1.0, clamp(beer * (1.0 - beer * beer) * 2.6, 0.0, 1.0)); // beer-powder |
| +добавлено | float c = dot(d, uSunDir); |
| +добавлено | float silver = clamp(0.51 / pow(1.49 - c * 1.4, 1.5), 0.0, 3.0); // HG g = 0.7 rim toward the sun |
| +добавлено | float edge = mask * (1.0 - mask) * 4.0; |
| +добавлено | float alpha = (1.0 - exp(-depth * 6.6)) * fade; // cloudDensity 0.55 |
| +добавлено | |
| +добавлено | // the deck point along d: sunlight through the atmosphere (and planet shadow) to it, and the |
| +добавлено | // eye-to-deck transmittance so distant clouds dissolve into the haze |
| +добавлено | float r0 = RB + OBS_H, rc = RB + CLOUD_H; |
| +добавлено | float t = -r0 * d.y + sqrt(r0 * r0 * d.y * d.y + (rc - r0) * (rc + r0)); |
| +добавлено | float muV = (r0 * d.y + t) / rc; |
| +добавлено | float muS = clamp((r0 * uSunDir.y + t * c) / rc, -1.0, 1.0); |
| +добавлено | vec3 sun = uSunIllum * transmittance(CLOUD_H, muS) * sunVisible(CLOUD_H, rc, muS) * 0.22; // albedo/pi |
| +добавлено | vec3 cloud = up + sun * (shade + silver * edge * 0.6); |
| +добавлено | vec3 tv = clamp(transmittance(OBS_H, d.y) / max(transmittance(CLOUD_H, muV), vec3(1e-4)), 0.0, 1.0); |
| +добавлено | col = mix(col, mix(col, cloud, tv), alpha); |
| +добавлено | vis = 1.0 - alpha; |
| +добавлено | } |
| +добавлено | fragColor = vec4(col, vis); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export class SkySystem { |
| +добавлено | constructor(renderer) { |
| +добавлено | this.renderer = renderer; |
| +добавлено | this.cubeSize = CUBE_SIZE; |
| +добавлено | this.sunDir = new THREE.Vector3(0, 1, 0); |
| +добавлено | this.sunColor = new THREE.Vector3(1, 1, 1); |
| +добавлено | this.params = { elevation: 3.5, azimuth: 205, turbidity: 2, rayleigh: 1, cloudCoverage: 0.38, sunIntensity: 9 }; |
| +добавлено | |
| +добавлено | this.atmosphere = new Atmosphere(); |
| +добавлено | this.cubeRT = new THREE.WebGLCubeRenderTarget(CUBE_SIZE, { |
| +добавлено | type: THREE.HalfFloatType, generateMipmaps: true, depthBuffer: false, |
| +добавлено | minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | }); |
| +добавлено | this.cube = this.cubeRT.texture; |
| +добавлено | this.cubePass = new FullscreenQuad(rawPass(CUBE_FRAG, { |
| +добавлено | ...this.atmosphere.uniforms, |
| +добавлено | uFace: { value: 0 }, uSunDir: { value: this.sunDir }, uSunColor: { value: this.sunColor }, |
| +добавлено | uCloudCoverage: { value: 0 }, |
| +добавлено | })); |
| +добавлено | this.camera = new THREE.Camera(); // unused by the fullscreen vertex shader |
| +добавлено | |
| +добавлено | this.background = new THREE.Mesh( |
| +добавлено | new THREE.BoxGeometry(1, 1, 1), |
| +добавлено | new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: BG_VERT, fragmentShader: BG_FRAG, |
| +добавлено | uniforms: { uCube: { value: this.cube }, uSunDir: { value: this.sunDir }, uSunColor: { value: this.sunColor } }, |
| +добавлено | side: THREE.BackSide, depthWrite: false, |
| +добавлено | }), |
| +добавлено | ); |
| +добавлено | this.background.frustumCulled = false; |
| +добавлено | // drawn after the opaque scene at the far plane, so only visible sky pixels shade |
| +добавлено | this.background.renderOrder = 1000; |
| +добавлено | } |
| +добавлено | |
| +добавлено | update() { |
| +добавлено | const p = this.params, r = this.renderer; |
| +добавлено | const phi = THREE.MathUtils.degToRad(90 - p.elevation); |
| +добавлено | const theta = THREE.MathUtils.degToRad(p.azimuth); |
| +добавлено | this.sunDir.setFromSphericalCoords(1, phi, theta); |
| +добавлено | |
| +добавлено | // sun radiance factor at sea level: sunIntensity x transmittance (same integral as the LUT), |
| +добавлено | // faded out as the disc sinks below the horizon |
| +добавлено | const c = atmosphereCoefficients(p); |
| +добавлено | const T = transmittance(c, OBSERVER_ALTITUDE, Math.max(this.sunDir.y, 0)); |
| +добавлено | const fade = THREE.MathUtils.smoothstep(p.elevation, -2, 2); |
| +добавлено | this.sunColor.set(T[0], T[1], T[2]).multiplyScalar(p.sunIntensity * fade); |
| +добавлено | |
| +добавлено | const target = r.getRenderTarget(), face = r.getActiveCubeFace(), mip = r.getActiveMipmapLevel(); |
| +добавлено | this.atmosphere.update(r, c, this.sunDir.y, Math.PI * p.sunIntensity); |
| +добавлено | const u = this.cubePass.material.uniforms; |
| +добавлено | u.uCloudCoverage.value = p.cloudCoverage; |
| +добавлено | // three builds the mip chain after a render into the cube, so only after the last face |
| +добавлено | for (let f = 0; f < 6; f++) { |
| +добавлено | u.uFace.value = f; |
| +добавлено | this.cube.generateMipmaps = f === 5; |
| +добавлено | r.setRenderTarget(this.cubeRT, f); |
| +добавлено | r.render(this.cubePass.mesh, this.camera); |
| +добавлено | } |
| +добавлено | r.setRenderTarget(target, face, mip); |
| +добавлено | this.cube.needsPMREMUpdate = true; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { mergeVertices } from 'three/addons/utils/BufferGeometryUtils.js'; |
| +добавлено | import { buildTerrain } from './terrainGeometry.js'; |
| +добавлено | import { islandHeight } from './islandHeight.js'; |
| +добавлено | import { fbm } from './noise.js'; |
| +добавлено | import { CAUSTICS_GLSL } from '../water/Caustics.js'; |
| +добавлено | import { FLOAT_SHADOW_GLSL } from './floaterShadow.js'; |
| +добавлено | import { SHORE_GLSL, SWASH_GLSL } from '../water/OceanSurface.js'; |
| +добавлено | |
| +добавлено | // Island + shore rocks on MeshStandardMaterial, patched with: biome colouring, |
| +добавлено | // wet sand sheen, refracted + absorbed sunlight under water, wave-driven caustics and |
| +добавлено | // the floater shadow map. |
| +добавлено | const VERT_PARS = /* glsl */` |
| +добавлено | varying vec3 vWPos; |
| +добавлено | varying vec3 vWNrm; |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const FRAG_PARS = /* glsl */` |
| +добавлено | varying vec3 vWPos; |
| +добавлено | varying vec3 vWNrm; |
| +добавлено | uniform samplerCube uSkyCube; |
| +добавлено | uniform vec3 uAbsorption; |
| +добавлено | uniform vec3 uSunDirT; |
| +добавлено | uniform float uCausticStrength; |
| +добавлено | uniform float uFogDensity; |
| +добавлено | ${CAUSTICS_GLSL} |
| +добавлено | ${FLOAT_SHADOW_GLSL} |
| +добавлено | ${SHORE_GLSL} |
| +добавлено | ${SWASH_GLSL} |
| +добавлено | float th(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 tn(vec2 p) { vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); |
| +добавлено | return mix(mix(th(i), th(i + vec2(1, 0)), u.x), mix(th(i + vec2(0, 1)), th(i + 1.0), u.x), u.y); } |
| +добавлено | // ripple marks: the phase along d (wavenumber w) is warped by noise of scale s and |
| +добавлено | // amplitude a (metres along d), so crests meander and fork where the warp gets steep |
| +добавлено | float ripplePhase(vec2 p, vec2 d, float w, float s, float a) { |
| +добавлено | return w * (dot(p, d) + (tn(p * s) - 0.5) * a + (tn(p * s * 0.27 + 4.0) - 0.5) * a * 3.0); |
| +добавлено | } |
| +добавлено | // slope of h = amp (sin ph - 0.25 cos 2ph): sharp crests, broad troughs |
| +добавлено | vec2 rippleSlope(vec2 p, vec2 d, float w, float s, float a, float amp) { |
| +добавлено | float ph = ripplePhase(p, d, w, s, a); |
| +добавлено | vec2 grad = (vec2(ripplePhase(p + vec2(0.01, 0.0), d, w, s, a), ripplePhase(p + vec2(0.0, 0.01), d, w, s, a)) - ph) / 0.01; |
| +добавлено | return grad * amp * (cos(ph) + 0.5 * sin(2.0 * ph)); |
| +добавлено | } |
| +добавлено | uniform mat4 uSunShadowMatrix; |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const ALBEDO = /* glsl */` |
| +добавлено | float hgt = vWPos.y; |
| +добавлено | float flat_ = clamp(vWNrm.y, 0.0, 1.0); |
| +добавлено | float n1 = tn(vWPos.xz * 0.08), n2 = tn(vWPos.xz * 0.6), n3 = tn(vWPos.xz * 0.013); |
| +добавлено | vec3 sand = mix(vec3(0.80, 0.71, 0.53), vec3(0.72, 0.62, 0.45), n1) * (0.92 + 0.16 * n2); |
| +добавлено | vec3 seabed = mix(vec3(0.78, 0.72, 0.56), vec3(0.62, 0.58, 0.44), n1 * n3); |
| +добавлено | vec3 grass = mix(vec3(0.20, 0.30, 0.10), vec3(0.33, 0.37, 0.15), n1) * (0.85 + 0.3 * n2); |
| +добавлено | vec3 rock = mix(vec3(0.33, 0.31, 0.29), vec3(0.45, 0.41, 0.36), n2) * (0.8 + 0.4 * n3); |
| +добавлено | #ifdef ROCK |
| +добавлено | vec3 albedo = rock * mix(0.9, 1.15, n1); |
| +добавлено | #else |
| +добавлено | float sandLine = 2.4 + 1.6 * n3 + 0.8 * n1; |
| +добавлено | vec3 albedo = hgt < 0.0 ? seabed : sand; |
| +добавлено | albedo = mix(albedo, grass, smoothstep(sandLine, sandLine + 1.5, hgt) * smoothstep(0.62, 0.8, flat_)); |
| +добавлено | albedo = mix(albedo, rock, smoothstep(0.78, 0.62, flat_) * smoothstep(-6.0, 1.0, hgt)); |
| +добавлено | albedo = mix(albedo, rock * 1.1, smoothstep(38.0, 52.0, hgt + n1 * 8.0)); |
| +добавлено | #endif |
| +добавлено | // wet band above the waterline, plus where the swash has run (dries over seconds) |
| +добавлено | vec3 sw = swash(vWPos.xz, hgt); |
| +добавлено | float wet = max(1.0 - smoothstep(0.35, 1.3 + 0.5 * n1, hgt), sw.z); |
| +добавлено | albedo *= mix(1.0, 0.58, wet); |
| +добавлено | // the swash film itself: a faint water tint and foam on its leading edge |
| +добавлено | float film = smoothstep(0.0, 0.015, sw.x) * step(0.0, hgt); |
| +добавлено | albedo *= mix(vec3(1.0), vec3(0.78, 0.88, 0.92), film); |
| +добавлено | albedo = mix(albedo, vec3(0.92), sw.y * (0.5 + 0.5 * n2)); |
| +добавлено | diffuseColor.rgb = albedo; |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // sand ripples + grain bump in world space, faded out before they alias |
| +добавлено | const RIPPLES = /* glsl */` |
| +добавлено | #ifndef ROCK |
| +добавлено | { |
| +добавлено | vec2 fw = fwidth(vWPos.xz); |
| +добавлено | float px = max(fw.x, fw.y); |
| +добавлено | if (px < 0.5) { // both ripple bands are faded out beyond this |
| +добавлено | float sandMask = (1.0 - smoothstep(sandLine - 0.5, sandLine + 0.5, hgt)) * smoothstep(0.85, 0.95, flat_); |
| +добавлено | sandMask *= mix(1.0, 0.25, smoothstep(-0.3, 0.6, hgt)); // dry sand: faint wind ripples only |
| +добавлено | // long wave-formed ripples (~1.6 m) and short ones (~0.3 m), each fading in and out |
| +добавлено | // in patches |
| +добавлено | vec2 p = vWPos.xz; |
| +добавлено | vec2 d1 = normalize(vec2(0.8, 0.6) + (vec2(tn(p * 0.02), tn(p * 0.02 + 5.0)) - 0.5)); |
| +добавлено | float a1 = 0.02 * (0.3 + 0.7 * smoothstep(0.25, 0.75, tn(p * 0.06 + 11.0))); |
| +добавлено | vec2 g = rippleSlope(p, d1, 3.9, 0.35, 0.8, a1) * (1.0 - smoothstep(0.15, 0.5, px)); |
| +добавлено | if (px < 0.09) { |
| +добавлено | float a2 = 0.002 * (0.3 + 0.7 * smoothstep(0.25, 0.75, tn(p * 0.15 + 3.0))); |
| +добавлено | g += rippleSlope(p, normalize(d1 + vec2(-d1.y, d1.x) * 0.3), 21.0, 2.2, 0.1, a2) * (1.0 - smoothstep(0.03, 0.09, px)); |
| +добавлено | } |
| +добавлено | vec3 nW = normalize(vWNrm - vec3(g.x, 0.0, g.y) * sandMask); |
| +добавлено | normal = normalize((viewMatrix * vec4(nW, 0.0)).xyz); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | #endif |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const UNDERWATER = /* glsl */` |
| +добавлено | float wdepth = max(-vWPos.y, 0.0); |
| +добавлено | // sun and sky light reaching the bed through the water column (the sun along its |
| +добавлено | // refracted path) |
| +добавлено | vec3 rsun = refract(-uSunDirT, vec3(0.0, 1.0, 0.0), 1.0 / 1.33); |
| +добавлено | float sunPath = wdepth / max(-rsun.y, 0.1); |
| +добавлено | diffuseColor.rgb *= exp(-uAbsorption * (sunPath * 0.6 + wdepth * 0.4)); |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // Direct sun (spliced into three's light loop, one directional light): floater shadows |
| +добавлено | // everywhere; below the surface the light arrives refracted (much steeper than the |
| +добавлено | // grazing sun outside), dimmed by the Fresnel transmission, and both shadow maps are |
| +добавлено | // read where it came through the surface, so the bed isn't shadowed along the |
| +добавлено | // unrefracted ray by every sand bar up-sun. |
| +добавлено | const SUN = /* glsl */` |
| +добавлено | getDirectionalLightInfo( directionalLight, directLight ); |
| +добавлено | float under = smoothstep(0.05, -0.25, vWPos.y); |
| +добавлено | vec3 shadowAt = vWPos + vWNrm * 0.04; |
| +добавлено | bool viaSurface = false; |
| +добавлено | if (under > 0.0) { |
| +добавлено | vec3 rsun = refract(-uSunDirT, vec3(0.0, 1.0, 0.0), 1.0 / 1.33); |
| +добавлено | viaSurface = rsun.y < -0.05 && under > 0.5; |
| +добавлено | if (viaSurface) shadowAt = vec3(vWPos.x - rsun.x / rsun.y * vWPos.y, 0.05, vWPos.z - rsun.z / rsun.y * vWPos.y); |
| +добавлено | directLight.direction = normalize(mix(directLight.direction, (viewMatrix * vec4(-rsun, 0.0)).xyz, under)); |
| +добавлено | float Ft = 0.02 + 0.98 * pow(1.0 - max(uSunDirT.y, 0.0), 5.0); |
| +добавлено | directLight.color *= 1.0 - Ft * under; |
| +добавлено | } |
| +добавлено | directLight.color *= floatShadow(shadowAt); |
| +добавлено | #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 |
| +добавлено | vec4 sunShadowCoord = viaSurface ? uSunShadowMatrix * vec4(shadowAt, 1.0) : vDirectionalShadowCoord[ 0 ]; |
| +добавлено | #endif |
| +добавлено | `; |
| +добавлено | const LIGHTS_BEGIN = THREE.ShaderChunk.lights_fragment_begin |
| +добавлено | .replace('getDirectionalLightInfo( directionalLight, directLight );', SUN) |
| +добавлено | .replace('vDirectionalShadowCoord[ i ]', 'sunShadowCoord'); |
| +добавлено | |
| +добавлено | const ROUGH = /* glsl */` |
| +добавлено | roughnessFactor = mix(mix(roughnessFactor, 0.32, wet * step(0.0, hgt)), 0.06, film); |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // caustics focused by the actual waves (Caustics.js); mean 1, so they only redistribute |
| +добавлено | // the direct sun |
| +добавлено | const CAUSTICS = /* glsl */` |
| +добавлено | if (wdepth > 0.0 && rsun.y < -0.05) { |
| +добавлено | vec2 entry = vWPos.xz + rsun.xz / rsun.y * wdepth; // where this light entered the surface |
| +добавлено | vec2 fwc = fwidth(entry); |
| +добавлено | float c = waveCaustic(entry, wdepth, log2(max(max(fwc.x, fwc.y) * CAUSTIC_TEXELS_PER_M, 1.0))); |
| +добавлено | reflectedLight.directDiffuse *= max(mix(1.0, c, uCausticStrength), 0.0); |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const FOG = /* glsl */` |
| +добавлено | vec3 fdir = normalize(vWPos - cameraPosition); |
| +добавлено | float fogAmt = 1.0 - exp(-length(vWPos - cameraPosition) * uFogDensity); |
| +добавлено | outgoingLight = mix(outgoingLight, textureLod(uSkyCube, vec3(fdir.x, max(fdir.y, 0.0), fdir.z), 3.0).rgb, fogAmt); |
| +добавлено | `; |
| +добавлено | |
| +добавлено | // mode: 'terrain' | 'rock' | 'prop' (props keep their own colours, just get the |
| +добавлено | // underwater light falloff, caustics and fog) |
| +добавлено | function patch(material, uniforms, mode) { |
| +добавлено | const ground = mode !== 'prop'; |
| +добавлено | if (mode === 'rock') material.defines = { ...material.defines, ROCK: '' }; |
| +добавлено | material.onBeforeCompile = (shader) => { |
| +добавлено | Object.assign(shader.uniforms, uniforms); |
| +добавлено | shader.vertexShader = shader.vertexShader |
| +добавлено | .replace('#include <common>', '#include <common>\n' + VERT_PARS) |
| +добавлено | .replace('#include <project_vertex>', `#include <project_vertex> |
| +добавлено | vec4 wp = vec4(transformed, 1.0); |
| +добавлено | #ifdef USE_INSTANCING |
| +добавлено | wp = instanceMatrix * wp; |
| +добавлено | #endif |
| +добавлено | vWPos = (modelMatrix * wp).xyz; |
| +добавлено | vec3 wn = objectNormal; |
| +добавлено | #ifdef USE_INSTANCING |
| +добавлено | wn = mat3(instanceMatrix) * wn; |
| +добавлено | #endif |
| +добавлено | vWNrm = normalize(mat3(modelMatrix) * wn);`); |
| +добавлено | shader.fragmentShader = shader.fragmentShader |
| +добавлено | .replace('#include <common>', '#include <common>\n' + FRAG_PARS) |
| +добавлено | .replace('#include <map_fragment>', '#include <map_fragment>\n' + (ground ? ALBEDO : '') + UNDERWATER) |
| +добавлено | .replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\n' + (ground ? ROUGH : '')) |
| +добавлено | .replace('#include <normal_fragment_maps>', '#include <normal_fragment_maps>\n' + (ground ? RIPPLES : '')) |
| +добавлено | .replace('#include <lights_fragment_begin>', LIGHTS_BEGIN) |
| +добавлено | .replace('#include <lights_fragment_end>', '#include <lights_fragment_end>\n' + CAUSTICS) |
| +добавлено | .replace('#include <opaque_fragment>', FOG + '#include <opaque_fragment>'); |
| +добавлено | }; |
| +добавлено | material.customProgramCacheKey = () => 'gelatin-' + mode; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function rockGeometry() { |
| +добавлено | let g = new THREE.IcosahedronGeometry(1, 4); |
| +добавлено | g.deleteAttribute('normal'); |
| +добавлено | g.deleteAttribute('uv'); |
| +добавлено | g = mergeVertices(g); |
| +добавлено | const p = g.attributes.position, v = new THREE.Vector3(); |
| +добавлено | for (let i = 0; i < p.count; i++) { |
| +добавлено | v.fromBufferAttribute(p, i); |
| +добавлено | const n = fbm(v.x * 1.4 + 3, v.z * 1.4 + v.y * 0.7, 5, 21); |
| +добавлено | const facet = Math.abs(fbm(v.x * 3.1, v.y * 3.1 + v.z, 3, 5)); |
| +добавлено | v.multiplyScalar(1 + 0.38 * n - 0.12 * facet); |
| +добавлено | if (v.y < -0.2) v.y = -0.2 + (v.y + 0.2) * 0.4; // flattish base |
| +добавлено | p.setXYZ(i, v.x, v.y, v.z); |
| +добавлено | } |
| +добавлено | g.computeVertexNormals(); |
| +добавлено | return g; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function placeRocks(count, rand) { |
| +добавлено | const out = []; |
| +добавлено | for (let i = 0; i < count * 6 && out.length < count; i++) { |
| +добавлено | const a = rand() * Math.PI * 2; |
| +добавлено | // walk outwards to the coast along this bearing, then jitter around it |
| +добавлено | let r = 150; |
| +добавлено | while (r < 700 && islandHeight(Math.cos(a) * r, Math.sin(a) * r) > 0) r += 4; |
| +добавлено | r += (rand() - 0.6) * 40; |
| +добавлено | const x = Math.cos(a) * r, z = Math.sin(a) * r; |
| +добавлено | const h = islandHeight(x, z); |
| +добавлено | if (h < -5 || h > 6) continue; |
| +добавлено | const s = 1.5 + Math.pow(rand(), 2.2) * 9; |
| +добавлено | out.push({ x, z, y: h - s * 0.15, s }); |
| +добавлено | // small satellites |
| +добавлено | for (let k = 0; k < 3 && out.length < count; k++) { |
| +добавлено | const ox = x + (rand() - 0.5) * s * 4, oz = z + (rand() - 0.5) * s * 4; |
| +добавлено | const ss = s * (0.25 + rand() * 0.35); |
| +добавлено | out.push({ x: ox, z: oz, y: islandHeight(ox, oz) - ss * 0.2, s: ss }); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | return out; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export function createTerrain({ sky, caustics, floatShadow, water, absorption, reflectionLayer = 1 }) { |
| +добавлено | const uniforms = { |
| +добавлено | ...floatShadow, |
| +добавлено | // shore maps + wave settings for the swash (same objects as the water's) |
| +добавлено | ...Object.fromEntries(['uShore', 'uTravel', 'uShoreExtent', 'uTime', 'uShoreWave', 'uSwellDir'].map((k) => [k, water[k]])), |
| +добавлено | ...caustics, |
| +добавлено | uSkyCube: { value: sky.cube }, |
| +добавлено | uAbsorption: { value: absorption }, |
| +добавлено | uSunDirT: { value: sky.sunDir }, |
| +добавлено | uSunShadowMatrix: { value: new THREE.Matrix4() }, // the sun light's shadow.matrix (main.js) |
| +добавлено | uCausticStrength: { value: 1.0 }, |
| +добавлено | uFogDensity: { value: 1 / 18000 }, |
| +добавлено | }; |
| +добавлено | |
| +добавлено | const { geometry } = buildTerrain(384); |
| +добавлено | const groundMat = new THREE.MeshStandardMaterial({ roughness: 0.92, metalness: 0, envMapIntensity: 0.9 }); |
| +добавлено | patch(groundMat, uniforms, 'terrain'); |
| +добавлено | const ground = new THREE.Mesh(geometry, groundMat); |
| +добавлено | ground.castShadow = ground.receiveShadow = true; |
| +добавлено | |
| +добавлено | let seed = 7; |
| +добавлено | const rand = () => ((seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 4294967296); |
| +добавлено | const spots = placeRocks(90, rand); |
| +добавлено | const rockMat = new THREE.MeshStandardMaterial({ roughness: 0.85, metalness: 0, envMapIntensity: 0.9 }); |
| +добавлено | patch(rockMat, uniforms, 'rock'); |
| +добавлено | const rocks = new THREE.InstancedMesh(rockGeometry(), rockMat, spots.length); |
| +добавлено | const m = new THREE.Matrix4(), qt = new THREE.Quaternion(), e = new THREE.Euler(), sc = new THREE.Vector3(); |
| +добавлено | spots.forEach((s, i) => { |
| +добавлено | e.set(rand() * 0.6, rand() * Math.PI * 2, rand() * 0.6); |
| +добавлено | sc.set(s.s * (0.8 + rand() * 0.6), s.s * (0.5 + rand() * 0.5), s.s * (0.8 + rand() * 0.6)); |
| +добавлено | m.compose(new THREE.Vector3(s.x, s.y, s.z), qt.setFromEuler(e), sc); |
| +добавлено | rocks.setMatrixAt(i, m); |
| +добавлено | }); |
| +добавлено | rocks.computeBoundingSphere(); |
| +добавлено | rocks.castShadow = rocks.receiveShadow = true; |
| +добавлено | |
| +добавлено | const group = new THREE.Group(); |
| +добавлено | group.add(ground, rocks); |
| +добавлено | for (const o of [ground, rocks]) o.layers.enable(reflectionLayer); |
| +добавлено | return { group, uniforms, patchProp: (m) => patch(m, uniforms, 'prop') }; |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { islandHeight, ISLAND_SIZE } from './islandHeight.js'; |
| +добавлено | |
| +добавлено | // Grid mesh of the island plus a float heightmap of the same footprint, |
| +добавлено | // which the water uses for shore depth (wave damping, shallow colour, foam). |
| +добавлено | export function buildTerrain(segments = 384, mapSize = 256) { |
| +добавлено | const geo = new THREE.PlaneGeometry(ISLAND_SIZE, ISLAND_SIZE, segments, segments); |
| +добавлено | geo.rotateX(-Math.PI / 2); |
| +добавлено | const pos = geo.attributes.position; |
| +добавлено | for (let i = 0; i < pos.count; i++) pos.setY(i, islandHeight(pos.getX(i), pos.getZ(i))); |
| +добавлено | // drop the deep seabed: below ~34 m the view through the water keeps <5% of it, so it |
| +добавлено | // was shading most of the screen in wide shots for nothing |
| +добавлено | const idx = geo.index.array, keep = []; |
| +добавлено | for (let t = 0; t < idx.length; t += 3) { |
| +добавлено | if (Math.max(pos.getY(idx[t]), pos.getY(idx[t + 1]), pos.getY(idx[t + 2])) > -34) keep.push(idx[t], idx[t + 1], idx[t + 2]); |
| +добавлено | } |
| +добавлено | geo.setIndex(keep); |
| +добавлено | geo.computeVertexNormals(); |
| +добавлено | geo.computeBoundingSphere(); |
| +добавлено | |
| +добавлено | const data = new Float32Array(mapSize * mapSize); |
| +добавлено | for (let j = 0; j < mapSize; j++) { |
| +добавлено | for (let i = 0; i < mapSize; i++) { |
| +добавлено | const x = ((i + 0.5) / mapSize - 0.5) * ISLAND_SIZE; |
| +добавлено | const z = ((j + 0.5) / mapSize - 0.5) * ISLAND_SIZE; |
| +добавлено | data[j * mapSize + i] = islandHeight(x, z); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | const heightMap = new THREE.DataTexture(data, mapSize, mapSize, THREE.RedFormat, THREE.FloatType); |
| +добавлено | heightMap.minFilter = heightMap.magFilter = THREE.LinearFilter; |
| +добавлено | heightMap.wrapS = heightMap.wrapT = THREE.ClampToEdgeWrapping; |
| +добавлено | heightMap.needsUpdate = true; |
| +добавлено | |
| +добавлено | return { geometry: geo, heightMap }; |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { N, CASCADE_LENGTHS } from './OceanSim.js'; |
| +добавлено | import { rawPass } from '../engine/fullscreen.js'; |
| +добавлено | |
| +добавлено | // Wave-driven caustics by area-ratio splatting (Evan Wallace's WebGL water): a grid over |
| +добавлено | // the 12 m cascade's period is refracted through its slopes onto planes at three depths, |
| +добавлено | // and every landed triangle adds (undisturbed area / landed area) to that depth's channel. |
| +добавлено | // Output, mipmapped + repeat, tiling every 12 m: intensity relative to flat water at the |
| +добавлено | // slice depths, mean 1 by construction (the mesh is watertight, so the splatted energy is |
| +добавлено | // the tile area), so it multiplies direct sun light. Two targets, sized by the sun-disc |
| +добавлено | // blur at each depth (~0.7% of the depth): near R16F 512² (2.3 cm) with 1.5 m, deep |
| +добавлено | // RG16F 256² with 4 m and 10 m. |
| +добавлено | // The landing offset of flat water is subtracted, registering the pattern to the surface |
| +добавлено | // entry point: look up at uv = entryXZ / 12 (see CAUSTICS_GLSL). |
| +добавлено | |
| +добавлено | const L = CASCADE_LENGTHS[2]; |
| +добавлено | const ETA = 1 / 1.33; |
| +добавлено | const MAX_RATIO = 16; // firefly clamp (calibration knob; energy above it is dropped) |
| +добавлено | // Fold slivers are far thinner than a texel: point-sampled they hit texel centres only |
| +добавлено | // now and then and the lines break into dots, so both targets are MSAA (each sliver adds |
| +добавлено | // by coverage). |
| +добавлено | const TARGETS = [ |
| +добавлено | { res: 512, format: THREE.RedFormat }, |
| +добавлено | { res: 256, format: THREE.RGFormat }, |
| +добавлено | ]; |
| +добавлено | // Per slice: target + channel, grid cells per tile, and a margin of cells beyond each |
| +добавлено | // tile edge that must cover the largest landing offset (wrap-around, instead of drawing |
| +добавлено | // 3×3 tiles). The cost goes with cells × target res (sliver quad overshading), and the |
| +добавлено | // B-spline slopes keep coarse grids smooth. Deeper slices are focused by longer waves, |
| +добавлено | // so they take coarser slope mips. |
| +добавлено | const SLICES = [ |
| +добавлено | { depth: 1.5, target: 0, channel: 0, cells: 128, margin: 6 }, // 0.38 m |
| +добавлено | { depth: 4, target: 1, channel: 0, cells: 64, margin: 7 }, // 0.94 m |
| +добавлено | { depth: 10, target: 1, channel: 1, cells: 32, margin: 8 }, // 2.25 m |
| +добавлено | ]; |
| +добавлено | const f = (x) => x.toPrecision(9); // GLSL float literal |
| +добавлено | const [D0, D1, D2] = SLICES.map((s) => f(s.depth)); |
| +добавлено | |
| +добавлено | const VERT = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | in vec3 position; // PlaneGeometry vertex: cell coords - uCells / 2 |
| +добавлено | uniform highp sampler2D uSlope; // cascade 2 (sx, sz, ...) |
| +добавлено | uniform vec3 uSun; // towards the sun |
| +добавлено | uniform float uDepth, uCells, uLod, uMargin, uRes; |
| +добавлено | out vec2 vOld; |
| +добавлено | |
| +добавлено | // cubic B-spline from 4 bilinear taps (GPU Gems 2, ch. 20). The landed intensity goes |
| +добавлено | // with the slope's derivative, which bilinear makes piecewise constant: every slope texel |
| +добавлено | // would land as its own bead along the caustic lines. |
| +добавлено | vec2 slopeBSpline(vec2 uv, float lod) { |
| +добавлено | vec2 size = vec2(textureSize(uSlope, int(lod))); |
| +добавлено | vec2 st = uv * size - 0.5, i = floor(st), f = st - i; |
| +добавлено | vec2 f2 = f * f, f3 = f2 * f; |
| +добавлено | vec2 w0 = (1.0 - 3.0 * f + 3.0 * f2 - f3) / 6.0, w1 = (4.0 - 6.0 * f2 + 3.0 * f3) / 6.0; |
| +добавлено | vec2 w2 = (1.0 + 3.0 * f + 3.0 * f2 - 3.0 * f3) / 6.0, w3 = f3 / 6.0; |
| +добавлено | vec2 g0 = w0 + w1, g1 = w2 + w3; |
| +добавлено | vec2 h0 = (i - 0.5 + w1 / g0) / size, h1 = (i + 1.5 + w3 / g1) / size; |
| +добавлено | return g0.y * (g0.x * textureLod(uSlope, h0, lod).xy + g1.x * textureLod(uSlope, vec2(h1.x, h0.y), lod).xy) |
| +добавлено | + g1.y * (g0.x * textureLod(uSlope, vec2(h0.x, h1.y), lod).xy + g1.x * textureLod(uSlope, h1, lod).xy); |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | vec2 t = (position.xy + 0.5 * uCells + 0.5) / uCells; // tile uv, at a texel centre of mip uLod |
| +добавлено | vec2 s = slopeBSpline(t, uLod); |
| +добавлено | vec3 r = refract(-uSun, normalize(vec3(-s.x, 1.0, -s.y)), ${f(ETA)}); |
| +добавлено | vec3 rf = refract(-uSun, vec3(0.0, 1.0, 0.0), ${f(ETA)}); |
| +добавлено | vec2 d = (r.xz / max(-r.y, 0.05) - rf.xz / -rf.y) * (uDepth / ${f(L)}); |
| +добавлено | // ponytail: offsets past the margin (steep facets at low sun) are clamped, widen the margin if it shows |
| +добавлено | d = clamp(d, -uMargin, uMargin); |
| +добавлено | vOld = t * uRes; |
| +добавлено | gl_Position = vec4((t + d) * 2.0 - 1.0, 0.0, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const FRAG = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | uniform vec3 uMask; |
| +добавлено | in vec2 vOld; |
| +добавлено | out vec4 outColor; |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | // raster space is the landed space at one texel per pixel, so the landed area is 1 and |
| +добавлено | // the ratio is the undisturbed area (in texels) per pixel |
| +добавлено | vec2 a = dFdx(vOld), b = dFdy(vOld); |
| +добавлено | outColor = vec4(uMask * min(abs(a.x * b.y - a.y * b.x), ${f(MAX_RATIO)}), 0.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // waveCaustic(entryXZ, depth, lod) -> direct-sun multiplier, mean ~1 (uniforms from |
| +добавлено | // WaveCaustics.uniforms). |
| +добавлено | // entryXZ: world xz (m) where the flat-water refracted sun ray through the shaded point |
| +добавлено | // crosses the surface: P.xz + rs.xz / rs.y * depth, rs = refract(-sunDir, up, 1/1.33). |
| +добавлено | // depth: metres below the surface (<= 0 gives 1.0). lod: extra mip blur in near texels, |
| +добавлено | // e.g. log2(footprint (m) * CAUSTIC_TEXELS_PER_M). |
| +добавлено | export const CAUSTICS_GLSL = /* glsl */` |
| +добавлено | uniform sampler2D uCaustics, uCausticsDeep; |
| +добавлено | const float CAUSTIC_TEXELS_PER_M = ${f(TARGETS[0].res / L)}; |
| +добавлено | float waveCaustic(vec2 entryXZ, float depth, float lod) { |
| +добавлено | vec2 uv = entryXZ * ${f(1 / L)}; |
| +добавлено | float v = textureLod(uCaustics, uv, lod).r; |
| +добавлено | if (depth > ${D0}) { |
| +добавлено | // deep texels are 2x the near ones; past the deepest slice keep it, one mip blurrier |
| +добавлено | // per doubling of depth |
| +добавлено | vec2 d = textureLod(uCausticsDeep, uv, max(lod - 1.0, 0.0) + log2(max(depth / ${D2}, 1.0))).rg; |
| +добавлено | v = depth < ${D1} ? mix(v, d.r, (depth - ${D0}) / (${D1} - ${D0})) |
| +добавлено | : mix(d.r, d.g, clamp((depth - ${D1}) / (${D2} - ${D1}), 0.0, 1.0)); |
| +добавлено | } |
| +добавлено | return mix(1.0, v, clamp(depth / ${D0}, 0.0, 1.0)); // no caustic at zero depth |
| +добавлено | } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const _color = new THREE.Color(); |
| +добавлено | |
| +добавлено | export class WaveCaustics { |
| +добавлено | constructor(renderer, sim) { |
| +добавлено | this.renderer = renderer; |
| +добавлено | this.sim = sim; |
| +добавлено | this.targets = TARGETS.map(({ res, format }) => new THREE.WebGLRenderTarget(res, res, { |
| +добавлено | type: THREE.HalfFloatType, format, samples: 4, minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | wrapS: THREE.RepeatWrapping, wrapT: THREE.RepeatWrapping, generateMipmaps: true, depthBuffer: false, |
| +добавлено | })); |
| +добавлено | this.uniforms = { uCaustics: { value: this.targets[0].texture }, uCausticsDeep: { value: this.targets[1].texture } }; |
| +добавлено | this.slope = { value: null }; |
| +добавлено | this.sun = { value: new THREE.Vector3() }; |
| +добавлено | this.scenes = TARGETS.map(() => new THREE.Group()); |
| +добавлено | SLICES.forEach(({ depth, target, channel, cells, margin }) => { |
| +добавлено | const mat = rawPass(FRAG, { |
| +добавлено | uSlope: this.slope, uSun: this.sun, uRes: { value: TARGETS[target].res }, |
| +добавлено | uDepth: { value: depth }, uCells: { value: cells }, uLod: { value: Math.max(0, Math.log2(N / cells)) }, |
| +добавлено | uMargin: { value: (margin - 1) / cells }, uMask: { value: new THREE.Vector3().setComponent(channel, 1) }, |
| +добавлено | }, { |
| +добавлено | vertexShader: VERT, side: THREE.DoubleSide, // folds past the focus land flipped |
| +добавлено | blending: THREE.CustomBlending, blendSrc: THREE.OneFactor, blendDst: THREE.OneFactor, |
| +добавлено | }); |
| +добавлено | const span = cells + 2 * margin; |
| +добавлено | const mesh = new THREE.Mesh(new THREE.PlaneGeometry(span, span, span, span), mat); |
| +добавлено | mesh.frustumCulled = false; |
| +добавлено | this.scenes[target].add(mesh); |
| +добавлено | }); |
| +добавлено | this.camera = new THREE.Camera(); |
| +добавлено | this.flat = false; |
| +добавлено | this.update(new THREE.Vector3(0, -1, 0)); // start at a flat 1.0 |
| +добавлено | } |
| +добавлено | |
| +добавлено | // once per frame, after sim.update(); sunDir points towards the sun |
| +добавлено | update(sunDir) { |
| +добавлено | const up = sunDir.y > 0; |
| +добавлено | if (!up && this.flat) return; |
| +добавлено | this.flat = !up; |
| +добавлено | const r = this.renderer; |
| +добавлено | const prevRT = r.getRenderTarget(), face = r.getActiveCubeFace(), mip = r.getActiveMipmapLevel(); |
| +добавлено | const prevAlpha = r.getClearAlpha(); |
| +добавлено | r.getClearColor(_color); |
| +добавлено | this.sun.value.copy(sunDir).normalize(); |
| +добавлено | this.slope.value = this.sim.slope[2]; |
| +добавлено | r.setClearColor(up ? 0x000000 : 0xffffff, 1); |
| +добавлено | this.targets.forEach((rt, i) => { |
| +добавлено | this.scenes[i].visible = up; // hidden still renders: render() rebuilds the mips of the clear |
| +добавлено | r.setRenderTarget(rt); |
| +добавлено | r.clear(true, false, false); |
| +добавлено | r.render(this.scenes[i], this.camera); |
| +добавлено | }); |
| +добавлено | r.setRenderTarget(prevRT, face, mip); |
| +добавлено | r.setClearColor(_color, prevAlpha); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | |
| +добавлено | // Drifting particulate underwater: points in a box that wraps around the camera, so |
| +добавлено | // a fixed set always surrounds it. They write depth and alpha 1 like any opaque |
| +добавлено | // object, so the underwater pass fogs each by its own distance. |
| +добавлено | const BOX = 24; |
| +добавлено | |
| +добавлено | const VERT = /* glsl */` |
| +добавлено | in vec3 aSeed; |
| +добавлено | uniform float uTime; |
| +добавлено | uniform vec3 uScatterColor; |
| +добавлено | uniform vec3 uSunColor; |
| +добавлено | uniform vec3 uSunDir; |
| +добавлено | uniform float uPx; // pixels per metre at 1 m (projection scale) |
| +добавлено | out vec3 vCol; |
| +добавлено | void main() { |
| +добавлено | // slow drift + wobble, wrapped into a box centred on the camera |
| +добавлено | vec3 p = aSeed * ${BOX.toFixed(1)} + vec3(0.11, -0.03, 0.07) * uTime |
| +добавлено | + 0.3 * sin(uTime * (0.3 + aSeed.yzx) + aSeed.zxy * 40.0); |
| +добавлено | p = cameraPosition + mod(p - cameraPosition + ${(BOX / 2).toFixed(1)}, ${BOX.toFixed(1)}) - ${(BOX / 2).toFixed(1)}; |
| +добавлено | vec4 view = viewMatrix * vec4(p, 1.0); |
| +добавлено | gl_Position = projectionMatrix * view; |
| +добавлено | float size = (0.004 + 0.01 * fract(aSeed.x * 91.7)) * uPx / max(-view.z, 0.1); |
| +добавлено | gl_PointSize = clamp(size, 1.0, 6.0); |
| +добавлено | vCol = uScatterColor * (uSunColor * max(uSunDir.y, 0.0) + 1.0) * 4.0 * (0.4 + fract(aSeed.y * 37.1)); |
| +добавлено | // too close to the lens: skip |
| +добавлено | if (-view.z < 0.4 || p.y > 0.0) gl_Position = vec4(2.0, 2.0, 2.0, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const FRAG = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | in vec3 vCol; |
| +добавлено | out vec4 fragColor; |
| +добавлено | void main() { |
| +добавлено | if (length(gl_PointCoord - 0.5) > 0.5) discard; |
| +добавлено | fragColor = vec4(vCol, 1.0); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | export class MarineSnow { |
| +добавлено | constructor(surface, count = 6000) { |
| +добавлено | const seeds = new Float32Array(count * 3); |
| +добавлено | let s = 3; |
| +добавлено | for (let i = 0; i < seeds.length; i++) seeds[i] = (s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 4294967296; |
| +добавлено | const geo = new THREE.BufferGeometry(); |
| +добавлено | geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(count * 3), 3)); |
| +добавлено | geo.setAttribute('aSeed', new THREE.BufferAttribute(seeds, 3)); |
| +добавлено | const u = surface.uniforms; |
| +добавлено | this.uniforms = { uTime: u.uTime, uScatterColor: u.uScatterColor, uSunColor: u.uSunColor, uSunDir: u.uSunDir, uPx: { value: 1000 } }; |
| +добавлено | this.mesh = new THREE.Points(geo, new THREE.ShaderMaterial({ |
| +добавлено | glslVersion: THREE.GLSL3, vertexShader: VERT, fragmentShader: FRAG, uniforms: this.uniforms, |
| +добавлено | })); |
| +добавлено | this.mesh.frustumCulled = false; |
| +добавлено | this.mesh.renderOrder = 1; |
| +добавлено | } |
| +добавлено | |
| +добавлено | update(camera, height, visible) { |
| +добавлено | this.mesh.visible = visible; |
| +добавлено | this.uniforms.uPx.value = height / (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2)); |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | import { FullscreenQuad, rawPass } from '../engine/fullscreen.js'; |
| +добавлено | |
| +добавлено | // Tessendorf FFT ocean: 4 cascades of 256² stacked in one 256×1024 atlas so every |
| +добавлено | // IFFT stage is a single draw. Output per cascade (RGBA16F, mipmapped, repeat): |
| +добавлено | // displacement = (λDx, Dy, λDz, turbulence) slope = (sx, sz, sx², sz²) |
| +добавлено | // Slopes are divided out at full resolution so their mips give mean + second moment |
| +добавлено | // (slope variance -> roughness, LEAN style). |
| +добавлено | |
| +добавлено | export const N = 256; |
| +добавлено | const LOG_N = 8; |
| +добавлено | // last cascade is the gravity-capillary detail layer; 12/2.1 is non-integer so tiles don't align |
| +добавлено | export const CASCADE_LENGTHS = [600, 85, 12, 2.1]; |
| +добавлено | const G = 9.81; |
| +добавлено | // surface tension / density (m³/s²): ω² = g·k + (σ/ρ)·k³ |
| +добавлено | const SIGMA_RHO = 7.4e-5; |
| +добавлено | // ω is quantised to multiples of 2π/LOOP and time wraps at LOOP, so the sim loops |
| +добавлено | // seamlessly and fp32 phase never degrades. |
| +добавлено | const LOOP = 300; |
| +добавлено | |
| +добавлено | const COMMON = /* glsl */` |
| +добавлено | precision highp float; |
| +добавлено | precision highp int; |
| +добавлено | #define N ${N} |
| +добавлено | #define PI 3.14159265359 |
| +добавлено | #define G ${G.toFixed(2)} |
| +добавлено | #define ST ${SIGMA_RHO.toExponential()} |
| +добавлено | vec2 cmul(vec2 a, vec2 b) { return vec2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x); } |
| +добавлено | float omega(float k) { return sqrt(G * k + ST * k * k * k); } |
| +добавлено | `; |
| +добавлено | |
| +добавлено | const INIT_FRAG = COMMON + /* glsl */` |
| +добавлено | uniform vec4 uSpecA[2]; // scale, angle, spreadBlend, swell |
| +добавлено | uniform vec4 uSpecB[2]; // alpha, peakOmega, gamma, shortWavesFade |
| +добавлено | uniform vec4 uLength; |
| +добавлено | uniform vec4 uCut; // c0 hi, c1 hi, c2 hi, - |
| +добавлено | uniform float uCapFade; // short-wave fade for cascade 3 (cascades 0-2 use uSpecB.w) |
| +добавлено | uniform uint uSeed; |
| +добавлено | out vec4 outColor; |
| +добавлено | |
| +добавлено | uvec2 pcg2d(uvec2 v) { |
| +добавлено | v = v * 1664525u + 1013904223u; |
| +добавлено | v.x += v.y * 1664525u; v.y += v.x * 1664525u; |
| +добавлено | v ^= v >> 16u; |
| +добавлено | v.x += v.y * 1664525u; v.y += v.x * 1664525u; |
| +добавлено | v ^= v >> 16u; |
| +добавлено | return v; |
| +добавлено | } |
| +добавлено | |
| +добавлено | vec2 gauss(ivec2 id, int c) { |
| +добавлено | uvec2 h = pcg2d(uvec2(id) + uvec2(uint(c) * 7919u, uint(c) * 104729u) + uSeed); |
| +добавлено | float u1 = (float(h.x) + 1.0) / 4294967296.0; |
| +добавлено | float u2 = float(h.y) / 4294967296.0; |
| +добавлено | float r = sqrt(-2.0 * log(u1)); |
| +добавлено | return r * vec2(cos(2.0 * PI * u2), sin(2.0 * PI * u2)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | float jonswap(float w, vec4 a, vec4 b) { |
| +добавлено | float wp = b.y; |
| +добавлено | float sigma = w <= wp ? 0.07 : 0.09; |
| +добавлено | float r = exp(-(w - wp) * (w - wp) / (2.0 * sigma * sigma * wp * wp)); |
| +добавлено | float iw = 1.0 / w; |
| +добавлено | float q = wp * iw; |
| +добавлено | return a.x * b.x * G * G * iw * iw * iw * iw * iw * exp(-1.25 * q * q * q * q) * pow(b.z, r); |
| +добавлено | } |
| +добавлено | |
| +добавлено | float normalisation(float s) { |
| +добавлено | float s2 = s * s, s3 = s2 * s, s4 = s3 * s; |
| +добавлено | if (s < 5.0) return -0.000564 * s4 + 0.00776 * s3 - 0.044 * s2 + 0.192 * s + 0.163; |
| +добавлено | return -4.80e-08 * s4 + 1.07e-05 * s3 - 9.53e-04 * s2 + 5.90e-02 * s + 3.93e-01; |
| +добавлено | } |
| +добавлено | |
| +добавлено | float directional(float theta, float w, vec4 a, vec4 b) { |
| +добавлено | float x = w / b.y; |
| +добавлено | float s = x > 1.0 ? 9.77 * pow(x, -2.5) : 6.97 * pow(x, 5.0); |
| +добавлено | s += 16.0 * tanh(min(x, 20.0)) * a.w * a.w; |
| +добавлено | float t = theta - a.y; |
| +добавлено | float cosine2s = normalisation(s) * pow(abs(cos(0.5 * t)), 2.0 * s); |
| +добавлено | return mix(2.0 / PI * cos(t) * cos(t), cosine2s, a.z); |
| +добавлено | } |
| +добавлено | |
| +добавлено | vec2 h0(ivec2 id, int c) { |
| +добавлено | float L = uLength[c]; |
| +добавлено | float dk = 2.0 * PI / L; |
| +добавлено | vec2 k = vec2(id - N / 2) * dk; |
| +добавлено | float kl = length(k); |
| +добавлено | float lo = c == 0 ? 1e-4 : uCut[c - 1]; |
| +добавлено | float hi = c == 3 ? 1e4 : uCut[c]; |
| +добавлено | if (kl < lo || kl > hi) return vec2(0.0); |
| +добавлено | float w = omega(kl); |
| +добавлено | float dwdk = (G + 3.0 * ST * kl * kl) / (2.0 * w); |
| +добавлено | float theta = atan(k.y, k.x); |
| +добавлено | float S = 0.0; |
| +добавлено | for (int i = 0; i < 2; i++) { |
| +добавлено | if (uSpecA[i].x <= 0.0) continue; |
| +добавлено | float fade = c == 3 ? uCapFade : uSpecB[i].w; |
| +добавлено | S += jonswap(w, uSpecA[i], uSpecB[i]) * directional(theta, w, uSpecA[i], uSpecB[i]) |
| +добавлено | * exp(-fade * fade * kl * kl); |
| +добавлено | } |
| +добавлено | return gauss(id, c) * sqrt(2.0 * S * dwdk / kl * dk * dk); |
| +добавлено | } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | ivec2 p = ivec2(gl_FragCoord.xy); |
| +добавлено | int c = p.y / N; |
| +добавлено | ivec2 id = ivec2(p.x, p.y - c * N); |
| +добавлено | vec2 a = h0(id, c); |
| +добавлено | vec2 b = h0((N - id) % N, c); |
| +добавлено | outColor = vec4(a, b.x, -b.y); // h0(k), conj(h0(-k)) |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const EVOLVE_FRAG = COMMON + /* glsl */` |
| +добавлено | uniform highp sampler2D uH0; |
| +добавлено | uniform vec4 uLength; |
| +добавлено | uniform float uTime; |
| +добавлено | layout(location = 0) out vec4 out0; |
| +добавлено | layout(location = 1) out vec4 out1; |
| +добавлено | |
| +добавлено | // two real fields packed as one complex spectrum: IFFT(A + iB) = a + ib |
| +добавлено | vec2 pack2(vec2 a, vec2 b) { return vec2(a.x - b.y, a.y + b.x); } |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | ivec2 p = ivec2(gl_FragCoord.xy); |
| +добавлено | int c = p.y / N; |
| +добавлено | vec2 k = vec2(ivec2(p.x, p.y - c * N) - N / 2) * (2.0 * PI / uLength[c]); |
| +добавлено | float kl = length(k); |
| +добавлено | float ik = kl > 1e-6 ? 1.0 / kl : 0.0; |
| +добавлено | const float W0 = 2.0 * PI / ${LOOP.toFixed(1)}; |
| +добавлено | // ω = n·W0; phase reduced to [0, 2π) before sin/cos (the capillary cascade reaches ω ≈ 130) |
| +добавлено | float ph = 2.0 * PI * fract(floor(omega(kl) / W0) * (uTime / ${LOOP.toFixed(1)})); |
| +добавлено | vec2 e = vec2(cos(ph), sin(ph)); |
| +добавлено | vec4 h0 = texelFetch(uH0, p, 0); |
| +добавлено | vec2 h = cmul(h0.xy, e) + cmul(h0.zw, vec2(e.x, -e.y)); |
| +добавлено | vec2 ih = vec2(-h.y, h.x); |
| +добавлено | |
| +добавлено | vec2 dx = ih * k.x * ik, dz = ih * k.y * ik; |
| +добавлено | vec2 dxdx = -h * k.x * k.x * ik, dzdz = -h * k.y * k.y * ik, dxdz = -h * k.x * k.y * ik; |
| +добавлено | vec2 dydx = ih * k.x, dydz = ih * k.y; |
| +добавлено | |
| +добавлено | out0 = vec4(pack2(dx, dz), pack2(h, dxdz)); |
| +добавлено | out1 = vec4(pack2(dydx, dydz), pack2(dxdx, dzdz)); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | // Stockham radix-2 inverse FFT stage (e^{+i}); verified against a naive DFT. |
| +добавлено | const FFT_FRAG = COMMON + /* glsl */` |
| +добавлено | uniform highp sampler2D uIn0; |
| +добавлено | uniform highp sampler2D uIn1; |
| +добавлено | uniform int uSub; // sub-transform size 2..N |
| +добавлено | uniform int uVertical; |
| +добавлено | layout(location = 0) out vec4 out0; |
| +добавлено | layout(location = 1) out vec4 out1; |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | ivec2 p = ivec2(gl_FragCoord.xy); |
| +добавлено | int i = uVertical == 1 ? p.y % N : p.x; |
| +добавлено | int hs = uSub >> 1; |
| +добавлено | int e = (i / uSub) * hs + (i & (hs - 1)); |
| +добавлено | ivec2 pe, po; |
| +добавлено | if (uVertical == 1) { int base = p.y - i; pe = ivec2(p.x, base + e); po = ivec2(p.x, base + e + N / 2); } |
| +добавлено | else { pe = ivec2(e, p.y); po = ivec2(e + N / 2, p.y); } |
| +добавлено | float a = 2.0 * PI * float(i & (uSub - 1)) / float(uSub); |
| +добавлено | vec2 tw = vec2(cos(a), sin(a)); |
| +добавлено | vec4 e0 = texelFetch(uIn0, pe, 0), o0 = texelFetch(uIn0, po, 0); |
| +добавлено | vec4 e1 = texelFetch(uIn1, pe, 0), o1 = texelFetch(uIn1, po, 0); |
| +добавлено | out0 = vec4(e0.xy + cmul(tw, o0.xy), e0.zw + cmul(tw, o0.zw)); |
| +добавлено | out1 = vec4(e1.xy + cmul(tw, o1.xy), e1.zw + cmul(tw, o1.zw)); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | const ASSEMBLE_FRAG = COMMON + /* glsl */` |
| +добавлено | uniform highp sampler2D uIn0; |
| +добавлено | uniform highp sampler2D uIn1; |
| +добавлено | uniform sampler2D uPrev; |
| +добавлено | uniform int uCascade; |
| +добавлено | uniform float uLambda; |
| +добавлено | uniform float uDt; |
| +добавлено | uniform float uFoamRecovery; |
| +добавлено | layout(location = 0) out vec4 outDisp; |
| +добавлено | layout(location = 1) out vec4 outSlope; |
| +добавлено | |
| +добавлено | void main() { |
| +добавлено | ivec2 id = ivec2(gl_FragCoord.xy); |
| +добавлено | ivec2 p = id + ivec2(0, uCascade * N); |
| +добавлено | // undo the centred-k frequency shift |
| +добавлено | float s = ((id.x + id.y) & 1) == 0 ? 1.0 : -1.0; |
| +добавлено | vec4 a = texelFetch(uIn0, p, 0) * s; // Dx, Dz, Dy, Dxz |
| +добавлено | vec4 b = texelFetch(uIn1, p, 0) * s; // Dyx, Dyz, Dxx, Dzz |
| +добавлено | float dxx = uLambda * b.z, dzz = uLambda * b.w, dxz = uLambda * a.w; |
| +добавлено | float jac = (1.0 + dxx) * (1.0 + dzz) - dxz * dxz; |
| +добавлено | vec2 slope = b.xy / max(vec2(1.0 + dxx, 1.0 + dzz), vec2(0.2)); |
| +добавлено | float prev = texelFetch(uPrev, id, 0).w; |
| +добавлено | // foam follows the jacobian down instantly and recovers at a dt-based rate |
| +добавлено | float turb = min(jac, prev + uDt * uFoamRecovery / max(jac, 0.5)); |
| +добавлено | outDisp = vec4(uLambda * a.x, a.z, uLambda * a.y, turb); |
| +добавлено | outSlope = vec4(slope, slope * slope); |
| +добавлено | }`; |
| +добавлено | |
| +добавлено | function jonswapParams(windSpeed, fetchKm) { |
| +добавлено | const fetch = fetchKm * 1000; |
| +добавлено | return { |
| +добавлено | alpha: 0.076 * Math.pow((G * fetch) / (windSpeed * windSpeed), -0.22), |
| +добавлено | peakOmega: 22 * Math.pow((windSpeed * fetch) / (G * G), -0.33), |
| +добавлено | }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export const defaultOceanParams = () => ({ |
| +добавлено | windSpeed: 9, |
| +добавлено | windDirection: 20, |
| +добавлено | fetchKm: 120, |
| +добавлено | spreadBlend: 0.85, |
| +добавлено | windSwell: 0.25, |
| +добавлено | gamma: 3.3, |
| +добавлено | shortWavesFade: 0.04, |
| +добавлено | // cascade 3 only (calibration knob): 0.004 is the bare capillary spectrum, but its |
| +добавлено | // mean square slope (0.145) is 3x Cox-Munk for the whole sea and turns the water to |
| +добавлено | // brushed metal; 0.08 keeps fine ripples up close and the water glossy |
| +добавлено | capillaryFade: 0.08, |
| +добавлено | waveScale: 1, |
| +добавлено | swellScale: 0.7, |
| +добавлено | swellWindSpeed: 7, |
| +добавлено | swellDirection: -15, |
| +добавлено | swellFetchKm: 900, |
| +добавлено | swellSwell: 1, |
| +добавлено | choppiness: 0.85, |
| +добавлено | foamRecovery: 0.7, |
| +добавлено | timeScale: 1, |
| +добавлено | }); |
| +добавлено | |
| +добавлено | export class OceanSim { |
| +добавлено | constructor(renderer, params = defaultOceanParams()) { |
| +добавлено | this.renderer = renderer; |
| +добавлено | this.params = params; |
| +добавлено | this.time = 0; |
| +добавлено | this.dirty = true; |
| +добавлено | this.parity = 0; |
| +добавлено | |
| +добавлено | const fft = { |
| +добавлено | type: THREE.FloatType, minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, |
| +добавлено | depthBuffer: false, generateMipmaps: false, |
| +добавлено | }; |
| +добавлено | const H = N * CASCADE_LENGTHS.length; |
| +добавлено | this.h0RT = new THREE.WebGLRenderTarget(N, H, fft); |
| +добавлено | // the 16 IFFT stages are bandwidth-bound; fp16 halves that, and its ~1e-3 relative |
| +добавлено | // error is about a millimetre of displacement on the largest cascade |
| +добавлено | const half = { ...fft, type: THREE.HalfFloatType, count: 2 }; |
| +добавлено | this.ping = new THREE.WebGLRenderTarget(N, H, half); |
| +добавлено | this.pong = new THREE.WebGLRenderTarget(N, H, half); |
| +добавлено | |
| +добавлено | const out = { |
| +добавлено | type: THREE.HalfFloatType, minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter, |
| +добавлено | wrapS: THREE.RepeatWrapping, wrapT: THREE.RepeatWrapping, generateMipmaps: true, |
| +добавлено | anisotropy: renderer.capabilities.getMaxAnisotropy(), depthBuffer: false, count: 2, |
| +добавлено | }; |
| +добавлено | this.out = CASCADE_LENGTHS.map(() => [new THREE.WebGLRenderTarget(N, N, out), new THREE.WebGLRenderTarget(N, N, out)]); |
| +добавлено | |
| +добавлено | // turbulence starts at 1 (no foam) |
| +добавлено | const prevClear = renderer.getClearColor(new THREE.Color()), prevAlpha = renderer.getClearAlpha(); |
| +добавлено | renderer.setClearColor(0x000000, 1); |
| +добавлено | for (const pair of this.out) for (const rt of pair) { renderer.setRenderTarget(rt); renderer.clear(true, false, false); } |
| +добавлено | renderer.setClearColor(prevClear, prevAlpha); |
| +добавлено | renderer.setRenderTarget(null); |
| +добавлено | |
| +добавлено | const lengths = new THREE.Vector4(...CASCADE_LENGTHS); |
| +добавлено | this.initMat = rawPass(INIT_FRAG, { |
| +добавлено | uSpecA: { value: [new THREE.Vector4(), new THREE.Vector4()] }, |
| +добавлено | uSpecB: { value: [new THREE.Vector4(), new THREE.Vector4()] }, |
| +добавлено | uLength: { value: lengths }, |
| +добавлено | // cascade c owns [cut[c-1], cut[c]); each cut sits at 6 fundamentals of the next cascade |
| +добавлено | uCut: { value: new THREE.Vector4(...CASCADE_LENGTHS.slice(1).map((L) => (2 * Math.PI / L) * 6), 0) }, |
| +добавлено | uCapFade: { value: 0 }, |
| +добавлено | uSeed: { value: 1337 }, |
| +добавлено | }); |
| +добавлено | this.evolveMat = rawPass(EVOLVE_FRAG, { |
| +добавлено | uH0: { value: this.h0RT.texture }, uLength: { value: lengths }, uTime: { value: 0 }, |
| +добавлено | }); |
| +добавлено | this.fftMat = rawPass(FFT_FRAG, { |
| +добавлено | uIn0: { value: null }, uIn1: { value: null }, uSub: { value: 2 }, uVertical: { value: 0 }, |
| +добавлено | }); |
| +добавлено | this.assembleMat = rawPass(ASSEMBLE_FRAG, { |
| +добавлено | uIn0: { value: null }, uIn1: { value: null }, uPrev: { value: null }, |
| +добавлено | uCascade: { value: 0 }, uLambda: { value: 1 }, uDt: { value: 0 }, uFoamRecovery: { value: 0.45 }, |
| +добавлено | }); |
| +добавлено | this.quad = new FullscreenQuad(this.initMat); |
| +добавлено | |
| +добавлено | this.lengths = CASCADE_LENGTHS; |
| +добавлено | this.displacement = this.out.map((p) => p[0].textures[0]); |
| +добавлено | this.slope = this.out.map((p) => p[0].textures[1]); |
| +добавлено | } |
| +добавлено | |
| +добавлено | updateSpectrum() { |
| +добавлено | const p = this.params, u = this.initMat.uniforms; |
| +добавлено | const wind = jonswapParams(p.windSpeed, p.fetchKm); |
| +добавлено | const swell = jonswapParams(p.swellWindSpeed, p.swellFetchKm); |
| +добавлено | const rad = THREE.MathUtils.degToRad; |
| +добавлено | u.uSpecA.value[0].set(p.waveScale, rad(p.windDirection), p.spreadBlend, p.windSwell); |
| +добавлено | u.uSpecB.value[0].set(wind.alpha, wind.peakOmega, p.gamma, p.shortWavesFade); |
| +добавлено | u.uSpecA.value[1].set(p.swellScale * p.waveScale, rad(p.swellDirection), 1, p.swellSwell); |
| +добавлено | u.uSpecB.value[1].set(swell.alpha, swell.peakOmega, p.gamma, p.shortWavesFade); |
| +добавлено | u.uCapFade.value = p.capillaryFade; |
| +добавлено | this.quad.material = this.initMat; |
| +добавлено | this.quad.render(this.renderer, this.h0RT); |
| +добавлено | this.dirty = false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | update(dt, timer) { |
| +добавлено | const p = this.params; |
| +добавлено | timer?.begin('sim.evolve'); |
| +добавлено | if (this.dirty) this.updateSpectrum(); |
| +добавлено | dt *= p.timeScale; |
| +добавлено | this.time = (this.time + dt) % LOOP; |
| +добавлено | const r = this.renderer, q = this.quad; |
| +добавлено | |
| +добавлено | this.evolveMat.uniforms.uTime.value = this.time; |
| +добавлено | q.material = this.evolveMat; |
| +добавлено | q.render(r, this.ping); |
| +добавлено | |
| +добавлено | timer?.begin('sim.fft'); |
| +добавлено | let src = this.ping, dst = this.pong; |
| +добавлено | const fu = this.fftMat.uniforms; |
| +добавлено | q.material = this.fftMat; |
| +добавлено | for (let dir = 0; dir < 2; dir++) { |
| +добавлено | fu.uVertical.value = dir; |
| +добавлено | for (let s = 1; s <= LOG_N; s++) { |
| +добавлено | fu.uSub.value = 1 << s; |
| +добавлено | fu.uIn0.value = src.textures[0]; |
| +добавлено | fu.uIn1.value = src.textures[1]; |
| +добавлено | q.render(r, dst); |
| +добавлено | [src, dst] = [dst, src]; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | |
| +добавлено | timer?.begin('sim.assemble'); |
| +добавлено | const au = this.assembleMat.uniforms; |
| +добавлено | au.uIn0.value = src.textures[0]; |
| +добавлено | au.uIn1.value = src.textures[1]; |
| +добавлено | au.uLambda.value = p.choppiness; |
| +добавлено | au.uDt.value = dt; |
| +добавлено | au.uFoamRecovery.value = p.foamRecovery; |
| +добавлено | q.material = this.assembleMat; |
| +добавлено | const next = this.parity ^ 1; |
| +добавлено | for (let c = 0; c < this.out.length; c++) { |
| +добавлено | au.uCascade.value = c; |
| +добавлено | au.uPrev.value = this.out[c][this.parity].textures[0]; |
| +добавлено | q.render(r, this.out[c][next]); |
| +добавлено | this.displacement[c] = this.out[c][next].textures[0]; |
| +добавлено | this.slope[c] = this.out[c][next].textures[1]; |
| +добавлено | } |
| +добавлено | this.parity = next; |
| +добавлено | } |
| +добавлено | } |
| +добавлено | import { World } from './world/world'; |
| +добавлено | |
| +добавлено | const canvas = document.getElementById('c') as HTMLCanvasElement; |
| +добавлено | const world = new World(canvas, 'low'); |
| +добавлено | const spawn = world.findSpawn(); |
| +добавлено | world.camera.position.set(spawn.x, spawn.y + 7, spawn.z + 28); |
| +добавлено | world.camera.lookAt(spawn.x, 1, spawn.z); |
| +добавлено | |
| +добавлено | let last = 0; |
| +добавлено | const loop = (now: number): void => { |
| +добавлено | requestAnimationFrame(loop); |
| +добавлено | const dt = Math.min(0.05, (now - last) / 1000 || 0); |
| +добавлено | last = now; |
| +добавлено | world.camera.lookAt(spawn.x, 0.5, spawn.z); |
| +добавлено | world.camera.position.y = spawn.y + 7; |
| +добавлено | world.render(dt); |
| +добавлено | }; |
| +добавлено | requestAnimationFrame(loop); |
| +добавлено | (window as unknown as { __world: World }).__world = world; |
| +добавлено | import * as THREE from 'three'; |
| +добавлено | |
| +добавлено | import { OceanSim, defaultOceanParams } from '../uw/water/OceanSim.js'; |
| +добавлено | import { OceanSurface } from '../uw/water/OceanSurface.js'; |
| +добавлено | import { bakeShoreMap } from '../uw/water/shoreMap.js'; |
| +добавлено | import { bakeWaterTextures } from '../uw/water/bakeTextures.js'; |
| +добавлено | import { WaveCaustics } from '../uw/water/Caustics.js'; |
| +добавлено | import { UnderwaterPass } from '../uw/water/UnderwaterPass.js'; |
| +добавлено | import { Spray } from '../uw/water/Spray.js'; |
| +добавлено | import { MarineSnow } from '../uw/water/MarineSnow.js'; |
| +добавлено | import { WaterQuery } from '../uw/water/WaterQuery.js'; |
| +добавлено | import { SkySystem } from '../uw/scene/sky.js'; |
| +добавлено | import { createTerrain } from '../uw/scene/terrain.js'; |
| +добавлено | import { islandHeight } from '../uw/scene/islandHeight.js'; |
| +добавлено | import { Floaters } from '../uw/scene/floaters.js'; |
| +добавлено | import { FloaterShadow } from '../uw/scene/floaterShadow.js'; |
| +добавлено | import { PlanarReflection } from '../uw/engine/PlanarReflection.js'; |
| +добавлено | import { PostFX } from '../uw/engine/PostFX.js'; |
| +добавлено | import { GpuTimer } from '../uw/engine/gpuTimer.js'; |
| +добавлено | import { FullscreenQuad, rawPass } from '../uw/engine/fullscreen.js'; |
| +добавлено | |
| +добавлено | /** |
| +добавлено | * Мир на движке Ultra-Water (Humpalumps, MIT): атмосферное небо, FFT-океан |
| +добавлено | * с каустиками и прибоем, подводный проход, постобработка. Здесь только |
| +добавлено | * сборка конвейера и один кадр — геймплей живёт слоем выше. |
| +добавлено | */ |
| +добавлено | |
| +добавлено | const REFLECT_LAYER = 1; |
| +добавлено | const RESTORE_FRAG = /* glsl */ ` |
| +добавлено | precision highp float; |
| +добавлено | uniform sampler2D uTex; |
| +добавлено | in vec2 vUv; |
| +добавлено | out vec4 outColor; |
| +добавлено | void main() { outColor = texture(uTex, vUv); }`; |
| +добавлено | |
| +добавлено | export type QualityProfile = 'high' | 'medium' | 'low' | 'min'; |
| +добавлено | |
| +добавлено | export interface WorldQuality { |
| +добавлено | resolution: number; |
| +добавлено | msaa: number; |
| +добавлено | reflections: boolean; |
| +добавлено | reflectionScale: number; |
| +добавлено | bloom: boolean; |
| +добавлено | } |
| +добавлено | |
| +добавлено | function profileFor(name: QualityProfile): WorldQuality { |
| +добавлено | if (name === 'min') return { resolution: 0.4, msaa: 0, reflections: false, reflectionScale: 0.25, bloom: false }; |
| +добавлено | if (name === 'low') return { resolution: 0.7, msaa: 2, reflections: false, reflectionScale: 0.35, bloom: false }; |
| +добавлено | if (name === 'medium') return { resolution: 1, msaa: 2, reflections: true, reflectionScale: 0.4, bloom: true }; |
| +добавлено | return { resolution: 1, msaa: 4, reflections: true, reflectionScale: 0.5, bloom: true }; |
| +добавлено | } |
| +добавлено | |
| +добавлено | export class World { |
| +добавлено | readonly renderer: THREE.WebGLRenderer; |
| +добавлено | readonly camera: THREE.PerspectiveCamera; |
| +добавлено | readonly scene = new THREE.Scene(); |
| +добавлено | readonly quality: WorldQuality; |
| +добавлено | |
| +добавлено | private sky: any; |
| +добавлено | private shore: any; |
| +добавлено | private ocean: any; |
| +добавлено | private caustics: any; |
| +добавлено | private floatShadow: any; |
| +добавлено | private surface: any; |
| +добавлено | private terrain: any; |
| +добавлено | private sunLight: THREE.DirectionalLight; |
| +добавлено | private query: any; |
| +добавлено | private floaters: any; |
| +добавлено | private underwater: any; |
| +добавлено | private reflection: any; |
| +добавлено | private spray: any; |
| +добавлено | private snow: any; |
| +добавлено | private post: any; |
| +добавлено | private timer: any; |
| +добавлено | private waterScene = new THREE.Scene(); |
| +добавлено | private hdrRT: THREE.WebGLRenderTarget | null = null; |
| +добавлено | private emptyReflection: THREE.DataTexture; |
| +добавлено | private reflectionRoots: THREE.Object3D[] = []; |
| +добавлено | |
| +добавлено | /** Высота воды под камерой (читается из GPU с задержкой 1–3 кадра). */ |
| +добавлено | camWater = 0; |
| +добавлено | /** Камера под водой — для кислорода и интерфейса. */ |
| +добавлено | submerged = false; |
| +добавлено | /** Сколько секунд камера под водой подряд (для эффектов). */ |
| +добавлено | underwaterTime = 0; |
| +добавлено | |
| +добавлено | private elapsed = 0; |
| +добавлено | private uwComp = 1; |
| +добавлено | private wasSubmerged = false; |
| +добавлено | private sunDirty = true; |
| +добавлено | private exposure = 1; |
| +добавлено | private eas = { elevation: 14, azimuth: 208 }; |
| +добавлено | |
| +добавлено | constructor(canvas: HTMLCanvasElement, quality: QualityProfile = 'high') { |
| +добавлено | this.quality = profileFor(quality); |
| +добавлено | |
| +добавлено | this.renderer = new THREE.WebGLRenderer({ |
| +добавлено | canvas, |
| +добавлено | antialias: false, |
| +добавлено | depth: false, |
| +добавлено | stencil: false, |
| +добавлено | alpha: false, |
| +добавлено | powerPreference: 'high-performance', |
| +добавлено | }); |
| +добавлено | this.renderer.autoClear = false; |
| +добавлено | this.renderer.shadowMap.enabled = true; |
| +добавлено | this.renderer.shadowMap.type = THREE.PCFShadowMap; |
| +добавлено | this.renderer.shadowMap.autoUpdate = false; |
| +добавлено | |
| +добавлено | this.camera = new THREE.PerspectiveCamera(62, 1, 0.4, 80000); |
| +добавлено | |
| +добавлено | // --- мир ------------------------------------------------------------------- |
| +добавлено | this.sky = new SkySystem(this.renderer); |
| +добавлено | this.sky.params.elevation = this.eas.elevation; |
| +добавлено | this.sky.params.azimuth = this.eas.azimuth; |
| +добавлено | |
| +добавлено | this.shore = bakeShoreMap(islandHeight, 1800, 512); |
| +добавлено | const tex = bakeWaterTextures(this.renderer); |
| +добавлено | this.ocean = new OceanSim(this.renderer, defaultOceanParams()); |
| +добавлено | this.caustics = new WaveCaustics(this.renderer, this.ocean); |
| +добавлено | this.floatShadow = new FloaterShadow(); |
| +добавлено | this.surface = new OceanSurface(this.ocean, this.shore, this.sky, this.floatShadow.uniforms); |
| +добавлено | this.surface.uniforms.uFoamTex.value = tex.foam; |
| +добавлено | |
| +добавлено | this.scene.environment = this.sky.cube; |
| +добавлено | this.scene.add(this.sky.background); |
| +добавлено | |
| +добавлено | this.terrain = createTerrain({ |
| +добавлено | sky: this.sky, |
| +добавлено | caustics: this.caustics.uniforms, |
| +добавлено | floatShadow: this.floatShadow.uniforms, |
| +добавлено | water: this.surface.uniforms, |
| +добавлено | absorption: this.surface.uniforms.uAbsorption.value, |
| +добавлено | reflectionLayer: REFLECT_LAYER, |
| +добавлено | }); |
| +добавлено | this.scene.add(this.terrain.group); |
| +добавлено | |
| +добавлено | this.sunLight = new THREE.DirectionalLight(0xffffff, Math.PI); |
| +добавлено | this.sunLight.castShadow = true; |
| +добавлено | this.sunLight.shadow.mapSize.set(2048, 2048); |
| +добавлено | Object.assign(this.sunLight.shadow.camera, { |
| +добавлено | left: -700, |
| +добавлено | right: 700, |
| +добавлено | top: 700, |
| +добавлено | bottom: -700, |
| +добавлено | near: 10, |
| +добавлено | far: 4000, |
| +добавлено | }); |
| +добавлено | this.sunLight.shadow.bias = -0.0004; |
| +добавлено | this.sunLight.shadow.normalBias = 0.6; |
| +добавлено | this.scene.add(this.sunLight, this.sunLight.target); |
| +добавлено | |
| +добавлено | this.surface.uniforms.uShadowMatrix.value = this.terrain.uniforms.uSunShadowMatrix.value = |
| +добавлено | this.sunLight.shadow.matrix; |
| +добавлено | this.surface.uniforms.uShadowBias.value = 0.05 / (this.sunLight.shadow.camera.far - this.sunLight.shadow.camera.near); |
| +добавлено | |
| +добавлено | this.query = new WaterQuery(this.renderer, this.surface, 512); |
| +добавлено | this.floaters = new Floaters({ |
| +добавлено | scene: this.scene, |
| +добавлено | heightAt: islandHeight, |
| +добавлено | patchMaterial: this.terrain.patchProp, |
| +добавлено | }); |
| +добавлено | this.enableReflection(this.floaters.scene); |
| +добавлено | |
| +добавлено | this.underwater = new UnderwaterPass(this.surface, this.camera, this.caustics.uniforms); |
| +добавлено | |
| +добавлено | this.reflection = new PlanarReflection(REFLECT_LAYER); |
| +добавлено | this.surface.uniforms.uReflMatrix.value = this.reflection.textureMatrix; |
| +добавлено | this.emptyReflection = new THREE.DataTexture(new Uint8Array(4), 1, 1); |
| +добавлено | this.emptyReflection.needsUpdate = true; |
| +добавлено | |
| +добавлено | const restore = new FullscreenQuad( |
| +добавлено | rawPass(RESTORE_FRAG, { uTex: { value: null } }), |
| +добавлено | ); |
| +добавлено | restore.mesh.renderOrder = -1; |
| +добавлено | if (/OculusBrowser/.test(navigator.userAgent)) this.waterScene.add(restore.mesh); |
| +добавлено | |
| +добавлено | this.spray = new Spray(this.surface, this.shore); |
| +добавлено | this.snow = new MarineSnow(this.surface); |
| +добавлено | this.waterScene.add(this.surface.mesh, this.spray.mesh, this.spray.splash, this.snow.mesh); |
| +добавлено | |
| +добавлено | this.post = new PostFX(this.renderer); |
| +добавлено | this.post.params.bloomStrength = this.quality.bloom ? 0.05 : 0; |
| +добавлено | this.post.params.bloomThreshold = 1.5; |
| +добавлено | |
| +добавлено | this.timer = new GpuTimer(this.renderer.getContext()); |
| +добавлено | this.setSun(this.eas.elevation, this.eas.azimuth); |
| +добавлено | this.resize(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- внешние запросы --------------------------------------------------------- |
| +добавлено | |
| +добавлено | /** Высота рельефа (суша и дно). */ |
| +добавлено | heightAt(x: number, z: number): number { |
| +добавлено | return islandHeight(x, z); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Точка на пляже — для спавна героя и врагов. */ |
| +добавлено | findSpawn(): THREE.Vector3 { |
| +добавлено | for (let a = 0; a < Math.PI * 2; a += 0.13) { |
| +добавлено | let r = 120; |
| +добавлено | while (r < 900 && islandHeight(Math.cos(a) * r, Math.sin(a) * r) > 1.6) r += 2; |
| +добавлено | const x = Math.cos(a) * r; |
| +добавлено | const z = Math.sin(a) * r; |
| +добавлено | const h = islandHeight(x, z); |
| +добавлено | if (h > 0.4 && h < 2.6) return new THREE.Vector3(x, h + 1.2, z); |
| +добавлено | } |
| +добавлено | return new THREE.Vector3(0, 3, 340); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Добавить объект геймплея в отражаемую сцену. */ |
| +добавлено | add(obj: THREE.Object3D): void { |
| +добавлено | this.scene.add(obj); |
| +добавлено | this.reflectionRoots.push(obj); |
| +добавлено | this.enableReflection(obj); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Зарегистрировать объект, который должен отражаться в воде. */ |
| +добавлено | register(obj: THREE.Object3D): void { |
| +добавлено | this.reflectionRoots.push(obj); |
| +добавлено | this.enableReflection(obj); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Все потомки попадают в отражение воды (слой 1). */ |
| +добавлено | enableReflection(root: THREE.Object3D): void { |
| +добавлено | root.traverse((o) => o.layers.enable(REFLECT_LAYER)); |
| +добавлено | } |
| +добавлено | |
| +добавлено | setExposure(v: number): void { |
| +добавлено | this.exposure = v; |
| +добавлено | } |
| +добавлено | |
| +добавлено | setSun(elevation: number, azimuth: number): void { |
| +добавлено | this.eas.elevation = elevation; |
| +добавлено | this.eas.azimuth = azimuth; |
| +добавлено | this.sky.params.elevation = elevation; |
| +добавлено | this.sky.params.azimuth = azimuth; |
| +добавлено | this.sunDirty = true; |
| +добавлено | } |
| +добавлено | |
| +добавлено | get sunDirection(): THREE.Vector3 { |
| +добавлено | return this.sky.sunDir; |
| +добавлено | } |
| +добавлено | |
| +добавлено | spawnFloater(position: THREE.Vector3, direction: THREE.Vector3): void { |
| +добавлено | this.floaters.spawn(position, direction); |
| +добавлено | } |
| +добавлено | |
| +добавлено | // --- кадр -------------------------------------------------------------------- |
| +добавлено | |
| +добавлено | private applySun(): void { |
| +добавлено | this.sky.update(); |
| +добавлено | this.sunLight.position.copy(this.sky.sunDir).multiplyScalar(2000); |
| +добавлено | this.sunLight.color |
| +добавлено | .setRGB(this.sky.sunColor.x, this.sky.sunColor.y, this.sky.sunColor.z) |
| +добавлено | .multiplyScalar(1 / Math.max(this.sky.sunColor.x, 1e-4)); |
| +добавлено | this.sunLight.intensity = Math.PI * Math.max(this.sky.sunColor.x, 1e-4); |
| +добавлено | this.renderer.shadowMap.needsUpdate = true; |
| +добавлено | this.sunDirty = false; |
| +добавлено | } |
| +добавлено | |
| +добавлено | private makeTargets(): void { |
| +добавлено | const size = this.renderer.getDrawingBufferSize(new THREE.Vector2()); |
| +добавлено | this.hdrRT?.dispose(); |
| +добавлено | this.hdrRT = new THREE.WebGLRenderTarget(size.x, size.y, { |
| +добавлено | type: THREE.HalfFloatType, |
| +добавлено | samples: this.quality.msaa, |
| +добавлено | generateMipmaps: false, |
| +добавлено | depthTexture: new THREE.DepthTexture(size.x, size.y, THREE.FloatType), |
| +добавлено | }); |
| +добавлено | const su = this.surface.uniforms; |
| +добавлено | su.uSceneColor.value = this.hdrRT.texture; |
| +добавлено | su.uSceneDepth.value = this.hdrRT.depthTexture; |
| +добавлено | su.uResolution.value.copy(size); |
| +добавлено | this.reflection.scale = this.quality.reflectionScale; |
| +добавлено | this.reflection.setSize(size.x, size.y); |
| +добавлено | this.post.setSize(size.x, size.y); |
| +добавлено | this.underwater.setSize(size.x, size.y); |
| +добавлено | } |
| +добавлено | |
| +добавлено | resize(): void { |
| +добавлено | this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2) * this.quality.resolution); |
| +добавлено | this.renderer.setSize(window.innerWidth, window.innerHeight); |
| +добавлено | this.camera.aspect = window.innerWidth / window.innerHeight; |
| +добавлено | this.camera.updateProjectionMatrix(); |
| +добавлено | this.makeTargets(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | /** Один кадр: вода, отражение, непрозрачное, подводный проход, пост. */ |
| +добавлено | render(dt: number): void { |
| +добавлено | const gl = this.renderer; |
| +добавлено | this.elapsed += dt; |
| +добавлено | if (this.sunDirty) this.applySun(); |
| +добавлено | this.timer.beginFrame(); |
| +добавлено | |
| +добавлено | for (const root of this.reflectionRoots) this.enableReflection(root); |
| +добавлено | |
| +добавлено | if (this.query.resultCount > 0) this.camWater = this.query.result[0]; |
| +добавлено | this.floaters.ingest(this.query, 1); |
| +добавлено | this.floaters.step(dt); |
| +добавлено | this.floatShadow.update(gl, this.floaters.scene, this.floaters.bodies, this.sky.sunDir); |
| +добавлено | |
| +добавлено | const su = this.surface.uniforms; |
| +добавлено | for (let i = 0; i < 8; i++) { |
| +добавлено | const e = this.floaters.impacts[i]; |
| +добавлено | const age = e ? this.floaters.time - e.t : 1e9; |
| +добавлено | su.uImpact.value[i].set(e?.x ?? 0, e?.z ?? 0, age, age < 30 ? e.amp : 0); |
| +добавлено | su.uImpactSize.value[i] = e?.size ?? 1; |
| +добавлено | } |
| +добавлено | |
| +добавлено | this.ocean.update(dt, this.timer); |
| +добавлено | if (this.quality.msaa > 0 || this.quality.resolution > 0.5) this.caustics.update(this.sky.sunDir); |
| +добавлено | this.surface.update(this.camera, this.elapsed % 3600); |
| +добавлено | this.spray.update(); |
| +добавлено | |
| +добавлено | const pts = this.floaters.collectPoints([this.camera.position]); |
| +добавлено | this.query.submit(pts, this.floaters.count, this.floaters.layout, this.elapsed); |
| +добавлено | |
| +добавлено | const camY = this.camera.position.y; |
| +добавлено | const submerged = camY < this.camWater - 0.3; |
| +добавлено | const nearSurface = camY < this.camWater + 1.2; |
| +добавлено | this.submerged = submerged; |
| +добавлено | this.underwaterTime = submerged ? this.underwaterTime + dt : 0; |
| +добавлено | su.uCamSide.value = camY > this.camWater + 0.5 ? -1 : camY < this.camWater - 0.5 ? 1 : 0; |
| +добавлено | |
| +добавлено | this.snow.update(this.camera, this.hdrRT ? this.hdrRT.height : window.innerHeight, nearSurface); |
| +добавлено | this.uwComp += ((submerged ? 0.55 : 1) - this.uwComp) * Math.min(1, dt * 3); |
| +добавлено | this.post.params.exposure = this.exposure * this.uwComp; |
| +добавлено | this.post.params.droplets = |
| +добавлено | this.wasSubmerged && !submerged ? 1 : submerged ? 0 : Math.max(0, this.post.params.droplets - dt / 5); |
| +добавлено | this.wasSubmerged = submerged; |
| +добавлено | |
| +добавлено | if (this.quality.reflections && !submerged) { |
| +добавлено | this.reflection.render(gl, this.scene, this.camera); |
| +добавлено | su.uReflection.value = this.reflection.target.texture; |
| +добавлено | } else { |
| +добавлено | su.uReflection.value = this.emptyReflection; |
| +добавлено | } |
| +добавлено | |
| +добавлено | gl.setRenderTarget(this.hdrRT); |
| +добавлено | gl.setClearColor(0x000000, 1); |
| +добавлено | gl.clear(true, true, false); |
| +добавлено | gl.render(this.scene, this.camera); |
| +добавлено | |
| +добавлено | su.uShadowMap.value = this.sunLight.shadow.map?.depthTexture ?? null; |
| +добавлено | if (this.hdrRT) this.hdrRT.resolveDepthBuffer = nearSurface; |
| +добавлено | gl.render(this.waterScene, this.camera); |
| +добавлено | if (this.hdrRT) this.hdrRT.resolveDepthBuffer = true; |
| +добавлено | |
| +добавлено | let frame: THREE.Texture = this.hdrRT!.texture; |
| +добавлено | if (nearSurface) frame = this.underwater.render(gl, this.hdrRT, camY < this.camWater - 0.8); |
| +добавлено | |
| +добавлено | this.post.render(frame, dt); |
| +добавлено | this.timer.endFrame(); |
| +добавлено | } |
| +добавлено | |
| +добавлено | dispose(): void { |
| +добавлено | this.hdrRT?.dispose(); |
| +добавлено | this.post?.dispose?.(); |
| +добавлено | } |
| +добавлено | } |