Back to Drift City
SOURCE / PINNED RELEASE

Made of little things.

Drift City

Release
098731aa0f0f…
Author-recorded commit
2822ea0a4f5b…
License
LICENSE
Author’s source reference
nostr://npub12lm3rxsva8kfempyjkxupt09e02n3fezurkyadyqfejdc5e0r2kscqty6r/wss%3A%2F%2Fgit.napplet.soy%2F/n-a4c0039c855

Archive hash verified: b3323e408235502b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/game/sky.ts
import * as THREE from 'three';
import { assetBlob } from '../../soy-assets.js';

/**
 * The sky: a port of the creator's Godot sky shader (`sky's/SourceCode/shader/main.gdshader`)
 * to three.js. Sky and horizon colours for day, sunset and night, blended by how high the
 * sun is; two layers of clouds drifting on the wind, given depth by a second look-up; stars
 * at night; and a sun disc with its glow, and a moon opposite it.
 *
 * Its textures are the Godot NoiseTexture2D resources beside it (`textures/clouds/*.tres`),
 * made ahead of time by tools/make-sky-textures.mjs with FastNoiseLite, the noise library
 * Godot uses, from the same settings. Which texture fed which of the shader's inputs was
 * set in a Godot scene that isn't among the files, so: the two clouds layers are
 * clouds_01 (simplex) and clouds_02 (Perlin); the stars are clouds_04 (inverted cellular:
 * bright points); and the night sky's mottling is clouds_03 (large cellular). The clouds
 * and stars fade in once their textures have loaded.
 */

/** The textures' assets, in the order of the shader's inputs below. */
const TEXTURES = ['sky-clouds-1', 'sky-clouds-2', 'sky-stars', 'sky-night'] as const;

/** One of the noise textures, tiling, from its PNG. */
async function noiseTexture(id: string): Promise<THREE.Texture> {
  const image = await createImageBitmap(await assetBlob(id), { imageOrientation: 'none', colorSpaceConversion: 'none' });
  const tex = new THREE.Texture(image);
  tex.flipY = false;
  tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
  tex.minFilter = THREE.LinearMipmapLinearFilter;
  tex.needsUpdate = true;
  return tex;
}

/** A Godot source_color (sRGB) as the linear colour the shader works in. */
const lin = (r: number, g: number, b: number) => new THREE.Color().setRGB(r, g, b, THREE.SRGBColorSpace);

/** The shader's colours and settings, as in the Godot material's defaults. */
export const SKY = {
  skyDay: lin(0.0, 0.3, 0.7),
  horizonDay: lin(0.75, 0.85, 0.85),
  horizonSunset: lin(0.9, 0.4, 0.1),
  skySunset: lin(0.15, 0.2, 0.4),
  horizonNight: lin(0.1, 0.15, 0.2),
  skyNight: lin(0.05, 0.1, 0.15),
  cloudColor: lin(0.8, 0.8, 0.8),
  sunColor: lin(1.0, 0.9, 0.0),
  moonColor: lin(0.5, 0.55, 0.7),
};

const vertexShader = /* glsl */ `
  varying vec3 vDir;
  void main() {
    vec4 world = modelMatrix * vec4(position, 1.0);
    vDir = world.xyz - cameraPosition;
    // On the far plane: drawn after everything else, only where nothing is in front.
    gl_Position = (projectionMatrix * viewMatrix * world).xyww;
  }
`;

// The Godot shader, line for line; where it calls clamp(0.0, 1.0, x) (its arguments the
// wrong way round) that's min(1.0, x), which is what it does there.
const fragmentShader = /* glsl */ `
  uniform vec3 sky_day, horizon_day, horizon_sunset, sky_sunset, horizon_night, sky_night;
  uniform float horizon_exponent, sunset_amount_exponent, night_amount_exponent;
  uniform sampler2D cloud_tex_01, cloud_tex_02, night_noise_01, night_noise_02;
  uniform vec3 cloud_color;
  uniform vec2 cloud_tiling, wind_speed;
  uniform float cloud_density, cloud_depth, cloud_shape_exponent, cloud_occlude_exponent;
  uniform float sun_scale, sun_strength, moon_scale, moon_strength;
  uniform vec3 sun_color, moon_color;
  uniform vec3 light_dir;
  uniform float time;
  /** 0 until the clouds' and stars' textures have loaded, then up to 1. */
  uniform float textures_ready;
  varying vec3 vDir;

  float plane_intersection(vec3 origin, vec3 normal, vec3 ray_start, vec3 ray_dir) {
    return dot(origin - ray_start, normal) / dot(ray_dir, normal);
  }
  float get_cloud_height(sampler2D tex, vec2 uv) {
    float height = texture2D(tex, uv).r;
    height = clamp((height - (1.0 - cloud_density)) / (cloud_density), 0.0, 1.0);
    return pow(height, cloud_shape_exponent);
  }

  void main() {
    vec3 EYEDIR = normalize(vDir);
    float t = plane_intersection(vec3(0.0, 1.0, 0.0), vec3(0.0, -1.0, 0.0), vec3(0.0), EYEDIR);
    float blend = light_dir.y;

    float cloud_value = 0.0;
    if (t >= 0.0) {
      vec3 wind = vec3(wind_speed.x, 0.0, wind_speed.y) * time * 0.1;
      vec3 tiling = vec3(cloud_tiling.x, 1.0, cloud_tiling.y) * 0.2;
      vec3 cloud_pos1 = EYEDIR * t * tiling + wind;
      vec3 cloud_pos2 = EYEDIR * t * tiling + (wind * 0.5);
      float height1 = get_cloud_height(cloud_tex_01, cloud_pos1.xz);
      float height2 = get_cloud_height(cloud_tex_02, cloud_pos2.xz);
      cloud_pos1 += EYEDIR * height1 * cloud_depth * 0.1;
      cloud_pos2 += EYEDIR * height2 * cloud_depth * 0.1;
      height1 = get_cloud_height(cloud_tex_01, cloud_pos1.xz);
      height2 = get_cloud_height(cloud_tex_02, cloud_pos2.xz);
      cloud_value = min(height1, height1 * height2);
      cloud_value *= smoothstep(0.0, 0.2, EYEDIR.y);
    }
    cloud_value *= textures_ready;

    float sun_distance = clamp(1.0 - distance(EYEDIR, light_dir) - pow(cloud_value, cloud_occlude_exponent), 0.0, 1.0);
    float sun_disc = clamp(smoothstep(1.0 - sun_scale, 1.0, sun_distance), 0.0, 1.0);
    float sun_glow = min(1.0, pow(sun_distance, 4.0) * 0.07);
    vec3 sun = mix(vec3(0.0), sun_color * sun_strength, max(sun_disc, sun_glow));

    float moon_distance = clamp(1.0 - distance(EYEDIR, -light_dir) - pow(cloud_value, cloud_occlude_exponent * 2.0), 0.0, 1.0);
    float moon_disc = clamp(smoothstep(1.0 - moon_scale, 1.0, moon_distance), 0.0, 1.0);
    float moon_glow = min(1.0, pow(moon_distance, 8.0) * 0.07);
    vec3 moon = mix(vec3(0.0), moon_color * moon_strength, max(moon_disc, moon_glow));

    vec2 star_uv = (EYEDIR / (1.0 - abs(t) * 0.05)).xz;
    float night_noise = texture2D(night_noise_02, star_uv).r * textures_ready;
    float stars = smoothstep(0.9, 0.95, texture2D(night_noise_01, star_uv).r) * textures_ready;
    float night_blend = min(1.0, 0.0 - blend);
    stars = clamp(clamp((stars - cloud_value * 2.0), 0.0, 1.0) * night_blend, 0.0, 1.0) + (night_noise * 0.01);

    vec3 horizon_color = mix(horizon_sunset, horizon_day, clamp(blend, 0.0, 1.0));
    horizon_color = mix(horizon_night, horizon_color, pow(clamp(1.0 + blend, 0.0, 1.0), 4.0));

    vec3 sky_night_mix = sky_night * (night_noise * 0.5 + 0.5);
    vec3 sky_color = mix(sky_sunset, sky_day, clamp(blend, 0.0, 1.0));
    sky_color = mix(sky_night_mix, sky_color, clamp(pow(1.0 + blend, 4.0), 0.0, 1.0));

    vec3 sky = mix(sky_color, horizon_color, pow(1.0 - abs(EYEDIR.y), horizon_exponent));
    sky = mix(sky, cloud_color * 1.0, pow(cloud_value, 0.8));
    sky += stars * 1.0;
    sky = mix(sky, mix(sky_color * 0.5, horizon_color, EYEDIR.y + 1.0), clamp(pow(1.0 - EYEDIR.y, 2.0), 0.0, 1.0));
    sky += sun * clamp(pow(EYEDIR.y + 1.0, 16.0), 0.0, 1.0);
    sky += moon * clamp(pow(EYEDIR.y + 1.0, 16.0), 0.0, 1.0);

    gl_FragColor = vec4(sky, 1.0);
    #include <tonemapping_fragment>
    #include <colorspace_fragment>
  }
`;

export class Sky {
  readonly mesh: THREE.Mesh;
  private readonly mat: THREE.ShaderMaterial;
  private readonly blank = new THREE.DataTexture(new Uint8Array([0]), 1, 1, THREE.RedFormat);
  private loaded = false;
  private fade = 0;

  constructor() {
    this.blank.needsUpdate = true;
    this.mat = new THREE.ShaderMaterial({
      vertexShader,
      fragmentShader,
      side: THREE.BackSide,
      depthWrite: false,
      depthFunc: THREE.LessEqualDepth,
      fog: false,
      uniforms: {
        sky_day: { value: SKY.skyDay },
        horizon_day: { value: SKY.horizonDay },
        horizon_sunset: { value: SKY.horizonSunset },
        sky_sunset: { value: SKY.skySunset },
        horizon_night: { value: SKY.horizonNight },
        sky_night: { value: SKY.skyNight },
        horizon_exponent: { value: 2.0 },
        sunset_amount_exponent: { value: 0.7 },
        night_amount_exponent: { value: 4.0 },
        cloud_tex_01: { value: this.blank },
        cloud_tex_02: { value: this.blank },
        night_noise_01: { value: this.blank },
        night_noise_02: { value: this.blank },
        cloud_color: { value: SKY.cloudColor },
        cloud_tiling: { value: new THREE.Vector2(1, 1) },
        // (The material's 0.5 sent them across overhead at some 20 degrees a second; this
        // is a fiftieth of that, under half a degree: they can barely be seen to move.)
        wind_speed: { value: new THREE.Vector2(0.01, 0.01) },
        cloud_density: { value: 0.7 },
        cloud_depth: { value: 2.0 },
        cloud_shape_exponent: { value: 2.0 },
        cloud_occlude_exponent: { value: 1.0 },
        sun_scale: { value: 0.05 },
        sun_strength: { value: 15.0 },
        sun_color: { value: SKY.sunColor },
        moon_scale: { value: 0.03 },
        moon_strength: { value: 15.0 },
        moon_color: { value: SKY.moonColor },
        light_dir: { value: new THREE.Vector3(0, 1, 0) },
        time: { value: 0 },
        textures_ready: { value: 0 },
      },
    });
    this.mesh = new THREE.Mesh(new THREE.SphereGeometry(3000, 48, 24), this.mat);
    // Last of the solid things, so it only shades the pixels the sky shows through.
    this.mesh.renderOrder = 1e6;
    this.mesh.frustumCulled = false;
  }

  /**
   * Loads the textures: one at a time, each sent to the graphics card in a frame of its own
   * (all at once, with their mipmaps, stalls software rendering). If one won't load, the
   * sky just has no clouds or stars.
   */
  async load(renderer: THREE.WebGLRenderer): Promise<void> {
    const uniforms = ['cloud_tex_01', 'cloud_tex_02', 'night_noise_01', 'night_noise_02'];
    const textures: THREE.Texture[] = [];
    try {
      for (const id of TEXTURES) {
        const tex = await noiseTexture(id);
        await new Promise((next) => requestAnimationFrame(next));
        renderer.initTexture(tex);
        textures.push(tex);
      }
    } catch (err) {
      console.warn('sky textures', err);
      return;
    }
    textures.forEach((tex, i) => (this.mat.uniforms[uniforms[i]!]!.value = tex));
    this.loaded = true;
  }

  /** The direction towards the sun (its height sets the colours; the moon is opposite). */
  setSun(dir: THREE.Vector3): void {
    (this.mat.uniforms.light_dir!.value as THREE.Vector3).copy(dir).normalize();
  }

  /** Each frame: the clouds drift, and fade in once their textures have loaded. */
  update(dt: number): void {
    this.mat.uniforms.time!.value += dt;
    if (this.loaded && this.fade < 1) {
      this.fade = Math.min(1, this.fade + dt / 2.5);
      this.mat.uniforms.textures_ready!.value = this.fade * this.fade * (3 - 2 * this.fade);
    }
  }

  /** The horizon's colour for a sun this high (as the shader works it out): for the haze. */
  static horizon(sunY: number, out: THREE.Color): THREE.Color {
    const day = SKY.horizonSunset.clone().lerp(SKY.horizonDay, Math.min(1, Math.max(0, sunY)));
    return out.copy(SKY.horizonNight).lerp(day, Math.pow(Math.min(1, Math.max(0, 1 + sunY)), 4));
  }

  /** The sky's colour overhead for a sun this high (for the light from the sky). */
  static zenith(sunY: number, out: THREE.Color): THREE.Color {
    const day = SKY.skySunset.clone().lerp(SKY.skyDay, Math.min(1, Math.max(0, sunY)));
    return out.copy(SKY.skyNight).lerp(day, Math.min(1, Math.max(0, Math.pow(1 + sunY, 4))));
  }
}