roamwright 0.1.1 → 0.4.0

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 (120) hide show
  1. package/CONTRIBUTING.md +39 -8
  2. package/README.md +74 -24
  3. package/examples/viaduct-camera.js +40 -0
  4. package/examples/viaduct-landscape.js +81 -0
  5. package/examples/viaduct.css +75 -0
  6. package/examples/viaduct.html +47 -0
  7. package/examples/viaduct.js +332 -0
  8. package/geometry/creased-sheet.js +127 -0
  9. package/geometry/ear.js +97 -0
  10. package/geometry/erosion.js +106 -0
  11. package/geometry/face-grid.js +143 -0
  12. package/geometry/foliage.js +47 -0
  13. package/geometry/garment-tags.js +11 -0
  14. package/geometry/hair-gathers.js +174 -0
  15. package/geometry/hair-locks.js +156 -0
  16. package/geometry/hair-patch.js +42 -0
  17. package/geometry/hair-shell.js +186 -0
  18. package/geometry/hair-tags.js +6 -0
  19. package/geometry/head-profile.js +138 -0
  20. package/geometry/head-shape.js +499 -0
  21. package/geometry/heightfield.js +68 -0
  22. package/geometry/index-parts.js +60 -0
  23. package/geometry/instance-visibility.js +41 -0
  24. package/geometry/instances.js +23 -0
  25. package/geometry/outline-grid.js +46 -0
  26. package/geometry/part-ranges.js +18 -0
  27. package/geometry/path-field.js +65 -0
  28. package/geometry/sagging-tube.js +58 -0
  29. package/geometry/sampled-surface.js +101 -0
  30. package/geometry/scatter-grid.js +32 -0
  31. package/geometry/sculpt.js +263 -0
  32. package/geometry/shore-grid.js +67 -0
  33. package/geometry/strata-field.js +339 -0
  34. package/geometry/strata-tiles.js +215 -0
  35. package/geometry/stream.js +94 -0
  36. package/geometry/terrain-chunks.js +304 -0
  37. package/geometry/terrain-extension.js +44 -0
  38. package/math/cell-edge.js +44 -0
  39. package/math/cloth-textures.js +83 -0
  40. package/math/cloud-textures.js +112 -0
  41. package/math/color.js +29 -0
  42. package/math/mountain-ranges.js +463 -0
  43. package/math/particle-noise.js +48 -0
  44. package/math/periodic.js +20 -0
  45. package/math/rock-texture.js +56 -0
  46. package/math/surface-textures.js +241 -0
  47. package/motion/arm-reach.js +74 -0
  48. package/motion/biped-stride.js +276 -0
  49. package/motion/crowd-alarms.js +127 -0
  50. package/motion/crowd-routine.js +183 -0
  51. package/motion/daily-clock.js +59 -0
  52. package/motion/ground-lookahead.js +29 -0
  53. package/motion/instance-sight.js +84 -0
  54. package/motion/quadruped.js +332 -0
  55. package/motion/weather.js +59 -0
  56. package/motion/wind.js +27 -0
  57. package/package.json +6 -4
  58. package/rendering/caster-motion.js +79 -0
  59. package/rendering/cell-lod.js +184 -0
  60. package/rendering/cloud-dome.js +371 -0
  61. package/rendering/cloud-field.js +83 -0
  62. package/rendering/compilation-schedule.js +34 -0
  63. package/rendering/contact-shadows.js +79 -0
  64. package/rendering/crowd-skinning.js +133 -0
  65. package/rendering/crust.js +28 -0
  66. package/rendering/daylight.js +50 -0
  67. package/rendering/far-shadow.js +186 -0
  68. package/rendering/flocks.js +323 -0
  69. package/rendering/garment-material.js +110 -0
  70. package/rendering/glow-lines.js +74 -0
  71. package/rendering/glow-shell.js +90 -0
  72. package/rendering/hair-strands.js +67 -0
  73. package/rendering/height-haze.js +129 -0
  74. package/rendering/height-probe.js +91 -0
  75. package/rendering/interior-mapping.js +19 -0
  76. package/rendering/light-budget.js +222 -0
  77. package/rendering/light-points.js +51 -0
  78. package/rendering/light-shafts.js +131 -0
  79. package/rendering/local-lights.js +28 -0
  80. package/rendering/low-light.js +13 -0
  81. package/rendering/material-lod.js +110 -0
  82. package/rendering/particle-emitters.js +223 -0
  83. package/rendering/particles.js +297 -0
  84. package/rendering/piece-batch.js +74 -20
  85. package/rendering/planar-reflection.js +175 -0
  86. package/rendering/post-shaders.js +21 -1
  87. package/rendering/post.js +4 -0
  88. package/rendering/rain-rings.js +22 -0
  89. package/rendering/road-surface.js +63 -0
  90. package/rendering/sea-shaders.js +230 -0
  91. package/rendering/shader-warmup.js +197 -0
  92. package/rendering/shadow-alignment.js +28 -0
  93. package/rendering/shadow-depth.js +129 -0
  94. package/rendering/sky-occlusion.js +187 -0
  95. package/rendering/sky.js +169 -0
  96. package/rendering/stage-lights.js +209 -0
  97. package/rendering/static-point-shadow.js +119 -0
  98. package/rendering/strata-material.js +93 -0
  99. package/rendering/stream-flow.js +36 -0
  100. package/rendering/surface-light.js +22 -0
  101. package/rendering/surface-projection.js +69 -0
  102. package/rendering/talus.js +26 -0
  103. package/rendering/terrain-rock.js +48 -0
  104. package/rendering/texture-fills.js +68 -0
  105. package/rendering/viewport.js +9 -0
  106. package/rendering/wakes.js +99 -0
  107. package/rendering/water-material.js +288 -0
  108. package/runtime/device-quality.js +27 -0
  109. package/runtime/diagnostic-log.js +80 -0
  110. package/runtime/events.js +14 -0
  111. package/runtime/first-use.js +3 -1
  112. package/runtime/frame-budget.js +49 -0
  113. package/runtime/frame-yield.js +14 -0
  114. package/runtime/gpu-timing.js +6 -3
  115. package/runtime/grid-cache.js +88 -0
  116. package/runtime/grid-rows.js +9 -0
  117. package/runtime/module-preload.js +15 -0
  118. package/runtime/search.js +69 -0
  119. package/runtime/spatial-audio.js +57 -0
  120. package/scripts/serve.py +26 -0
@@ -0,0 +1,241 @@
1
+ import { cellEdge } from './cell-edge.js';
2
+ import { mulberry32 } from './random.js';
3
+ import { clamp, sstep } from './scalar.js';
4
+
5
+ // Tileable surface textures worked out in code: masonry, plaster, roof tiles, rock, planks, foliage, ground, road, brick and ice.
6
+ // Each maker returns fill(u, v, out): for the place (u, v) of the tile, 0 to 1 each way, it writes the texel's channels into
7
+ // `out` as numbers from 0 to 255. The makers need nothing of the page, so a worker can fill them (fillPixels below).
8
+ // noise: a seeded { tfbm, tnoise } of math/noise.js; hash2: a seeded hash of math/random.js. The same seeds give the same
9
+ // textures every time.
10
+ export function createSurfaceTextures({ noise: { tfbm, tnoise }, hash2 }) {
11
+ // Coursed ashlar: courses of uneven height, blocks of uneven length, thin joints, and each block its own tone.
12
+ function ashlar({ seed = 611, courses = 10 } = {}) {
13
+ const R = mulberry32(seed),
14
+ N = courses,
15
+ rows = [];
16
+ let acc = 0;
17
+ for (let i = 0; i < N; i++) {
18
+ const h = 0.75 + R() * 0.6;
19
+ rows.push({ y0: acc, h });
20
+ acc += h;
21
+ }
22
+ for (const r of rows) {
23
+ r.y0 /= acc;
24
+ r.h /= acc;
25
+ const n = 3 + ((R() * 3) | 0),
26
+ cuts = [];
27
+ let a = R();
28
+ for (let k = 0; k < n; k++) {
29
+ cuts.push(a % 1);
30
+ a += (0.7 + R() * 0.6) / n;
31
+ }
32
+ r.cuts = cuts.sort((p, q) => p - q);
33
+ r.tone = cuts.map(() => 0.86 + R() * 0.26);
34
+ r.warm = cuts.map(() => R());
35
+ }
36
+ return (u, v, o) => {
37
+ let r = rows[N - 1];
38
+ for (let i = 0; i < N; i++)
39
+ if (v < rows[i].y0 + rows[i].h) {
40
+ r = rows[i];
41
+ break;
42
+ }
43
+ const c_ = r.cuts,
44
+ m = c_.length;
45
+ let k = m - 1;
46
+ for (let i = 0; i < m; i++)
47
+ if (u < c_[i]) {
48
+ k = (i + m - 1) % m;
49
+ break;
50
+ }
51
+ const a = c_[k],
52
+ b = c_[(k + 1) % m],
53
+ w = (b - a + 1) % 1 || 1,
54
+ bu = ((u - a + 1) % 1) / w,
55
+ bv = (v - r.y0) / r.h;
56
+ const dj = Math.min(Math.min(bu, 1 - bu) * w, Math.min(bv, 1 - bv) * r.h); // distance to the nearest joint, in tile units
57
+ const joint = sstep(0.0, 0.0055, dj),
58
+ edge = sstep(0.0, 0.028, dj),
59
+ n = tfbm(u, v, 8, 4, 62),
60
+ pit = sstep(0.62, 0.8, tfbm(u, v, 32, 2, 65));
61
+ const c = (158 + n * 62) * r.tone[k] * (0.72 + 0.28 * joint) * (0.93 + 0.07 * edge) * (1 - 0.12 * pit),
62
+ wm = r.warm[k];
63
+ o[0] = c * (1 + 0.03 * wm);
64
+ o[1] = c * 0.985;
65
+ o[2] = c * (0.95 - 0.04 * wm);
66
+ };
67
+ }
68
+
69
+ // Rubble masonry: rough stones of every size, unsquared and in no courses, bedded in thick mortar. Each stone has its own tone
70
+ // and grain and rounds over to its rim; the mortar lies back between them. Two sizes of stone are mixed: a large stone is
71
+ // split where its own number says. big, small: stones a side of the tile; joint, rim: the mortar's half-width and the
72
+ // rim's, in tile units.
73
+ function rubble({ big: BIG = 6, small: SMALL = 11, split: SPLIT = 0.5, joint: JOINT = 0.008, rim: RIM = 0.016 } = {}) {
74
+ const big = [0, 0],
75
+ small = [0, 0];
76
+ return (u, v, o) => {
77
+ const w = (tfbm(u, v, 5, 3, 91) - 0.5) * 0.09 + (tfbm(u, v, 13, 2, 102) - 0.5) * 0.025, // warped twice, so no stone is a polygon
78
+ eb = cellEdge(hash2, u + w, v - w * 0.8, BIG, 92, big),
79
+ split = hash2(big[0], big[1], 93) < SPLIT,
80
+ es = split ? cellEdge(hash2, u - w * 0.8, v + w, SMALL, 94, small) : 1,
81
+ e = Math.min(eb, es),
82
+ id = split ? hash2(small[0], small[1], 95) : hash2(big[0], big[1], 96);
83
+ const joint = JOINT * (0.6 + 1.3 * tfbm(u, v, 9, 2, 97)), // the mortar's width wanders
84
+ inStone = sstep(joint, joint + 0.005, e),
85
+ rim = sstep(joint, joint + RIM, e), // a rough stone rounds over to its rim
86
+ grain = tfbm(u, v, 24, 3, 98),
87
+ pit = sstep(0.66, 0.82, tfbm(u, v, 40, 2, 99));
88
+ const tone = 0.8 + 0.35 * id,
89
+ stone = (150 + 60 * grain) * tone * (0.72 + 0.28 * Math.sqrt(rim)) * (1 - 0.12 * pit),
90
+ mortar = 84 + 26 * tfbm(u, v, 14, 3, 100) + 14 * tfbm(u, v, 60, 2, 103), // lying back, flat and sandy
91
+ c = mortar + (stone - mortar) * inStone,
92
+ warm = (hash2(big[0] + 7, big[1], 101) - 0.5) * 0.08 * inStone; // ironstone, limestone and grey field stone
93
+ o[0] = clamp(c * (1 + warm), 0, 255);
94
+ o[1] = clamp(c * 0.985, 0, 255);
95
+ o[2] = clamp(c * (0.95 - warm), 0, 255);
96
+ };
97
+ }
98
+
99
+ // Lime plaster: broad blotches and faint streaks down the wall.
100
+ const plaster = () => (u, v, o) => {
101
+ const n = tfbm(u, v, 5, 5, 63),
102
+ streak = tfbm(u * 3, v * 0.4, 4, 3, 64);
103
+ const c = clamp(170 + n * 60 + streak * 24 - 20 * sstep(0.9, 1.0, (v * 6) % 1), 0, 255);
104
+ o[0] = c;
105
+ o[1] = c * 0.99;
106
+ o[2] = c * 0.97;
107
+ };
108
+
109
+ // Roof tiles in rows that break joint: each tile its own shade, its lower lip lit, a gap between neighbours.
110
+ const roofTiles =
111
+ ({ rows = 12, columns: cols = 10 } = {}) =>
112
+ (u, v, o) => {
113
+ const r = Math.floor(v * rows),
114
+ tu = (u * cols + (r % 2) * 0.5) % 1,
115
+ tv = (v * rows) % 1;
116
+ const shade = 0.72 + 0.28 * hash2(Math.floor(u * cols + (r % 2) * 0.5) % cols, r, 65);
117
+ const lip = 0.66 + 0.34 * sstep(0.0, 0.5, tv),
118
+ gap = 0.75 + 0.25 * sstep(0, 0.12, tu) * sstep(1, 0.88, tu);
119
+ const c = (150 + tfbm(u, v, 8, 3, 66) * 70) * shade * lip * gap;
120
+ o[0] = c;
121
+ o[1] = c * 0.98;
122
+ o[2] = c * 0.96;
123
+ };
124
+
125
+ // Bare rock: mottled grey with dark cracks.
126
+ const rock = () => (u, v, o) => {
127
+ const n = tfbm(u, v, 4, 6, 67),
128
+ crack = Math.abs(tfbm(u, v, 6, 4, 68) - 0.5) * 2;
129
+ const c = clamp((130 + n * 110) * (0.55 + 0.45 * sstep(0.0, 0.12, crack)), 0, 255);
130
+ o[0] = c;
131
+ o[1] = c;
132
+ o[2] = c * 0.98;
133
+ };
134
+
135
+ // Planks side by side: grain along each, a dark edge between them, each plank its own tone.
136
+ const planks =
137
+ ({ count = 8 } = {}) =>
138
+ (u, v, o) => {
139
+ const plank = Math.floor(u * count),
140
+ g = tfbm(u * 0.6 + plank * 0.13, v, 4, 5, 69),
141
+ edge = sstep(0, 0.06, (u * count) % 1);
142
+ const c = (130 + g * 90) * (0.82 + 0.18 * hash2(plank, 0, 70)) * (0.6 + 0.4 * edge);
143
+ o[0] = c * 1.05;
144
+ o[1] = c * 0.95;
145
+ o[2] = c * 0.8;
146
+ };
147
+
148
+ // Leaf clusters, as one grey value: bright clumps, dark gaps.
149
+ const foliage = () => (u, v, o) => {
150
+ const a = tfbm(u, v, 10, 3, 71),
151
+ b = tnoise(u * 34, v * 34, 34, 72),
152
+ c = tnoise(u * 90, v * 90, 90, 73);
153
+ const n = clamp(sstep(0.34, 0.62, a) * 0.62 + b * 0.3 + c * 0.16, 0, 1) * 255;
154
+ o[0] = o[1] = o[2] = n;
155
+ };
156
+
157
+ // The grain of open ground. alpha(u, v), 0 to 1, when given, is packed into the fourth channel: a shader short of texture
158
+ // units can carry a second field there.
159
+ const groundGrain =
160
+ ({ alpha = null } = {}) =>
161
+ (u, v, o) => {
162
+ const n = tfbm(u, v, 6, 6, 3),
163
+ g = tnoise(u * 160, v * 160, 160, 9);
164
+ const c = clamp(168 + n * 72 + g * 30, 0, 255);
165
+ o[0] = c;
166
+ o[1] = c * 0.99;
167
+ o[2] = c * 0.96;
168
+ if (alpha) o[3] = 255 * alpha(u, v);
169
+ };
170
+
171
+ // One tile of a road's ground detail: R fine soil, G pale pebbles, B the dark lines of dried cracks.
172
+ const roadGrit = () => (u, v, o) => {
173
+ const crack = Math.abs(tfbm(u, v, 3, 3, 71) - 0.5);
174
+ o[0] = 255 * tfbm(u, v, 16, 4, 61);
175
+ o[1] = (255 * Math.max(0, tnoise(u * 48, v * 48, 48, 67) - 0.72)) / 0.28;
176
+ o[2] = 255 * Math.max(0, 1 - crack / 0.03);
177
+ };
178
+
179
+ // Sun-dried brick in mud mortar: courses that break joint, each brick its own tone, flecked with straw and worn at its edges.
180
+ function brick({ seed = 733, courses: COURSES = 13, perCourse: BRICKS = 4 } = {}) {
181
+ const R = mulberry32(seed),
182
+ tone = Array.from({ length: COURSES * BRICKS * 2 }, () => 0.84 + R() * 0.3),
183
+ shift = Array.from({ length: COURSES }, () => R() * 0.18);
184
+ return (u, v, o) => {
185
+ const row = Math.min(COURSES - 1, Math.floor(v * COURSES)),
186
+ bv = v * COURSES - row,
187
+ x = u * BRICKS + (row % 2) * 0.5 + shift[row],
188
+ col = Math.floor(x),
189
+ bu = x - col,
190
+ k = row * BRICKS * 2 + (((col % (BRICKS * 2)) + BRICKS * 2) % (BRICKS * 2)),
191
+ worn = tfbm(u, v, 16, 3, 741), // edges eaten back by wind and rain
192
+ edge = Math.min(Math.min(bu, 1 - bu) * 0.36, Math.min(bv, 1 - bv) * 0.12) / 0.12 + (worn - 0.5) * 0.5,
193
+ joint = sstep(0.06, 0.2, edge),
194
+ grain = tfbm(u, v, 24, 4, 742),
195
+ straw = sstep(0.8, 0.86, tfbm(u * 3, v * 0.6, 48, 2, 743));
196
+ const c = clamp((128 + grain * 70) * (0.74 + 0.26 * joint) * (joint > 0.5 ? tone[k] : 0.92) * (1 + straw * 0.12), 0, 255);
197
+ o[0] = c * 1.02;
198
+ o[1] = c * 0.97;
199
+ o[2] = c * 0.9;
200
+ };
201
+ }
202
+
203
+ // Old ice: R how near the nearest crack is, in a net of straight cracks at two sizes, the finer only in places (255 on a
204
+ // crack, 0 at `reach` of the sheet away); G the milky cloud in it; B the grain of its frost; A a broad field for where
205
+ // cracks show and stains run.
206
+ const crackedIce =
207
+ ({ reach = 0.05 } = {}) =>
208
+ (u, v, o) => {
209
+ const w = tfbm(u, v, 3, 3, 871) - 0.5,
210
+ broad = cellEdge(hash2, u + w * 0.04, v - w * 0.03, 4, 872),
211
+ fine = cellEdge(hash2, u - w * 0.03, v + w * 0.04, 9, 873) + reach * sstep(0.62, 0.48, tfbm(u, v, 3, 2, 874));
212
+ o[0] = 255 * (1 - clamp(Math.min(broad, fine) / reach, 0, 1));
213
+ o[1] = 255 * clamp(tfbm(u, v, 4, 4, 875) * 1.3 - 0.15, 0, 1);
214
+ o[2] = 255 * tfbm(u, v, 24, 3, 876);
215
+ o[3] = 255 * tfbm(u, v, 3, 3, 877);
216
+ };
217
+
218
+ return { ashlar, rubble, plaster, roofTiles, rock, planks, foliage, groundGrain, roadGrit, brick, crackedIce };
219
+ }
220
+
221
+ // A fill's pixels, four bytes each, row by row from the fill's highest v down to its lowest. size: texels a side; make(): returns the fill(u, v, out, w); depth: for a block, its layers one after another, each
222
+ // filled from its height w in the block. A fill that leaves the fourth channel alone gets 255 there.
223
+ export function fillPixels({ size, depth = 1, make }) {
224
+ const fn = make(),
225
+ layer = size * size * 4,
226
+ data = new Uint8ClampedArray(layer * depth),
227
+ out = [0, 0, 0, 255];
228
+ for (let z = 0; z < depth; z++)
229
+ for (let y = 0; y < size; y++) {
230
+ let k = z * layer + (size - 1 - y) * size * 4;
231
+ for (let x = 0; x < size; x++, k += 4) {
232
+ out[3] = 255;
233
+ fn((x + 0.5) / size, (y + 0.5) / size, out, (z + 0.5) / depth);
234
+ data[k] = out[0];
235
+ data[k + 1] = out[1];
236
+ data[k + 2] = out[2];
237
+ data[k + 3] = out[3];
238
+ }
239
+ }
240
+ return data;
241
+ }
@@ -0,0 +1,74 @@
1
+ import * as THREE from 'three';
2
+ import { clamp } from '../math/scalar.js';
3
+
4
+ /**
5
+ * `createArmReach({elbowDirection,minBend,maxBend})` returns a solver for a negative-Y upper arm with an X-hinged
6
+ * forearm. Call it with the upper arm, forearm, hand, item rest offset, local grip, world target, side (−1 or 1) and
7
+ * blend weight (0–1) after updating the shoulder parent’s world matrix. Bend limits are radians. The elbow direction
8
+ * is in the shoulder parent’s frame, mirrored by side on X.
9
+ */
10
+ export function createArmReach({ elbowDirection, minBend, maxBend }) {
11
+ const _to = new THREE.Vector3(), // scratch
12
+ _end = new THREE.Vector3(),
13
+ _g = new THREE.Vector3(),
14
+ _elbow = new THREE.Vector3(),
15
+ _want = new THREE.Vector3(),
16
+ _a = new THREE.Vector3(),
17
+ _b = new THREE.Vector3(),
18
+ _size = new THREE.Vector3(),
19
+ _hand = new THREE.Matrix4(),
20
+ _item = new THREE.Matrix4(),
21
+ _inv = new THREE.Matrix4(),
22
+ _q = new THREE.Quaternion(),
23
+ _swivel = new THREE.Quaternion(),
24
+ _x = new THREE.Quaternion(),
25
+ NONE = new THREE.Quaternion(),
26
+ X_AXIS = new THREE.Vector3(1, 0, 0);
27
+
28
+ // Turns the upper arm `arm` and the forearm `fore` of one side (s: 1 the right, -1 the left) by weight k toward the pose in which
29
+ // the point `grip` (in the own space of the bone of what the hand `hand` holds, taken at its place `rest` and unturned)
30
+ // comes to `target` in the world. The arm's parent's world matrix must be current.
31
+ function reachArm(arm, fore, hand, rest, grip, target, s, k) {
32
+ if (k <= 0) return;
33
+ // the target from the shoulder, in the frame the arm hangs in
34
+ _inv.copy(arm.parent.matrixWorld).invert();
35
+ _to.copy(target).applyMatrix4(_inv).sub(arm.position);
36
+ // what the hand holds at `grip`, in the forearm's frame: through the hand as it is turned, and the held bone as it rests
37
+ hand.updateMatrix();
38
+ _item.compose(rest, NONE, _size.setScalar(1 / hand.scale.x)); // what is held keeps its own size in a larger hand, shown or not
39
+ _g.copy(grip).applyMatrix4(_item).applyMatrix4(_hand.copy(hand.matrix));
40
+ // the elbow's bend that puts the grip as far from the shoulder as the target is (or as far as the arm reaches)
41
+ const l1 = -fore.position.y,
42
+ rho = Math.hypot(_g.y, _g.z),
43
+ phi = Math.atan2(_g.z, _g.y);
44
+ if (l1 <= 0 || rho <= Number.EPSILON) return;
45
+ const far = _to.length(),
46
+ c = clamp((_g.x * _g.x + l1 * l1 + rho * rho - far * far) / (2 * l1 * rho), -1, 1),
47
+ turn = Math.acos(c);
48
+ let bend = turn - phi;
49
+ bend = Math.atan2(Math.sin(bend), Math.cos(bend));
50
+ if (bend > maxBend || bend < minBend) {
51
+ const other = Math.atan2(Math.sin(-turn - phi), Math.cos(-turn - phi));
52
+ if (Math.abs(other - (maxBend + minBend) / 2) < Math.abs(bend - (maxBend + minBend) / 2)) bend = other;
53
+ }
54
+ bend = clamp(bend, minBend, maxBend);
55
+ // the end of the arm so bent, in the upper arm's own frame, turned onto the target, then swung about the line to the target
56
+ // until the elbow is as near as it gets to where an elbow goes
57
+ _x.setFromAxisAngle(X_AXIS, bend);
58
+ _end.copy(_g).applyQuaternion(_x).add(fore.position);
59
+ _q.setFromUnitVectors(_a.copy(_end).normalize(), _b.copy(_to).normalize());
60
+ _elbow.copy(fore.position).applyQuaternion(_q);
61
+ _want.set(s * elbowDirection[0], elbowDirection[1], elbowDirection[2]);
62
+ _elbow.addScaledVector(_b, -_elbow.dot(_b));
63
+ _want.addScaledVector(_b, -_want.dot(_b));
64
+ if (_elbow.lengthSq() > 1e-10 && _want.lengthSq() > 1e-10) {
65
+ _elbow.normalize();
66
+ _want.normalize();
67
+ const swing = Math.atan2(_a.crossVectors(_elbow, _want).dot(_b), _elbow.dot(_want));
68
+ _q.premultiply(_swivel.setFromAxisAngle(_b, swing));
69
+ }
70
+ arm.quaternion.slerp(_q, k);
71
+ fore.rotation.x += (bend - fore.rotation.x) * k;
72
+ }
73
+ return reachArm;
74
+ }
@@ -0,0 +1,276 @@
1
+ import { TAU, clamp, lerp, sstep } from '../math/scalar.js';
2
+
3
+ /** Create one stride solver for a rig, ground sampler and motion profile. */
4
+ export function createBipedStride({ rig, foot, pace, ground }) {
5
+ const reach = rig.thigh + rig.shin - 0.0005;
6
+ const _leg = [0, 0],
7
+ _ankle = [0, 0];
8
+ // What the legs do this frame, filled by stride(): thigh and knee angles, how far the figure's origin rides above the ground,
9
+ // the measure of the stride the arms and trunk swing to, the hips' own turn (to the right is less) and list (the left side
10
+ // down is more), each sole's pitch against the trunk the legs are solved in (toes down is more), how far its toes bend up to
11
+ // stay on the ground, and the roll both soles take on ground that falls away to one side.
12
+ const step = {
13
+ thighL: 0,
14
+ kneeL: 0,
15
+ thighR: 0,
16
+ kneeR: 0,
17
+ rise: 0,
18
+ swing: 0,
19
+ arms: 0,
20
+ go: 0,
21
+ run: 0,
22
+ bearing: 0,
23
+ lean: 0,
24
+ turn: 0,
25
+ list: 0,
26
+ soleL: 0,
27
+ soleR: 0,
28
+ toesL: 0,
29
+ toesR: 0,
30
+ roll: 0,
31
+ };
32
+
33
+ // Two-bone leg from hip to ankle in the fore-and-aft plane: for an ankle at (forward, up) from the hip, the thigh's and the
34
+ // knee's rotation, written into _leg.
35
+ function solveLeg(forward, up) {
36
+ const D = clamp(Math.sqrt(forward * forward + up * up), 0.3, rig.thigh + rig.shin - 1e-4),
37
+ bend = Math.acos(clamp((D * D - rig.thigh * rig.thigh - rig.shin * rig.shin) / (2 * rig.thigh * rig.shin), -1, 1));
38
+ _leg[0] = -(Math.atan2(forward, -up) + Math.atan2(rig.shin * Math.sin(bend), rig.thigh + rig.shin * Math.cos(bend)));
39
+ _leg[1] = bend;
40
+ }
41
+ // The pitch of a foot's sole (toes down is more) at share u of its stride: it lands on its heel with the toes up by `strike`,
42
+ // lies flat while the body passes over it, rolls up onto its toes until the heel has risen by `push`, and in the air comes
43
+ // round from toes down to toes up. A step backwards (`back`) does it the other way round.
44
+ function soleAt(u, duty, back, strike, push) {
45
+ const planted = u < duty;
46
+ let s = planted ? u / duty : (u - duty) / (1 - duty);
47
+ if (back) s = 1 - s;
48
+ return planted ? push * sstep(foot.riseAt, 1, s) - strike * sstep(foot.flatAt, 0, s) : lerp(push, -strike, sstep(0.08, 0.8, s));
49
+ }
50
+ // Where a foot's ankle is from the point of its sole under the ankle when it lies flat, written into _ankle (forward, up), for a
51
+ // sole pitched by `pitch` (about the ball of the foot with the heel up, about the heel with the toes up) on ground that itself
52
+ // pitches by `slope` (both radians, toes down is more).
53
+ function ankleAt(pitch, slope) {
54
+ const c = Math.cos(pitch),
55
+ s = Math.sin(pitch),
56
+ forward = pitch >= 0 ? rig.ballOffset - rig.ballOffset * c + rig.ankleHeight * s : -rig.heelOffset + rig.heelOffset * c + rig.ankleHeight * s,
57
+ up = pitch >= 0 ? rig.ballOffset * s + rig.ankleHeight * c : -rig.heelOffset * s + rig.ankleHeight * c;
58
+ if (slope) {
59
+ const cs = Math.cos(slope),
60
+ ss = Math.sin(slope);
61
+ _ankle[0] = forward * cs + up * ss;
62
+ _ankle[1] = up * cs - forward * ss;
63
+ } else {
64
+ _ankle[0] = forward;
65
+ _ankle[1] = up;
66
+ }
67
+ }
68
+ // One foot (0 the left, 1 the right) at share u of its stride, kept in a.feet as how far forward of the middle it is and how
69
+ // high. Striding, a foot on the ground stays where it was set down, so it is carried back as the body goes forward, and a foot
70
+ // in the air swings from where it left the ground to where it will land; `drift` makes it leave and meet the ground moving as
71
+ // the ground does. Standing, a foot that is not where the pose wants it steps there (`mayStep`: one foot at a time).
72
+ function footAt(a, i, u, duty, landing, drift, lift, gone, striding, stance, mayStep, dt) {
73
+ const F = a.feet;
74
+ let air = 0;
75
+ if (striding) {
76
+ const back = gone < 0;
77
+ if (u < duty) {
78
+ F[i] -= gone;
79
+ F[i + 2] = F[i];
80
+ } else {
81
+ const s = back ? 1 - (u - duty) / (1 - duty) : (u - duty) / (1 - duty),
82
+ s2 = s * s,
83
+ s3 = s2 * s;
84
+ F[i] = F[i + 2] + (landing - F[i + 2]) * (3 * s2 - 2 * s3) + drift * (2 * s3 - 3 * s2 + s);
85
+ air = lift * Math.sin(Math.PI * Math.pow(s, 0.8));
86
+ }
87
+ } else {
88
+ const off = stance - F[i];
89
+ if (mayStep) F[i] += clamp(off, -foot.settleSpeed * dt, foot.settleSpeed * dt);
90
+ air = mayStep ? Math.min(foot.settleLift, Math.abs(off) * 0.45) : 0;
91
+ F[i + 2] = F[i];
92
+ }
93
+ F[i + 4] += (air - F[i + 4]) * Math.min(1, dt * 22);
94
+ }
95
+ const fraction = x => ((x % 1) + 1) % 1;
96
+ const GROUND_KEPT = 0.04, // metres a foot's spot may move before the ground under it is looked up again
97
+ GROUND_FRESH = 30; // and lookups it is kept for at most, so that a floor raised under someone standing still is found
98
+ // The ground at (x, z) under foot k (0 left, 1 right; 2 and 3 under their toes) of actor a, looked up again only once the foot
99
+ // has moved (or now and then): a planted or standing foot keeps its height, and no number is made for the garbage each frame
100
+ // (a.footGround: x, z, y and the lookups since, a spot).
101
+ function groundUnder(a, k, x, z) {
102
+ const g = a.footGround || (a.footGround = new Float64Array(16).fill(NaN)),
103
+ i = k * 4;
104
+ if (!(Math.abs(x - g[i]) <= GROUND_KEPT && Math.abs(z - g[i + 1]) <= GROUND_KEPT && g[i + 3] < GROUND_FRESH)) {
105
+ g[i] = x;
106
+ g[i + 1] = z;
107
+ g[i + 2] = ground(x, z);
108
+ g[i + 3] = 0;
109
+ }
110
+ g[i + 3]++;
111
+ return g[i + 2];
112
+ }
113
+ // A step's length on a stair: one tread, as far as actor a is on one (kept with the feet: how far on a stair, its tread in
114
+ // metres, and the seconds since an edge of it was seen); `len` otherwise, the walk's own, which a stair's is never longer than.
115
+ function treadStep(a, len, h) {
116
+ const F = a.feet;
117
+ return F && F[13] > 0.01 ? lerp(len, Math.min(len, F[14] / h), F[13]) : len;
118
+ }
119
+ // Notes a step's edge of `riser` metres seen under a foot: on a climb or a descent it is a stair's, whose tread is the riser
120
+ // over the slope walked.
121
+ function stairSeen(a, riser) {
122
+ const steep = Math.abs(a.slope),
123
+ F = a.feet;
124
+ if (steep < foot.stairSlope) return;
125
+ F[14] += (clamp(riser / steep, foot.treadRange[0], foot.treadRange[1]) - F[14]) * 0.25;
126
+ F[15] = foot.stairMemory;
127
+ }
128
+ // The legs of someone on their feet this frame, written into `step`. lean: the trunk's lean forward; sink: how far the pose
129
+ // lowers the hips; hipZ: how far it shifts them forward; stanceL, stanceR: where the pose plants each foot, forward of the
130
+ // middle; free: standing on open ground (the ground under each foot is then looked up, and a.y set between them); list: how
131
+ // far the hips list as their owner stands with the weight on one leg (the left side down is more).
132
+ function stride(a, dt, h, lean, sink, hipZ, stanceL, stanceR, free, list, strideScale = 1, liftScale = 1, hipScale = 1) {
133
+ const v = a.fwd / h,
134
+ speed = Math.abs(v),
135
+ go = sstep(0.06, 0.5, speed), // how much of a stride the legs take
136
+ run = sstep(pace.runFrom, pace.runFull, speed),
137
+ shuffle = Math.max(go, 0.45 * Math.max(sstep(0.15, 0.7, a.side / h), sstep(0.6, 2.4, Math.abs(a.spin)))), // feet also lift to turn and to step aside
138
+ striding = shuffle > 0.02,
139
+ len = treadStep(
140
+ a,
141
+ Math.min(pace.maxStep, pace.baseStep + pace.stepGain * speed) * strideScale * (1 - 0.35 * Math.min(1, Math.abs(a.slope) * 2.2)),
142
+ h,
143
+ ),
144
+ duty = lerp(pace.walkDuty, pace.runDuty, run),
145
+ sweep = 2 * len * duty * go,
146
+ lift = (lerp(pace.walkLift, pace.runLift, run) * liftScale + Math.max(0, a.slope) * len * 0.45) * shuffle,
147
+ tip = run * go * pace.runLean + go * clamp(a.slope * 0.2, -0.06, 0.12); // a runner leans into the run, a climber into the hill
148
+ // each foot: where it is forward of the middle, where it left the ground, how high it is, its sole's pitch in the stride
149
+ // and the pitch of the ground it stands on; then the roll of both, and the ground each foot goes by (metres)
150
+ // then how far they are on a stair, its tread, and the seconds a stair is still underfoot
151
+ if (!a.feet) a.feet = [stanceL, stanceR, stanceL, stanceR, 0, 0, 0, 0, 0, 0, 0, NaN, NaN, 0, 0.3, 0];
152
+ if (striding && !a.striding) a.phase = TAU * (duty - 0.5 + 0.02 + (a.seed > 0.5 ? 0.5 : 0)); // setting off: one foot has just taken the weight, the other leaves the ground
153
+ a.striding = striding;
154
+ a.phase += striding
155
+ ? (Math.PI * dt * (v + (1 - go) * (a.side / h) * 1.4)) / len + (1 - go) * Math.abs(a.spin) * dt * 1.6
156
+ : dt * pace.idleRate;
157
+ lean += tip;
158
+ const uL = fraction(a.phase / TAU),
159
+ uR = fraction(uL + 0.5),
160
+ sinL = Math.sin(lean),
161
+ cosL = Math.cos(lean),
162
+ hipAt = rig.hipHeight * sinL + hipZ, // the hips forward of the point between the feet; a stride is taken under them
163
+ landing = hipAt * go + (v < 0 ? -sweep : sweep) / 2,
164
+ drift = ((v < 0 ? sweep : -sweep) * (1 - duty)) / duty,
165
+ gone = (a.fwd * dt) / h,
166
+ F = a.feet,
167
+ leftFirst = Math.abs(stanceL - F[0]) >= Math.abs(stanceR - F[1]); // of two feet out of place, the one further out steps first
168
+ footAt(a, 0, uL, duty, landing, drift, lift, gone, striding, stanceL, leftFirst || Math.abs(stanceR - F[1]) < 0.03, dt);
169
+ footAt(a, 1, uR, duty, landing, drift, lift, gone, striding, stanceR, !leftFirst || Math.abs(stanceL - F[0]) < 0.03, dt);
170
+ // the hips turn with the leg that leads and drop on the side of the one in the air, which carries each leg's joint forward
171
+ // or back and up or down: the legs are solved from where their joints then are, so the feet stay where they are planted
172
+ const turn = Math.cos(TAU * uL) * go * lerp(pace.hipTurn[0], pace.hipTurn[1], run) * hipScale,
173
+ listed = list - Math.cos(TAU * (uL - duty / 2)) * go * pace.hipDrop * hipScale,
174
+ jointZ = a.lx * Math.sin(turn), // the left leg's joint forward of the hips' middle, and the right one's behind it
175
+ jointY = a.lx * Math.sin(listed), // the right leg's joint above the hips' middle, and the left one's below it
176
+ zL = F[0],
177
+ zR = F[1],
178
+ airL = F[4],
179
+ airR = F[5],
180
+ soleEase = Math.min(1, dt * foot.response),
181
+ roll = go * (v < 0 ? foot.reverseRoll : 1),
182
+ strike = roll * lerp(foot.heelStrike[0], foot.heelStrike[1], run),
183
+ push = roll * lerp(foot.pushOff[0], foot.pushOff[1], run);
184
+ // each sole rolls from heel to toe through its stride
185
+ F[6] += ((striding ? soleAt(uL, duty, v < 0, strike, push) : 0) - F[6]) * soleEase;
186
+ F[7] += ((striding ? soleAt(uR, duty, v < 0, strike, push) : 0) - F[7]) * soleEase;
187
+ let groundL = 0,
188
+ groundR = 0,
189
+ over = 0,
190
+ slopeL = 0,
191
+ slopeR = 0,
192
+ across = 0;
193
+ if (free) {
194
+ const cy = Math.cos(a.yaw),
195
+ sy = Math.sin(a.yaw),
196
+ wide = a.lx * h,
197
+ ahead = foot.sampleAhead * h,
198
+ xL = a.x - cy * wide + sy * zL * h,
199
+ xR = a.x + cy * wide + sy * zR * h,
200
+ atL = a.z + sy * wide + cy * zL * h,
201
+ atR = a.z - sy * wide + cy * zR * h,
202
+ gL = groundUnder(a, 0, xL, atL),
203
+ gR = groundUnder(a, 1, xR, atR);
204
+ // the ground each foot goes by follows what is under it: at once under a foot that stands, over a moment under one in the
205
+ // air, so that a step's edge crossed in mid-stride (a stair, a kerb) carries the foot and the hips up to it instead of
206
+ // jerking them there, and the foot is lifted higher to clear it
207
+ if (!(Math.abs(gL - F[11]) < foot.snapHeight)) F[11] = gL;
208
+ if (!(Math.abs(gR - F[12]) < foot.snapHeight)) F[12] = gR;
209
+ F[11] += (gL - F[11]) * Math.min(1, dt * foot.groundResponse[airL < 0.004 ? 0 : 1]);
210
+ F[12] += (gR - F[12]) * Math.min(1, dt * foot.groundResponse[airR < 0.004 ? 0 : 1]);
211
+ a.y = (F[11] + F[12]) / 2;
212
+ groundL = clamp((F[11] - a.y) / h, -0.3, 0.3);
213
+ groundR = -groundL;
214
+ over = lift > 0.01 ? Math.min(foot.stepClearance[1], (Math.abs(gL - gR) / h) * foot.stepClearance[0]) / lift : 0;
215
+ // a planted sole lies along the ground under it: the slope from the ankle's line to the toes, unless that is a step's
216
+ // edge; a foot in the air keeps the slope it left
217
+ slopeL = F[8];
218
+ slopeR = F[9];
219
+ if (airL < 0.01) {
220
+ const grade = (groundUnder(a, 2, xL + sy * ahead, atL + cy * ahead) - gL) / ahead;
221
+ slopeL = Math.abs(grade) < foot.edgeSlope ? -Math.atan(grade) : 0;
222
+ if (!slopeL && grade) stairSeen(a, Math.abs(grade) * ahead);
223
+ }
224
+ if (airR < 0.01) {
225
+ const grade = (groundUnder(a, 3, xR + sy * ahead, atR + cy * ahead) - gR) / ahead;
226
+ slopeR = Math.abs(grade) < foot.edgeSlope ? -Math.atan(grade) : 0;
227
+ if (!slopeR && grade) stairSeen(a, Math.abs(grade) * ahead);
228
+ }
229
+ across = Math.abs(gR - gL) < foot.edgeSlope * 2 * wide ? Math.atan((gR - gL) / (2 * wide)) : 0;
230
+ }
231
+ F[15] = Math.max(0, F[15] - dt);
232
+ F[13] += ((F[15] > 0 && striding ? 1 : 0) - F[13]) * Math.min(1, dt * foot.stairResponse);
233
+ F[8] += (clamp(slopeL, -foot.maxSlopeAngle, foot.maxSlopeAngle) - F[8]) * soleEase;
234
+ F[9] += (clamp(slopeR, -foot.maxSlopeAngle, foot.maxSlopeAngle) - F[9]) * soleEase;
235
+ F[10] += (clamp(across, -foot.maxSlopeAngle, foot.maxSlopeAngle) - F[10]) * soleEase;
236
+ // where each ankle then is: forward of the middle, and above the ground
237
+ ankleAt(F[6], F[8]);
238
+ const ankleZL = zL + _ankle[0],
239
+ ankleYL = groundL + airL * (1 + over) + _ankle[1];
240
+ ankleAt(F[7], F[9]);
241
+ const ankleZR = zR + _ankle[0],
242
+ ankleYR = groundR + airR * (1 + over) + _ankle[1];
243
+ // the hips ride as high as the pose asks and the planted legs allow
244
+ let hip = rig.hipHeight * cosL + sink + run * go * (pace.runDip - pace.runBob * Math.cos(2 * TAU * (uL - duty / 2)));
245
+ if (airL < 0.004) hip = Math.min(hip, ankleYL + jointY + Math.sqrt(Math.max(0.05, reach * reach - (ankleZL - hipAt - jointZ) ** 2)));
246
+ if (airR < 0.004) hip = Math.min(hip, ankleYR - jointY + Math.sqrt(Math.max(0.05, reach * reach - (ankleZR - hipAt + jointZ) ** 2)));
247
+ a.hip = Number.isNaN(a.hip) ? hip : a.hip + (hip - a.hip) * Math.min(1, dt * pace.hipResponse);
248
+ // each leg from the hip to its ankle, in the leaning trunk's own frame
249
+ let z = ankleZL - hipAt - jointZ,
250
+ y = ankleYL - a.hip + jointY;
251
+ solveLeg(z * cosL - y * sinL, y * cosL + z * sinL);
252
+ step.thighL = _leg[0];
253
+ step.kneeL = _leg[1];
254
+ z = ankleZR - hipAt + jointZ;
255
+ y = ankleYR - a.hip - jointY;
256
+ solveLeg(z * cosL - y * sinL, y * cosL + z * sinL);
257
+ step.thighR = _leg[0];
258
+ step.kneeR = _leg[1];
259
+ step.soleL = F[6] + F[8] - lean; // against the leaning trunk the legs are solved in
260
+ step.soleR = F[7] + F[9] - lean;
261
+ step.toesL = -Math.max(0, F[6]) * sstep(foot.toeReleaseHeight, 0, airL); // the toes stay on the ground while the heel rises
262
+ step.toesR = -Math.max(0, F[7]) * sstep(foot.toeReleaseHeight, 0, airR);
263
+ step.roll = F[10];
264
+ step.rise = a.hip - rig.hipHeight * cosL;
265
+ step.swing = Math.cos(TAU * uL) * go; // 1 as the left foot lands ahead, -1 as the right does
266
+ step.arms = Math.cos(TAU * (uL - pace.armLag)) * go; // the arms' swing against it: 1 with the left arm furthest back
267
+ step.bearing = Math.cos(TAU * (uL - duty / 2)) * go * (1 - run); // 1 with the weight over the left foot, -1 over the right
268
+ step.go = go;
269
+ step.run = run * go;
270
+ step.lean = tip;
271
+ step.turn = turn;
272
+ step.list = listed;
273
+ return step;
274
+ }
275
+ return stride;
276
+ }