@wardic/three 0.0.0-stage → 1.3.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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +84 -2
  3. package/THIRD_PARTY_NOTICES.md +145 -0
  4. package/dist/TestStage.d.ts +45 -0
  5. package/dist/TestStage.d.ts.map +1 -0
  6. package/dist/TestStage.js +140 -0
  7. package/dist/TestStage.js.map +1 -0
  8. package/dist/ThreeColours.d.ts +52 -0
  9. package/dist/ThreeColours.d.ts.map +1 -0
  10. package/dist/ThreeColours.js +237 -0
  11. package/dist/ThreeColours.js.map +1 -0
  12. package/dist/ThreeDrag.d.ts +82 -0
  13. package/dist/ThreeDrag.d.ts.map +1 -0
  14. package/dist/ThreeDrag.js +243 -0
  15. package/dist/ThreeDrag.js.map +1 -0
  16. package/dist/ThreeInput.d.ts +69 -0
  17. package/dist/ThreeInput.d.ts.map +1 -0
  18. package/dist/ThreeInput.js +592 -0
  19. package/dist/ThreeInput.js.map +1 -0
  20. package/dist/ThreeInstances.d.ts +47 -0
  21. package/dist/ThreeInstances.d.ts.map +1 -0
  22. package/dist/ThreeInstances.js +392 -0
  23. package/dist/ThreeInstances.js.map +1 -0
  24. package/dist/ThreeRenderer.d.ts +45 -0
  25. package/dist/ThreeRenderer.d.ts.map +1 -0
  26. package/dist/ThreeRenderer.js +121 -0
  27. package/dist/ThreeRenderer.js.map +1 -0
  28. package/dist/ThreeValues.d.ts +15 -0
  29. package/dist/ThreeValues.d.ts.map +1 -0
  30. package/dist/ThreeValues.js +61 -0
  31. package/dist/ThreeValues.js.map +1 -0
  32. package/dist/WardicThree.d.ts +194 -0
  33. package/dist/WardicThree.d.ts.map +1 -0
  34. package/dist/WardicThree.js +162 -0
  35. package/dist/WardicThree.js.map +1 -0
  36. package/dist/index.d.ts +26 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +27 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/internal/dev.d.ts +10 -0
  41. package/dist/internal/dev.d.ts.map +1 -0
  42. package/dist/internal/dev.js +11 -0
  43. package/dist/internal/dev.js.map +1 -0
  44. package/dist/internal/dev.production.d.ts +8 -0
  45. package/dist/internal/dev.production.d.ts.map +1 -0
  46. package/dist/internal/dev.production.js +8 -0
  47. package/dist/internal/dev.production.js.map +1 -0
  48. package/dist/internal/lookup.d.ts +29 -0
  49. package/dist/internal/lookup.d.ts.map +1 -0
  50. package/dist/internal/lookup.js +245 -0
  51. package/dist/internal/lookup.js.map +1 -0
  52. package/dist/internal/shared-material.d.ts +8 -0
  53. package/dist/internal/shared-material.d.ts.map +1 -0
  54. package/dist/internal/shared-material.js +95 -0
  55. package/dist/internal/shared-material.js.map +1 -0
  56. package/dist/solid/feature.d.ts +42 -0
  57. package/dist/solid/feature.d.ts.map +1 -0
  58. package/dist/solid/feature.js +2 -0
  59. package/dist/solid/feature.js.map +1 -0
  60. package/dist/solid/scene-batch.d.ts +10 -0
  61. package/dist/solid/scene-batch.d.ts.map +1 -0
  62. package/dist/solid/scene-batch.js +436 -0
  63. package/dist/solid/scene-batch.js.map +1 -0
  64. package/dist/solid/scene-object.d.ts +27 -0
  65. package/dist/solid/scene-object.d.ts.map +1 -0
  66. package/dist/solid/scene-object.js +111 -0
  67. package/dist/solid/scene-object.js.map +1 -0
  68. package/dist/solid/stage-batches.d.ts +10 -0
  69. package/dist/solid/stage-batches.d.ts.map +1 -0
  70. package/dist/solid/stage-batches.js +6 -0
  71. package/dist/solid/stage-batches.js.map +1 -0
  72. package/dist/solid/stage-drag.d.ts +4 -0
  73. package/dist/solid/stage-drag.d.ts.map +1 -0
  74. package/dist/solid/stage-drag.js +19 -0
  75. package/dist/solid/stage-drag.js.map +1 -0
  76. package/dist/solid/stage.d.ts +107 -0
  77. package/dist/solid/stage.d.ts.map +1 -0
  78. package/dist/solid/stage.js +320 -0
  79. package/dist/solid/stage.js.map +1 -0
  80. package/dist/solid/test-stage.d.ts +29 -0
  81. package/dist/solid/test-stage.d.ts.map +1 -0
  82. package/dist/solid/test-stage.js +16 -0
  83. package/dist/solid/test-stage.js.map +1 -0
  84. package/dist/solid.d.ts +55 -0
  85. package/dist/solid.d.ts.map +1 -0
  86. package/dist/solid.js +9 -0
  87. package/dist/solid.js.map +1 -0
  88. package/package.json +99 -4
  89. package/src/TestStage.ts +177 -0
  90. package/src/ThreeColours.ts +247 -0
  91. package/src/ThreeDrag.ts +341 -0
  92. package/src/ThreeInput.ts +744 -0
  93. package/src/ThreeInstances.ts +481 -0
  94. package/src/ThreeRenderer.ts +159 -0
  95. package/src/ThreeValues.ts +69 -0
  96. package/src/WardicThree.ts +347 -0
  97. package/src/index.ts +26 -0
  98. package/src/internal/dev.production.ts +7 -0
  99. package/src/internal/dev.ts +10 -0
  100. package/src/internal/lookup.ts +247 -0
  101. package/src/internal/shared-material.ts +101 -0
  102. package/src/solid/feature.ts +38 -0
  103. package/src/solid/scene-batch.ts +490 -0
  104. package/src/solid/scene-object.ts +145 -0
  105. package/src/solid/stage-batches.ts +13 -0
  106. package/src/solid/stage-drag.ts +26 -0
  107. package/src/solid/stage.ts +409 -0
  108. package/src/solid/test-stage.ts +40 -0
  109. package/src/solid.ts +111 -0
@@ -0,0 +1,481 @@
1
+ /**
2
+ * An `InstancedMesh`'s instances as a Batch's members: `wardic.batch(instanced)` animates each
3
+ * instance's transforms and colour by its index, as one run, where three would update an `Object3D` and
4
+ * call `setMatrixAt` for each. The writer composes each moving instance's matrix in place, uploads only
5
+ * the span of instances it wrote, and keeps the mesh's bounding sphere around them while they move, so
6
+ * culling and the raycast stay right.
7
+ *
8
+ * - **Its members** are every instance the mesh holds, its capacity. Its `count`, how many are drawn,
9
+ * stays the app's.
10
+ * - **Each starts** where its matrix puts it, read once when the Batch is made: its position, its
11
+ * rotation in degrees (Euler XYZ, three's default order) and its scale. A key the Batch doesn't take
12
+ * keeps that value.
13
+ * - **The matrices are the Batch's** from then on: a `setMatrixAt` of the app's is drawn over at that
14
+ * instance's next write.
15
+ * - **`color`** is an instance's colour, which three multiplies into the material's: in linear light,
16
+ * as `ThreeColours` splits it, `colorR`, `colorG` and `colorB`. The instances start white.
17
+ * - **One Batch a mesh** in a runtime: a second `wardic.batch` of it is an error.
18
+ *
19
+ * @example
20
+ * import * as WardicThree from "@wardic/three/WardicThree"
21
+ *
22
+ * const wardic = WardicThree.make()
23
+ * const swarm = wardic.batch(instanced)
24
+ * wardic.animate(swarm, { y: (i) => rowY(i), rotateY: 90 }, { type: "spring", delay: stagger(0.002) })
25
+ * wardic.animate(swarm.at(42), { scale: 1.4, color: "#ff8800" })
26
+ */
27
+ // `@wardic/three/ThreeInstances` (#883's PR 4; ADR-0069 decisions 11, 13, 14 and 19, ADR-0073 *Amendment
28
+ // (#883)*, PR 4's Q1–Q5). Probe `.tmp/883-instanced/` at 10,000 instances: three's way 561–584 µs a frame,
29
+ // `rotateY` alone 205–239 µs with the other axes' trig kept, translation alone 14–23 µs; the bounds' two
30
+ // passes over the matrices 68–73 µs, three's `computeBoundingSphere()` 370 µs. Per frame: plain code.
31
+ import type * as Batch from "@wardic/core/Batch"
32
+ import type * as WardicObject from "@wardic/object/WardicObject"
33
+ import * as Arr from "effect/Array"
34
+ import * as Predicate from "effect/Predicate"
35
+ import * as Lookup from "./internal/lookup.ts"
36
+
37
+ /** A three buffer attribute Wardic writes: its floats, and how three is told what changed. */
38
+ interface AttributeLike {
39
+ readonly array: Float32Array
40
+ readonly count: number
41
+ needsUpdate: boolean
42
+ readonly addUpdateRange?: ((start: number, count: number) => void) | undefined
43
+ }
44
+
45
+ /** A three `Sphere`, as the bounds write one. */
46
+ interface SphereLike {
47
+ readonly center: { readonly x: number; readonly y: number; readonly z: number; readonly set: (x: number, y: number, z: number) => unknown }
48
+ radius: number
49
+ }
50
+
51
+ /** What three's `setColorAt` reads of a colour: its channels, into an array. */
52
+ interface ColourWriter {
53
+ readonly toArray: (array: Float32Array, offset: number) => unknown
54
+ }
55
+
56
+ /** A three `InstancedMesh`, by its flag, as Wardic reads and writes one. */
57
+ // ADR-0069 decision 3.
58
+ interface InstancedLike {
59
+ readonly isInstancedMesh: true
60
+ readonly instanceMatrix: AttributeLike
61
+ readonly instanceColor: AttributeLike | null
62
+ readonly count: number
63
+ readonly geometry: { readonly boundingSphere: SphereLike | null; readonly computeBoundingSphere: () => void }
64
+ boundingSphere: SphereLike | null
65
+ boundingBox: unknown
66
+ readonly computeBoundingSphere: () => void
67
+ readonly setColorAt: (index: number, colour: ColourWriter) => unknown
68
+ }
69
+
70
+ /** One instance of an `InstancedMesh` `M`, as its Batch's member: the mesh, and the instance's index. */
71
+ export interface Instance<M extends object = object> {
72
+ readonly mesh: M
73
+ readonly index: number
74
+ }
75
+
76
+ /** An instance's keys in a Batch: its transforms, and its colour's channels in linear light. */
77
+ export type InstanceKey = "x" | "y" | "z" | "rotateX" | "rotateY" | "rotateZ" | "scale" | "scaleX" | "scaleY" | "scaleZ" | "colorR" | "colorG" | "colorB"
78
+
79
+ /** The keys an instance takes, as `InstanceKey` names them. */
80
+ const KEYS: ReadonlySet<string> = new Set(["x", "y", "z", "rotateX", "rotateY", "rotateZ", "scale", "scaleX", "scaleY", "scaleZ", "colorR", "colorG", "colorB"])
81
+
82
+ /**
83
+ * A member's start, kept by the Batch: its position, its rotation in degrees, its scale, then each
84
+ * rotation axis's cos and sin, so a frame's trig is only for the axes the Batch turns.
85
+ */
86
+ const STORE = 15
87
+ const AT_X = 0
88
+ const AT_Y = 1
89
+ const AT_Z = 2
90
+ const AT_SX = 6
91
+ const AT_SY = 7
92
+ const AT_SZ = 8
93
+ const COS_X = 9
94
+ const SIN_X = 10
95
+ const COS_Y = 11
96
+ const SIN_Y = 12
97
+ const COS_Z = 13
98
+ const SIN_Z = 14
99
+
100
+ /** Where a transform key's start is kept. `scale` is its `x`, as the lookup reads a mesh's. */
101
+ const STORE_AT: ReadonlyMap<string, number> = new Map([
102
+ ["x", 0],
103
+ ["y", 1],
104
+ ["z", 2],
105
+ ["rotateX", 3],
106
+ ["rotateY", 4],
107
+ ["rotateZ", 5],
108
+ ["scale", 6],
109
+ ["scaleX", 6],
110
+ ["scaleY", 7],
111
+ ["scaleZ", 8],
112
+ ])
113
+
114
+ /** A colour channel key's place among an instance's three. */
115
+ const CHANNEL_AT: ReadonlyMap<string, number> = new Map([
116
+ ["colorR", 0],
117
+ ["colorG", 1],
118
+ ["colorB", 2],
119
+ ])
120
+
121
+ /** White, as `setColorAt` reads a colour: what makes a mesh's instance colours, every one white. */
122
+ const WHITE: ColourWriter = { toArray: (array, offset) => array.fill(1, offset, offset + 3) }
123
+
124
+ /** The meshes that have a Batch, in any runtime: what tells an instance's handle. */
125
+ // Module state: held weakly by the mesh.
126
+ const INSTANCED = new WeakSet<object>()
127
+
128
+ /** Whether `given` is a three `InstancedMesh`, by its flag. */
129
+ export const isInstancedMesh = (given: unknown): boolean => Predicate.isObject(given) && (given as { readonly isInstancedMesh?: unknown }).isInstancedMesh === true
130
+
131
+ /** Whether `given` is an instance a Batch's member handle names: one of a mesh that has a Batch. */
132
+ export const isInstance = (given: unknown): given is Instance => {
133
+ if (!Predicate.isObject(given)) return false
134
+ const mesh = (given as { readonly mesh?: unknown }).mesh
135
+ return Predicate.isObject(mesh) && INSTANCED.has(mesh) && Predicate.isNumber((given as { readonly index?: unknown }).index)
136
+ }
137
+
138
+ /** `1 / s`, and 0 for a scale of 0: an axis scaled to nothing keeps no rotation to read. */
139
+ const inverse = (s: number): number => {
140
+ if (s === 0) return 0
141
+ return 1 / s
142
+ }
143
+
144
+ /**
145
+ * The matrix at `o` in `te` read into `out` at `at`: its position, its rotation in degrees (Euler XYZ),
146
+ * its scale, and each axis's cos and sin. three's `decompose` and `Euler.setFromRotationMatrix`, with a
147
+ * mirrored matrix's sign on its x scale.
148
+ */
149
+ export const decompose = (te: ArrayLike<number>, o: number, out: Float64Array, at: number): void => {
150
+ const m0 = te[o]
151
+ const m1 = te[o + 1]
152
+ const m2 = te[o + 2]
153
+ const m4 = te[o + 4]
154
+ const m5 = te[o + 5]
155
+ const m6 = te[o + 6]
156
+ const m8 = te[o + 8]
157
+ const m9 = te[o + 9]
158
+ const m10 = te[o + 10]
159
+ let sx = Math.hypot(m0, m1, m2)
160
+ const sy = Math.hypot(m4, m5, m6)
161
+ const sz = Math.hypot(m8, m9, m10)
162
+ if (m0 * (m5 * m10 - m9 * m6) - m4 * (m1 * m10 - m9 * m2) + m8 * (m1 * m6 - m5 * m2) < 0) sx = -sx
163
+ const ix = inverse(sx)
164
+ const iy = inverse(sy)
165
+ const iz = inverse(sz)
166
+ const m13 = m8 * iz
167
+ const ry = Math.asin(Math.min(Math.max(m13, -1), 1))
168
+ let rx = Math.atan2(m6 * iy, m5 * iy)
169
+ let rz = 0
170
+ if (Math.abs(m13) < 0.9999999) {
171
+ rx = Math.atan2(-m9 * iz, m10 * iz)
172
+ rz = Math.atan2(-m4 * iy, m0 * ix)
173
+ }
174
+ out[at] = te[o + 12]
175
+ out[at + 1] = te[o + 13]
176
+ out[at + 2] = te[o + 14]
177
+ out[at + 3] = rx / Lookup.RADIANS
178
+ out[at + 4] = ry / Lookup.RADIANS
179
+ out[at + 5] = rz / Lookup.RADIANS
180
+ out[at + 6] = sx
181
+ out[at + 7] = sy
182
+ out[at + 8] = sz
183
+ out[at + 9] = Math.cos(rx)
184
+ out[at + 10] = Math.sin(rx)
185
+ out[at + 11] = Math.cos(ry)
186
+ out[at + 12] = Math.sin(ry)
187
+ out[at + 13] = Math.cos(rz)
188
+ out[at + 14] = Math.sin(rz)
189
+ }
190
+
191
+ /**
192
+ * The matrix of a position, a rotation by its axes' cos and sin (`a`, `b` for x; `c`, `d` for y; `e`,
193
+ * `f` for z; Euler XYZ) and a scale, written at `o` in `te`: three's `makeRotationFromEuler`, scaled.
194
+ */
195
+ export const compose = (te: Float32Array, o: number, x: number, y: number, z: number, a: number, b: number, c: number, d: number, e: number, f: number, sx: number, sy: number, sz: number): void => {
196
+ const ae = a * e
197
+ const af = a * f
198
+ const be = b * e
199
+ const bf = b * f
200
+ te[o] = c * e * sx
201
+ te[o + 1] = (af + be * d) * sx
202
+ te[o + 2] = (bf - ae * d) * sx
203
+ te[o + 3] = 0
204
+ te[o + 4] = -c * f * sy
205
+ te[o + 5] = (ae - bf * d) * sy
206
+ te[o + 6] = (be + af * d) * sy
207
+ te[o + 7] = 0
208
+ te[o + 8] = d * sz
209
+ te[o + 9] = -b * c * sz
210
+ te[o + 10] = a * c * sz
211
+ te[o + 11] = 0
212
+ te[o + 12] = x
213
+ te[o + 13] = y
214
+ te[o + 14] = z
215
+ te[o + 15] = 1
216
+ }
217
+
218
+ /** A key's value for a member: the Batch's, at key index `k`, else its start's, kept at `at`. */
219
+ const valueAt = (positions: Float64Array, base: number, k: number, store: Float64Array, at: number): number => {
220
+ if (k < 0) return store[at]
221
+ return positions[base + k]
222
+ }
223
+
224
+ /** A rotation axis's cos for a member: of the Batch's angle, in degrees, else its start's, kept. */
225
+ const cosAt = (positions: Float64Array, base: number, k: number, store: Float64Array, at: number): number => {
226
+ if (k < 0) return store[at]
227
+ return Math.cos(positions[base + k] * Lookup.RADIANS)
228
+ }
229
+
230
+ /** A rotation axis's sin for a member: of the Batch's angle, in degrees, else its start's, kept. */
231
+ const sinAt = (positions: Float64Array, base: number, k: number, store: Float64Array, at: number): number => {
232
+ if (k < 0) return store[at]
233
+ return Math.sin(positions[base + k] * Lookup.RADIANS)
234
+ }
235
+
236
+ /** An axis's scale for a member: its own key, else `scale`, else its start's, kept. */
237
+ const scaleAt = (positions: Float64Array, base: number, axis: number, all: number, store: Float64Array, at: number): number => {
238
+ if (axis >= 0) return positions[base + axis]
239
+ if (all >= 0) return positions[base + all]
240
+ return store[at]
241
+ }
242
+
243
+ /** `attribute`'s floats from `start`, `count` of them, uploaded at the next render: the span alone where three takes one. */
244
+ const upload = (attribute: AttributeLike, start: number, count: number): void => {
245
+ if (Predicate.isFunction(attribute.addUpdateRange)) attribute.addUpdateRange(start, count)
246
+ attribute.needsUpdate = true
247
+ }
248
+
249
+ /**
250
+ * The sphere around the first `count` instances of `te`, into `sphere`: each instance's geometry sphere
251
+ * (`geometry`) through its matrix, kept in `reach`, an AABB of them, then the farthest reach from its
252
+ * middle. Every instance is inside it.
253
+ */
254
+ // ADR-0069 decision 19, as PR 4's Q3 amends it: from the matrices, which hold every member, where a writer
255
+ // sees only those it writes. Two passes, no matrix product: 68–73 µs at 10,000 (`.tmp/883-instanced/`).
256
+ export const boundsOf = (te: Float32Array, count: number, geometry: SphereLike, reach: Float64Array, sphere: SphereLike): void => {
257
+ if (count === 0) {
258
+ sphere.center.set(0, 0, 0)
259
+ sphere.radius = -1
260
+ return
261
+ }
262
+ const cx = geometry.center.x
263
+ const cy = geometry.center.y
264
+ const cz = geometry.center.z
265
+ const radius = geometry.radius
266
+ let minX = Number.POSITIVE_INFINITY
267
+ let minY = Number.POSITIVE_INFINITY
268
+ let minZ = Number.POSITIVE_INFINITY
269
+ let maxX = Number.NEGATIVE_INFINITY
270
+ let maxY = Number.NEGATIVE_INFINITY
271
+ let maxZ = Number.NEGATIVE_INFINITY
272
+ for (let i = 0; i < count; i++) {
273
+ const o = i * 16
274
+ const m0 = te[o]
275
+ const m1 = te[o + 1]
276
+ const m2 = te[o + 2]
277
+ const m4 = te[o + 4]
278
+ const m5 = te[o + 5]
279
+ const m6 = te[o + 6]
280
+ const m8 = te[o + 8]
281
+ const m9 = te[o + 9]
282
+ const m10 = te[o + 10]
283
+ const px = m0 * cx + m4 * cy + m8 * cz + te[o + 12]
284
+ const py = m1 * cx + m5 * cy + m9 * cz + te[o + 13]
285
+ const pz = m2 * cx + m6 * cy + m10 * cz + te[o + 14]
286
+ const r = radius * Math.sqrt(Math.max(m0 * m0 + m1 * m1 + m2 * m2, m4 * m4 + m5 * m5 + m6 * m6, m8 * m8 + m9 * m9 + m10 * m10))
287
+ const c = i * 4
288
+ reach[c] = px
289
+ reach[c + 1] = py
290
+ reach[c + 2] = pz
291
+ reach[c + 3] = r
292
+ minX = Math.min(minX, px - r)
293
+ minY = Math.min(minY, py - r)
294
+ minZ = Math.min(minZ, pz - r)
295
+ maxX = Math.max(maxX, px + r)
296
+ maxY = Math.max(maxY, py + r)
297
+ maxZ = Math.max(maxZ, pz + r)
298
+ }
299
+ const mx = (minX + maxX) / 2
300
+ const my = (minY + maxY) / 2
301
+ const mz = (minZ + maxZ) / 2
302
+ let far = 0
303
+ for (let i = 0; i < count; i++) {
304
+ const c = i * 4
305
+ far = Math.max(far, Math.hypot(reach[c] - mx, reach[c + 1] - my, reach[c + 2] - mz) + reach[c + 3])
306
+ }
307
+ sphere.center.set(mx, my, mz)
308
+ sphere.radius = far
309
+ }
310
+
311
+ /** A key an instance doesn't take, refused when its Batch is made: an error naming why, and the way. */
312
+ const refuse = (key: string): never => {
313
+ if (key === "color") {
314
+ throw new Error(`wardic.batch: an InstancedMesh's instance colour takes its channels here, colorR, colorG and colorB, in linear light: its material has no Color to read "color" by.`)
315
+ }
316
+ throw new Error(`wardic.batch: an InstancedMesh's instances take their transforms (x, rotateY, scale…) and their colour (color), not "${key}". They share one material: animate it for all of them, wardic.animate(instanced.material, { ${key}: … }).`)
317
+ }
318
+
319
+ /** Whether any of `ks`, key indices, is a key the Batch has. */
320
+ const anyOf = (ks: ReadonlyArray<number>): boolean => Arr.some(ks, (k) => k >= 0)
321
+
322
+ /** `mesh`'s instances as a Batch's: their read, and a writer of their own, whose `flush` uploads what it wrote and bounds them. */
323
+ const instancesOf = (mesh: InstancedLike, capacity: number): Pick<WardicObject.BatchSource, "writer" | "read"> => {
324
+ const store = new Float64Array(capacity * STORE)
325
+ const scratch = new Float64Array(STORE)
326
+ // The bounds' per-instance spheres, made at their first need.
327
+ let reach = new Float64Array(0)
328
+ let started = false
329
+ // The span of instances a frame wrote, empty while `high < low`.
330
+ let low = capacity
331
+ let high = -1
332
+ let colourLow = capacity
333
+ let colourHigh = -1
334
+
335
+ /** Every instance's matrix read once into its start, when the Batch is made. */
336
+ const start = (): void => {
337
+ const te = mesh.instanceMatrix.array
338
+ for (let i = 0; i < capacity; i++) decompose(te, i * 16, store, i * STORE)
339
+ started = true
340
+ }
341
+
342
+ /** The mesh's bounding sphere around its drawn instances, in place: three makes it the first time. Its box, computed again when it's asked for. */
343
+ const bound = (): void => {
344
+ if (Predicate.isNotNull(mesh.boundingBox)) mesh.boundingBox = null
345
+ const sphere = mesh.boundingSphere
346
+ if (Predicate.isNull(sphere)) {
347
+ mesh.computeBoundingSphere()
348
+ return
349
+ }
350
+ const geometry = mesh.geometry
351
+ if (Predicate.isNull(geometry.boundingSphere)) geometry.computeBoundingSphere()
352
+ const count = Math.min(mesh.count, capacity)
353
+ if (reach.length < count * 4) reach = new Float64Array(capacity * 4)
354
+ boundsOf(mesh.instanceMatrix.array, count, geometry.boundingSphere as SphereLike, reach, sphere)
355
+ }
356
+
357
+ const read = (subject: object, key: string): unknown => {
358
+ const index = (subject as Instance).index
359
+ const channel = CHANNEL_AT.get(key)
360
+ if (Predicate.isNotUndefined(channel)) {
361
+ const colours = mesh.instanceColor
362
+ if (Predicate.isNull(colours)) return 1
363
+ return colours.array[index * 3 + channel]
364
+ }
365
+ const at = STORE_AT.get(key)
366
+ if (Predicate.isUndefined(at)) return undefined
367
+ if (started) return store[index * STORE + at]
368
+ // Before the Batch is made: its matrix now, as `get` reads it.
369
+ decompose(mesh.instanceMatrix.array, index * 16, scratch, 0)
370
+ return scratch[at]
371
+ }
372
+
373
+ const writer: Batch.Writer<object> = {
374
+ writes: (key) => {
375
+ if (KEYS.has(key)) return true
376
+ return refuse(key)
377
+ },
378
+ forKeys: (keys) => {
379
+ start()
380
+ const ix = keys.indexOf("x")
381
+ const iy = keys.indexOf("y")
382
+ const iz = keys.indexOf("z")
383
+ const irx = keys.indexOf("rotateX")
384
+ const iry = keys.indexOf("rotateY")
385
+ const irz = keys.indexOf("rotateZ")
386
+ const is = keys.indexOf("scale")
387
+ const isx = keys.indexOf("scaleX")
388
+ const isy = keys.indexOf("scaleY")
389
+ const isz = keys.indexOf("scaleZ")
390
+ const icr = keys.indexOf("colorR")
391
+ const icg = keys.indexOf("colorG")
392
+ const icb = keys.indexOf("colorB")
393
+ // A Batch that turns or scales composes each matrix; one that only moves writes its translation alone.
394
+ const whole = anyOf([irx, iry, irz, is, isx, isy, isz])
395
+ const transforms = whole || anyOf([ix, iy, iz])
396
+ const colours = anyOf([icr, icg, icb])
397
+ if (colours && Predicate.isNull(mesh.instanceColor)) mesh.setColorAt(0, WHITE)
398
+ return (subject, positions, base) => {
399
+ const index = (subject as Instance).index
400
+ if (transforms) {
401
+ const te = mesh.instanceMatrix.array
402
+ const o = index * 16
403
+ const s = index * STORE
404
+ const x = valueAt(positions, base, ix, store, s + AT_X)
405
+ const y = valueAt(positions, base, iy, store, s + AT_Y)
406
+ const z = valueAt(positions, base, iz, store, s + AT_Z)
407
+ if (whole) {
408
+ compose(
409
+ te,
410
+ o,
411
+ x,
412
+ y,
413
+ z,
414
+ cosAt(positions, base, irx, store, s + COS_X),
415
+ sinAt(positions, base, irx, store, s + SIN_X),
416
+ cosAt(positions, base, iry, store, s + COS_Y),
417
+ sinAt(positions, base, iry, store, s + SIN_Y),
418
+ cosAt(positions, base, irz, store, s + COS_Z),
419
+ sinAt(positions, base, irz, store, s + SIN_Z),
420
+ scaleAt(positions, base, isx, is, store, s + AT_SX),
421
+ scaleAt(positions, base, isy, is, store, s + AT_SY),
422
+ scaleAt(positions, base, isz, is, store, s + AT_SZ),
423
+ )
424
+ }
425
+ if (!whole) {
426
+ te[o + 12] = x
427
+ te[o + 13] = y
428
+ te[o + 14] = z
429
+ }
430
+ low = Math.min(low, index)
431
+ high = Math.max(high, index)
432
+ }
433
+ if (colours) {
434
+ const array = (mesh.instanceColor as AttributeLike).array
435
+ const c = index * 3
436
+ if (icr >= 0) array[c] = positions[base + icr]
437
+ if (icg >= 0) array[c + 1] = positions[base + icg]
438
+ if (icb >= 0) array[c + 2] = positions[base + icb]
439
+ colourLow = Math.min(colourLow, index)
440
+ colourHigh = Math.max(colourHigh, index)
441
+ }
442
+ }
443
+ },
444
+ flush: () => {
445
+ if (high >= low) {
446
+ upload(mesh.instanceMatrix, low * 16, (high - low + 1) * 16)
447
+ low = capacity
448
+ high = -1
449
+ bound()
450
+ }
451
+ if (colourHigh >= colourLow) {
452
+ upload(mesh.instanceColor as AttributeLike, colourLow * 3, (colourHigh - colourLow + 1) * 3)
453
+ colourLow = capacity
454
+ colourHigh = -1
455
+ }
456
+ },
457
+ }
458
+ return { writer, read }
459
+ }
460
+
461
+ /**
462
+ * A runtime's Batches of instances, its Environment's `batchSource`: an `InstancedMesh`'s instances as a
463
+ * Batch's members, a handle each, `{ mesh, index }`, drawn by a writer of its own; `undefined` for
464
+ * anything else. A mesh is one Batch's in the runtime.
465
+ */
466
+ // PR 4's Q1. Per runtime, so a disposed one (a hot reload's) leaves its meshes free for the next.
467
+ export const batchSource = (): ((given: object) => WardicObject.BatchSource | undefined) => {
468
+ // Held weakly by the mesh.
469
+ const batched = new WeakSet<object>()
470
+ return (given) => {
471
+ if (!isInstancedMesh(given)) return undefined
472
+ const mesh = given as InstancedLike
473
+ if (batched.has(mesh)) throw new Error("wardic.batch: this InstancedMesh has a Batch already, which draws its instances: keep the one wardic.batch gave. An InstancedMesh is one Batch's.")
474
+ const capacity = mesh.instanceMatrix.count
475
+ if (capacity === 0) throw new Error("wardic.batch: this InstancedMesh holds no instances: a Batch of it has a member for each instance it holds.")
476
+ batched.add(mesh)
477
+ INSTANCED.add(mesh)
478
+ const members = Arr.makeBy(capacity, (index): Instance => ({ mesh, index }))
479
+ return { members, ...instancesOf(mesh, capacity) }
480
+ }
481
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The scene writer: Wardic's values written onto three.js objects once a frame, in the frame that
3
+ * computed them. A scene object's transform keys go in one call per vector:
4
+ * - `x`, `y` and `z` as `position.set`;
5
+ * - `rotateX`, `rotateY` and `rotateZ`, in degrees, as one `rotation.set` in radians;
6
+ * - `scale`, and `scaleX`, `scaleY` and `scaleZ`, as one `scale.set`, an axis's own key over `scale`.
7
+ *
8
+ * Any other key goes where the lookup finds it: the object's own number, its material's (each of an
9
+ * array of them), a uniform's `value`, a TSL uniform node's, or a vector's axis. Two of three's own
10
+ * rules follow a write: a camera's projection keys end with `updateProjectionMatrix()`, and a
11
+ * material's `opacity` below 1 draws it transparent. `layer` is what `WardicThree` provides; `GATE` is what its
12
+ * Flush gate reads of an object; `writer` draws a Batch of objects.
13
+ *
14
+ * @example
15
+ * import * as ThreeRenderer from "@wardic/three/ThreeRenderer"
16
+ *
17
+ * ThreeRenderer.commit(mesh, { x: 2, rotateY: 90, opacity: 0.5 })
18
+ * // mesh.position.x === 2, mesh.rotation.y === Math.PI / 2, mesh.material.opacity === 0.5
19
+ */
20
+ // `@wardic/three/ThreeRenderer` (#883; ADR-0069 decisions 4–6, ADR-0073 *Amendment (#883)*, Q3): core's
21
+ // `Renderer`, as `@wardic/object/ObjectRenderer` is for plain objects. P3 measured one `rotation.set` a
22
+ // commit 2.4–2.9× cheaper than three's setters (ADR-0069 decision 6). Per frame: plain code.
23
+ import type * as Batch from "@wardic/core/Batch"
24
+ import * as Renderer from "@wardic/core/Renderer"
25
+ import type * as FlushGate from "@wardic/core/unstable/FlushGate"
26
+ import * as Layer from "effect/Layer"
27
+ import * as Predicate from "effect/Predicate"
28
+ import * as Lookup from "./internal/lookup.ts"
29
+
30
+ /** Any object Wardic writes. */
31
+ type Holder = Record<string, unknown>
32
+
33
+ /** A vector three gives a scene object: `position`, `rotation` and `scale` are each set in one call. */
34
+ interface Settable {
35
+ readonly x: number
36
+ readonly y: number
37
+ readonly z: number
38
+ readonly set: (x: number, y: number, z: number) => unknown
39
+ }
40
+
41
+ /**
42
+ * What the gate saves of a property before its first write, to put back if the key ever drops out:
43
+ * nothing. A scene's values stay where Wardic leaves them, so a commit skips a key given this.
44
+ */
45
+ const NOTHING_SAVED = ""
46
+
47
+ /** A camera's projection keys: after one, its projection matrix is worked out again. */
48
+ const PROJECTION: ReadonlySet<string> = new Set(["fov", "zoom", "near", "far", "aspect", "left", "right", "top", "bottom"])
49
+
50
+ /** `value` as an axis's number, `NaN` where it's none: a key the patch doesn't give, or one put back with nothing. */
51
+ const axisOf = (value: unknown): number => {
52
+ if (Predicate.isNumber(value)) return value
53
+ return Number.NaN
54
+ }
55
+
56
+ /** `given` unless it's `NaN`, else `current`. */
57
+ const or = (given: number, current: number): number => {
58
+ if (Number.isNaN(given)) return current
59
+ return given
60
+ }
61
+
62
+ /** An axis's scale: its own key, else `scale`, else as it is. */
63
+ const scaleOr = (axis: number, all: number, current: number): number => {
64
+ if (!Number.isNaN(axis)) return axis
65
+ if (!Number.isNaN(all)) return all
66
+ return current
67
+ }
68
+
69
+ /** Whether any of three axes is given. */
70
+ const anyOf = (a: number, b: number, c: number): boolean => !Number.isNaN(a) || !Number.isNaN(b) || !Number.isNaN(c)
71
+
72
+ /**
73
+ * A scene object's transforms written, `NaN` for a key not given: one `position.set`, one `rotation.set`
74
+ * from degrees, one `scale.set`, each only where one of its keys is given, the rest of its axes kept.
75
+ */
76
+ export const writeTransforms = (object: Holder, x: number, y: number, z: number, rx: number, ry: number, rz: number, s: number, sx: number, sy: number, sz: number): void => {
77
+ if (anyOf(x, y, z)) {
78
+ const position = object.position as Settable
79
+ position.set(or(x, position.x), or(y, position.y), or(z, position.z))
80
+ }
81
+ if (anyOf(rx, ry, rz)) {
82
+ const rotation = object.rotation as Settable
83
+ const radians = Lookup.RADIANS
84
+ rotation.set(or(rx * radians, rotation.x), or(ry * radians, rotation.y), or(rz * radians, rotation.z))
85
+ }
86
+ if (anyOf(sx, sy, sz) || !Number.isNaN(s)) {
87
+ const scale = object.scale as Settable
88
+ scale.set(scaleOr(sx, s, scale.x), scaleOr(sy, s, scale.y), scaleOr(sz, s, scale.z))
89
+ }
90
+ }
91
+
92
+ /** A scene's patch: its values as they are; the commit groups them. */
93
+ export const project = (values: Readonly<Record<string, unknown>>): Renderer.Patch => values as Renderer.Patch
94
+
95
+ /** `patch` written onto `target`: a scene object's transforms grouped, every other key where the lookup finds it. */
96
+ export const commit = (target: unknown, patch: Renderer.Patch): void => {
97
+ const object = target as Holder
98
+ const scene = Lookup.isObject3D(object)
99
+ if (scene) {
100
+ writeTransforms(object, axisOf(patch.x), axisOf(patch.y), axisOf(patch.z), axisOf(patch.rotateX), axisOf(patch.rotateY), axisOf(patch.rotateZ), axisOf(patch.scale), axisOf(patch.scaleX), axisOf(patch.scaleY), axisOf(patch.scaleZ))
101
+ }
102
+ let projection = false
103
+ for (const key in patch) {
104
+ const value = patch[key]
105
+ if (value === NOTHING_SAVED) continue
106
+ if (scene && Lookup.isTransformKey(key)) continue
107
+ Lookup.write(object, key, value)
108
+ if (PROJECTION.has(key)) projection = true
109
+ }
110
+ if (projection && object.isCamera === true && Predicate.isFunction(object.updateProjectionMatrix)) (object as { readonly updateProjectionMatrix: () => void }).updateProjectionMatrix()
111
+ }
112
+
113
+ /** The Flush gate's reads of an object: nothing saved before a write, and a template key no object has. */
114
+ export const GATE: FlushGate.GateEnvironment = { valueBeforeOf: () => NOTHING_SAVED, templateKey: "@wardic/three/template" }
115
+
116
+ /** The scene writer as the Environment's `Renderer`. */
117
+ export const layer: Layer.Layer<Renderer.Renderer> = /*#__PURE__*/ Layer.succeed(Renderer.Renderer, { project, commit })
118
+
119
+ /** Where `key` is in a Batch's keys, `-1` where it isn't. */
120
+ const indexIn = (keys: ReadonlyArray<string>, key: string): number => keys.indexOf(key)
121
+
122
+ /** A Batch's position for key index `k` of a member, `NaN` for a key it doesn't have. */
123
+ const at = (positions: Float64Array, base: number, k: number): number => {
124
+ if (k < 0) return Number.NaN
125
+ return positions[base + k]
126
+ }
127
+
128
+ /**
129
+ * The scene writer for a Batch of objects: each member's transforms grouped as
130
+ * the commit's are, any other key where the lookup finds it. Its keys' places are found once, by index.
131
+ */
132
+ // ADR-0069 decision 11.
133
+ export const writer: Batch.Writer<object> = {
134
+ writes: () => true,
135
+ forKeys: (keys) => {
136
+ const ix = indexIn(keys, "x")
137
+ const iy = indexIn(keys, "y")
138
+ const iz = indexIn(keys, "z")
139
+ const irx = indexIn(keys, "rotateX")
140
+ const iry = indexIn(keys, "rotateY")
141
+ const irz = indexIn(keys, "rotateZ")
142
+ const is = indexIn(keys, "scale")
143
+ const isx = indexIn(keys, "scaleX")
144
+ const isy = indexIn(keys, "scaleY")
145
+ const isz = indexIn(keys, "scaleZ")
146
+ return (subject, positions, base) => {
147
+ const object = subject as Holder
148
+ const scene = Lookup.isObject3D(object)
149
+ if (scene) {
150
+ writeTransforms(object, at(positions, base, ix), at(positions, base, iy), at(positions, base, iz), at(positions, base, irx), at(positions, base, iry), at(positions, base, irz), at(positions, base, is), at(positions, base, isx), at(positions, base, isy), at(positions, base, isz))
151
+ }
152
+ for (let k = 0; k < keys.length; k++) {
153
+ const key = keys[k]
154
+ if (scene && Lookup.isTransformKey(key)) continue
155
+ Lookup.write(object, key, positions[base + k])
156
+ }
157
+ }
158
+ },
159
+ }