File size: 13,166 Bytes
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c20baa
 
 
c36e12e
 
 
 
 
 
 
 
 
6c20baa
c36e12e
 
 
 
 
 
 
6c20baa
ba7ed3f
6c20baa
 
c36e12e
 
 
 
 
 
 
 
 
 
 
 
 
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c36e12e
95a7e69
 
 
 
 
 
 
 
c36e12e
 
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c36e12e
95a7e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Baked light for the Lit renderer (tools/bake_light.mjs): the scenery shows its light map, and everything
// that moves (the robot, the objects, doors and drawers) takes its diffuse light from the probe grid at
// its place, so it darkens under a table or inside a cupboard as the scenery around it does. Reflections
// come from an environment map captured in the room, dimmed where the baked light is dim (a corner does
// not mirror the bright room).
//
// What moves is not in the bake, so it casts no shade there: SkyOcclusion draws it from above every frame
// (coverage and height, mipmapped) and every lit surface below it loses part of its sky, over a penumbra
// that widens with the height above it, as under the overcast sky the room was baked with.
import * as THREE from "three";
import { download, json } from "../core/assets.js";
import { gunzip } from "../meshpack.js";

/** The layer of the meshes that cast sky occlusion (the moving ones). */
export const OCCLUSION_LAYER = 5;
// Heights in the occlusion map's blue channel are stored as CEILING minus the height (metres).
const CEILING = 4;

/** Load an environment's bake: { meta, lightmap, probes, occlusion }, or null when baked for another layout. */
export async function loadBake(url, fingerprint) {
  const meta = await json(url);
  if (meta.fingerprint !== fingerprint) {
    console.warn(`${url}: baked for another layout (${meta.fingerprint}, this scene is ${fingerprint}); bake again (tools/bake_light.mjs)`);
    return null;
  }
  const base = url.slice(0, url.lastIndexOf("/") + 1);
  const [png, packed] = await Promise.all([download(base + meta.lightmap.file), download(base + meta.probes.file)]);
  const bitmap = await createImageBitmap(new Blob([png], { type: "image/png" }), { premultiplyAlpha: "none", colorSpaceConversion: "none" });
  const lightmap = new THREE.Texture(bitmap);
  lightmap.flipY = false;
  lightmap.colorSpace = THREE.SRGBColorSpace;
  lightmap.channel = 1; // the "uv1" attribute (statics.js)
  lightmap.minFilter = THREE.LinearFilter;
  lightmap.magFilter = THREE.LinearFilter;
  lightmap.generateMipmaps = false;
  lightmap.needsUpdate = true;
  const bytes = await gunzip(packed);
  const [nx, ny, nz] = meta.probes.dims;
  const n = nx * ny * nz;
  const probes = Array.from({ length: 6 }, (_, d) => {
    const t = new THREE.Data3DTexture(bytes.slice(4 * d * n, 4 * (d + 1) * n), nx, ny, nz);
    t.format = THREE.RGBAFormat;
    t.type = THREE.UnsignedByteType;
    t.colorSpace = THREE.SRGBColorSpace;
    t.minFilter = THREE.LinearFilter;
    t.magFilter = THREE.LinearFilter;
    t.unpackAlignment = 1;
    t.needsUpdate = true;
    return t;
  });
  const { origin, step } = meta.probes;
  const occlusion = new SkyOcclusion(origin[0], origin[1], origin[0] + step[0] * (nx - 1), origin[1] + step[1] * (ny - 1));
  const dispose = () => {
    for (const t of [lightmap, ...probes]) t.dispose();
    occlusion.dispose();
  };
  return { meta, lightmap, probes, occlusion, dispose };
}

// A pose in a matrix's elements (column-major): the rotation's columns and the translation (12 to 14).
const POSE = [0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14];

/**
 * Whether meshes moved: `changed(movers, hz)` is true when any pose (or the set of meshes) differs from the
 * last time it was true, at most `hz` times a second. What only needs drawing again when something moved
 * (the sky occlusion map, the sun's shadow map) asks it each frame.
 */
export class MotionWatch {
  changed(movers, hz = 30) {
    const now = performance.now();
    if (this.poses && now - this.last < 1000 / hz) return false;
    const n = POSE.length * movers.length;
    let moved = false;
    if (this.poses?.length !== n) {
      this.poses = new Float32Array(n);
      moved = true;
    }
    for (let k = 0; k < movers.length; k++) {
      const e = movers[k].matrix.elements;
      for (let j = 0; j < POSE.length; j++) {
        const v = e[POSE[j]]; // shown or not: a hidden shape stands for a model drawn on it
        if (Math.abs(v - this.poses[POSE.length * k + j]) > 1e-4) {
          this.poses[POSE.length * k + j] = v;
          moved = true;
        }
      }
    }
    if (moved) this.last = now;
    return moved;
  }

  invalidate() {
    this.poses = null;
  }
}

/**
 * What moves, drawn from straight above into a small map: whether it covers each texel (red), the height
 * of its top there (green) and of its bottom (blue, as CEILING minus the height), all three kept by a max
 * blend in one pass and zero where nothing is. Mipmapped, so a surface reads the coverage and the mean top
 * and bottom over any footprint in one lookup.
 */
export class SkyOcclusion {
  constructor(x0, y0, x1, y1, size = 512) {
    const pad = 0.3;
    [x0, y0, x1, y1] = [x0 - pad, y0 - pad, x1 + pad, y1 + pad];
    this.target = new THREE.WebGLRenderTarget(size, size, {
      type: THREE.HalfFloatType,
      generateMipmaps: true,
      minFilter: THREE.LinearMipmapLinearFilter,
      magFilter: THREE.LinearFilter,
    });
    this.camera = new THREE.OrthographicCamera(x0, x1, y1, y0, 0.05, 4);
    this.camera.position.set(0, 0, 3.5);
    this.camera.up.set(0, 1, 0);
    this.camera.lookAt(0, 0, 0);
    this.camera.updateMatrixWorld();
    this.camera.layers.set(OCCLUSION_LAYER);
    this.material = new THREE.ShaderMaterial({
      vertexShader: /* glsl */ `
        varying float vZ;
        void main() {
          vec4 w = modelMatrix * vec4( position, 1.0 );
          vZ = w.z;
          gl_Position = projectionMatrix * viewMatrix * w;
        }`,
      fragmentShader: /* glsl */ `
        varying float vZ;
        void main() { gl_FragColor = vec4( 1.0, max( vZ, 0.0 ), ${CEILING.toFixed(1)} - vZ, 1.0 ); }`,
      side: THREE.DoubleSide,
      depthTest: false,
      depthWrite: false,
      blending: THREE.CustomBlending,
      blendEquation: THREE.MaxEquation,
      blendSrc: THREE.OneFactor,
      blendDst: THREE.OneFactor,
    });
    this.uniforms = {
      skyMap: { value: this.target.texture },
      skyRect: { value: new THREE.Vector4(x0, y0, 1 / (x1 - x0), 1 / (y1 - y0)) },
      skyTexel: { value: (x1 - x0) / size },
      skyStrength: { value: 0.7 },
    };
    this.clear = new THREE.Color();
    this.watch = new MotionWatch();
  }

  /**
   * Draw the moving meshes (those on OCCLUSION_LAYER) into the map when any of `movers` has moved since
   * the last time, at most `hz` times a second: soft shade a frame late is not seen, and a still scene
   * costs nothing.
   */
  update(renderer, scene, movers, hz = 30) {
    if (!this.watch.changed(movers, hz)) return;
    this.drawn = performance.now();
    const { overrideMaterial, background } = scene;
    const target = renderer.getRenderTarget();
    renderer.getClearColor(this.clear);
    const alpha = renderer.getClearAlpha();
    scene.overrideMaterial = this.material;
    scene.background = null;
    renderer.setRenderTarget(this.target);
    renderer.setClearColor(0x000000, 0);
    renderer.clear();
    renderer.render(scene, this.camera);
    renderer.setRenderTarget(target);
    renderer.setClearColor(this.clear, alpha);
    scene.overrideMaterial = overrideMaterial;
    scene.background = background;
  }

  /** Draw again at the next update, moved or not (after the style or the scene changed). */
  invalidate() {
    this.watch.invalidate();
  }

  dispose() {
    this.target.dispose();
    this.material.dispose();
  }
}

const LUMA = "vec3( 0.2126, 0.7152, 0.0722 )";
// Irradiance over pi under the open sky (tools/bake_light.mjs): where a surface gets this much or more,
// it reflects the room in full.
const OPEN = "0.75";

const COMMON = /* glsl */ `
varying vec3 vBakedPos;
uniform sampler2D skyMap;
uniform vec4 skyRect;
uniform float skyTexel;
uniform float skyStrength;
// The share of the sky that what moves hides from a surface at p facing n. Round about (30 cm), the movers'
// mean top and bottom: how far above p the nearest of them is (their bottom when all of them is above p,
// half their height above it when they stand beside it); then their coverage within cones of that
// distance, as an overcast sky is hidden by a slab above.
float skyOcclusion( vec3 p, vec3 n ) {
	vec2 uv = ( p.xy - skyRect.xy ) * skyRect.zw;
	if ( uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0 || n.z < -0.5 ) return 0.0;
	vec3 near = textureLod( skyMap, uv, log2( 0.3 / skyTexel ) ).rgb;
	if ( near.r < 0.002 ) return 0.0;
	float top = near.g / near.r - p.z;
	if ( top < 0.01 ) return 0.0;
	float bottom = ${CEILING.toFixed(1)} - near.b / near.r - p.z;
	float h = clamp( bottom > 0.01 ? bottom : 0.5 * top, 0.01, 1.0 );
	float inner = textureLod( skyMap, uv, max( 0.0, log2( 2.0 * h / skyTexel ) ) ).r;
	float outer = textureLod( skyMap, uv, max( 0.0, log2( 6.0 * h / skyTexel ) ) ).r;
	return ( 0.65 * inner + 0.35 * outer ) * smoothstep( 0.01, 0.04, top ) * ( 0.6 + 0.4 * n.z );
}`;

// three.js's light-map and environment chunk: the sky occlusion of what moves on the light map or on the
// probes, the environment's diffuse light left out where those give it, and the environment's reflections
// dimmed by them.
const MAPS_CHUNK = THREE.ShaderChunk.lights_fragment_maps
  .replace(
    "#if defined( RE_IndirectDiffuse )",
    `#if defined( RE_IndirectDiffuse )
	vec3 bakedNormal = inverseTransformDirection( geometryNormal, viewMatrix );
	float skySeen = 1.0 - skyStrength * skyOcclusion( vBakedPos, bakedNormal );
	#if defined( USE_PROBES )
		vec3 probeE = probeIrradiance( vBakedPos, bakedNormal ) * skySeen;
		irradiance += probeE;
	#endif`,
  )
  .replace("vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;", "vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity * skySeen;")
  .replace(
    "iblIrradiance += getIBLIrradiance( geometryNormal );",
    `#if !defined( USE_PROBES ) && !defined( USE_LIGHTMAP )
				iblIrradiance += getIBLIrradiance( geometryNormal );
			#endif`,
  )
  .replace(
    "radiance += iblRadiance;",
    `#if defined( USE_PROBES )
		iblRadiance *= clamp( dot( probeE, ${LUMA} ) / ( PI * ${OPEN} ), 0.0, 1.0 );
	#elif defined( USE_LIGHTMAP )
		iblRadiance *= clamp( dot( lightMapIrradiance, ${LUMA} ) / ( PI * ${OPEN} ), 0.0, 1.0 );
	#endif
	radiance += iblRadiance;`,
  );
if (MAPS_CHUNK.split("skySeen").length !== 4 || !MAPS_CHUNK.includes("!defined( USE_LIGHTMAP )")) {
  console.warn("baked.js: three.js's lights_fragment_maps changed; baked light may look wrong");
}

/** The world position, for the probes and the sky occlusion. */
function withPosition(shader, extra = "") {
  shader.vertexShader = shader.vertexShader
    .replace("#include <common>", "#include <common>\nvarying vec3 vBakedPos;")
    .replace("#include <project_vertex>", "#include <project_vertex>\n\tvBakedPos = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;");
  shader.fragmentShader = shader.fragmentShader.replace("#include <common>", `#include <common>\n${COMMON}\n${extra}`).replace("#include <lights_fragment_maps>", MAPS_CHUNK);
}

/** A scenery material (with "uv1"): its light map instead of the environment's diffuse light. */
export function bakeScenery(material, bake) {
  material.lightMap = bake.lightmap;
  material.lightMapIntensity = Math.PI * bake.meta.scale;
  material.onBeforeCompile = (shader) => {
    Object.assign(shader.uniforms, bake.occlusion.uniforms);
    withPosition(shader);
  };
  material.customProgramCacheKey = () => "baked-scenery";
  material.needsUpdate = true;
}

/** A moving thing's material: diffuse light from the probes at each fragment's place. */
export function bakeMoving(material, bake) {
  const { origin, step, dims } = bake.meta.probes;
  const uniforms = {
    probeTex: { value: bake.probes },
    probeOrigin: { value: new THREE.Vector3(...origin) },
    probeSpan: { value: new THREE.Vector3(step[0] * (dims[0] - 1), step[1] * (dims[1] - 1), step[2] * (dims[2] - 1)) },
    probeDims: { value: new THREE.Vector3(...dims) },
    probeScale: { value: Math.PI * bake.meta.scale },
  };
  material.onBeforeCompile = (shader) => {
    Object.assign(shader.uniforms, uniforms, bake.occlusion.uniforms);
    shader.defines = { ...shader.defines, USE_PROBES: "" };
    withPosition(
      shader,
      /* glsl */ `
uniform highp sampler3D probeTex[ 6 ];
uniform vec3 probeOrigin;
uniform vec3 probeSpan;
uniform vec3 probeDims;
uniform float probeScale;
// Irradiance at p for a surface facing n: the six directions' irradiance, weighted by n squared (an
// ambient cube), looked up a little off the surface, so that a probe behind it counts less.
vec3 probeIrradiance( vec3 p, vec3 n ) {
	vec3 g = clamp( ( p + n * 0.06 - probeOrigin ) / probeSpan, 0.0, 1.0 );
	vec3 t = ( g * ( probeDims - 1.0 ) + 0.5 ) / probeDims;
	vec3 w = n * n;
	vec3 e = w.x * ( n.x > 0.0 ? texture( probeTex[ 0 ], t ).rgb : texture( probeTex[ 1 ], t ).rgb )
		+ w.y * ( n.y > 0.0 ? texture( probeTex[ 2 ], t ).rgb : texture( probeTex[ 3 ], t ).rgb )
		+ w.z * ( n.z > 0.0 ? texture( probeTex[ 4 ], t ).rgb : texture( probeTex[ 5 ], t ).rgb );
	return e * probeScale;
}`,
    );
  };
  material.customProgramCacheKey = () => "baked-moving";
  material.needsUpdate = true;
}