roamwright 0.61.28 → 0.61.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,7 @@
6
6
  import * as THREE from 'three';
7
7
  import { stillMesh } from './still-mesh.js';
8
8
  import { box, TRS } from './primitives.js';
9
+ import { flatNormals, flattenInPlace, padParts, padded } from './part-ops.js';
9
10
 
10
11
  // ════════════════════════════════════════════════════════════════════════
11
12
  // Geometry toolkit: a builder that merges many coloured parts into one geometry (GB), the geometry of what it filled
@@ -114,17 +115,6 @@ function withRoom(array, room, used) {
114
115
  const normalByte = component => Math.round(component * 127),
115
116
  colourByte = component => Math.min(255, Math.round(component * 255)),
116
117
  OPAQUE = 255; // a padded colour's fourth byte: an alpha of one
117
- // The first `count` bytes of three to a vertex, four to a vertex: the three and then `fourth`
118
- function padded(bytes, count, fourth) {
119
- const out = new bytes.constructor((count / 3) * 4);
120
- for (let i = 0, writeOffset = 0; i < count; i += 3, writeOffset += 4) {
121
- out[writeOffset] = bytes[i];
122
- out[writeOffset + 1] = bytes[i + 1];
123
- out[writeOffset + 2] = bytes[i + 2];
124
- out[writeOffset + 3] = fourth;
125
- }
126
- return out;
127
- }
128
118
  /**
129
119
  * Accumulate coloured primitives and triangles in one set of vertex buffers.
130
120
  * Import this class as `GeometryBuilder` from the package root. Use `parts`
@@ -484,6 +474,11 @@ class GB {
484
474
  }
485
475
  }
486
476
  }
477
+ /** Replace every non-indexed triangle's vertex normals with its unit face normal in place. */
478
+ flatten() {
479
+ flattenInPlace(this.positions, this.normals, this.normalBytes, this.count);
480
+ return this;
481
+ }
487
482
  /**
488
483
  * Copy the filled attributes into right-sized typed arrays for `geometryOf`.
489
484
  * The arrays can be transferred to another thread. The builder retains its own storage.
@@ -553,4 +548,4 @@ class GB {
553
548
  }
554
549
  }
555
550
 
556
- export { GB, geometryOf, geometryView, meshOf, releaseArray, sphereOf, stillMesh };
551
+ export { GB, flatNormals, geometryOf, geometryView, meshOf, padParts, releaseArray, sphereOf, stillMesh };
package/geometry/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  // ── Context, math & core geometry ────────────────────────────────────────
7
- export { GB as GeometryBuilder, geometryOf } from './builder.js';
7
+ export { GB as GeometryBuilder, flatNormals, geometryOf, padParts } from './builder.js';
8
8
  export { stillMesh } from './still-mesh.js';
9
9
  export { createUnitShapes, createFigureUnitShapes } from './primitives.js';
10
10
 
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Typed-array part operations shared with GeometryBuilder: four-byte GPU padding and per-triangle flat face normals.
3
+ * @module
4
+ */
5
+
6
+ const PART_ATTRIBUTES = { position: 3, normal: 3, color: 3, aTag: 1, skinIndex: 4, skinWeight: 4 };
7
+ const OPAQUE = 255;
8
+ const normalByte = component => Math.round(component * 127);
9
+
10
+ /** Pad `count` three-byte vertex entries into four-byte strides using `fourth` for the added lane. */
11
+ export function padded(bytes, count, fourth) {
12
+ const out = new bytes.constructor((count / 3) * 4);
13
+ for (let i = 0, writeOffset = 0; i < count; i += 3, writeOffset += 4) {
14
+ out[writeOffset] = bytes[i];
15
+ out[writeOffset + 1] = bytes[i + 1];
16
+ out[writeOffset + 2] = bytes[i + 2];
17
+ out[writeOffset + 3] = fourth;
18
+ }
19
+ return out;
20
+ }
21
+
22
+ /**
23
+ * Pad three-byte compact normal and colour arrays in `parts` to four bytes per vertex (opaque alpha 255)
24
+ * so GPU buffers align on four-byte strides and share vertex-alpha programs with padded settlement blocks.
25
+ * Already padded or float arrays are returned unchanged.
26
+ *
27
+ * @param {object} parts Typed-array part record from `GB.parts()`.
28
+ * @returns {object}
29
+ */
30
+ export function padParts(parts) {
31
+ const count = parts?.position?.length ?? 0;
32
+ if (!count) return parts;
33
+ const padNormal = parts.normal instanceof Int8Array && parts.normal.length === count;
34
+ const padColor = parts.color instanceof Uint8Array && parts.color.length === count;
35
+ if (!padNormal && !padColor) return parts;
36
+ return {
37
+ ...parts,
38
+ normal: padNormal ? padded(parts.normal, count, 0) : parts.normal,
39
+ color: padColor ? padded(parts.color, count, OPAQUE) : parts.color,
40
+ };
41
+ }
42
+
43
+ /**
44
+ * Replace vertex normals in `parts` with per-triangle unit face normals so faceted geometry renders flat without
45
+ * compiling a separate `FLAT_SHADED` shader program. De-indexes indexed parts so adjacent faces never share normals.
46
+ * Supports float normals as well as three- and four-byte compact `Int8Array` normals.
47
+ *
48
+ * @param {object} parts Typed-array part record from `GB.parts()`.
49
+ * @returns {object}
50
+ */
51
+ export function flatNormals(parts) {
52
+ const srcPos = parts?.position;
53
+ if (!srcPos?.length) return parts;
54
+ let out = parts;
55
+ if (parts.index) {
56
+ const idx = parts.index,
57
+ nVerts = idx.length,
58
+ srcVerts = srcPos.length / 3;
59
+ out = { ...parts, index: undefined };
60
+ delete out.index;
61
+ for (const name in PART_ATTRIBUTES) {
62
+ const array = parts[name];
63
+ if (!array) continue;
64
+ const stride = array.length / srcVerts,
65
+ expanded = new array.constructor(nVerts * stride);
66
+ for (let i = 0; i < nVerts; i++) {
67
+ const from = idx[i] * stride,
68
+ to = i * stride;
69
+ for (let k = 0; k < stride; k++) expanded[to + k] = array[from + k];
70
+ }
71
+ out[name] = expanded;
72
+ }
73
+ }
74
+ const pos = out.position,
75
+ srcNorm = out.normal;
76
+ if (!srcNorm) return out;
77
+ const verts = pos.length / 3,
78
+ stride = srcNorm.length / verts,
79
+ isByte = srcNorm instanceof Int8Array,
80
+ normals = new srcNorm.constructor(srcNorm.length);
81
+ for (let t = 0; t < verts; t += 3) {
82
+ const p0 = t * 3,
83
+ p1 = p0 + 3,
84
+ p2 = p0 + 6;
85
+ const ax = pos[p1] - pos[p0],
86
+ ay = pos[p1 + 1] - pos[p0 + 1],
87
+ az = pos[p1 + 2] - pos[p0 + 2];
88
+ const bx = pos[p2] - pos[p0],
89
+ by = pos[p2 + 1] - pos[p0 + 1],
90
+ bz = pos[p2 + 2] - pos[p0 + 2];
91
+ let nx = ay * bz - az * by,
92
+ ny = az * bx - ax * bz,
93
+ nz = ax * by - ay * bx;
94
+ const len = Math.hypot(nx, ny, nz);
95
+ if (len > 0) {
96
+ nx /= len;
97
+ ny /= len;
98
+ nz /= len;
99
+ } else {
100
+ nx = 0;
101
+ ny = 1;
102
+ nz = 0;
103
+ }
104
+ const wx = isByte ? normalByte(nx) : nx,
105
+ wy = isByte ? normalByte(ny) : ny,
106
+ wz = isByte ? normalByte(nz) : nz;
107
+ for (let k = 0; k < 3; k++) {
108
+ const at = (t + k) * stride;
109
+ normals[at] = wx;
110
+ normals[at + 1] = wy;
111
+ normals[at + 2] = wz;
112
+ if (stride === 4) normals[at + 3] = 0;
113
+ }
114
+ }
115
+ return { ...out, normal: normals };
116
+ }
117
+
118
+ /** Replace non-indexed triangle float and byte normals in place with per-triangle unit face normals. */
119
+ export function flattenInPlace(positions, normals, normalBytes, count) {
120
+ for (let i = 0; i + 8 < count; i += 9) {
121
+ const ax = positions[i + 3] - positions[i],
122
+ ay = positions[i + 4] - positions[i + 1],
123
+ az = positions[i + 5] - positions[i + 2];
124
+ const bx = positions[i + 6] - positions[i],
125
+ by = positions[i + 7] - positions[i + 1],
126
+ bz = positions[i + 8] - positions[i + 2];
127
+ let nx = ay * bz - az * by,
128
+ ny = az * bx - ax * bz,
129
+ nz = ax * by - ay * bx;
130
+ const len = Math.hypot(nx, ny, nz);
131
+ if (len > 0) {
132
+ nx /= len;
133
+ ny /= len;
134
+ nz /= len;
135
+ } else {
136
+ nx = 0;
137
+ ny = 1;
138
+ nz = 0;
139
+ }
140
+ const bxn = normalByte(nx),
141
+ byn = normalByte(ny),
142
+ bzn = normalByte(nz);
143
+ for (let k = 0; k < 9; k += 3) {
144
+ normals[i + k] = nx;
145
+ normals[i + k + 1] = ny;
146
+ normals[i + k + 2] = nz;
147
+ normalBytes[i + k] = bxn;
148
+ normalBytes[i + k + 1] = byn;
149
+ normalBytes[i + k + 2] = bzn;
150
+ }
151
+ }
152
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.61.28",
3
+ "version": "0.61.29",
4
4
  "description": "A procedural worldbuilding engine built on top of Three.js. Generate landscapes with rivers and changing weather, animate crowds, and explore on foot or in flight.",
5
5
  "keywords": [
6
6
  "threejs",
@@ -109,6 +109,8 @@ export function createLongFlierCompany({
109
109
  opacity: 0.3,
110
110
  depthWrite: false,
111
111
  side: THREE.DoubleSide,
112
+ // Flat translucent wing blades have no closed back/front overlap, so one pass avoids a duplicate FLIP_SIDED program.
113
+ forceSinglePass: true,
112
114
  }),
113
115
  key + ':wings',
114
116
  time,
@@ -179,46 +179,51 @@ export function createFlock({
179
179
  }) {
180
180
  const bird = !!look,
181
181
  geometry = bird ? birdGeometry(look) : plainBirdGeometry(),
182
- flap = bird ? new THREE.InstancedBufferAttribute(new Float32Array(n * 2), 2) : null;
183
- if (flap) geometry.setAttribute('aFlap', flap.setUsage(THREE.DynamicDrawUsage));
182
+ verts = geometry.attributes.position.count,
183
+ flap = new THREE.InstancedBufferAttribute(new Float32Array(n * 2), 2);
184
+ if (bird) flap.setUsage(THREE.DynamicDrawUsage);
185
+ geometry.setAttribute('aFlap', flap);
186
+ if (!geometry.attributes.color) geometry.setAttribute('color', new THREE.Float32BufferAttribute(new Float32Array(verts * 3).fill(1), 3));
187
+ if (!geometry.attributes.aUnder) geometry.setAttribute('aUnder', new THREE.Float32BufferAttribute(new Float32Array(verts * 4), 4));
184
188
  const coloured = bird && !!look.colours,
185
- under = bird && !!look.under,
186
189
  material = new THREE.MeshStandardMaterial({
187
190
  color: coloured ? 0xffffff : bird ? plumage(color, least) : color,
188
- vertexColors: coloured,
191
+ vertexColors: true,
189
192
  roughness: (bird && look.gloss) || roughness,
190
193
  side: THREE.DoubleSide,
191
194
  flatShading: true,
192
195
  });
193
196
  material.onBeforeCompile = sh => {
194
197
  sh.uniforms.uTime = time;
195
- if (bird) sh.uniforms.uBeat = { value: look.beat * TAU };
198
+ sh.uniforms.uBeat = { value: bird ? look.beat * TAU : 0 };
199
+ sh.uniforms.uPlain = { value: bird ? 0 : 1 };
196
200
  sh.vertexShader = sh.vertexShader
197
201
  .replace(
198
202
  '#include <common>',
199
- '#include <common>\nattribute float aW; uniform float uTime;' +
200
- (bird ? ' attribute vec2 aFlap; uniform float uBeat;' : '') +
201
- (under ? UNDER_HEAD : ''),
203
+ '#include <common>\nattribute float aW; uniform float uTime; attribute vec2 aFlap; uniform float uBeat; uniform float uPlain;' +
204
+ UNDER_HEAD,
202
205
  )
203
206
  .replace(
204
207
  '#include <begin_vertex>',
205
- bird
206
- ? '#include <begin_vertex>' + BEAT + (under ? '\n vUnder = aUnder;' : '')
207
- : `/* glsl */
208
+ `/* glsl */
208
209
  #include <begin_vertex>
209
- #ifdef USE_INSTANCING
210
- float ph = instanceMatrix[3].x * 0.31 + instanceMatrix[3].z * 0.17;
211
- #else
212
- float ph = 0.0;
213
- #endif
214
- transformed.y += aW * sin(uTime * 5.5 + ph) * 0.75;`,
210
+ if (uPlain > 0.5) {
211
+ #ifdef USE_INSTANCING
212
+ float ph = instanceMatrix[3].x * 0.31 + instanceMatrix[3].z * 0.17;
213
+ #else
214
+ float ph = 0.0;
215
+ #endif
216
+ transformed.y += aW * sin(uTime * 5.5 + ph) * 0.75;
217
+ } else {${BEAT}
218
+ }
219
+ vUnder = aUnder;`,
215
220
  );
216
- if (under)
217
- sh.fragmentShader = sh.fragmentShader
218
- .replace('#include <common>', '#include <common>\nvarying vec4 vUnder;')
219
- .replace('#include <color_fragment>', '#include <color_fragment>' + UNDER);
221
+ sh.fragmentShader = sh.fragmentShader
222
+ .replace('#include <common>', '#include <common>\nvarying vec4 vUnder;')
223
+ .replace('#include <color_fragment>', '#include <color_fragment>' + UNDER);
220
224
  };
221
- material.customProgramCacheKey = () => 'flock:' + key + (coloured ? ':coloured' : '') + (under ? ':under' : '');
225
+ const cacheKey = key === 'bird' || key === 'plain' ? 'flock' : 'flock:' + key;
226
+ material.customProgramCacheKey = () => cacheKey;
222
227
  const mesh = new THREE.InstancedMesh(geometry, material, n);
223
228
  mesh.frustumCulled = false;
224
229
  const birds = [];
@@ -51,16 +51,16 @@ export function createHeightProbe(renderer, scene, { layer, size, above, below,
51
51
  }
52
52
 
53
53
  function depth() {
54
- return (depthMaterial ??= new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking }));
54
+ return (depthMaterial ??= new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, side: THREE.DoubleSide }));
55
55
  }
56
56
 
57
- // Prepare the same depth override as a measurement. The probe includes every visible light
58
- // on its reserved layer, and preserves scene fog when rendering the override.
57
+ // Prepare the same depth override as a measurement (double-sided and without fog so depth
58
+ // programs are shared with sky-occlusion passes).
59
59
  function warm(root, warmStandIns) {
60
60
  const previous = view.layers.mask;
61
61
  view.layers.enableAll();
62
62
  try {
63
- const geometry = warmStandIns(root, object => solidMesh(object) && depth(), view, undefined, scene.fog, true);
63
+ const geometry = warmStandIns(root, object => solidMesh(object) && depth(), view, undefined, null, true);
64
64
  return useQueries ? Promise.all([geometry, depthResult().warm()]) : geometry;
65
65
  } finally {
66
66
  view.layers.mask = previous;
@@ -80,6 +80,7 @@ export function createHeightProbe(renderer, scene, { layer, size, above, below,
80
80
  mip = renderer.getActiveMipmapLevel();
81
81
  const alpha = renderer.getClearAlpha(),
82
82
  background = scene.background,
83
+ fog = scene.fog,
83
84
  override = scene.overrideMaterial;
84
85
  const { autoUpdate, needsUpdate } = renderer.shadowMap;
85
86
  renderer.getClearColor(clear);
@@ -88,6 +89,7 @@ export function createHeightProbe(renderer, scene, { layer, size, above, below,
88
89
  scene.traverse(select);
89
90
  scene.overrideMaterial = depth();
90
91
  scene.background = null;
92
+ scene.fog = null;
91
93
  renderer.shadowMap.autoUpdate = renderer.shadowMap.needsUpdate = false;
92
94
  renderer.setRenderTarget(target);
93
95
  renderer.setClearColor(0xffffff, 1);
@@ -99,6 +101,7 @@ export function createHeightProbe(renderer, scene, { layer, size, above, below,
99
101
  renderer.setClearColor(clear, alpha);
100
102
  scene.overrideMaterial = override;
101
103
  scene.background = background;
104
+ scene.fog = fog;
102
105
  renderer.shadowMap.autoUpdate = autoUpdate;
103
106
  renderer.shadowMap.needsUpdate = needsUpdate;
104
107
  for (let i = 0; i < prevLayers.length; i += 2) prevLayers[i].layers.mask = prevLayers[i + 1];
@@ -1,9 +1,10 @@
1
1
  // A house kit's arrays as meshes: one mesh to a kind, instanced copies of them, or the cells of a cut kit as batches that
2
2
  // cull cell by cell and are written to the graphics card a frame's share at a time.
3
3
  import * as THREE from 'three';
4
- import { geometryOf } from '../geometry/builder.js';
4
+ import { geometryOf, padParts } from '../geometry/builder.js';
5
5
  import { KIT_KEYS } from '../geometry/house-kit-frame.js';
6
6
  import { markStill } from './still-casters.js';
7
+ import { whiteInstanceColor } from './material-lod.js';
7
8
  import { createHandOver } from '../runtime/hand-over.js';
8
9
 
9
10
  const SYNC_HAND_OVER = createHandOver({ painted: () => Promise.resolve(), frameShare: () => Infinity });
@@ -63,7 +64,8 @@ export function createHouseKitMaterials({
63
64
  * @param {() => boolean} [o.worldDrawn] Whether the world has been drawn yet: until it has, steps written to the card
64
65
  * run all at once (behind a loading bar) rather than paced.
65
66
  * @param {object} [o.handOver] The renderer's hand-over (`createHandOver`): `paced`, `drain` and `heldBytes`; defaults to a synchronous hand-over.
66
- * @returns {object} `materials` (the resolved material map), `kitStatic(kit, parent, materialOf)`, `kitMeshes(parts, parent, materialOf)`,
67
+ * @param {boolean} [o.padded=false] Pad three-byte compact normal and colour arrays of static kit meshes and cells to four bytes per vertex, matching padded settlement-quarter blocks so both share one WebGL program per material.
68
+ * @returns {object} `materials` (the resolved material map), `kitStatic(kit, parent, materialOf, pad)`, `kitMeshes(parts, parent, materialOf, pad)`,
67
69
  * `instancedOf(meshes, n, group)`, `kitInstanced(kit, n, group)`, `cellPieces(cellsOfKinds, parent, far, detail, materialOf)`,
68
70
  * `pieceSwitch(batch, id)`, and `toCard(steps, signal)`.
69
71
  */
@@ -73,23 +75,25 @@ export function createHouseKitMeshes({
73
75
  instancedMaterial = m => m,
74
76
  worldDrawn = () => true,
75
77
  handOver = SYNC_HAND_OVER,
78
+ padded = false,
79
+ tinted = false,
76
80
  } = {}) {
77
81
  const { drain, heldBytes, paced } = handOver,
78
82
  ownMaterial = k => materials[k];
79
83
 
80
84
  // A filled kit as meshes, one to a kind, and the kit let go; materialOf(kind) gives each kind's material, where a place has
81
85
  // stone of its own.
82
- function kitStatic(B, parent, materialOf) {
83
- const parts = KIT_KEYS.map(k => B[k].parts(true));
86
+ function kitStatic(B, parent, materialOf, pad = padded) {
87
+ const parts = KIT_KEYS.map(k => B[k].parts(true, pad));
84
88
  for (const k of KIT_KEYS) B[k].release();
85
- return kitMeshes(parts, parent, materialOf);
89
+ return kitMeshes(parts, parent, materialOf, pad);
86
90
  }
87
91
  // A kit's arrays (GB.parts, a kind to each of KIT_KEYS) as meshes, one to a kind that has any.
88
- function kitMeshes(parts, parent, materialOf = ownMaterial) {
92
+ function kitMeshes(parts, parent, materialOf = ownMaterial, pad = padded) {
89
93
  const out = [];
90
94
  KIT_KEYS.forEach((k, kind) => {
91
95
  if (!parts[kind].position.length) return;
92
- const m = new THREE.Mesh(geometryOf(parts[kind]), materialOf(k));
96
+ const m = new THREE.Mesh(geometryOf(pad ? padParts(parts[kind]) : parts[kind]), materialOf(k));
93
97
  m.castShadow = k !== 'glass' && k !== 'trim' && k !== 'stain';
94
98
  if (m.castShadow) markStill(m); // put in place once (still-casters.js)
95
99
  m.receiveShadow = k !== 'stain';
@@ -105,6 +109,7 @@ export function createHouseKitMeshes({
105
109
  function instancedOf(meshes, n, group) {
106
110
  return meshes.map(mesh => {
107
111
  const many = new THREE.InstancedMesh(mesh.geometry, instancedMaterial(mesh.material), n);
112
+ if (tinted) whiteInstanceColor(many);
108
113
  many.frustumCulled = false;
109
114
  many.castShadow = many.receiveShadow = true;
110
115
  many.count = 0;
@@ -114,8 +119,8 @@ export function createHouseKitMeshes({
114
119
  return many;
115
120
  });
116
121
  }
117
- // A filled kit as instanced meshes of up to n under group (instancedOf); the kit is let go.
118
- const kitInstanced = (B, n, group) => instancedOf(kitStatic(B, new THREE.Group()), n, group);
122
+ // A filled kit as instanced meshes of up to n under group (instancedOf); kept unpadded so instanced props share 3-byte colour programs with other instanced meshes.
123
+ const kitInstanced = (B, n, group) => instancedOf(kitStatic(B, new THREE.Group(), undefined, false), n, group);
119
124
  // Runs steps that write to the card (cellPieces, or a place's near detail made of them): no faster than the hand-over lets a
120
125
  // frame take once the world is drawn, and all at once while the page is still loading behind its bar, where pacing would
121
126
  // only lengthen the wait. The promise gives what the steps return.
@@ -147,7 +152,7 @@ export function createHouseKitMeshes({
147
152
  batches[small] = batch;
148
153
  }
149
154
  for (const c of cells) {
150
- const geometry = geometryOf(c.parts, c.sphere),
155
+ const geometry = geometryOf(padded ? padParts(c.parts) : c.parts, c.sphere),
151
156
  bytes = bytesOf(geometry),
152
157
  batch = batches[c.small],
153
158
  id = batch.add(geometry);
@@ -18,6 +18,8 @@ export function createLampWashMaterial({ night, cacheKey = 'lamp-wash' }) {
18
18
  depthWrite: false,
19
19
  fog: false,
20
20
  side: THREE.DoubleSide, // the fans wind either way, as the wall faces
21
+ // Additive blending is commutative regardless of face order, so one pass avoids a duplicate FLIP_SIDED compile.
22
+ forceSinglePass: true,
21
23
  polygonOffset: true,
22
24
  polygonOffsetFactor: -2,
23
25
  polygonOffsetUnits: -2,
@@ -8,27 +8,30 @@ const SCATTER = 'fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056,
8
8
  // A copy of a material that draws only a share of its pixels (share.value, from 0 to 1), scattered evenly: a house built in detail dissolves in over its far version instead of jumping into place, and out again
9
9
  // when it is let go. One copy to a material and share (a land's own stone has its own); all share one program.
10
10
  const fadings = new WeakMap();
11
+ const rawFading = new WeakMap();
11
12
  export function fadingOf(base, share) {
12
- let variants = fadings.get(base);
13
- if (!variants) fadings.set(base, (variants = new Map()));
13
+ const raw = rawFading.get(base) ?? base;
14
+ let variants = fadings.get(raw);
15
+ if (!variants) fadings.set(raw, (variants = new Map()));
14
16
  let variant = variants.get(share);
15
17
  if (variant) return variant;
16
- variants.set(share, (variant = base.clone()));
18
+ variants.set(share, (variant = raw.clone()));
19
+ rawFading.set(variant, raw);
17
20
  variant.onBeforeCompile = (shader, renderer) => {
18
- base.onBeforeCompile(shader, renderer);
21
+ raw.onBeforeCompile(shader, renderer);
19
22
  shader.uniforms.uShare = share;
20
23
  shader.fragmentShader = shader.fragmentShader
21
24
  .replace('#include <common>', '#include <common>\nuniform float uShare;')
22
25
  .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>\nif (${SCATTER} > uShare) discard;`);
23
26
  };
24
- variant.customProgramCacheKey = () => base.customProgramCacheKey() + ':dissolving';
27
+ variant.customProgramCacheKey = () => raw.customProgramCacheKey() + ':dissolving';
25
28
  return variant;
26
29
  }
27
30
  // A copy of a material that draws only what lies nearer the eye than `reach.value` metres or, with `beyond`, only what lies
28
31
  // further: a thing's near version and its far one hand over pixel by pixel across a band `band` metres deep about that distance,
29
32
  // each drawing the pixels of the screen-fixed scatter (SCATTER) the other leaves, a share that follows the pixel's distance. No
30
33
  // pixel is drawn by both, none by neither, and no stretch of the thing changes all at once. One copy to a material, reach, side
31
- // and band; the two sides share one program each.
34
+ // and band; both sides and all bands share one program via `uBeyond` and `uHalfBand`.
32
35
  const reaching = new WeakMap();
33
36
  export function reachOf(base, reach, beyond = false, band = 1) {
34
37
  let variants = reaching.get(base);
@@ -37,59 +40,64 @@ export function reachOf(base, reach, beyond = false, band = 1) {
37
40
  let sides = variants.get(reach);
38
41
  if (!sides) variants.set(reach, (sides = {}));
39
42
  if (sides[key]) return sides[key];
40
- const variant = (sides[key] = base.clone());
43
+ const variant = (sides[key] = base.clone()),
44
+ beyondUniform = { value: beyond ? 1 : 0 },
45
+ halfBandUniform = { value: band * 0.5 };
41
46
  variant.onBeforeCompile = (shader, renderer) => {
42
47
  base.onBeforeCompile(shader, renderer);
43
48
  shader.uniforms.uReach = reach;
49
+ shader.uniforms.uBeyond = beyondUniform;
50
+ shader.uniforms.uHalfBand = halfBandUniform;
44
51
  shader.fragmentShader = shader.fragmentShader
45
- .replace('#include <common>', '#include <common>\nuniform float uReach;')
52
+ .replace('#include <common>', '#include <common>\nuniform float uReach;\nuniform float uBeyond;\nuniform float uHalfBand;')
46
53
  .replace(
47
54
  '#include <clipping_planes_fragment>',
48
- `#include <clipping_planes_fragment>\n${handedOver(beyond, nearShare('length(vViewPosition)', band))}`,
55
+ `#include <clipping_planes_fragment>\n{ float rwNear = 1.0 - smoothstep(uReach - uHalfBand, uReach + uHalfBand, length(vViewPosition));\n${handedOver('rwNear')} }`,
49
56
  );
50
57
  };
51
- variant.customProgramCacheKey = () => base.customProgramCacheKey() + (beyond ? ':beyond-reach:' : ':within-reach:') + band;
58
+ variant.customProgramCacheKey = () => base.customProgramCacheKey() + ':reach';
52
59
  return variant;
53
60
  }
54
61
  // The same for the instances of an InstancedMesh, each handed over whole and in its own time, using its geometry's `aNear` (an instanced attribute, 0 to 1) is the near version's share of the instance's
55
62
  // pixels, which its builder moves from the one end to the other over a moment once the viewer comes within or goes beyond its
56
63
  // reach. An instance its version does not draw at all has its vertices put out of sight. handOverShadow gives the near or far
57
64
  // version's shadow body, which casts wherever its version draws anything: while an instance is handed over both cast, and their
58
- // shadows, of one shape in two levels of detail, lie over each other.
65
+ // shadows, of one shape in two levels of detail, lie over each other. Both sides share one colour and one shadow program via `uBeyond`.
59
66
  const handing = new WeakMap();
60
67
  export function handOverOf(base, beyond = false) {
61
68
  let variants = handing.get(base);
62
69
  if (!variants) handing.set(base, (variants = {}));
63
70
  if (variants[beyond]) return variants[beyond];
64
- const variant = (variants[beyond] = base.clone());
71
+ const variant = (variants[beyond] = base.clone()),
72
+ beyondUniform = { value: beyond ? 1 : 0 };
65
73
  variant.onBeforeCompile = (shader, renderer) => {
66
74
  base.onBeforeCompile(shader, renderer);
67
- handOverVertices(shader, beyond);
75
+ handOverVertices(shader, beyondUniform);
68
76
  shader.fragmentShader = shader.fragmentShader
69
- .replace('#include <common>', '#include <common>\nvarying float vNearShare;')
70
- .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>\n${handedOver(beyond, 'vNearShare')}`);
77
+ .replace('#include <common>', '#include <common>\nvarying float vNearShare;\nuniform float uBeyond;')
78
+ .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>\n${handedOver('vNearShare')}`);
71
79
  };
72
- variant.customProgramCacheKey = () => base.customProgramCacheKey() + (beyond ? ':handed-far' : ':handed-near');
80
+ variant.customProgramCacheKey = () => base.customProgramCacheKey() + ':handed';
73
81
  return variant;
74
82
  }
75
83
  export function handOverShadow(beyond = false) {
76
- const variant = new THREE.MeshDepthMaterial();
77
- variant.onBeforeCompile = shader => handOverVertices(shader, beyond);
78
- variant.customProgramCacheKey = () => (beyond ? 'handed-far-depth' : 'handed-near-depth');
84
+ const variant = new THREE.MeshDepthMaterial(),
85
+ beyondUniform = { value: beyond ? 1 : 0 };
86
+ variant.onBeforeCompile = shader => handOverVertices(shader, beyondUniform);
87
+ variant.customProgramCacheKey = () => 'handed-depth';
79
88
  return variant;
80
89
  }
81
- // The near version's share, 1 short of the band about uReach and 0 past it, at a distance (a GLSL expression) from the eye
82
- const nearShare = (distance, band) => `1.0 - smoothstep(uReach - ${(band / 2).toFixed(2)}, uReach + ${(band / 2).toFixed(2)}, ${distance})`;
83
- // The fragment's test: the near version keeps the scatter's pixels under its share, the far version the rest
84
- const handedOver = (beyond, share) => `if (${SCATTER} ${beyond ? '<' : '>='} ${share}) discard;`;
90
+ // The fragment's test: the near version (`uBeyond <= 0.5`) keeps the scatter's pixels under its share, the far version the rest
91
+ const handedOver = share => `if (uBeyond > 0.5 ? (${SCATTER} < ${share}) : (${SCATTER} >= ${share})) discard;`;
85
92
  // Hands an instance's share (aNear) to the fragments (vNearShare), and puts the vertices of an instance its version does not draw
86
93
  // at all out of sight.
87
- function handOverVertices(shader, beyond) {
94
+ function handOverVertices(shader, beyondUniform) {
95
+ shader.uniforms.uBeyond = beyondUniform;
88
96
  shader.vertexShader = shader.vertexShader
89
- .replace('#include <common>', '#include <common>\nattribute float aNear;\nvarying float vNearShare;')
97
+ .replace('#include <common>', '#include <common>\nattribute float aNear;\nvarying float vNearShare;\nuniform float uBeyond;')
90
98
  .replace(
91
99
  '#include <project_vertex>',
92
- `#include <project_vertex>\nvNearShare = aNear;\nif (aNear ${beyond ? '>= 1.0' : '<= 0.0'}) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);`,
100
+ `#include <project_vertex>\nvNearShare = aNear;\nif (uBeyond > 0.5 ? (aNear >= 1.0) : (aNear <= 0.0)) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);`,
93
101
  );
94
102
  }
95
103
  // The same material for meshes of another kind (kind: 'plain', 'instanced', or 'tinted' for instances with a colour each), drawn as
@@ -107,3 +115,19 @@ export function twinMaterial(base, kind) {
107
115
  }
108
116
  return variants[kind];
109
117
  }
118
+
119
+ /**
120
+ * Attach a unit-white `instanceColor` buffer `(1, 1, 1)` to an `InstancedMesh` so untinted instanced meshes
121
+ * share `USE_INSTANCING_COLOR` WebGL programs with tinted batches of the same material without changing shading.
122
+ *
123
+ * @template {THREE.InstancedMesh} T
124
+ * @param {T} mesh
125
+ * @returns {T}
126
+ */
127
+ export function whiteInstanceColor(mesh) {
128
+ if (!mesh.instanceColor) {
129
+ const count = mesh.instanceMatrix.count;
130
+ mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(count * 3).fill(1), 3);
131
+ }
132
+ return mesh;
133
+ }
@@ -9,6 +9,7 @@ import * as THREE from 'three';
9
9
  import { TAU, clamp } from '../math/scalar.js';
10
10
  import { evaluateBallisticLodge, sampleBallisticFlight, solveBallisticLodge } from '../motion/ballistic-arc.js';
11
11
  import { buildArrowGeometry, buildKnifeGeometry, buildQuarrelGeometry } from '../geometry/projectile-shapes.js';
12
+ import { whiteInstanceColor } from './material-lod.js';
12
13
 
13
14
  const SHUDDER_SECONDS = 0.28,
14
15
  HIDDEN_MATRIX = new THREE.Matrix4().makeScale(0, 0, 0),
@@ -52,6 +53,7 @@ export function createProjectilePool({
52
53
  onGroundHit = null,
53
54
  maxPerKind = 32,
54
55
  layer = 1,
56
+ tinted = false,
55
57
  } = {}) {
56
58
  const _to = new THREE.Vector3(),
57
59
  _pos = new THREE.Vector3(),
@@ -100,6 +102,7 @@ export function createProjectilePool({
100
102
 
101
103
  function makePoolMesh(geo, material) {
102
104
  const m = new THREE.InstancedMesh(geo, material, maxPerKind + 1);
105
+ if (tinted) whiteInstanceColor(m);
103
106
  m.setMatrixAt(0, HIDDEN_MATRIX);
104
107
  m.count = 1;
105
108
  m.frustumCulled = false;
@@ -61,7 +61,12 @@ export function createTowns({ shapes, farMaterial, gableMaterial, towns = [] })
61
61
  for (let i = 0; i < list.length; i++) if (!wall || (list[i].wall || 0) === k) count++;
62
62
  if (!count) continue;
63
63
  // every town draws the same unit shapes, each part through a view of its own (geometryView)
64
- const im = new THREE.InstancedMesh(geometryView(shapes[type]), material, count);
64
+ const geo = geometryView(shapes[type]);
65
+ if (material.vertexColors && !geo.attributes.color) {
66
+ const verts = geo.attributes.position.count;
67
+ geo.setAttribute('color', new THREE.BufferAttribute(new Uint8Array(verts * 3).fill(255), 3, true));
68
+ }
69
+ const im = new THREE.InstancedMesh(geo, material, count);
65
70
  let n = 0;
66
71
  for (let i = 0; i < list.length; i++) {
67
72
  const b = list[i];
@@ -6,12 +6,12 @@
6
6
  import * as THREE from 'three';
7
7
  import { dim } from '../math/color.js';
8
8
  import { sstep } from '../math/scalar.js';
9
- import { GB, meshOf } from '../geometry/builder.js';
9
+ import { GB, meshOf, padParts } from '../geometry/builder.js';
10
10
  import { C } from '../geometry/primitives.js';
11
11
  import { shipLines } from '../geometry/ship-lines.js';
12
12
  import { gripOf, oarMatrix, oarPorts, oarPose } from '../geometry/ship-oars.js';
13
13
  import { YARD_APART } from '../geometry/ship-rig.js';
14
- import { twinMaterial } from './material-lod.js';
14
+ import { twinMaterial, whiteInstanceColor } from './material-lod.js';
15
15
 
16
16
  const _stretch = new THREE.Matrix4(),
17
17
  _m = new THREE.Matrix4();
@@ -34,6 +34,8 @@ const runHere = (job, inputOf, here) => Promise.resolve().then(here);
34
34
  * @param {(job: string, inputOf: () => object, here: () => object) => Promise<object>} [options.runOrHere] - Runs a job on a
35
35
  * worker pool, or `here()` on the page where there is none (as `createPool().runOrHere`). The page by default.
36
36
  * @param {string} [options.job] - The pool's job that answers `{ spec, options }` with `kit.shipParts(spec, options)`.
37
+ * @param {boolean} [options.padded=false] - Pad compact byte normals and colours on static ship meshes to 4 bytes per vertex
38
+ * so they align on 4-byte GPU strides and share vertex-alpha programs with padded settlement blocks.
37
39
  * @returns {{ buildShip: Function, orderShip: Function, shipOf: Function, raiseOars: Function }} buildShip(spec, options) a
38
40
  * ship now; orderShip(spec, options) the promise of her, built by the pool; shipOf(spec, options, parts) one from her arrays;
39
41
  * raiseOars(parent, spec, lines) her oars to pull. A ship is `{ group, set, setOther, furl, yard, stow, half, lines,
@@ -42,7 +44,7 @@ const runHere = (job, inputOf, here) => Promise.resolve().then(here);
42
44
  * `moving` (oars left out, to be rowed), `tacks` (lateen sails set on both sides), `yardApart` (the lateen yard built apart,
43
45
  * hoisted or stowed), `riding` (the riding light, a group to take in when she puts out).
44
46
  */
45
- export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere = runHere, job = 'ship' }) {
47
+ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere = runHere, job = 'ship', padded = false, tinted = false }) {
46
48
  // The spec a boat with a lateen yard is built from when the yard is to stand apart from her hull (`yardApart`: a boat that
47
49
  // both sails and lies): the yard, the sail furled on it and its hoisted ropes are left out of her own builders, and shipOf
48
50
  // builds them of their own in both poses.
@@ -58,7 +60,7 @@ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere
58
60
  function shipOf(spec, { far = false, yardApart = false }, parts) {
59
61
  const group = new THREE.Group(),
60
62
  lines = shipLines(spec),
61
- mesh = (p, mat, shadow = !far, parent = group) => (p ? meshOf(p, mat, parent, shadow) : null);
63
+ mesh = (p, mat, shadow = !far, parent = group) => (p ? meshOf(padded ? padParts(p) : p, mat, parent, shadow) : null);
62
64
  mesh(parts.wood, materials.wood);
63
65
  mesh(parts.rope, materials.cloth, false); // rope and iron cast none: a line a few centimetres thick is finer than the shadow map, and its shadow falls as dark smears
64
66
  mesh(parts.glass, materials.glass, false);
@@ -88,8 +90,8 @@ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere
88
90
  if (parts.ride) {
89
91
  ship.ridingLight = new THREE.Group();
90
92
  group.add(ship.ridingLight);
91
- meshOf(parts.ride.glass, materials.glass, ship.ridingLight, false);
92
- meshOf(parts.ride.iron, materials.cloth, ship.ridingLight, !far);
93
+ mesh(parts.ride.glass, materials.glass, false, ship.ridingLight);
94
+ mesh(parts.ride.iron, materials.cloth, !far, ship.ridingLight);
93
95
  }
94
96
  if (!spec.open) {
95
97
  const ladder = 1.5, // metres of deck over which a ladder climbs
@@ -118,7 +120,8 @@ export function createShipMeshes({ kit, materials = plainMaterials(), runOrHere
118
120
  const ports = oarPorts(spec, lines),
119
121
  colour = dim(C(spec.deckTone), 0.85),
120
122
  instanced = (gb, count) => {
121
- const mesh = new THREE.InstancedMesh(gb.build(), twinMaterial(materials.wood, 'instanced'), count);
123
+ const mesh = new THREE.InstancedMesh(gb.build(), twinMaterial(materials.wood, tinted ? 'tinted' : 'instanced'), count);
124
+ if (tinted) whiteInstanceColor(mesh);
122
125
  mesh.castShadow = mesh.receiveShadow = true;
123
126
  mesh.frustumCulled = false; // its instances spread wider than its geometry's bounds
124
127
  parent.add(mesh);
@@ -8,6 +8,7 @@ import { C, TRS } from '../geometry/primitives.js';
8
8
  import { litShare } from '../math/lit-share.js';
9
9
  import { sstep, TAU } from '../math/scalar.js';
10
10
  import { createLightPoints } from './light-points.js';
11
+ import { whiteInstanceColor } from './material-lod.js';
11
12
  import { falloffAt, pixelTexture } from './textures.js';
12
13
 
13
14
  /** The iron of a lamp's post and lantern, and its burner. */
@@ -107,6 +108,7 @@ export function createStreetLamps({
107
108
  seed = i => (i * 0.618034) % 1,
108
109
  points: more = {},
109
110
  iron = LAMP_IRON,
111
+ tinted = false,
110
112
  }) {
111
113
  const n = lamps.length;
112
114
  const post = new GB();
@@ -120,7 +122,8 @@ export function createStreetLamps({
120
122
  post.add(U.box, C(iron.post), TRS(Math.cos(a) * 0.19, 3.28, Math.sin(a) * 0.19, 0.035, 0.46, 0.035));
121
123
  } // four bars between them,
122
124
  post.add(U.cyl6, C(iron.burner), TRS(0, 3.3, 0, 0.045, MANTLE.burner, 0.045)); // and the burner the mantle sits on
123
- const posts = new THREE.InstancedMesh(geometryOf(indexParts(post.parts(!post.wide))), postMaterial, n);
125
+ const posts = new THREE.InstancedMesh(geometryOf(indexParts(post.flatten().parts(!post.wide))), postMaterial, n);
126
+ if (tinted) whiteInstanceColor(posts);
124
127
  const pos = new Float32Array(n * 3),
125
128
  seeds = new Float32Array(n);
126
129
  const mantles = new THREE.InstancedMesh(mantleGeometry(), mantleMaterial(FLAME, uniforms), n);
@@ -42,7 +42,15 @@ const S = 'uLook.x',
42
42
  STOREY = 'uFloors.x',
43
43
  TIMBER = 'uFloors.y',
44
44
  WINW = 'uFloors.z',
45
- WINH = 'uFloors.w';
45
+ WINH = 'uFloors.w',
46
+ // Triplanar non-skin surfaces reuse uFloors (unused outside kind === 'wall') for uniform-gated feature switches
47
+ // so stone, rock, wood, plaster, mossed stone, and bedded rock share one WebGL program.
48
+ TRI_TAG = 'uFloors.x',
49
+ TRI_WASH = 'uFloors.y',
50
+ TRI_BEDS = 'uFloors.z',
51
+ TRI_NIGHT = 'uFloors.w',
52
+ WALL_LAMP = 'uMore.z',
53
+ ROOF_TILE = 'uFloors.x';
46
54
 
47
55
  function defaultSurfaceUniforms() {
48
56
  return {
@@ -123,19 +131,28 @@ export function createSurfaceMaterialFactory({
123
131
  side: o.side ?? THREE.FrontSide,
124
132
  };
125
133
  const look = { value: new THREE.Vector4(o.scale ?? 0.16, o.gain ?? 1.7, o.bump ?? 4, o.base ?? 0) };
126
- const more = { value: new THREE.Vector4(o.windows ?? 1, o.gas ?? 0, o.moss ?? 0, o.fine ?? 0) };
127
- const floors = { value: new THREE.Vector4(o.storey ?? 3, o.timber ?? 0, o.windowW ?? 0, o.windowH ?? 0) };
128
-
129
- const garment = o.skin ? garmentShader({ scale: S, threads: clothThreads, smoothness: hair.smoothOf('vSk'), wear: garmentWear }) : null;
130
- const ruin = (o.windows ?? 1) === 0;
134
+ const isWall = o.kind === 'wall';
131
135
  const leaf = o.kind === 'leaf';
132
136
  const roof = o.kind === 'roof' || o.kind === 'tile';
137
+ const triPlain = !isWall && !roof && !leaf && !o.skin;
133
138
  const useLamp = lampWash && !!o.lamp;
134
139
  const useLampWall = lampWash && !!o.lampWall;
135
- const useCityLight = lampWash && !!(o.tag || o.lampWall);
140
+ const useCityLight = lampWash && !!(triPlain || o.tag || isWall);
141
+ const more = {
142
+ value: new THREE.Vector4(o.windows ?? 1, o.gas ?? 0, isWall ? (useLampWall ? 1 : 0) : (o.moss ?? 0), o.fine ?? 0),
143
+ };
144
+ const floors = {
145
+ value: triPlain
146
+ ? new THREE.Vector4(o.tag ? 1 : 0, o.wash ? 1 : 0, o.beds || 0, o.tag || o.night ? 1 : 0)
147
+ : roof
148
+ ? new THREE.Vector4(o.kind === 'tile' ? 1 : 0, 0, 0, 0)
149
+ : new THREE.Vector4(o.storey ?? 3, o.timber ?? 0, o.windowW ?? 0, o.windowH ?? 0),
150
+ };
151
+
152
+ const garment = o.skin ? garmentShader({ scale: S, threads: clothThreads, smoothness: hair.smoothOf('vSk'), wear: garmentWear }) : null;
136
153
 
137
154
  let map;
138
- if (o.kind === 'wall') {
155
+ if (isWall) {
139
156
  map = facadeColorGLSL({
140
157
  scale: S,
141
158
  gain: G,
@@ -146,16 +163,27 @@ export function createSurfaceMaterialFactory({
146
163
  timber: TIMBER,
147
164
  windowW: WINW,
148
165
  windowH: WINH,
149
- ruin,
150
- lampWall: useLampWall,
166
+ ruin: 'uniform',
167
+ lampWall: useCityLight ? WALL_LAMP : false,
151
168
  lampWash,
152
169
  });
153
- } else if (o.kind === 'roof') {
154
- map = roofColorGLSL({ scale: S, gain: G });
155
- } else if (o.kind === 'tile') {
156
- map = tileRoofColorGLSL({ scale: S, gain: G });
170
+ } else if (roof) {
171
+ map = `/* glsl */
172
+ if (${ROOF_TILE} > 0.5) {
173
+ ${tileRoofColorGLSL({ scale: S, gain: G })}
174
+ } else {
175
+ ${roofColorGLSL({ scale: S, gain: G })}
176
+ }`;
157
177
  } else if (leaf) {
158
178
  map = foliageColorGLSL({ scale: S });
179
+ } else if (triPlain) {
180
+ map = `/* glsl */
181
+ ${triplanarColor({ texture: 'uTex', scale: S, gain: G, height: 'gH' })}
182
+ float wallHeight = vWy - 1000.0 * step(500.0, vWy);${beddedRockGLSL(TRI_BEDS)}${fineGrainGLSL(FINE)}${mossAndLichenGLSL({
183
+ scale: S,
184
+ moss: MOSS,
185
+ tagged: TRI_TAG,
186
+ })}${weatheredWallGLSL({ wash: TRI_WASH, dustTint: wallDustTint, lampWash, gas: GAS, enabled: TRI_TAG })}`;
159
187
  } else {
160
188
  map = `/* glsl */
161
189
  ${triplanarColor({ texture: 'uTex', scale: S, gain: G, height: 'gH' })}${o.tag ? '\nfloat wallHeight = vWy - 1000.0 * step(500.0, vWy);' : ''}${
@@ -195,29 +223,37 @@ ${triplanarColor({ texture: 'uTex', scale: S, gain: G, height: 'gH' })}${o.tag ?
195
223
  uniforms.uActorWear = actorWearUniform;
196
224
  }
197
225
 
198
- const nightIrradiance =
199
- o.tag || o.kind === 'wall' || o.night
200
- ? `irradiance += vec3(${wallNightSky.map(c => (c * wallNight * Math.PI).toFixed(4)).join(', ')}) * uNight * uNightSky * (1.0 - abs(normalize(vLN).y));`
226
+ const nightSkyVec = wallNightSky.map(c => (c * wallNight * Math.PI).toFixed(4)).join(', ');
227
+ const nightIrradiance = triPlain
228
+ ? `irradiance += vec3(${nightSkyVec}) * uNight * uNightSky * ${TRI_NIGHT} * (1.0 - abs(normalize(vLN).y));`
229
+ : o.tag || o.kind === 'wall' || o.night
230
+ ? `irradiance += vec3(${nightSkyVec}) * uNight * uNightSky * (1.0 - abs(normalize(vLN).y));`
201
231
  : '';
202
232
 
203
- const cacheKey =
204
- 'surf:' +
205
- [o.kind, ruin, !!o.moss, !!o.fine, o.beds || 0, !!o.flat, !!o.tag, !!o.wash, !!o.skin, useLamp, useLampWall, !!o.night].join(':') +
206
- (lampWash ? '' : ':nolamp');
233
+ const cacheKey = triPlain
234
+ ? 'surf:tri:' + [!!o.flat, useLamp].join(':') + (lampWash ? '' : ':nolamp')
235
+ : isWall
236
+ ? 'surf:wall:' + !!o.flat + (lampWash ? '' : ':nolamp')
237
+ : roof
238
+ ? 'surf:roof:' + !!o.flat + (lampWash ? '' : ':nolamp')
239
+ : 'surf:' +
240
+ [o.kind, !!o.moss, !!o.fine, o.beds || 0, !!o.flat, !!o.tag, !!o.wash, !!o.skin, useLamp, useLampWall, !!o.night].join(':') +
241
+ (lampWash ? '' : ':nolamp');
207
242
 
243
+ const hasWallTag = triPlain || !!o.tag;
208
244
  const mat = createProjectedMaterial(parameters, {
209
245
  cacheKey,
210
246
  uniforms,
211
247
  vertex: {
212
248
  declarations:
213
249
  (leaf ? '\nattribute float aLeaf; varying float vLeaf; uniform float uTime; uniform vec3 uWind;' + WIND_SWAY_GLSL : '') +
214
- (o.tag ? '\nattribute float aTag; varying float vWy;' : '') +
250
+ (hasWallTag ? '\nattribute float aTag; varying float vWy;' : '') +
215
251
  (o.skin ? '\nattribute float aTag; varying float vSk;' : '') +
216
252
  (useLamp ? '\nuniform sampler2D uLampMap; uniform vec4 uLampR; uniform float uNight; varying float vLamp;' : ''),
217
253
  deformInstance: leaf
218
254
  ? 'transformed.xz += aLeaf * windSway(instanceMatrix[3].xyz, position.y, 0.004, 0.008, position.y * 0.6);'
219
255
  : '',
220
- assign: `${leaf ? ' vLeaf = aLeaf;' : ''}${o.tag ? ' vWy = position.y - aTag;' : ''}${
256
+ assign: `${leaf ? ' vLeaf = aLeaf;' : ''}${hasWallTag ? ' vWy = position.y - aTag;' : ''}${
221
257
  o.skin ? ` vSk = aTag${o.tagSteps ? ' / ' + o.tagSteps.toFixed(1) : ''};` : ''
222
258
  }${
223
259
  useLamp
@@ -235,7 +271,7 @@ ${triplanarColor({ texture: 'uTex', scale: S, gain: G, height: 'gH' })}${o.tag ?
235
271
  `\nuniform sampler2D uTex; uniform float uNight, uNightSky, uDamp;${lampWash ? ' uniform vec3 uGas;' : ''} uniform vec4 uLook, uMore, uFloors; ` +
236
272
  projectedVaryings +
237
273
  (leaf ? ' varying float vLeaf; uniform float uSunLight;' : '') +
238
- (o.tag ? ' varying float vWy;' : '') +
274
+ (hasWallTag ? ' varying float vWy;' : '') +
239
275
  (useLamp ? ' varying float vLamp;' : '') +
240
276
  (useCityLight ? ' uniform sampler2D uLampMap;' : '') +
241
277
  (roof ? LOW_LIGHT_REFLECTANCE : '') +
@@ -23,8 +23,8 @@ import { groundDustGradient } from './surface-projection.js';
23
23
  * @param {string} options.timber GLSL expression enabling timber-framed upper storeys.
24
24
  * @param {string} options.windowW GLSL expression for district window width in metres (0 for fixed grid).
25
25
  * @param {string} options.windowH GLSL expression for district window height in metres.
26
- * @param {boolean} [options.ruin=false] Omit doors, glazing bars, shutters, and lit interiors.
27
- * @param {boolean} [options.lampWall=false] Use local lamp map sampling instead of ambient city wash.
26
+ * @param {boolean | 'uniform'} [options.ruin=false] Omit doors, glazing bars, shutters, and lit interiors (`'uniform'` switches via `${windows} <= 0.0`).
27
+ * @param {boolean | string} [options.lampWall=false] Use local lamp map sampling instead of ambient city wash (boolean or uniform GLSL expression `> 0.5`).
28
28
  * @param {boolean} [options.lampWash=true] Emit night lamp wash on the facade.
29
29
  * @returns {string} GLSL snippet for `#include <map_fragment>`.
30
30
  */
@@ -42,9 +42,52 @@ export function facadeColorGLSL({
42
42
  lampWall = false,
43
43
  lampWash = true,
44
44
  }) {
45
- const lampLine = lampWash
46
- ? `\n if (uNight > 0.0) gGlow = ${lampWall ? 'localLampGlow(cityLight(vCW).r, wy) * (0.5 + gH)' : 'exp(-max(wy, 0.0) * 0.28) * gasHere()'} * ${gas};`
47
- : '';
45
+ const uniformRuin = ruin === 'uniform';
46
+ const lampExpr =
47
+ typeof lampWall === 'string'
48
+ ? `(${lampWall} > 0.5 ? localLampGlow(cityLight(vCW).r, wy) * (0.5 + gH) : exp(-max(wy, 0.0) * 0.28) * gasHere())`
49
+ : lampWall
50
+ ? 'localLampGlow(cityLight(vCW).r, wy) * (0.5 + gH)'
51
+ : 'exp(-max(wy, 0.0) * 0.28) * gasHere()';
52
+ const lampLine = lampWash ? `\n if (uNight > 0.0) gGlow = ${lampExpr} * ${gas};` : '';
53
+ const doorFaceExpr = uniformRuin ? '(1.0 - isRuin)' : ruin ? '0.0' : '1.0';
54
+ const hasThresh = uniformRuin ? 'mix(0.3, 0.45, isRuin)' : ruin ? '0.45' : '0.3';
55
+ const muntExpr = uniformRuin
56
+ ? '(1.0 - isRuin) * open * max(step(abs(wc.x), 0.07), step(abs(wc.y + 0.12), 0.06))'
57
+ : ruin
58
+ ? '0.0'
59
+ : 'open * max(step(abs(wc.x), 0.07), step(abs(wc.y + 0.12), 0.06))';
60
+ const shutExpr = uniformRuin
61
+ ? '(1.0 - isRuin) * step(0.55, fract(vSeed * 3.7)) * has * step(1.24, abs(wc.x)) * step(abs(wc.x), 1.96) * step(abs(wc.y), 1.02)'
62
+ : ruin
63
+ ? '0.0'
64
+ : 'step(0.55, fract(vSeed * 3.7)) * has * step(1.24, abs(wc.x)) * step(abs(wc.x), 1.96) * step(abs(wc.y), 1.02)';
65
+ const winWeight = uniformRuin ? `mix(${windows}, 1.0, isRuin)` : ruin ? '1.0' : windows;
66
+ const litExpr = uniformRuin
67
+ ? '(1.0 - isRuin) * open * (1.0 - munt) * step(0.7, fract(r * 7.13 + 0.2))'
68
+ : ruin
69
+ ? '0.0'
70
+ : 'open * (1.0 - munt) * step(0.7, fract(r * 7.13 + 0.2))';
71
+ const interiorBlock =
72
+ ruin === true
73
+ ? ''
74
+ : `if (open > 0.0${uniformRuin ? ' && isRuin < 0.5' : ''}) { // each window its own: curtains of dyed cloth drawn to the sides or nearly shut, an inner shutter half closed, and behind a lit one a room
75
+ float r2 = fract(r * 31.7 + 0.13), r3 = fract(r * 5.13 + 0.41), r4 = fract(r * 3.31 + 0.77);
76
+ float cw = mix(0.22, 0.9, r3 * r3), curt = step(0.35, r2) * open * max(step(1.0 - cw, abs(wc.x)), step(0.78, wc.y));
77
+ float ishut = step(0.8, r4) * open * step(wc.x, -0.04) * (1.0 - curt);
78
+ vec3 cloth = r2 < 0.55 ? vec3(0.42, 0.12, 0.09) : r2 < 0.7 ? vec3(0.5, 0.38, 0.17) : r2 < 0.85 ? vec3(0.62, 0.58, 0.5) : vec3(0.16, 0.27, 0.19);
79
+ float fold = 0.72 + 0.28 * sin(wc.x * 21.0 + r * 9.0);
80
+ diffuseColor.rgb = mix(diffuseColor.rgb, cloth * fold * 0.8, curt);
81
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.21, 0.14, 0.085) * (0.8 + 0.2 * step(0.5, fract(wc.x * 2.6))), ishut); // plain boards inside the glass
82
+ if (uNight > 0.0 && gLit > 0.0) {
83
+ gWarm = floor(fract(r * 13.71) * 3.0) * 0.5;
84
+ gPower = 0.7 + 0.58 * fract(r * 17.71);
85
+ float lx = (fract(r * 71.3) - 0.5) * 1.2, hot = exp(-((wc.x - lx) * (wc.x - lx) * 2.2 + (wc.y - 0.15) * (wc.y - 0.15) * 3.0));
86
+ float furn = step(wc.y, -0.42 + 0.22 * step(0.5, fract((wc.x + r) * 1.7))) * step(0.3, fract(r * 13.1 + floor((wc.x + 1.0) * 1.6) * 0.29));
87
+ gTint = mix(vec3(0.55 + 0.75 * hot) * (1.0 - 0.75 * furn) * (0.75 + 0.25 * smoothstep(-1.0, 1.0, wc.y)), cloth * 1.1 * fold, curt);
88
+ }
89
+ gLit *= 1.0 - ishut; gH += (curt * 0.25 + ishut * 0.4) * gWin;
90
+ }`;
48
91
  return `/* glsl */
49
92
  vec3 bw = abs(vLN);
50
93
  vec2 wuv = bw.y > 0.5 ? vL.xz : (bw.x > 0.5 ? vL.zy : vL.xy);
@@ -72,13 +115,13 @@ export function facadeColorGLSL({
72
115
  float timber = mix(0.22, max(max(post, rail), brace), smoothstep(0.2, 0.09, max(ax, ay))) * framed; // finer than a pixel: the frame's share of the wall
73
116
  diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.07, 0.042, 0.026) * (0.75 + 0.5 * gH), timber); gH += timber * 0.3;
74
117
  }
75
- if (halfW > 1.3) {
118
+ if (halfW > 1.3) {${uniformRuin ? `\n float isRuin = step(${windows}, 0.0);` : ''}
76
119
  vec2 gq = vec2(gx, wy / ${storey}); vec2 cell = floor(gq), fq = fract(gq);
77
120
  float r = fract(sin(dot(cell + floor(vSeed * 13.0), vec2(12.9898, 78.233))) * 43758.5453);
78
- float isDoorFace = step(0.5, bw.z) * ${ruin ? '0.0' : '1.0'};
121
+ float isDoorFace = step(0.5, bw.z) * ${doorFaceExpr};
79
122
  float door = step(abs(wuv.x), 0.62) * step(wy, 2.3) * step(0.0, wy) * isDoorFace;
80
123
  float dframe = step(abs(wuv.x), 0.84) * step(wy, 2.54) * step(0.0, wy) * isDoorFace - door;
81
- float has = step(${ruin ? '0.45' : '0.3'}, r) * step(0.2, wy) * step(wy, hgt - 0.5) * step(abs(wuv.x), halfW - 0.6) * (1.0 - step(abs(wuv.x), 1.25) * step(wy, ${storey}) * isDoorFace);
124
+ float has = step(${hasThresh}, r) * step(0.2, wy) * step(wy, hgt - 0.5) * step(abs(wuv.x), halfW - 0.6) * (1.0 - step(abs(wuv.x), 1.25) * step(wy, ${storey}) * isDoorFace);
82
125
  vec2 wc = (fq - vec2(0.5, 0.58)) / vec2(0.2, 0.22);
83
126
  if (${windowW} > 0.0) { // a near house's window: its sill 1.05 m over the floor below and 0.88 m over the upper ones
84
127
  float ground = step(cell.y, 0.5), wh = min(${windowH}, ${storey} - mix(1.45, 1.7, ground)), wb = mix(0.88, 1.05, ground);
@@ -87,33 +130,13 @@ export function facadeColorGLSL({
87
130
  float open = step(abs(wc.x), 1.0) * step(abs(wc.y), 1.0) * has;
88
131
  float frame = step(abs(wc.x), 1.24) * step(abs(wc.y), 1.2) * has - open; // stone surround
89
132
  float sill = step(abs(wc.x), 1.42) * step(-1.44, wc.y) * step(wc.y, -1.2) * has;
90
- float munt = ${ruin ? '0.0' : 'open * max(step(abs(wc.x), 0.07), step(abs(wc.y + 0.12), 0.06))'}; // glazing bars
91
- float shut = ${ruin ? '0.0' : 'step(0.55, fract(vSeed * 3.7)) * has * step(1.24, abs(wc.x)) * step(abs(wc.x), 1.96) * step(abs(wc.y), 1.02)'};
92
- gWin = open * (1.0 - munt) * ${ruin ? '1.0' : windows};
93
- gLit = ${ruin ? '0.0' : 'open * (1.0 - munt) * step(0.7, fract(r * 7.13 + 0.2))'}; // a lit window shines across the pane
133
+ float munt = ${muntExpr}; // glazing bars
134
+ float shut = ${shutExpr};
135
+ gWin = open * (1.0 - munt) * ${winWeight};
136
+ gLit = ${litExpr}; // a lit window shines across the pane
94
137
  vec3 glass = vec3(0.028, 0.04, 0.06) * (1.0 - 0.6 * smoothstep(0.2, 1.0, wc.y)); // darker under the lintel
95
138
  diffuseColor.rgb = mix(diffuseColor.rgb, glass, gWin);
96
- ${
97
- ruin
98
- ? ''
99
- : `if (open > 0.0) { // each window its own: curtains of dyed cloth drawn to the sides or nearly shut, an inner shutter half closed, and behind a lit one a room
100
- float r2 = fract(r * 31.7 + 0.13), r3 = fract(r * 5.13 + 0.41), r4 = fract(r * 3.31 + 0.77);
101
- float cw = mix(0.22, 0.9, r3 * r3), curt = step(0.35, r2) * open * max(step(1.0 - cw, abs(wc.x)), step(0.78, wc.y));
102
- float ishut = step(0.8, r4) * open * step(wc.x, -0.04) * (1.0 - curt);
103
- vec3 cloth = r2 < 0.55 ? vec3(0.42, 0.12, 0.09) : r2 < 0.7 ? vec3(0.5, 0.38, 0.17) : r2 < 0.85 ? vec3(0.62, 0.58, 0.5) : vec3(0.16, 0.27, 0.19);
104
- float fold = 0.72 + 0.28 * sin(wc.x * 21.0 + r * 9.0);
105
- diffuseColor.rgb = mix(diffuseColor.rgb, cloth * fold * 0.8, curt);
106
- diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.21, 0.14, 0.085) * (0.8 + 0.2 * step(0.5, fract(wc.x * 2.6))), ishut); // plain boards inside the glass
107
- if (uNight > 0.0 && gLit > 0.0) {
108
- gWarm = floor(fract(r * 13.71) * 3.0) * 0.5;
109
- gPower = 0.7 + 0.58 * fract(r * 17.71);
110
- float lx = (fract(r * 71.3) - 0.5) * 1.2, hot = exp(-((wc.x - lx) * (wc.x - lx) * 2.2 + (wc.y - 0.15) * (wc.y - 0.15) * 3.0));
111
- float furn = step(wc.y, -0.42 + 0.22 * step(0.5, fract((wc.x + r) * 1.7))) * step(0.3, fract(r * 13.1 + floor((wc.x + 1.0) * 1.6) * 0.29));
112
- gTint = mix(vec3(0.55 + 0.75 * hot) * (1.0 - 0.75 * furn) * (0.75 + 0.25 * smoothstep(-1.0, 1.0, wc.y)), cloth * 1.1 * fold, curt);
113
- }
114
- gLit *= 1.0 - ishut; gH += (curt * 0.25 + ishut * 0.4) * gWin;
115
- }`
116
- }
139
+ ${interiorBlock}
117
140
  diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.15, 0.11, 0.08), munt);
118
141
  diffuseColor.rgb *= 1.0 + frame * 0.26 + sill * 0.34 + dframe * 0.24;
119
142
  vec3 shc = mix(vec3(0.09, 0.2, 0.18), vec3(0.28, 0.1, 0.08), step(0.5, fract(vSeed * 5.3)));
@@ -182,15 +205,18 @@ export function foliageColorGLSL({ scale }) {
182
205
 
183
206
  /**
184
207
  * Horizontal bedding laminae for sedimentary rock faces, fading via `fwidth` before sub-pixel aliasing.
208
+ * Accepts either a fixed number of laminae per metre or a uniform GLSL expression (skipped when `<= 0`).
185
209
  *
186
- * @param {number} beds Laminae per metre.
210
+ * @param {number | string} beds Laminae per metre or GLSL uniform expression.
187
211
  * @returns {string} GLSL snippet appended after `triplanarColor`.
188
212
  */
189
213
  export function beddedRockGLSL(beds) {
214
+ const expr = typeof beds === 'string' ? beds : beds.toFixed(2);
215
+ const open = typeof beds === 'string' ? `if (${expr} > 0.0) {` : '{';
190
216
  return `
191
- { // laminae of a bedded rock, o.beds to the metre, wandering a little: on its faces, not on what faces the sky. Each fades
217
+ ${open} // laminae of a bedded rock, o.beds to the metre, wandering a little: on its faces, not on what faces the sky. Each fades
192
218
  // as it nears a pixel's height, so a far face is even, not striped
193
- float ly = vL.y * ${beds.toFixed(2)} + 1.7 * texture2D(uTex, vec2(vL.x + vL.z, vL.y * 0.2) * 0.031).g;
219
+ float ly = vL.y * ${expr} + 1.7 * texture2D(uTex, vec2(vL.x + vL.z, vL.y * 0.2) * 0.031).g;
194
220
  float lam = sin(ly * 6.2832) * (1.0 - smoothstep(0.05, 0.18, fwidth(ly))) * (1.0 - smoothstep(0.45, 0.8, abs(vLN.y)));
195
221
  diffuseColor.rgb *= 1.0 + 0.07 * lam;
196
222
  gH += 0.18 * lam; }`;
@@ -198,13 +224,15 @@ export function beddedRockGLSL(beds) {
198
224
 
199
225
  /**
200
226
  * Secondary close-range triplanar grain so large stone and rock faces keep fine detail at walking height.
227
+ * Guarded by `${fineScale} > 0.0` so materials without fine grain share one program with zero extra texture reads.
201
228
  *
202
229
  * @param {string} fineScale GLSL expression for the fine grain scale.
203
230
  * @returns {string} GLSL snippet appended after `triplanarColor`.
204
231
  */
205
232
  export function fineGrainGLSL(fineScale) {
206
233
  return `
207
- { float fk = 1.0 - smoothstep(6.0, 45.0, length(vViewPosition));
234
+ if (${fineScale} > 0.0) {
235
+ float fk = 1.0 - smoothstep(6.0, 45.0, length(vViewPosition));
208
236
  if (fk > 0.0) {
209
237
  vec3 fp = vL * ${fineScale} + 0.37;
210
238
  float f = dot(texture2D(uTex, fp.zy).rgb * bw.x + texture2D(uTex, fp.xz).rgb * bw.y + texture2D(uTex, fp.xy).rgb * bw.z, vec3(0.333));
@@ -214,15 +242,22 @@ export function fineGrainGLSL(fineScale) {
214
242
 
215
243
  /**
216
244
  * Procedural moss cushions (tops, ledges, damp north faces, wall feet, and mortar joints) and pale lichen rosettes.
245
+ * Guarded by `${moss} > 0.0` so unmossed surfaces share one program with zero extra texture reads.
217
246
  *
218
- * @param {{ scale: string, moss: string, tagged?: boolean }} options
247
+ * @param {{ scale: string, moss: string, tagged?: boolean | string }} options
219
248
  * @returns {string} GLSL snippet appended after `triplanarColor`.
220
249
  */
221
250
  export function mossAndLichenGLSL({ scale, moss, tagged = false }) {
251
+ const footExpr =
252
+ typeof tagged === 'string'
253
+ ? `${tagged} > 0.5 ? (1.0 - smoothstep(0.1, 1.4, wallHeight)) * step(abs(vLN.y), 0.5) : 0.0`
254
+ : tagged
255
+ ? '(1.0 - smoothstep(0.1, 1.4, wallHeight)) * step(abs(vLN.y), 0.5)'
256
+ : '0.0';
222
257
  return `
223
- { float upf = smoothstep(0.55, 0.95, vLN.y); // what faces the sky;
258
+ if (${moss} > 0.0) { float upf = smoothstep(0.55, 0.95, vLN.y); // what faces the sky;
224
259
  float north = smoothstep(0.1, 0.8, -vLN.z) * (1.0 - upf); // a face turned from the sun (north is -z);
225
- float foot = ${tagged ? '(1.0 - smoothstep(0.1, 1.4, wallHeight)) * step(abs(vLN.y), 0.5)' : '0.0'}; // the foot of a wall, wet from the ground or the water
260
+ float foot = ${footExpr}; // the foot of a wall, wet from the ground or the water
226
261
  float damp = max(north * 0.75, foot); // the faces that stay wet; a top dries between rains and is walked on
227
262
  vec3 bj = abs(vLN); vec2 fuv = bj.y > 0.5 ? vL.xz : (bj.x > 0.5 ? vL.zy : vL.xy), juv = fuv * ${scale};
228
263
  // the joints and pits: where the stone is darker than round it. The texture's own blur (its coarser levels) takes them away
@@ -250,16 +285,18 @@ export function mossAndLichenGLSL({ scale, moss, tagged = false }) {
250
285
  * optional worn limewash patches, and optional city lamp/window bounce at night.
251
286
  *
252
287
  * @param {object} options
253
- * @param {boolean} [options.wash=false] Include worn limewash patches and sill rain runs.
288
+ * @param {boolean | string} [options.wash=false] Include worn limewash patches and sill rain runs (boolean or uniform expression `> 0.5`).
254
289
  * @param {string | [number, number, number]} options.dustTint Ground dust tint RGB expression or tuple.
255
290
  * @param {boolean} [options.lampWash=true] Sample city lamp map and ambient wash at night.
256
291
  * @param {string} [options.gas='uMore.y'] GLSL expression for lamp wash gain.
292
+ * @param {string | null} [options.enabled=null] Optional uniform GLSL expression (`> 0.5`) gating the whole block.
257
293
  * @returns {string} GLSL snippet appended after `triplanarColor`.
258
294
  */
259
- export function weatheredWallGLSL({ wash = false, dustTint, lampWash = true, gas = 'uMore.y' }) {
260
- const washBlock = wash
295
+ export function weatheredWallGLSL({ wash = false, dustTint, lampWash = true, gas = 'uMore.y', enabled = null }) {
296
+ const washOpen = typeof wash === 'string' ? `if (${wash} > 0.5) {` : wash ? '{' : null;
297
+ const washBlock = washOpen
261
298
  ? `
262
- { float upr = step(abs(vLN.y), 0.5); vec2 wv = vec2(vL.x + vL.z, vL.y);
299
+ ${washOpen} float upr = step(abs(vLN.y), 0.5); vec2 wv = vec2(vL.x + vL.z, vL.y);
263
300
  // limewash worn through in patches a metre or two across, ragged as the moss's (differences of the texture with itself),
264
301
  // the render under it greyer and darker, with a shadowed lip where the coat stands proud; more of them near the street
265
302
  float pw = 0.5 + 2.0 * (texture2D(uTex, wv * 0.083 + 0.21).g - texture2D(uTex, wv * 0.061 + 0.58).r)
@@ -279,7 +316,7 @@ export function weatheredWallGLSL({ wash = false, dustTint, lampWash = true, gas
279
316
  gGlow = (0.3 * exp(-max(vWy, 0.0) * 0.28) * gasHere() + localLampGlow(lm.r, lampWy)) * (0.5 + gH) * ${gas}; // a faint wash over the gaslit city, and real light where a lamp stands
280
317
  gWindow = lm.g * exp(-max(vWy - 0.6, 0.0) * 0.7) * step(abs(vLN.y), 0.5); } // and the foot of a wall takes the warm light of a lit window across the lane`
281
318
  : '';
282
- return `
319
+ const body = `
283
320
  { float upr = step(abs(vLN.y), 0.5);
284
321
  float run = texture2D(uTex, vec2((vL.x + vL.z) * 0.52, vL.y * 0.019)).g; // rain runs: narrow across a wall, long down it
285
322
  float lip = texture2D(uTex, vec2(vL.x - vL.z, 0.31) * 0.047).r; // damp rises from the ground to an uneven tide line, and greens the foot of the wall
@@ -289,6 +326,7 @@ export function weatheredWallGLSL({ wash = false, dustTint, lampWash = true, gas
289
326
  diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * vec3(0.4, 0.45, 0.35) * (0.75 + 0.5 * tx.g), damp * 0.85); // wet and greened below it, mottled
290
327
  diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.62, 0.6, 0.55), salt * 0.22); } // a pale fringe of salts where it dries
291
328
  ${groundDustGradient({ height: 'wallHeight', dustTint })}${washBlock}${lampBlock}`;
329
+ return enabled ? `\n if (${enabled} > 0.5) {${body}\n }` : body;
292
330
  }
293
331
 
294
332
  /**
@@ -49,6 +49,7 @@ export function createVehicleTrains({ kitNew, kitAt, kitInstanced, propCart, pro
49
49
  const cloneUnshadowed = list =>
50
50
  list.map(src => {
51
51
  const m = new THREE.InstancedMesh(src.geometry, src.material, src.instanceMatrix.count);
52
+ if (src.instanceColor) m.instanceColor = src.instanceColor;
52
53
  m.frustumCulled = false;
53
54
  m.castShadow = false;
54
55
  m.receiveShadow = src.receiveShadow;
@@ -429,12 +429,20 @@ function stillByDefault(material) {
429
429
  material.defaultAttributeValues.aBank = [DEEP, 1, FAR, FAR];
430
430
  }
431
431
 
432
+ /** Horizontal open-water plane without a normal attribute so it shares one water program with streams and sea grids. */
433
+ export function waterPlane(width, depth, widthSegments = 1, depthSegments = 1) {
434
+ const geometry = new THREE.PlaneGeometry(width, depth, widthSegments, depthSegments).rotateX(-Math.PI / 2);
435
+ geometry.deleteAttribute('normal');
436
+ return geometry;
437
+ }
438
+
432
439
  /** Populate `aBank` visibility weights across a partial open-water sheet. */
433
440
  export function partSheet(geometry, shareAt) {
434
441
  const pos = geometry.attributes.position,
435
442
  bank = new Float32Array(pos.count * 4);
436
443
  for (let v = 0; v < pos.count; v++) bank.set([DEEP, shareAt(pos.getX(v), pos.getZ(v)), FAR, FAR], v * 4);
437
444
  geometry.setAttribute('aBank', new THREE.BufferAttribute(bank, 4));
445
+ geometry.deleteAttribute('normal');
438
446
  return geometry;
439
447
  }
440
448
 
@@ -444,6 +452,7 @@ export function sheetDepths(geometry, depthAt) {
444
452
  bank = new Float32Array(count * 4);
445
453
  for (let v = 0; v < count; v++) bank.set([depthAt(v) ?? DEEP, 1, FAR, FAR], v * 4);
446
454
  geometry.setAttribute('aBank', new THREE.BufferAttribute(bank, 4));
455
+ geometry.deleteAttribute('normal');
447
456
  return geometry;
448
457
  }
449
458
 
package/scripts/build.py CHANGED
@@ -45,6 +45,8 @@ GLSL_COMMENTS = re.compile(r"//[^\n]*|/\*.*?\*/", re.S)
45
45
  GLSL_DIRECTIVES = re.compile(r"(^[ \t]*#(?:[^\n]*\\\n)*[^\n]*(?:\n|$))", re.M)
46
46
  PART_IMPORT = re.compile(r'(\bimport\("\./(part-[0-9A-Za-z]+\.js)"\))') # an import() of a hashed bundle
47
47
  PRELOAD = os.environ.get("BUILD_PRELOAD_FN", "preloadParts")
48
+ # How long one bundling or parsing step may take: a busy machine (several builds at once) needs far more than an idle one.
49
+ STEP_TIMEOUT = int(os.environ.get("BUILD_STEP_TIMEOUT", "600"))
48
50
  SPLIT_PREFIX = re.compile(r"^split:") # how scripts/bundle.mjs names a piece of a module split into parts
49
51
  GLSL_JOINED_OPERATORS = {
50
52
  "++",
@@ -99,7 +101,7 @@ def esbuild(args, text=None, root=None):
99
101
  cwd = ROOT if root is None else Path(root)
100
102
  cmd = [cwd / "node_modules/.bin/esbuild", "--target=es2022", "--log-level=warning"] + args
101
103
  try:
102
- r = subprocess.run(cmd, input=text, capture_output=True, text=True, timeout=180, cwd=cwd)
104
+ r = subprocess.run(cmd, input=text, capture_output=True, text=True, timeout=STEP_TIMEOUT, cwd=cwd)
103
105
  except (OSError, subprocess.TimeoutExpired) as e:
104
106
  print(f" esbuild could not be run ({e})", file=sys.stderr)
105
107
  return None
@@ -119,7 +121,7 @@ def bundle_modules(options, bundle_script=None, root=None):
119
121
  script = bundle_script or os.environ.get("BUILD_BUNDLE_SCRIPT", "scripts/bundle.mjs")
120
122
  args = ["node", "--no-warnings", script]
121
123
  try:
122
- r = subprocess.run(args, input=json.dumps(options), capture_output=True, text=True, timeout=180, cwd=cwd)
124
+ r = subprocess.run(args, input=json.dumps(options), capture_output=True, text=True, timeout=STEP_TIMEOUT, cwd=cwd)
123
125
  except (OSError, subprocess.TimeoutExpired) as e:
124
126
  print(f" esbuild could not be run ({e})", file=sys.stderr)
125
127
  return False
@@ -202,7 +204,7 @@ def minify_shader_literals(js, root=None):
202
204
  capture_output=True,
203
205
  text=True,
204
206
  encoding="utf-8",
205
- timeout=180,
207
+ timeout=STEP_TIMEOUT,
206
208
  cwd=cwd,
207
209
  check=True,
208
210
  )