Back to Moon Phase
SOURCE / PINNED RELEASE

Made of little things.

Moon Phase

Release
3f174dd4bdf5…
Author-recorded commit
Not provided
License
Check the original source

The hash-verified playable HTML, which may contain bundled or minified code. This view does not execute it.

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Moon Phase</title>
    <meta name="description" content="Tonight's moon, lit as it is right now.">
    <meta name="napplet-id" content="moon-phase">
    <style>
      html, body {
        margin: 0;
        height: 100%;
        overflow: hidden;
        background: transparent;
      }
      body {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      canvas { display: block; cursor: pointer; }
    </style>
  </head>
  <body>
    <canvas id="moon"></canvas>
    <script>
      // ---------- Astronomy (low-precision Meeus, good to a few minutes) ----------
      const RAD = Math.PI / 180;
      const norm = (a) => ((a % 360) + 360) % 360;

      /** Moon–Sun elongation in ecliptic longitude, degrees: 0 new, 90 first quarter, 180 full. */
      function elongation(date) {
        const d = date.getTime() / 86400000 - 10957.5; // days since J2000.0
        const T = d / 36525;
        const L0 = 280.46646 + 0.98564736 * d;
        const M = (357.52911 + 0.98560028 * d) * RAD;
        const sunLon = L0 + (1.914602 - 0.004817 * T) * Math.sin(M) + 0.019993 * Math.sin(2 * M);
        const Lm = 218.3164477 + 13.17639648 * d;
        const Mm = (134.9633964 + 13.06499295 * d) * RAD;
        const D = (297.8501921 + 12.19074912 * d) * RAD;
        const F = (93.272095 + 13.22935024 * d) * RAD;
        const moonLon = Lm
          + 6.288774 * Math.sin(Mm) + 1.274027 * Math.sin(2 * D - Mm)
          + 0.658314 * Math.sin(2 * D) + 0.213618 * Math.sin(2 * Mm)
          - 0.185116 * Math.sin(M) - 0.114332 * Math.sin(2 * F)
          + 0.058793 * Math.sin(2 * D - 2 * Mm) + 0.057066 * Math.sin(2 * D - M - Mm)
          + 0.053322 * Math.sin(2 * D + Mm) + 0.045758 * Math.sin(2 * D - M)
          - 0.040923 * Math.sin(M - Mm) - 0.034720 * Math.sin(D)
          - 0.030383 * Math.sin(M + Mm);
        return norm(moonLon - sunLon);
      }

      // South of the equator the moon appears upside down; guess from the time zone.
      const southern = (() => {
        const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || '';
        return /^(Australia|Antarctica)\/|^Pacific\/(Auckland|Chatham|Fiji|Tongatapu|Apia|Noumea|Port_Moresby)|^America\/(Argentina|Sao_Paulo|Santiago|Montevideo|Asuncion|La_Paz|Lima|Punta_Arenas)|^Africa\/(Johannesburg|Maputo|Harare|Windhoek|Gaborone|Lusaka|Maseru|Mbabane|Luanda|Lubumbashi|Blantyre)|^Indian\/(Mauritius|Reunion|Antananarivo)/.test(tz);
      })();

      // ---------- Shader ----------
      const VERT = `#version 300 es
      in vec2 pos;
      void main() { gl_Position = vec4(pos, 0.0, 1.0); }`;

      const FRAG = `#version 300 es
      precision highp float;
      uniform vec2 res;
      uniform float phase;     // elongation, radians
      uniform vec2 lib;        // libration (lon, lat), radians
      uniform float flip;      // 1 north, -1 south
      out vec4 outColor;

      const float DISC = 0.8;  // disc radius as a fraction of the half-size; the rest is halo

      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);
      }
      float hash13(vec3 p) {
        p = fract(p * 0.1031);
        p += dot(p, p.zyx + 31.32);
        return fract((p.x + p.y) * p.z);
      }
      float vnoise(vec3 p) {
        vec3 i = floor(p), f = fract(p);
        f = f * f * (3.0 - 2.0 * f);
        return mix(
          mix(mix(hash13(i), hash13(i + vec3(1,0,0)), f.x), mix(hash13(i + vec3(0,1,0)), hash13(i + vec3(1,1,0)), f.x), f.y),
          mix(mix(hash13(i + vec3(0,0,1)), hash13(i + vec3(1,0,1)), f.x), mix(hash13(i + vec3(0,1,1)), hash13(i + vec3(1,1,1)), f.x), f.y),
          f.z);
      }
      float fbm(vec3 p) {
        float s = 0.0, a = 0.5;
        for (int i = 0; i < 5; i++) { s += a * vnoise(p); p = p * 2.07 + 17.1; a *= 0.5; }
        return s;
      }

      // One octave of craters: x = height, y = albedo change.
      vec2 craters(vec3 p, float freq, float seed, float density) {
        vec3 q = p * freq + seed;
        vec3 i = floor(q), f = fract(q);
        vec2 acc = vec2(0.0);
        for (int z = -1; z <= 1; z++)
        for (int y = -1; y <= 1; y++)
        for (int x = -1; x <= 1; x++) {
          vec3 g = vec3(float(x), float(y), float(z));
          vec3 r = hash33(i + g);
          if (hash13(i + g + 7.7) > density) continue;
          float rad = 0.12 + 0.33 * r.x * r.x;
          float d = length(g + r - f) / rad;
          if (d > 2.2) continue;
          float bowl = d < 1.0 ? (d * d - 1.0) * 0.55 : 0.0;
          float rim = 0.3 * exp(-pow((d - 1.0) / 0.2, 2.0));
          float ejecta = d > 1.0 ? -0.05 * exp(-(d - 1.0) * 3.0) : 0.0;
          acc.x += (bowl + rim + ejecta) * rad;
          float fresh = step(0.88, r.y);
          acc.y += fresh * (0.1 * exp(-pow((d - 1.0) / 0.35, 2.0)) + 0.05 * smoothstep(2.2, 1.0, d))
                 - (1.0 - fresh) * 0.025 * step(d, 1.0);
        }
        return acc;
      }

      vec3 dir(vec2 xy) { return vec3(xy, sqrt(max(0.0, 1.0 - dot(xy, xy)))); }

      float mare(vec3 p, vec2 c, vec2 r, float wob) {
        vec3 m = dir(c);
        vec3 t = normalize(cross(vec3(0,1,0), m));
        vec3 b = cross(m, t);
        vec3 dv = p - m;
        float d = pow(dot(dv, t) / r.x, 2.0) + pow(dot(dv, b) / r.y, 2.0);
        d = sqrt(d) + wob;
        return 1.0 - smoothstep(0.7, 1.05, d);
      }

      void main() {
        float half_ = min(res.x, res.y) * 0.5;
        vec2 uv = (gl_FragCoord.xy - res * 0.5) / (half_ * DISC) * flip;
        float r = length(uv);
        float px = 1.0 / (half_ * DISC);
        float illum = 0.5 - 0.5 * cos(phase);

        // Halo around the disc.
        if (r > 1.0) {
          float g = (0.06 + 0.3 * illum) * exp(-(r - 1.0) * 9.0) * smoothstep(1.0 / DISC, 1.0, r);
          outColor = vec4(vec3(1.0, 0.96, 0.86) * g, g);
          return;
        }

        vec3 n = dir(uv);
        // Rotate into the moon's body frame for libration.
        float cl = cos(lib.x), sl = sin(lib.x), cb = cos(lib.y), sb = sin(lib.y);
        vec3 p = vec3(cl * n.x + sl * n.z, n.y, -sl * n.x + cl * n.z);
        p = vec3(p.x, cb * p.y - sb * p.z, sb * p.y + cb * p.z);

        // Maria (rough near side, north up).
        float wob = 1.8 * (fbm(p * 2.2 + 11.0) - 0.5) + 0.7 * (fbm(p * 7.0 + 3.0) - 0.5);
        float m = 0.0;
        m = max(m, mare(p, vec2(-0.30, 0.42), vec2(0.27, 0.24), wob));  // Imbrium
        m = max(m, mare(p, vec2(-0.58, 0.02), vec2(0.30, 0.42), wob));  // Procellarum
        m = max(m, mare(p, vec2(0.17, 0.40), vec2(0.16, 0.15), wob));   // Serenitatis
        m = max(m, mare(p, vec2(0.33, 0.10), vec2(0.22, 0.18), wob));   // Tranquillitatis
        m = max(m, mare(p, vec2(0.68, 0.30), vec2(0.11, 0.10), wob));   // Crisium
        m = max(m, mare(p, vec2(0.56, -0.14), vec2(0.13, 0.17), wob));  // Fecunditatis
        m = max(m, mare(p, vec2(0.32, -0.31), vec2(0.10, 0.09), wob));  // Nectaris
        m = max(m, mare(p, vec2(-0.20, -0.36), vec2(0.17, 0.13), wob)); // Nubium
        m = max(m, mare(p, vec2(-0.05, -0.10), vec2(0.12, 0.10), wob)); // Insularum
        m = max(m, mare(p, vec2(-0.50, -0.42), vec2(0.10, 0.09), wob)); // Humorum
        m = max(m, 0.6 * mare(p, vec2(0.00, 0.70), vec2(0.36, 0.06), wob * 1.5)); // Frigoris
        m = clamp(m * (0.55 + 0.7 * fbm(p * 4.0 + 40.0)), 0.0, 1.0);

        // Craters: heights for relief, plus albedo.
        float h = 0.0, a = 0.0, amp = 1.0;
        float freqs[5] = float[5](7.0, 13.0, 25.0, 49.0, 97.0);
        for (int k = 0; k < 5; k++) {
          vec2 c = craters(p, freqs[k], float(k) * 13.7, 0.12 + 0.11 * float(k));
          float smooth_ = k < 2 ? (1.0 - 0.6 * m) : 1.0; // maria are smoother
          h += c.x / freqs[k] * amp * smooth_;
          a += c.y * amp * (k < 2 ? 0.25 : 1.0);
          amp *= 0.8;
        }
        // Rays from a couple of young craters (Tycho, Copernicus).
        vec3 ty = dir(vec2(-0.14, -0.72)), co = dir(vec2(-0.38, 0.12));
        float dty = acos(clamp(dot(p, ty), -1.0, 1.0));
        float dco = acos(clamp(dot(p, co), -1.0, 1.0));
        vec3 tA = normalize(cross(ty, vec3(0,0,1)));
        float angT = atan(dot(p - ty, cross(ty, tA)), dot(p - ty, tA));
        float rays = pow(vnoise(vec3(cos(angT) * 11.0, sin(angT) * 11.0, 3.0)), 6.0) * exp(-dty * 1.8) * 0.22 * smoothstep(0.03, 0.15, dty);
        float spots = 0.18 * exp(-pow(dty / 0.04, 2.0)) + 0.12 * exp(-pow(dco / 0.035, 2.0));

        float alb = 0.92 - 0.4 * m
          + 0.10 * (fbm(p * 12.0) - 0.5)
          + 0.05 * (fbm(p * 60.0 + 5.0) - 0.5)
          + a + rays + spots;
        alb = clamp(alb, 0.3, 1.25);

        // Relief from screen-space slopes of the crater heights.
        vec2 grad = vec2(dFdx(h), dFdy(h)) / px * flip;
        vec3 nb = normalize(n - vec3(grad * 0.7, 0.0));

        vec3 s = vec3(sin(phase), 0.0, -cos(phase));
        float flat_ = dot(n, s);
        float ndl = dot(nb, s);
        // Relief shows mostly near the terminator, where the sun is low.
        float low = 1.0 - smoothstep(0.0, 0.45, flat_);
        float bump = clamp(ndl - flat_, -0.6, 0.6);
        float lit = smoothstep(-0.015, 0.06, flat_ + bump * 0.2 * low);
        float shade = 0.8 + 0.2 * clamp(flat_ * 2.0, 0.0, 1.0)
                    + bump * (0.25 + 0.9 * low);
        shade = clamp(shade, 0.25, 1.15);
        float limb = 0.85 + 0.15 * pow(n.z, 0.35);

        vec3 day = vec3(1.0, 0.965, 0.9) * alb * shade * limb;
        vec3 night = vec3(0.10, 0.115, 0.15) * (0.6 + 0.4 * alb) * (1.0 - 0.6 * illum);
        vec3 col = mix(night, day, lit);
        float alpha = mix(0.82, 1.0, lit) * smoothstep(1.0, 1.0 - 1.5 * px, r);
        outColor = vec4(col * alpha, alpha);
      }`;

      // ---------- Setup ----------
      const canvas = document.getElementById('moon');
      const gl = canvas.getContext('webgl2', { premultipliedAlpha: true, antialias: false });

      function compile(type, src) {
        const sh = gl.createShader(type);
        gl.shaderSource(sh, src);
        gl.compileShader(sh);
        if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh));
        return sh;
      }

      let prog, U;
      if (gl) {
        prog = gl.createProgram();
        gl.attachShader(prog, compile(gl.VERTEX_SHADER, VERT));
        gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, FRAG));
        gl.linkProgram(prog);
        if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog));
        gl.useProgram(prog);
        const buf = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, buf);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
        const loc = gl.getAttribLocation(prog, 'pos');
        gl.enableVertexAttribArray(loc);
        gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
        U = Object.fromEntries(['res', 'phase', 'lib', 'flip'].map((k) => [k, gl.getUniformLocation(prog, k)]));
        gl.uniform1f(U.flip, southern ? -1 : 1);
        gl.clearColor(0, 0, 0, 0);
      }

      // ---------- Animation ----------
      const INTRO_MS = 3200;
      let target = elongation(new Date()) * RAD;
      let introStart = performance.now();
      let lastFrame = 0;

      function resize() {
        const dpr = window.devicePixelRatio || 1;
        const css = Math.max(16, Math.floor(Math.min(innerWidth, innerHeight)));
        const n = Math.min(2048, Math.round(css * dpr));
        if (canvas.width !== n) {
          canvas.width = canvas.height = n;
          canvas.style.width = canvas.style.height = css + 'px';
        }
      }

      const easeOut = (t) => 1 - Math.pow(1 - t, 4);

      function frame(now) {
        requestAnimationFrame(frame);
        const intro = Math.min(1, (now - introStart) / INTRO_MS);
        // After the intro, a gentle sway is all that moves: 20 fps is plenty.
        if (intro >= 1 && now - lastFrame < 50) return;
        lastFrame = now;
        resize();

        // Time-lapse through most of a lunation, landing on tonight's phase.
        const phase = target - (1 - easeOut(intro)) * 1.85 * Math.PI;
        const t = now / 1000;
        const lib = [0.09 * Math.sin(t * 0.21), 0.06 * Math.sin(t * 0.16 + 1.3)];

        if (gl) {
          gl.viewport(0, 0, canvas.width, canvas.height);
          gl.clear(gl.COLOR_BUFFER_BIT);
          gl.uniform2f(U.res, canvas.width, canvas.height);
          gl.uniform1f(U.phase, phase);
          gl.uniform2f(U.lib, lib[0], lib[1]);
          gl.drawArrays(gl.TRIANGLES, 0, 3);
        } else {
          draw2d(phase);
        }
      }

      // Plain fallback when WebGL 2 isn't available.
      function draw2d(phase) {
        const c = canvas.getContext('2d');
        const n = canvas.width, R = n * 0.4, cx = n / 2;
        c.clearRect(0, 0, n, n);
        c.save();
        c.translate(cx, cx);
        if (southern) c.rotate(Math.PI);
        c.fillStyle = 'rgba(26,29,38,0.82)';
        c.beginPath(); c.arc(0, 0, R, 0, 2 * Math.PI); c.fill();
        const k = Math.cos(phase), waxing = Math.sin(phase) >= 0;
        c.fillStyle = '#efe9da';
        c.beginPath();
        c.arc(0, 0, R, -Math.PI / 2, Math.PI / 2, !waxing);
        c.ellipse(0, 0, Math.abs(k) * R, R, 0, Math.PI / 2, -Math.PI / 2, (k > 0) === waxing);
        c.fill();
        c.restore();
      }

      canvas.addEventListener('click', () => { introStart = performance.now(); });
      setInterval(() => { target = elongation(new Date()) * RAD; }, 5 * 60 * 1000);
      requestAnimationFrame(frame);
    </script>
  </body>
</html>