roamwright 0.2.0 → 0.20.1

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.
Files changed (140) hide show
  1. package/CONTRIBUTING.md +3 -1
  2. package/README.md +19 -21
  3. package/geometry/bedding.js +141 -0
  4. package/geometry/builder-cells.js +42 -0
  5. package/geometry/builder-frame.js +47 -0
  6. package/geometry/builder.js +189 -177
  7. package/geometry/cell-mask.js +25 -0
  8. package/geometry/creased-sheet.js +34 -34
  9. package/geometry/ear.js +36 -36
  10. package/geometry/erosion.js +65 -42
  11. package/geometry/face-grid.js +65 -65
  12. package/geometry/foliage.js +47 -0
  13. package/geometry/hair-gathers.js +41 -41
  14. package/geometry/hair-locks.js +41 -41
  15. package/geometry/hair-patch.js +18 -18
  16. package/geometry/hair-shell.js +31 -31
  17. package/geometry/head-profile.js +15 -15
  18. package/geometry/head-shape.js +77 -77
  19. package/geometry/heightfield.js +27 -18
  20. package/geometry/index-parts.js +60 -0
  21. package/geometry/instance-visibility.js +41 -0
  22. package/geometry/instances.js +35 -12
  23. package/geometry/outline-grid.js +7 -7
  24. package/geometry/part-ranges.js +18 -0
  25. package/geometry/path-field.js +63 -33
  26. package/geometry/placement.js +52 -52
  27. package/geometry/point-buckets.js +50 -0
  28. package/geometry/primitives.js +63 -47
  29. package/geometry/sagging-tube.js +27 -27
  30. package/geometry/sampled-surface.js +109 -77
  31. package/geometry/scatter-grid.js +46 -6
  32. package/geometry/sculpt.js +93 -93
  33. package/geometry/shore-grid.js +77 -34
  34. package/geometry/strata-field.js +92 -92
  35. package/geometry/strata-tiles.js +91 -91
  36. package/geometry/stream.js +70 -48
  37. package/geometry/terrain-chunks.js +101 -92
  38. package/geometry/terrain-extension.js +6 -6
  39. package/index.js +5 -0
  40. package/math/cell-edge.js +16 -16
  41. package/math/cell-key.js +6 -0
  42. package/math/circle-clearances.js +19 -0
  43. package/math/cloth-textures.js +6 -6
  44. package/math/cloud-textures.js +20 -20
  45. package/math/color.js +14 -14
  46. package/math/curve.js +22 -22
  47. package/math/mountain-ranges.js +216 -165
  48. package/math/noise.js +101 -49
  49. package/math/particle-noise.js +28 -28
  50. package/math/periodic.js +5 -5
  51. package/math/random.js +24 -15
  52. package/math/rectangles.js +52 -0
  53. package/math/rock-texture.js +7 -7
  54. package/math/scalar.js +5 -5
  55. package/math/surface-textures.js +54 -54
  56. package/motion/arm-reach.js +24 -24
  57. package/motion/ballistic-arc.js +11 -0
  58. package/motion/biped-cycle.js +44 -0
  59. package/motion/biped-leg.js +37 -0
  60. package/motion/biped-stride.js +98 -122
  61. package/motion/contact-transition.js +33 -0
  62. package/motion/crowd-alarms.js +39 -39
  63. package/motion/crowd-routine.js +94 -65
  64. package/motion/daily-clock.js +9 -9
  65. package/motion/deck-surface.js +38 -0
  66. package/motion/ground-lookahead.js +29 -0
  67. package/motion/instance-sight.js +8 -8
  68. package/motion/player.js +36 -28
  69. package/motion/quadruped.js +155 -155
  70. package/motion/spaces.js +32 -32
  71. package/motion/weather.js +73 -24
  72. package/motion/wind.js +32 -13
  73. package/package.json +8 -4
  74. package/rendering/caster-motion.js +5 -5
  75. package/rendering/cell-lod.js +147 -82
  76. package/rendering/cloud-dome.js +28 -28
  77. package/rendering/cloud-field.js +2 -2
  78. package/rendering/compilation-schedule.js +68 -11
  79. package/rendering/contact-shadows.js +2 -2
  80. package/rendering/context.js +12 -0
  81. package/rendering/crowd-skinning.js +13 -13
  82. package/rendering/crust.js +18 -12
  83. package/rendering/daylight.js +3 -3
  84. package/rendering/detail-range.js +28 -0
  85. package/rendering/dispose-meshes.js +18 -0
  86. package/rendering/dof.js +9 -9
  87. package/rendering/eye-adapt.js +14 -14
  88. package/rendering/far-shadow.js +8 -8
  89. package/rendering/flocks.js +78 -78
  90. package/rendering/garment-material.js +17 -17
  91. package/rendering/glow-lines.js +13 -13
  92. package/rendering/hair-strands.js +20 -20
  93. package/rendering/height-probe.js +149 -19
  94. package/rendering/label-layout.js +46 -0
  95. package/rendering/label-range.js +38 -0
  96. package/rendering/light-budget.js +52 -52
  97. package/rendering/light-shafts.js +23 -23
  98. package/rendering/local-lights.js +15 -4
  99. package/rendering/material-lod.js +49 -49
  100. package/rendering/particle-emitters.js +90 -90
  101. package/rendering/particles.js +78 -67
  102. package/rendering/piece-batch.js +91 -26
  103. package/rendering/planar-reflection.js +38 -38
  104. package/rendering/post-shaders.js +17 -13
  105. package/rendering/post.js +71 -71
  106. package/rendering/rain-streaks.js +67 -0
  107. package/rendering/road-surface.js +11 -11
  108. package/rendering/sea-shaders.js +11 -11
  109. package/rendering/shader-warmup.js +29 -16
  110. package/rendering/shadow-alignment.js +4 -4
  111. package/rendering/shadow-depth.js +7 -7
  112. package/rendering/sky-occlusion.js +16 -16
  113. package/rendering/sky.js +16 -6
  114. package/rendering/stage-lights.js +6 -6
  115. package/rendering/static-point-shadow.js +3 -3
  116. package/rendering/still-casters.js +1 -1
  117. package/rendering/strata-material.js +10 -10
  118. package/rendering/stream-flow.js +10 -10
  119. package/rendering/taa.js +26 -26
  120. package/rendering/talus.js +15 -15
  121. package/rendering/terrain-rock.js +7 -7
  122. package/rendering/texture-fills.js +8 -8
  123. package/rendering/textures.js +28 -28
  124. package/rendering/wakes.js +24 -24
  125. package/rendering/water-material.js +36 -23
  126. package/rendering/world-matrices.js +38 -38
  127. package/runtime/diagnostic-log.js +2 -2
  128. package/runtime/first-use.js +33 -28
  129. package/runtime/frame-budget.js +49 -0
  130. package/runtime/frame-pacing.js +33 -0
  131. package/runtime/gpu-timing.js +13 -10
  132. package/runtime/grid-cache.js +1 -1
  133. package/runtime/grid-rows.js +44 -5
  134. package/runtime/hand-over.js +41 -23
  135. package/runtime/pool.js +58 -16
  136. package/runtime/quality-fit.js +1 -1
  137. package/runtime/search.js +22 -22
  138. package/runtime/spatial-audio.js +13 -13
  139. package/runtime/withdrawable-task.js +35 -0
  140. package/runtime/worker.js +7 -0
@@ -25,7 +25,7 @@ export function createCloudDome({ renderer, field, warmProgram }) {
25
25
  JUMP = 0.6, // the viewer carried further than this in one frame (the field's units) is a cut: the clouds are drawn whole at once
26
26
  TURNED = 0.96, // and so is a light that turned by more than this cosine,
27
27
  CHANGED = 0.1; // or a sky whose threshold moved by more
28
- const f = (v, digits = 4) => v.toFixed(digits);
28
+ const formatFloat = (v, digits = 4) => v.toFixed(digits);
29
29
 
30
30
  const DOME_FS = `/* glsl */
31
31
  precision highp float; precision highp sampler3D;
@@ -43,15 +43,15 @@ export function createCloudDome({ renderer, field, warmProgram }) {
43
43
  const float ERODE = 0.12; // how far the creases between billows eat into the body, and
44
44
  const float FINER = 0.42; // the finer ones, as a share of that
45
45
  // Where a point lies in the block of billows: p from the viewer in the field's units, h its height in the layer.
46
- vec3 inBlock(vec2 p, float h) { return vec3(uAt * ${f(CLOUD_SHEET, 1)} + p, h * ${f(DEPTH)}).xzy * ${f(BLOCKS)}; }
46
+ vec3 inBlock(vec2 p, float h) { return vec3(uAt * ${formatFloat(CLOUD_SHEET, 1)} + p, h * ${formatFloat(DEPTH)}).xzy * ${formatFloat(BLOCKS)}; }
47
47
  // How far inside a cloud's body a point lies, in the field's value: 0 at its edge, SOFT and more in full cloud, below 0 in
48
48
  // clear air. p: from the viewer in the field's units; h: its height in the layer (0 the base, 1 the top). over: how far the
49
49
  // field stands over the threshold there; base: what the cloud's underside leaves of it there (0 below it, 1 well above);
50
50
  // rough: how far the billows eat into it there.
51
51
  float bodyAt(vec2 p, float h, float lod, out float over, out float base, out float rough) {
52
- vec4 texel = textureLod(uCloudField, uAt + p * ${f(1 / CLOUD_SHEET, 6)}, lod);
52
+ vec4 texel = textureLod(uCloudField, uAt + p * ${formatFloat(1 / CLOUD_SHEET, 6)}, lod);
53
53
  over = cloudField(texel) - uCloud;
54
- float h2 = h * h, body = over - ${f(SPAN)} * h2 * h2;
54
+ float h2 = h * h, body = over - ${formatFloat(SPAN)} * h2 * h2;
55
55
  rough = ERODE * (0.45 + 0.55 * smoothstep(0.0, 0.3, h)); // a cloud's base is smoother than its sides and top
56
56
  // the base is level but for shallow hollows between hanging bulges (the sheet's finer lumps), deeper under a closed sky
57
57
  base = smoothstep(0.0, BASE_SOFT, h - (BASE_HOLLOW + BASE_HOLLOW_CLOSED * smoothstep(0.25, 0.6, over)) * (1.0 - texel.g));
@@ -60,22 +60,22 @@ export function createCloudDome({ renderer, field, warmProgram }) {
60
60
  }
61
61
  // The share of a stretch that is cloud when its two ends lie a and b inside the body, the body taken to change evenly between
62
62
  // them: a cloud's edge is found where it lies between two steps, not at the nearer step (which drew it in terraces).
63
- float filled(float a, float b) {
64
- vec2 e = max(vec2(a, b), 0.0), sum = mix(e * e * ${f(0.5)} / SOFT, e - 0.5 * SOFT, step(SOFT, e));
65
- return abs(b - a) > 1e-4 ? clamp((sum.y - sum.x) / (b - a), 0.0, 1.0) : clamp(a / SOFT, 0.0, 1.0);
63
+ float filled(float startDensity, float endDensity) {
64
+ vec2 densities = max(vec2(startDensity, endDensity), 0.0), sum = mix(densities * densities * ${formatFloat(0.5)} / SOFT, densities - 0.5 * SOFT, step(SOFT, densities));
65
+ return abs(endDensity - startDensity) > 1e-4 ? clamp((sum.y - sum.x) / (endDensity - startDensity), 0.0, 1.0) : clamp(startDensity / SOFT, 0.0, 1.0);
66
66
  }
67
67
  void main() {
68
- vec2 r = (vUv - 0.5) * ${f(2 * RIM)};
68
+ vec2 r = (vUv - 0.5) * ${formatFloat(2 * RIM)};
69
69
  float r2 = dot(r, r);
70
- if (r2 >= ${f(RIM * RIM)}) { gl_FragColor = vec4(0.0); return; }
70
+ if (r2 >= ${formatFloat(RIM * RIM)}) { gl_FragColor = vec4(0.0); return; }
71
71
  float up = (1.0 - r2) / (1.0 + r2); // the direction's height: 1 overhead, 0 at the horizon
72
- if (up < ${f(LOWEST - 0.012)}) { gl_FragColor = vec4(0.0); return; } // no cloud is drawn that low in the sky (cloud-field.js)
73
- vec2 q = r * (1.0 + up) / (max(up, 0.0) + ${f(DIP)}); // how far the ray runs level for each unit it climbs
72
+ if (up < ${formatFloat(LOWEST - 0.012)}) { gl_FragColor = vec4(0.0); return; } // no cloud is drawn that low in the sky (cloud-field.js)
73
+ vec2 q = r * (1.0 + up) / (max(up, 0.0) + ${formatFloat(DIP)}); // how far the ray runs level for each unit it climbs
74
74
  float reach = length(q), slope = sqrt(1.0 + reach * reach);
75
75
  int steps = int(min(float(STEPS) + 9.0 * reach, float(MAX_STEPS))); // a ray near the horizon runs long through the layer
76
76
  float dh = 1.0 / float(steps);
77
77
  // the sheet's level of detail: a step is not finer than the way it travels, or a far cloud showed as a stack of slivers
78
- float lod = clamp(log2(max(reach * dh * ${f(DEPTH * TEXELS)}, 0.01)) - 0.5, 0.0, 3.0);
78
+ float lod = clamp(log2(max(reach * dh * ${formatFloat(DEPTH * TEXELS)}, 0.01)) - 0.5, 0.0, 3.0);
79
79
  float finer = FINER * (1.0 - lod / 1.5); // the finer billows fade out where a step is too long to show them
80
80
  // each ray's steps stand a little higher or lower than its neighbours', so what is left of the layer's levels in a cloud's
81
81
  // shading does not run on as lines
@@ -85,7 +85,7 @@ export function createCloudDome({ renderer, field, warmProgram }) {
85
85
  for (int i = 0; i < MAX_STEPS; i++) {
86
86
  if (i >= steps) break;
87
87
  float h = (float(i) + shift) * dh;
88
- vec2 p = q * (${f(FLARE)} * (1.0 + h * ${f(THICK)}));
88
+ vec2 p = q * (${formatFloat(FLARE)} * (1.0 + h * ${formatFloat(THICK)}));
89
89
  float body = bodyAt(p, h, lod, over, base, rough), cloud;
90
90
  #if FINE
91
91
  if (finer > 0.0 && max(was, body) > 0.0) {
@@ -94,7 +94,7 @@ export function createCloudDome({ renderer, field, warmProgram }) {
94
94
  for (int k = 1; k <= 3; k++) {
95
95
  float t = float(k) / 3.0, hk = h - (1.0 - t) * dh, part = mix(was, body, t);
96
96
  if (part > 0.0) {
97
- vec3 small = textureLod(uBillows, inBlock(q * (${f(FLARE)} * (1.0 + hk * ${f(THICK)})), hk) * 4.0 + uChurn.zxy * 3.0, lod).rgb;
97
+ vec3 small = textureLod(uBillows, inBlock(q * (${formatFloat(FLARE)} * (1.0 + hk * ${formatFloat(THICK)})), hk) * 4.0 + uChurn.zxy * 3.0, lod).rgb;
98
98
  part -= rough * finer * (1.0 - dot(small, vec3(0.5, 0.3, 0.2)));
99
99
  }
100
100
  cloud += filled(wasFine, part);
@@ -115,9 +115,9 @@ export function createCloudDome({ renderer, field, warmProgram }) {
115
115
  if (cloud < 0.003) continue;
116
116
  // the cloud between this point and the light, in steps that lengthen
117
117
  float between = 0.0, gone = 0.0, span = float(L_FIRST);
118
- vec2 from = q * (${f(FLARE)} * (1.0 + lit * ${f(THICK)}));
118
+ vec2 from = q * (${formatFloat(FLARE)} * (1.0 + lit * ${formatFloat(THICK)}));
119
119
  for (int j = 0; j < LIGHT_STEPS; j++) {
120
- float l = gone + 0.5 * span, hl = lit + uLight.y * l * ${f(1 / DEPTH)};
120
+ float l = gone + 0.5 * span, hl = lit + uLight.y * l * ${formatFloat(1 / DEPTH)};
121
121
  if (hl <= 0.0 || hl >= 1.0) break;
122
122
  between += clamp(bodyAt(from + uLight.xz * l, hl, max(lod, 0.5) + 0.5 * float(j), none, base, rough) / SOFT, 0.0, 1.0) * base * span;
123
123
  gone += span; span *= float(L_GROW);
@@ -125,17 +125,17 @@ export function createCloudDome({ renderer, field, warmProgram }) {
125
125
  between *= SIGMA;
126
126
  float once = exp(-between); // light that comes straight through
127
127
  float many = 0.7 * exp(-between * 0.3) + 0.3 * exp(-between * 0.1); // and light passed on from drop to drop, which reaches deeper
128
- float top = sqrt(sqrt(clamp(over * ${f(1 / SPAN)}, 0.0, 1.0)));
128
+ float top = sqrt(sqrt(clamp(over * ${formatFloat(1 / SPAN)}, 0.0, 1.0)));
129
129
  // the sky's light: from above, less the deeper under the cloud's top, and a little from below on its base
130
130
  float sky = 0.84 * exp(-3.0 * max(top - lit, 0.0)) * (0.5 + 0.5 * lit) + 0.16 * exp(-5.0 * lit);
131
- float a = 1.0 - exp(-cloud * (SIGMA * ${f(DEPTH)}) * dh * slope);
131
+ float a = 1.0 - exp(-cloud * (SIGMA * ${formatFloat(DEPTH)}) * dh * slope);
132
132
  sum += seen * a * vec3(many, once, sky);
133
133
  seen *= 1.0 - a;
134
134
  if (seen < 0.02) break;
135
135
  }
136
136
  // each is kept in a byte: a grain of half a step of it hides the steps between
137
137
  float grain = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) - 0.5;
138
- gl_FragColor = vec4(sum, min((1.0 - seen) * ${f(1 / 0.98)}, 1.0)) + grain * ${f(1 / 255, 6)};
138
+ gl_FragColor = vec4(sum, min((1.0 - seen) * ${formatFloat(1 / 0.98)}, 1.0)) + grain * ${formatFloat(1 / 255, 6)};
139
139
  }`;
140
140
 
141
141
  // For the sky's shader: declares cloudDome(d), the clouds' picture in a direction above the horizon (r, g, b, a as above).
@@ -143,11 +143,11 @@ export function createCloudDome({ renderer, field, warmProgram }) {
143
143
  uniform sampler2D uDome, uDomeNext; uniform vec4 uDomeShift; uniform float uDomeMix;
144
144
  // where a ray that runs q level for each unit it climbs lies in a map
145
145
  vec2 domeUv(vec2 q) {
146
- float Q = dot(q, q), up = (sqrt(1.0 + Q * ${f(1 - DIP * DIP, 6)}) - Q * ${f(DIP)}) / (1.0 + Q);
147
- return 0.5 + q * ((up + ${f(DIP)}) / (1.0 + up) * ${f(0.5 / RIM, 6)});
146
+ float Q = dot(q, q), up = (sqrt(1.0 + Q * ${formatFloat(1 - DIP * DIP, 6)}) - Q * ${formatFloat(DIP)}) / (1.0 + Q);
147
+ return 0.5 + q * ((up + ${formatFloat(DIP)}) / (1.0 + up) * ${formatFloat(0.5 / RIM, 6)});
148
148
  }
149
149
  vec4 cloudDome(vec3 d) {
150
- vec2 q = d.xz / (max(d.y, 0.0) + ${f(DIP)});
150
+ vec2 q = d.xz / (max(d.y, 0.0) + ${formatFloat(DIP)});
151
151
  vec4 c = textureLod(uDome, domeUv(q + uDomeShift.xy), 0.0);
152
152
  if (uDomeMix > 0.0) c = mix(c, textureLod(uDomeNext, domeUv(q + uDomeShift.zw), 0.0), uDomeMix);
153
153
  return c;
@@ -200,12 +200,12 @@ export function createCloudDome({ renderer, field, warmProgram }) {
200
200
  function equalBands(size, bands) {
201
201
  const below = y => 0.5 + (y * Math.sqrt(1 - y * y) + Math.asin(y)) / Math.PI, // the share of a circle below y (-1 its foot, 1 its top)
202
202
  rows = [0];
203
- for (let k = 1; k < bands; k++) {
203
+ for (let bandIndex = 1; bandIndex < bands; bandIndex++) {
204
204
  let low = -1,
205
205
  high = 1;
206
206
  for (let i = 0; i < 30; i++) {
207
207
  const mid = (low + high) / 2;
208
- if (below(mid) < k / bands) low = mid;
208
+ if (below(mid) < bandIndex / bands) low = mid;
209
209
  else high = mid;
210
210
  }
211
211
  rows.push(Math.round(((low + 1) / 2) * size));
@@ -241,8 +241,8 @@ export function createCloudDome({ renderer, field, warmProgram }) {
241
241
  STEPS: level.steps,
242
242
  MAX_STEPS: level.most,
243
243
  LIGHT_STEPS: level.light,
244
- L_FIRST: f(level.first),
245
- L_GROW: f(level.grow),
244
+ L_FIRST: formatFloat(level.first),
245
+ L_GROW: formatFloat(level.grow),
246
246
  FINE: level.fine,
247
247
  });
248
248
  domeMat.needsUpdate = true;
@@ -293,7 +293,7 @@ export function createCloudDome({ renderer, field, warmProgram }) {
293
293
  // sky where the maps lie. light: towards the sun or the moon, whichever lights the clouds; threshold: the field's value
294
294
  // where cloud begins; seconds: the world's time; bright: how strong that light is now (a dark one may turn unseen, as when
295
295
  // the moon takes over from the sun that has set).
296
- function updateCloudDome(dt, light, threshold, seconds, bright, region) {
296
+ function updateCloudDome(deltaSeconds, light, threshold, seconds, bright, region) {
297
297
  const { level, last } = dome,
298
298
  sheet = cloudU.uCloudField.value,
299
299
  billows = cloudBillows.value;
@@ -320,7 +320,7 @@ export function createCloudDome({ renderer, field, warmProgram }) {
320
320
  dome.band = 0;
321
321
  dome.mix = 0;
322
322
  } else if (dome.fading) {
323
- dome.mix += dt / FADE;
323
+ dome.mix += deltaSeconds / FADE;
324
324
  if (dome.mix >= 1) {
325
325
  const shown = dome.next,
326
326
  at = dome.nextAt;
@@ -53,10 +53,10 @@ export function createCloudField({
53
53
  const driftX = drift.x * ALOFT * FIELD_PER_METRE,
54
54
  driftZ = drift.y * ALOFT * FIELD_PER_METRE,
55
55
  slant = (FLARE * (1 + SHADOW_AT * THICK)) / (Math.max(light.y, 0) + DIP),
56
- sh = cloudU.uCloudSh.value;
56
+ cloudShadow = cloudU.uCloudSh.value;
57
57
  overhead.x = x * FIELD_PER_METRE + driftX;
58
58
  overhead.z = z * FIELD_PER_METRE + driftZ;
59
- sh.set(
59
+ cloudShadow.set(
60
60
  wrap((driftX + light.x * slant) / CLOUD_SHEET),
61
61
  wrap((driftZ + light.z * slant) / CLOUD_SHEET),
62
62
  threshold + SHADOW_FROM,
@@ -1,7 +1,13 @@
1
- // Coordinate early, whole-scene and incremental program warmup. The application supplies its pass
2
- // graph and decides how newly linked programs enter the renderer's first-use queue.
1
+ /**
2
+ * Coordinate shader compilation and first use across an application's render passes.
3
+ * During loading, await `warmShaders(roots, { blocking: true })` to pass the blocking
4
+ * flag to `beginCompiles` and submit shader programs together. During play, omit
5
+ * the flag to follow the application's incremental schedule. The roots can be one
6
+ * subtree or several disjoint subtrees that share a lighting environment.
7
+ */
3
8
  export function createCompilationSchedule({renderer, scene, beginCompiles, putToUse, useProgram, timeoutMs = 20000, onError = () => {}}) {
4
9
  let warmed = false;
10
+ const interrupted = new WeakMap();
5
11
  const programs = () => renderer.info.programs;
6
12
  const addedSince = known => programs().filter(program => !known.has(program));
7
13
  function beginWarm() {
@@ -10,25 +16,76 @@ export function createCompilationSchedule({renderer, scene, beginCompiles, putTo
10
16
  try {
11
17
  const done = beginCompiles(scene, warmed);
12
18
  const added = addedSince(known);
13
- return Promise.resolve(done).then(() => putToUse(added.filter(p => programs().includes(p)))).catch(onError);
19
+ return Promise.resolve(done).then(() => putToUse(added.filter(program => programs().includes(program)))).catch(onError);
14
20
  } catch (error) { onError(error); }
15
21
  }
16
- async function warmShaders(root = scene) {
22
+ // Disjoint subtrees of one scene can share a pass without being reparented. A blocking load
23
+ // may submit them together and initialize the programs before its first draw.
24
+ async function warmShaders(root = scene, {blocking = false, signal, retryKey = root} = {}) {
25
+ signal?.throwIfAborted();
26
+ if (Array.isArray(root)) {
27
+ const roots = root;
28
+ if (!roots.length) return;
29
+ root = {
30
+ traverse(visit) { for (const tree of roots) tree.traverse(visit); },
31
+ traverseVisible(visit) {
32
+ // The target scene already contributes its visible lights. Only detached roots
33
+ // bring additional lights to Three's compile pass.
34
+ for (const tree of roots) {
35
+ let parent = tree;
36
+ while (parent && parent !== scene) parent = parent.parent;
37
+ if (!parent) tree.traverseVisible(visit);
38
+ }
39
+ }
40
+ };
41
+ }
17
42
  const known = new Set(programs());
18
- let timer;
43
+ const unfinished = signal && interrupted.get(retryKey);
44
+ if (unfinished) for (const program of known) if (unfinished.has(program)) known.delete(program);
45
+ let timer, onAbort;
46
+ const deadline = signal && new AbortController();
47
+ const active = signal && AbortSignal.any([signal, deadline.signal]);
19
48
  try {
20
- const done = beginCompiles(root, warmed);
21
- if (root !== scene && !warmed) {
49
+ const done = beginCompiles(root, warmed, blocking, active);
50
+ if (root !== scene && !warmed && !blocking && !signal) {
22
51
  Promise.resolve(done).catch(onError);
23
52
  return;
24
53
  }
25
- await Promise.race([done, new Promise(resolve => { timer = setTimeout(resolve, timeoutMs); })]);
54
+ const limit = new Promise((resolve, reject) => {
55
+ if (!active) {
56
+ timer = setTimeout(resolve, timeoutMs);
57
+ return;
58
+ }
59
+ onAbort = () => reject(active.reason);
60
+ if (active.aborted) { onAbort(); return; }
61
+ active.addEventListener('abort', onAbort, { once: true });
62
+ timer = setTimeout(() => deadline.abort(new Error('Shader preparation timed out')), timeoutMs);
63
+ });
64
+ await Promise.race([done, limit]);
65
+ active?.throwIfAborted();
26
66
  if (root === scene) {
27
67
  for (const program of programs()) useProgram(program);
28
68
  warmed = true;
29
- } else await putToUse(addedSince(known));
30
- } catch (error) { onError(error); }
31
- finally { clearTimeout(timer); }
69
+ } else if (blocking) {
70
+ for (const program of addedSince(known)) useProgram(program);
71
+ } else await putToUse(addedSince(known), active);
72
+ if (unfinished) interrupted.delete(retryKey);
73
+ } catch (error) {
74
+ if (signal) {
75
+ const unclaimed = unfinished || new WeakSet();
76
+ for (const program of addedSince(known)) unclaimed.add(program);
77
+ interrupted.set(retryKey, unclaimed);
78
+ // Other passes in the same preparation may still have an incremental submission queued.
79
+ deadline.abort(error);
80
+ if (signal.aborted) throw signal.reason;
81
+ }
82
+ onError(error);
83
+ if (signal) throw error;
84
+ }
85
+ finally {
86
+ clearTimeout(timer);
87
+ if (onAbort) active.removeEventListener('abort', onAbort);
88
+ }
32
89
  }
33
90
  return {beginWarm, warmShaders};
34
91
  }
@@ -28,8 +28,8 @@ export class ContactShadows {
28
28
  void main() {
29
29
  offset = position.xz;
30
30
  weight = intensity;
31
- vec3 p = contact.xyz + vec3(position.x * contact.w, lift, position.z * contact.w);
32
- gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
31
+ vec3 contactPosition = contact.xyz + vec3(position.x * contact.w, lift, position.z * contact.w);
32
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(contactPosition, 1.0);
33
33
  }`,
34
34
  fragmentShader: `
35
35
  uniform float opacityScale;
@@ -1,5 +1,17 @@
1
+ /**
2
+ * Create the Three.js renderer, scenes and camera used by a Roamwright world.
3
+ * @module
4
+ */
5
+
1
6
  import * as THREE from 'three';
2
7
 
8
+ /**
9
+ * Create a shadow-enabled renderer, a perspective camera and a group for world objects.
10
+ * Size the renderer to the canvas and update the camera aspect ratio before rendering.
11
+ * @param {HTMLCanvasElement} canvas - Drawing surface for the WebGL renderer.
12
+ * @param options - Antialiasing, vertical field of view in degrees, and near and far clipping distances in world units.
13
+ * @returns The renderer, main scene, camera, world group and a separate scene for effects.
14
+ */
3
15
  export function createRenderContext(canvas, { antialias = true, fov = 68, near = 0.25, far = 7000 } = {}) {
4
16
  const renderer = new THREE.WebGLRenderer({ canvas, antialias, powerPreference: 'high-performance', stencil: false });
5
17
  renderer.outputColorSpace = THREE.SRGBColorSpace;
@@ -57,10 +57,10 @@ export function applyCrowdSkinning(shader, { poseUniform, walk = null, depth = f
57
57
  }
58
58
  }
59
59
 
60
- export function createCrowdBatch(scene, geo, max, mat, [depth, distance], name, casts = true) {
61
- const mesh = new THREE.InstancedMesh(geo, mat, max);
60
+ export function createCrowdBatch(scene, geometry, max, material, [depth, distance], name, casts = true) {
61
+ const mesh = new THREE.InstancedMesh(geometry, material, max);
62
62
  const rows = new THREE.InstancedBufferAttribute(new Float32Array(max * 2), 2).setUsage(THREE.DynamicDrawUsage);
63
- geo.setAttribute('aCrowdRows', rows);
63
+ geometry.setAttribute('aCrowdRows', rows);
64
64
  mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
65
65
  mesh.name = name;
66
66
  mesh.frustumCulled = false;
@@ -73,10 +73,10 @@ export function createCrowdBatch(scene, geo, max, mat, [depth, distance], name,
73
73
  return { mesh, rows, count: 0, shadow: null };
74
74
  }
75
75
 
76
- export function castCrowdShadow(scene, near, geo, [depth, distance]) {
77
- const mesh = new THREE.InstancedMesh(geo, near.mesh.material, 0);
76
+ export function castCrowdShadow(scene, near, geometry, [depth, distance]) {
77
+ const mesh = new THREE.InstancedMesh(geometry, near.mesh.material, 0);
78
78
  let held = 0;
79
- geo.setAttribute('aCrowdRows', near.rows);
79
+ geometry.setAttribute('aCrowdRows', near.rows);
80
80
  mesh.instanceMatrix = near.mesh.instanceMatrix;
81
81
  mesh.name = near.mesh.name + ' shadow';
82
82
  mesh.frustumCulled = false;
@@ -100,8 +100,8 @@ export function bakeCrowdFrame(walk, bones) {
100
100
  vertices = walk.vertices;
101
101
  let k = walk.k;
102
102
  for (let i = 0; i < position.count; i++) {
103
- const a = aJoints.getX(i) * 12,
104
- b = aJoints.getY(i) * 12,
103
+ const firstJointOffset = aJoints.getX(i) * 12,
104
+ secondJointOffset = aJoints.getY(i) * 12,
105
105
  w = aWeight.getX(i);
106
106
  const x = position.getX(i),
107
107
  y = position.getY(i),
@@ -109,11 +109,11 @@ export function bakeCrowdFrame(walk, bones) {
109
109
  const nx = normal.getX(i),
110
110
  ny = normal.getY(i),
111
111
  nz = normal.getZ(i);
112
- const m = j => lerp(bones[b + j], bones[a + j], w);
113
- const after = (v, u, q, j) => m(j) * v + m(j + 1) * u + m(j + 2) * q;
114
- vertices[k++] = after(x, y, z, 0) + m(3);
115
- vertices[k++] = after(x, y, z, 4) + m(7);
116
- vertices[k++] = after(x, y, z, 8) + m(11);
112
+ const boneComponent = j => lerp(bones[secondJointOffset + j], bones[firstJointOffset + j], w);
113
+ const after = (v, u, q, j) => boneComponent(j) * v + boneComponent(j + 1) * u + boneComponent(j + 2) * q;
114
+ vertices[k++] = after(x, y, z, 0) + boneComponent(3);
115
+ vertices[k++] = after(x, y, z, 4) + boneComponent(7);
116
+ vertices[k++] = after(x, y, z, 8) + boneComponent(11);
117
117
  let vx = after(nx, ny, nz, 0),
118
118
  vy = after(nx, ny, nz, 4);
119
119
  const vz = after(nx, ny, nz, 8),
@@ -3,26 +3,32 @@ export const crustGLSL = /* glsl */ `
3
3
  // a cell's number is wrapped before it is hashed: far from the world's middle it ran to tens of thousands, sin() was asked
4
4
  // for the sine of millions, and a graphics card that takes sines quickly and roughly (iOS) laid the cells out in fans and rows
5
5
  const float CELL_WRAP = 289.0;
6
- vec2 cellPoint(vec2 c) { c = mod(c, CELL_WRAP); return fract(sin(vec2(dot(c, vec2(127.1, 311.7)), dot(c, vec2(269.5, 183.3)))) * 43758.5453); }
6
+ vec2 cellPoint(vec2 cell) { cell = mod(cell, CELL_WRAP); return fract(sin(vec2(dot(cell, vec2(127.1, 311.7)), dot(cell, vec2(269.5, 183.3)))) * 43758.5453); }
7
7
  // the cells nearest q: x and y the nearest two distances, zw the nearest cell
8
- vec4 nearestCells(vec2 q) {
9
- vec2 ci = floor(q), cf = fract(q), near = ci; float f1 = 9.0, f2 = 9.0;
8
+ vec4 nearestCells(vec2 gridPosition) {
9
+ vec2 cellIndex = floor(gridPosition), cellFraction = fract(gridPosition), nearestCell = cellIndex; float nearestSquared = 9.0, secondSquared = 9.0;
10
10
  for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
11
- vec2 o = vec2(float(i), float(j)), r = o + cellPoint(ci + o) - cf; float dd = dot(r, r);
12
- if (dd < f1) { f2 = f1; f1 = dd; near = ci + o; } else if (dd < f2) f2 = dd;
11
+ vec2 cellOffset = vec2(float(i), float(j)), pointOffset = cellOffset + cellPoint(cellIndex + cellOffset) - cellFraction; float distanceSquared = dot(pointOffset, pointOffset);
12
+ if (distanceSquared < nearestSquared) {
13
+ secondSquared = nearestSquared;
14
+ nearestSquared = distanceSquared;
15
+ nearestCell = cellIndex + cellOffset;
16
+ } else if (distanceSquared < secondSquared) {
17
+ secondSquared = distanceSquared;
18
+ }
13
19
  }
14
- return vec4(sqrt(f1), sqrt(f2), near);
20
+ return vec4(sqrt(nearestSquared), sqrt(secondSquared), nearestCell);
15
21
  }
16
22
  // the crust at q (in plates: a plate is about one across), warped by w (-1 to 1, smooth): x its seams, y the plates' curled
17
23
  // rims, z the finer seams within a plate
18
- vec3 crustCracks(vec2 q, vec2 w) {
19
- q += w * 0.45;
20
- vec4 c = nearestCells(q); float blur = length(fwidth(q)), edge = c.y - c.x;
21
- vec2 own = cellPoint(c.zw + 7.0); // the plate's own numbers: how wide its seams gape, whether it splits
24
+ vec3 crustCracks(vec2 platePosition, vec2 warp) {
25
+ platePosition += warp * 0.45;
26
+ vec4 nearestPair = nearestCells(platePosition); float blur = length(fwidth(platePosition)), edge = nearestPair.y - nearestPair.x;
27
+ vec2 own = cellPoint(nearestPair.zw + 7.0); // the plate's own numbers: how wide its seams gape, whether it splits
22
28
  float gape = mix(0.022, 0.07, own.x);
23
29
  float seam = (1.0 - smoothstep(gape * 0.4, gape + blur, edge)) * (1.0 - smoothstep(0.2, 0.6, blur));
24
30
  float rim = (1.0 - smoothstep(gape, gape + 0.22, edge)) * (1.0 - seam) * (1.0 - smoothstep(0.3, 0.8, blur));
25
- vec2 s = q * 2.3 + 3.7; vec4 f = nearestCells(s); float sBlur = length(fwidth(s));
26
- float fine = (1.0 - smoothstep(0.015, 0.045 + sBlur, f.y - f.x)) * (1.0 - smoothstep(0.15, 0.45, sBlur)) * step(0.45, own.y) * (1.0 - seam);
31
+ vec2 finePosition = platePosition * 2.3 + 3.7; vec4 finePair = nearestCells(finePosition); float sBlur = length(fwidth(finePosition));
32
+ float fine = (1.0 - smoothstep(0.015, 0.045 + sBlur, finePair.y - finePair.x)) * (1.0 - smoothstep(0.15, 0.45, sBlur)) * step(0.45, own.y) * (1.0 - seam);
27
33
  return vec3(seam, rim, fine);
28
34
  }`;
@@ -22,11 +22,11 @@ export function createSunMoonCycle({
22
22
  .set(Math.cos(moonAngle) * moonEast, Math.sin(moonAngle) * moonRise, moonOffset + moonTilt * Math.sin(moonAngle))
23
23
  .normalize();
24
24
  if (moonTurn) {
25
- const c = Math.cos(moonTurn),
25
+ const cosMoonTurn = Math.cos(moonTurn),
26
26
  s = Math.sin(moonTurn);
27
27
  const { x, z } = moon;
28
- moon.x = x * c + z * s;
29
- moon.z = z * c - x * s;
28
+ moon.x = x * cosMoonTurn + z * s;
29
+ moon.z = z * cosMoonTurn - x * s;
30
30
  }
31
31
  return (1 - Math.cos(elongation)) / 2;
32
32
  };
@@ -0,0 +1,28 @@
1
+ /** Perspective magnification relative to a reference vertical FOV in degrees. Compute once per view. */
2
+ export function detailLens(camera, referenceFov = camera.fov) {
3
+ if (camera.fov === referenceFov) return camera.zoom;
4
+ return camera.zoom * Math.tan(referenceFov * Math.PI / 360) / Math.tan(camera.fov * Math.PI / 360);
5
+ }
6
+
7
+ /**
8
+ * Choose near detail using squared world distance and [enter, leave] distances at unit magnification.
9
+ * Pass the last boolean result for this object, or undefined on first sight to use the midpoint.
10
+ * Magnification can include object scale when the edges describe a unit-sized model.
11
+ */
12
+ export function withinDetailRange(distanceSquared, wasNear, magnification, edges) {
13
+ const edge = wasNear === undefined ? (edges[0] + edges[1]) / 2 : edges[wasNear ? 1 : 0];
14
+ const range = edge * magnification;
15
+ return distanceSquared < range * range;
16
+ }
17
+
18
+ /**
19
+ * A level of detail chosen with hysteresis: 3 near, 2 medium, 1 light, 0 past them. `near`, `medium` and `light` are each level's
20
+ * outer edge in metres at a lens of 1, as [for one outside it, for one already inside it]: an edge lies a little further out for
21
+ * one inside, so that nobody standing on it changes every frame. `d2` is the distance squared, `previous` the level last frame,
22
+ * `lens` how much nearer the lens brings things (edges move out with it).
23
+ */
24
+ export function detailLevel(d2, previous, lens, near, medium, light) {
25
+ if (withinDetailRange(d2, previous === 3, lens, near)) return 3;
26
+ if (withinDetailRange(d2, previous >= 2, lens, medium)) return 2;
27
+ return withinDetailRange(d2, previous >= 1, lens, light) ? 1 : 0;
28
+ }
@@ -0,0 +1,18 @@
1
+ // Detach owned roots and release their geometry and instance buffers. Materials are
2
+ // borrowed. A shared shape can outlive its instances by listing it in sharedGeometries.
3
+ export function disposeMeshRoots(roots, sharedGeometries) {
4
+ const released = new Set();
5
+ function release(mesh) {
6
+ const geometry = mesh.geometry;
7
+ if (mesh.isInstancedMesh) mesh.dispose();
8
+ if (!geometry || released.has(geometry) || sharedGeometries?.has(geometry)) return;
9
+ released.add(geometry);
10
+ if (mesh.isPieceBatch) mesh.free();
11
+ else geometry.dispose();
12
+ }
13
+ for (let childIndex = roots.length - 1; childIndex >= 0; childIndex--) {
14
+ const root = roots[childIndex];
15
+ root.removeFromParent();
16
+ root.traverse(release);
17
+ }
18
+ }
package/rendering/dof.js CHANGED
@@ -15,17 +15,17 @@ const DOF_FS = `/* glsl */ uniform sampler2D tScene, tDepth; uniform vec4 uDof;
15
15
  float viewDepth(vec2 uv){ return -uNF.x * uNF.y / ((uNF.y - uNF.x) * texture2D(tDepth, uv).x - uNF.y); }
16
16
  ${DOF_COC}
17
17
  void main(){
18
- float r = cocAt(viewDepth(vUv));
19
- vec3 sum = texture2D(tScene, vUv).rgb; float wsum = 1.0;
18
+ float blurRadius = cocAt(viewDepth(vUv));
19
+ vec3 sum = texture2D(tScene, vUv).rgb; float totalWeight = 1.0;
20
20
  for (int i = 1; i < ${TAPS}; i++) {
21
- float f = float(i) / ${TAPS}.0, a = float(i) * 2.39996;
22
- vec2 o = vec2(cos(a), sin(a)) * sqrt(f) * max(r, 0.5);
23
- vec2 uv = vUv + o * uPx;
24
- float rs = cocAt(viewDepth(uv)), d = length(o);
25
- float w = clamp(min(rs, r) - d + 1.0, 0.0, 1.0); // a sample counts as far as its own circle, and this one's, reach here
26
- sum += clamp(texture2D(tScene, uv).rgb, 0.0, 48.0) * w; wsum += w;
21
+ float sampleFraction = float(i) / ${TAPS}.0, sampleAngle = float(i) * 2.39996;
22
+ vec2 sampleOffset = vec2(cos(sampleAngle), sin(sampleAngle)) * sqrt(sampleFraction) * max(blurRadius, 0.5);
23
+ vec2 uv = vUv + sampleOffset * uPx;
24
+ float sampleRadius = cocAt(viewDepth(uv)), sampleDistance = length(sampleOffset);
25
+ float sampleWeight = clamp(min(sampleRadius, blurRadius) - sampleDistance + 1.0, 0.0, 1.0); // a sample counts as far as its own circle, and this one's, reach here
26
+ sum += clamp(texture2D(tScene, uv).rgb, 0.0, 48.0) * sampleWeight; totalWeight += sampleWeight;
27
27
  }
28
- gl_FragColor = vec4(sum / wsum, 1.0);
28
+ gl_FragColor = vec4(sum / totalWeight, 1.0);
29
29
  }`;
30
30
  export function createDepthOfField() {
31
31
  const dof = {
@@ -13,7 +13,7 @@ const METER = { w: 64, h: 36 }, // the first boiled-down picture, in texels: eac
13
13
  REDUCED = { w: 16, h: 9 }, // then 4 x 4 of those to a texel, then all of these to one
14
14
  SPEED = { brighter: 2.4, darker: 0.9 }; // how fast the eye follows, a share a second: it closes on light faster than it opens in the dark
15
15
 
16
- const LUM = `/* glsl */ float logLum(vec3 c){ return log2(max(dot(c, vec3(0.2126, 0.7152, 0.0722)), 1e-4)); }`;
16
+ const LUM = `/* glsl */ float logLum(vec3 sceneColor){ return log2(max(dot(sceneColor, vec3(0.2126, 0.7152, 0.0722)), 1e-4)); }`;
17
17
  // The scene to METER: the log brightness of 4 x 4 samples in each texel's span, weighted toward the middle of the picture, as (sum of
18
18
  // weighted values, sum of weights) so later steps may average both and divide at the end.
19
19
  const METER_FS = `/* glsl */ uniform sampler2D tSrc; uniform vec2 uSpan; varying vec2 vUv; ${LUM}
@@ -47,8 +47,8 @@ const ADAPT_FS = `/* glsl */ uniform sampler2D tMean, tPrev; uniform float uDt,
47
47
  gl_FragColor = vec4(uFirst > 0.5 ? now : prev + (now - prev) * k, 0.0, 0.0, 1.0);
48
48
  }`;
49
49
 
50
- const target = (w, h, format) =>
51
- new THREE.WebGLRenderTarget(w, h, {
50
+ const target = (width, height, format) =>
51
+ new THREE.WebGLRenderTarget(width, height, {
52
52
  type: THREE.HalfFloatType,
53
53
  format,
54
54
  depthBuffer: false,
@@ -83,27 +83,27 @@ export function createEyeAdaptation() {
83
83
  quadScene.add(quad);
84
84
  const eye = { level: levels[0].texture, flip: 0, last: 0 };
85
85
 
86
- function draw(rn, material, into) {
86
+ function draw(renderer, material, into) {
87
87
  quad.material = material;
88
- rn.setRenderTarget(into);
89
- rn.render(quadScene, quadCam);
88
+ renderer.setRenderTarget(into);
89
+ renderer.render(quadScene, quadCam);
90
90
  }
91
91
  // Meters the scene's picture (a texture of light before tone mapping) and moves the eye on; a pause of more than a second (a
92
92
  // crossing, a page that was hidden) starts the eye afresh where it looks.
93
- function adaptEye(rn, sceneTexture) {
93
+ function adaptEye(renderer, sceneTexture) {
94
94
  const now = performance.now(),
95
- dt = (now - eye.last) / 1000;
95
+ deltaSeconds = (now - eye.last) / 1000;
96
96
  eye.last = now;
97
97
  meterMat.uniforms.tSrc.value = sceneTexture;
98
- draw(rn, meterMat, meter);
99
- draw(rn, reduceMat, reduced);
100
- draw(rn, meanMat, mean);
98
+ draw(renderer, meterMat, meter);
99
+ draw(renderer, reduceMat, reduced);
100
+ draw(renderer, meanMat, mean);
101
101
  const from = levels[eye.flip],
102
102
  into = levels[1 - eye.flip];
103
103
  adaptMat.uniforms.tPrev.value = from.texture;
104
- adaptMat.uniforms.uDt.value = Math.min(dt, 0.1);
105
- adaptMat.uniforms.uFirst.value = dt > 1 ? 1 : 0;
106
- draw(rn, adaptMat, into);
104
+ adaptMat.uniforms.uDt.value = Math.min(deltaSeconds, 0.1);
105
+ adaptMat.uniforms.uFirst.value = deltaSeconds > 1 ? 1 : 0;
106
+ draw(renderer, adaptMat, into);
107
107
  eye.flip = 1 - eye.flip;
108
108
  eye.level = into.texture;
109
109
  }
@@ -151,18 +151,18 @@ export function createFarShadow({scene, camera, direction, ground, config: FAR,
151
151
  size = farSun.shadow.mapSize.x,
152
152
  across = (2 * R) / size,
153
153
  upward = span / size;
154
- const c = farSun.shadow.camera;
155
- c.left = -R;
156
- c.right = R;
157
- c.bottom = Math.round((top + bottom - span) / 2 / upward) * upward;
158
- c.top = c.bottom + span;
159
- c.updateProjectionMatrix();
154
+ const shadowCamera = farSun.shadow.camera;
155
+ shadowCamera.left = -R;
156
+ shadowCamera.right = R;
157
+ shadowCamera.bottom = Math.round((top + bottom - span) / 2 / upward) * upward;
158
+ shadowCamera.top = shadowCamera.bottom + span;
159
+ shadowCamera.updateProjectionMatrix();
160
160
  snapToTexels(farSun.target.position, x, y0, z, L, across, upward);
161
161
  farSun.position.copy(farSun.target.position).addScaledVector(L, FAR.lift);
162
162
  }
163
- function updateFarShadow(dt) {
163
+ function updateFarShadow(deltaSeconds) {
164
164
  if (!farSun.castShadow || !active()) return;
165
- drawn.age += dt;
165
+ drawn.age += deltaSeconds;
166
166
  const yaw = camera.rotation.y,
167
167
  x = camera.position.x - Math.sin(yaw) * FAR.range * FAR.lead,
168
168
  z = camera.position.z - Math.cos(yaw) * FAR.range * FAR.lead;