@krate/3d 0.0.0-stage → 0.5.0-rc.14

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 (43) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +9 -0
  3. package/README.md +45 -2
  4. package/materials/VERSION +1 -0
  5. package/materials/build.mjs +59 -0
  6. package/materials/physical.filamat +0 -0
  7. package/materials/physical_transparent.filamat +0 -0
  8. package/materials/src/physical.mat +90 -0
  9. package/materials/src/standard.mat +77 -0
  10. package/materials/src/unlit.mat +28 -0
  11. package/materials/standard.filamat +0 -0
  12. package/materials/standard_transparent.filamat +0 -0
  13. package/materials/unlit.filamat +0 -0
  14. package/materials/unlit_transparent.filamat +0 -0
  15. package/package.json +66 -3
  16. package/src/index.ts +3 -0
  17. package/src/runtime/aim.ts +40 -0
  18. package/src/runtime/calibration.ts +29 -0
  19. package/src/runtime/canvas.tsx +18 -0
  20. package/src/runtime/canvas_style.ts +11 -0
  21. package/src/runtime/color.ts +183 -0
  22. package/src/runtime/compiled.ts +39 -0
  23. package/src/runtime/compiled_canvas.tsx +37 -0
  24. package/src/runtime/context.ts +14 -0
  25. package/src/runtime/controls.ts +146 -0
  26. package/src/runtime/entities.ts +50 -0
  27. package/src/runtime/environment.ts +50 -0
  28. package/src/runtime/filament.ts +309 -0
  29. package/src/runtime/geometry.ts +195 -0
  30. package/src/runtime/gltf.ts +77 -0
  31. package/src/runtime/hooks.ts +10 -0
  32. package/src/runtime/index.ts +18 -0
  33. package/src/runtime/lights.ts +75 -0
  34. package/src/runtime/materials.ts +267 -0
  35. package/src/runtime/mount.ts +52 -0
  36. package/src/runtime/picking.ts +123 -0
  37. package/src/runtime/renderables.ts +62 -0
  38. package/src/runtime/rt.ts +33 -0
  39. package/src/runtime/scene.ts +484 -0
  40. package/src/runtime/transforms.ts +182 -0
  41. package/src/runtime/tree.ts +283 -0
  42. package/src/runtime/view.ts +121 -0
  43. package/src/types.ts +205 -0
@@ -0,0 +1,484 @@
1
+ // One Filament engine, scene, view and frame loop per <canvas>. Calls made
2
+ // before the engine is ready (Filament initialises asynchronously) are queued
3
+ // and replayed in order, so compiled code can run synchronously.
4
+
5
+ import type { PointerHandler } from '../types.js';
6
+ import { lightIntensity } from './calibration.js';
7
+ import { Entities } from './entities.js';
8
+ import type {
9
+ FAssetLoader,
10
+ FCamera,
11
+ FColorGrading,
12
+ FEngine,
13
+ FEntity,
14
+ FIndirectLight,
15
+ FRenderer,
16
+ FScene,
17
+ FSkybox,
18
+ FSwapChain,
19
+ FView,
20
+ FilamentModule,
21
+ FilamentSource,
22
+ Mat4,
23
+ } from './filament.js';
24
+ import { loadFilament } from './filament.js';
25
+ import { buildGeometry, uploadGeometry, type GeometryKind, type GpuGeometry } from './geometry.js';
26
+ import { buildAmbient, buildLight, updateLight, type LightKind, type LightProps } from './lights.js';
27
+ import { MaterialManager, type CustomMaterialSpec, type MaterialHandle, type MaterialKind, type MaterialParams, type ParamValue } from './materials.js';
28
+ import { Picker, type PointerEventName } from './picking.js';
29
+ import { buildInstanced, buildMesh, type MeshFlags } from './renderables.js';
30
+ import { TransformBuffer } from './transforms.js';
31
+ import {
32
+ applyExposure,
33
+ applyLookAt,
34
+ applyProjection,
35
+ applyView,
36
+ cameraState,
37
+ type CameraState,
38
+ type SceneCameraOptions,
39
+ type ViewOptions,
40
+ } from './view.js';
41
+
42
+ export interface SceneOptions {
43
+ /** Number of dynamic transform slots the compiled code uses. */
44
+ slots?: number;
45
+ view?: ViewOptions;
46
+ camera?: SceneCameraOptions;
47
+ /** Base URL of the compiled .filamat files; defaults to the package's own materials. */
48
+ materialBase?: string;
49
+ /** URL of the filament.js the build copied into the site (the compiler fills it in). */
50
+ filamentUrl?: string;
51
+ /** An already loaded Filament module (or loader) instead of the script at `filamentUrl`. */
52
+ filament?: FilamentSource;
53
+ pixelRatio?: number;
54
+ /** Fetches bytes for materials and textures; defaults to fetch(). */
55
+ fetchBytes?: (url: string) => Promise<Uint8Array>;
56
+ onError?: (err: unknown) => void;
57
+ }
58
+
59
+ export interface GeometryHandle {
60
+ kind: GeometryKind;
61
+ args: number[];
62
+ gpu?: GpuGeometry;
63
+ }
64
+ export interface MeshHandle {
65
+ /** Filament entity id once built, else 0. */
66
+ id: number;
67
+ slot: number;
68
+ entities: FEntity[];
69
+ built: Array<() => void>;
70
+ }
71
+ export interface LightHandle {
72
+ kind: LightKind;
73
+ props: LightProps;
74
+ entity?: FEntity;
75
+ ibl?: FIndirectLight;
76
+ }
77
+ export interface InitialTransform {
78
+ pos?: readonly number[];
79
+ quat?: readonly number[];
80
+ scale?: readonly number[];
81
+ }
82
+ export type FrameCallback = (delta: number, time: number) => void;
83
+
84
+ export class Scene3D {
85
+ readonly canvas: HTMLCanvasElement;
86
+ readonly opts: SceneOptions;
87
+ readonly transforms: TransformBuffer;
88
+ /** Resolves once the engine is up and queued calls have replayed. */
89
+ readonly ready: Promise<void>;
90
+ isReady = false;
91
+ disposed = false;
92
+ error: unknown;
93
+
94
+ F!: FilamentModule;
95
+ engine!: FEngine;
96
+ fscene!: FScene;
97
+ view!: FView;
98
+ camera!: FCamera;
99
+ entities!: Entities;
100
+ materials!: MaterialManager;
101
+ picker!: Picker;
102
+ camState: CameraState;
103
+ private cameraEntity!: FEntity;
104
+ private renderer!: FRenderer;
105
+ private swapChain!: FSwapChain;
106
+ private grading?: FColorGrading;
107
+ private loader?: FAssetLoader;
108
+ private assets: Array<{ destroy(): void }> = [];
109
+ private geometries = new Map<string, GeometryHandle>();
110
+ private queue: Array<() => void> = [];
111
+ private frameCallbacks: FrameCallback[] = [];
112
+ private ambient?: FIndirectLight;
113
+ private env?: { ibl?: FIndirectLight; sky?: FSkybox };
114
+ private nextSlot: number;
115
+ private nextId = 1;
116
+ private cameraDirty = true;
117
+ private resizeObserver?: ResizeObserver;
118
+ private visibility?: IntersectionObserver;
119
+ private visible = true;
120
+ private raf = 0;
121
+ private last = 0;
122
+
123
+ constructor(canvas: HTMLCanvasElement, opts: SceneOptions = {}) {
124
+ this.canvas = canvas;
125
+ this.opts = opts;
126
+ this.transforms = new TransformBuffer(opts.slots ?? 0);
127
+ this.nextSlot = opts.slots ?? 0;
128
+ this.camState = cameraState(opts.camera);
129
+ this.ready = this.init().catch((err) => {
130
+ this.error = err;
131
+ (opts.onError ?? console.error)(err);
132
+ });
133
+ }
134
+
135
+ get pixelRatio(): number {
136
+ return this.opts.pixelRatio ?? (typeof window !== 'undefined' ? window.devicePixelRatio : 1) ?? 1;
137
+ }
138
+
139
+ private async init(): Promise<void> {
140
+ const F = await loadFilament(this.opts.filament, this.opts.filamentUrl);
141
+ if (this.disposed) return;
142
+ this.F = F;
143
+ this.sizeCanvas();
144
+ const engine = (this.engine = F.Engine.create(this.canvas, { alpha: true }));
145
+ this.entities = new Entities(F, engine);
146
+ this.fscene = engine.createScene();
147
+ this.swapChain = engine.createSwapChain();
148
+ this.renderer = engine.createRenderer();
149
+ this.view = engine.createView();
150
+ this.renderer.setClearOptions({ clearColor: [0, 0, 0, 0], clear: true });
151
+ this.view.setBlendMode(F.View$BlendMode.TRANSLUCENT);
152
+ this.cameraEntity = this.entities.create();
153
+ this.camera = engine.createCamera(this.cameraEntity);
154
+ this.view.setCamera(this.camera);
155
+ this.view.setScene(this.fscene);
156
+ applyExposure(this.camera, this.opts.camera);
157
+ this.grading = applyView(F, engine, this.view, this.opts.view ?? {});
158
+ this.materials = new MaterialManager(F, engine, this.opts.materialBase, this.opts.fetchBytes);
159
+ this.picker = new Picker(this.view, this.canvas, () => this.pixelRatio);
160
+ if (typeof ResizeObserver !== 'undefined') {
161
+ this.resizeObserver = new ResizeObserver(() => this.applySize());
162
+ this.resizeObserver.observe(this.canvas);
163
+ }
164
+ if (typeof IntersectionObserver !== 'undefined') {
165
+ this.visibility = new IntersectionObserver((entries) => {
166
+ for (const e of entries) this.visible = e.isIntersecting;
167
+ });
168
+ this.visibility.observe(this.canvas);
169
+ }
170
+ this.isReady = true;
171
+ this.applySize();
172
+ for (const fn of this.queue.splice(0)) this.run(fn);
173
+ this.raf = requestAnimationFrame(this.loop);
174
+ }
175
+
176
+ private run(fn: () => void): void {
177
+ try {
178
+ fn();
179
+ } catch (err) {
180
+ this.error = err;
181
+ (this.opts.onError ?? console.error)(err);
182
+ }
183
+ }
184
+
185
+ /** Runs fn now if the engine is up, else after it is. */
186
+ whenReady(fn: () => void): void {
187
+ if (this.disposed) return;
188
+ if (this.isReady) this.run(fn);
189
+ else this.queue.push(fn);
190
+ }
191
+
192
+ private sizeCanvas(): void {
193
+ const dpr = this.pixelRatio;
194
+ const w = Math.max(1, Math.round(this.canvas.clientWidth * dpr));
195
+ const h = Math.max(1, Math.round(this.canvas.clientHeight * dpr));
196
+ if (this.canvas.width !== w) this.canvas.width = w;
197
+ if (this.canvas.height !== h) this.canvas.height = h;
198
+ }
199
+
200
+ /** Matches the drawing buffer to the CSS size and device pixel ratio. */
201
+ applySize(): void {
202
+ if (this.disposed || !this.isReady) return;
203
+ this.sizeCanvas();
204
+ const { width, height } = this.canvas;
205
+ this.view.setViewport([0, 0, width, height]);
206
+ applyProjection(this.F, this.camera, this.camState, width, height);
207
+ }
208
+
209
+ // Slots and handles
210
+
211
+ allocSlot(): number {
212
+ const s = this.nextSlot++;
213
+ this.transforms.ensure(this.nextSlot);
214
+ return s;
215
+ }
216
+
217
+ geometry(kind: GeometryKind, args: readonly number[] = []): GeometryHandle {
218
+ const key = `${kind}:${args.join(',')}`;
219
+ let h = this.geometries.get(key);
220
+ if (!h) {
221
+ h = { kind, args: [...args] };
222
+ this.geometries.set(key, h);
223
+ }
224
+ return h;
225
+ }
226
+
227
+ private gpu(h: GeometryHandle): GpuGeometry {
228
+ return (h.gpu ??= uploadGeometry(this.F, this.engine, buildGeometry(h.kind, h.args)));
229
+ }
230
+
231
+ material(kind: MaterialKind, params?: MaterialParams): MaterialHandle;
232
+ /** A shaderMaterial compiled by the build: `url` is the hashed .filamat, `params` the initial uniforms. */
233
+ material(kind: 'custom', spec: CustomMaterialSpec): MaterialHandle;
234
+ material(kind: MaterialKind | 'custom', params: MaterialParams | CustomMaterialSpec = {}): MaterialHandle {
235
+ const h =
236
+ kind === 'custom'
237
+ ? MaterialManager.customHandle(params as CustomMaterialSpec)
238
+ : MaterialManager.handle(kind === ('basic' as string) ? 'unlit' : kind, params as MaterialParams);
239
+ this.whenReady(() => this.materials.start(h));
240
+ return h;
241
+ }
242
+
243
+ setMaterialParam(m: MaterialHandle, name: string, value: ParamValue): void {
244
+ if (this.isReady) this.materials.set(m, name, value);
245
+ else m.params[name] = value;
246
+ }
247
+
248
+ private newMesh(slot: number): MeshHandle {
249
+ return { id: 0, slot, entities: [], built: [] };
250
+ }
251
+
252
+ /** Builds the mesh once its material instance exists (immediately if it already does). */
253
+ private build(m: MaterialHandle, fn: () => void): void {
254
+ this.whenReady(() => {
255
+ if (m.instance) fn();
256
+ else m.waiters.push(() => this.run(fn));
257
+ });
258
+ }
259
+
260
+ private finish(h: MeshHandle, entities: FEntity[]): void {
261
+ h.entities = entities;
262
+ h.id = entities[0].getId();
263
+ this.fscene.addEntities(entities);
264
+ for (const fn of h.built.splice(0)) fn();
265
+ }
266
+
267
+ staticMesh(g: GeometryHandle, m: MaterialHandle, matrix: ArrayLike<number>, flags?: MeshFlags): MeshHandle {
268
+ const h = this.newMesh(-1);
269
+ this.build(m, () => {
270
+ const e = buildMesh(this.F, this.engine, this.entities, this.gpu(g), m.instance!, flags, !!this.opts.view?.shadows);
271
+ const tcm = this.engine.getTransformManager();
272
+ tcm.setTransform(tcm.getInstance(e), matrix as Mat4);
273
+ this.finish(h, [e]);
274
+ });
275
+ return h;
276
+ }
277
+
278
+ dynamicMesh(
279
+ slot: number,
280
+ g: GeometryHandle,
281
+ m: MaterialHandle,
282
+ parent: ArrayLike<number>,
283
+ initial?: InitialTransform,
284
+ flags?: MeshFlags
285
+ ): MeshHandle {
286
+ const t = this.transforms;
287
+ t.ensure(slot + 1);
288
+ this.nextSlot = Math.max(this.nextSlot, slot + 1);
289
+ t.setParent(slot, parent);
290
+ if (initial) {
291
+ const p = initial.pos;
292
+ const q = initial.quat;
293
+ const s = initial.scale;
294
+ if (p) t.pos(slot, p[0], p[1], p[2]);
295
+ if (s) t.scale(slot, s[0], s[1], s[2]);
296
+ if (q) {
297
+ const o = slot * 10 + 3;
298
+ t.data[o] = q[0];
299
+ t.data[o + 1] = q[1];
300
+ t.data[o + 2] = q[2];
301
+ t.data[o + 3] = q[3];
302
+ t.markDirty(slot);
303
+ }
304
+ }
305
+ const h = this.newMesh(slot);
306
+ this.build(m, () => {
307
+ const e = buildMesh(this.F, this.engine, this.entities, this.gpu(g), m.instance!, flags, !!this.opts.view?.shadows);
308
+ t.instances[slot] = this.engine.getTransformManager().getInstance(e);
309
+ t.markDirty(slot);
310
+ this.finish(h, [e]);
311
+ });
312
+ return h;
313
+ }
314
+
315
+ /** Writes a slot's position; accepts (x, y, z) or one [x, y, z] array. */
316
+ pos(slot: number, x: number | readonly number[], y?: number, z?: number): void {
317
+ if (typeof x === 'number') this.transforms.pos(slot, x, y!, z!);
318
+ else this.transforms.pos(slot, x[0], x[1], x[2]);
319
+ }
320
+ /** Writes a slot's Euler XYZ rotation; accepts (x, y, z) or one array. */
321
+ rot(slot: number, x: number | readonly number[], y?: number, z?: number): void {
322
+ if (typeof x === 'number') this.transforms.rot(slot, x, y!, z!);
323
+ else this.transforms.rot(slot, x[0], x[1], x[2]);
324
+ }
325
+ /** Writes a slot's scale; accepts (x, y, z), one [x, y, z] array, or one number for uniform scale. */
326
+ scale(slot: number, x: number | readonly number[], y?: number, z?: number): void {
327
+ if (typeof x !== 'number') this.transforms.scale(slot, x[0], x[1], x[2]);
328
+ else this.transforms.scale(slot, x, y ?? x, z ?? x);
329
+ }
330
+
331
+ /** `count` static copies of one mesh; matrices holds count column-major 4x4 matrices. */
332
+ instanced(g: GeometryHandle, m: MaterialHandle, count: number, matrices: Float32Array, flags?: MeshFlags): MeshHandle {
333
+ const h = this.newMesh(-1);
334
+ this.build(m, () => {
335
+ const es = buildInstanced(this.F, this.engine, this.entities, this.gpu(g), m.instance!, count, matrices, flags, !!this.opts.view?.shadows);
336
+ this.finish(h, es);
337
+ });
338
+ return h;
339
+ }
340
+
341
+ light(kind: LightKind, props: LightProps = {}): LightHandle {
342
+ const h: LightHandle = { kind, props: { ...props } };
343
+ this.whenReady(() => {
344
+ if (kind === 'ambient') {
345
+ const old = this.ambient;
346
+ h.ibl = this.ambient = buildAmbient(this.F, this.engine, h.props);
347
+ this.refreshIndirect();
348
+ if (old) this.engine.destroyIndirectLight(old);
349
+ return;
350
+ }
351
+ h.entity = buildLight(this.F, this.engine, this.entities, kind, h.props, !!this.opts.view?.shadows);
352
+ this.fscene.addEntity(h.entity);
353
+ });
354
+ return h;
355
+ }
356
+
357
+ /** Reactive light update; intensity is in Filament units (see lightIntensity). */
358
+ setLight(h: LightHandle, name: 'intensity' | 'color' | 'position' | 'direction', value: number | readonly number[]): void {
359
+ (h.props as Record<string, unknown>)[name] = value;
360
+ if (h.entity) updateLight(this.engine, h.entity, name, value);
361
+ else if (h.ibl && name === 'intensity') h.ibl.setIntensity(value as number);
362
+ }
363
+
364
+ /** Three.js-scale intensity to Filament units. */
365
+ intensity(kind: LightKind, threeIntensity: number): number {
366
+ return lightIntensity(kind, threeIntensity);
367
+ }
368
+
369
+ /** Registers a pointer handler for a mesh; events: click, pointerover, pointerout, pointermove, pointerdown, pointerup. */
370
+ on(mesh: MeshHandle, event: PointerEventName, handler: PointerHandler): void {
371
+ const register = (): void => {
372
+ for (const e of mesh.entities) this.picker.on(e.getId(), event, handler);
373
+ };
374
+ this.whenReady(() => (mesh.entities.length ? register() : mesh.built.push(register)));
375
+ }
376
+
377
+ // Environment and camera
378
+
379
+ /** Replaces the image-based light (and optional skybox); ambient lights yield to it. */
380
+ setEnvironment(ibl?: FIndirectLight, sky?: FSkybox): void {
381
+ this.destroyEnv();
382
+ this.env = { ibl, sky };
383
+ this.fscene.setSkybox(sky ?? null);
384
+ this.refreshIndirect();
385
+ }
386
+
387
+ private refreshIndirect(): void {
388
+ this.fscene.setIndirectLight(this.env?.ibl ?? this.ambient ?? null);
389
+ }
390
+
391
+ private destroyEnv(): void {
392
+ if (!this.env) return;
393
+ if (this.env.ibl) this.engine.destroyIndirectLight(this.env.ibl);
394
+ if (this.env.sky) this.engine.destroySkybox(this.env.sky);
395
+ this.env = undefined;
396
+ }
397
+
398
+ /** Updates the camera; applied on the next frame. */
399
+ setCamera(c: Partial<CameraState>): void {
400
+ Object.assign(this.camState, c);
401
+ this.cameraDirty = true;
402
+ }
403
+
404
+ getLoader(): FAssetLoader {
405
+ return (this.loader ??= this.engine.createAssetLoader());
406
+ }
407
+
408
+ /** Registers something to destroy on dispose (glTF assets and the like). */
409
+ track(destroy: () => void): void {
410
+ this.assets.push({ destroy });
411
+ }
412
+
413
+ /** Per-frame callback, before transforms are flushed. Returns an unsubscribe function. */
414
+ onFrame(cb: FrameCallback): () => void {
415
+ this.frameCallbacks.push(cb);
416
+ return () => {
417
+ const i = this.frameCallbacks.indexOf(cb);
418
+ if (i !== -1) this.frameCallbacks.splice(i, 1);
419
+ };
420
+ }
421
+
422
+ // Frame loop
423
+
424
+ private loop = (time: number): void => {
425
+ if (this.disposed) return;
426
+ this.raf = requestAnimationFrame(this.loop);
427
+ if (!this.canvas.isConnected) {
428
+ this.dispose();
429
+ return;
430
+ }
431
+ if (this.visible) this.tick(time);
432
+ };
433
+
434
+ /** One frame: callbacks, camera, dirty transforms, pick, render. Public for tests. */
435
+ tick(time: number): void {
436
+ if (!this.isReady || this.disposed) return;
437
+ const delta = this.last ? (time - this.last) / 1000 : 0;
438
+ this.last = time;
439
+ const cbs = this.frameCallbacks;
440
+ for (let i = 0; i < cbs.length; i++) cbs[i](delta, time / 1000);
441
+ if (this.cameraDirty) {
442
+ this.cameraDirty = false;
443
+ applyLookAt(this.camera, this.camState);
444
+ applyProjection(this.F, this.camera, this.camState, this.canvas.width, this.canvas.height);
445
+ }
446
+ this.transforms.flush(this.engine.getTransformManager());
447
+ this.picker.update();
448
+ this.renderer.render(this.swapChain, this.view);
449
+ }
450
+
451
+ dispose(): void {
452
+ if (this.disposed) return;
453
+ this.disposed = true;
454
+ this.queue = [];
455
+ this.frameCallbacks = [];
456
+ if (this.raf) cancelAnimationFrame(this.raf);
457
+ this.resizeObserver?.disconnect();
458
+ this.visibility?.disconnect();
459
+ if (!this.isReady) return;
460
+ const engine = this.engine;
461
+ this.picker.dispose();
462
+ for (const a of this.assets.splice(0)) a.destroy();
463
+ this.loader?.delete();
464
+ this.destroyEnv();
465
+ this.fscene.setIndirectLight(null);
466
+ this.fscene.setSkybox(null);
467
+ if (this.ambient) engine.destroyIndirectLight(this.ambient);
468
+ engine.destroyCameraComponent(this.cameraEntity);
469
+ this.entities.destroyAll();
470
+ for (const g of this.geometries.values()) {
471
+ if (!g.gpu) continue;
472
+ engine.destroyVertexBuffer(g.gpu.vb);
473
+ engine.destroyIndexBuffer(g.gpu.ib);
474
+ }
475
+ this.materials.dispose();
476
+ if (this.grading) engine.destroyColorGrading(this.grading);
477
+ engine.destroyView(this.view);
478
+ engine.destroyRenderer(this.renderer);
479
+ engine.destroyScene(this.fscene);
480
+ engine.destroySwapChain(this.swapChain);
481
+ this.F.Engine.destroy(engine);
482
+ }
483
+
484
+ }
@@ -0,0 +1,182 @@
1
+ // Transform buffer: one Float32Array of [px,py,pz,qx,qy,qz,qw,sx,sy,sz] per
2
+ // dynamic slot plus a dirty bitmask. flush() composes parent * T * R * S for
3
+ // the dirty slots only, without allocating.
4
+
5
+ import type { FInstance, FTransformManager } from './filament.js';
6
+
7
+ export const STRIDE = 10;
8
+
9
+ /** Euler XYZ (radians, Three.js order) to a unit quaternion written at out[o..o+3]. */
10
+ export function eulerToQuat(out: Float32Array, o: number, x: number, y: number, z: number): void {
11
+ const c1 = Math.cos(x / 2);
12
+ const c2 = Math.cos(y / 2);
13
+ const c3 = Math.cos(z / 2);
14
+ const s1 = Math.sin(x / 2);
15
+ const s2 = Math.sin(y / 2);
16
+ const s3 = Math.sin(z / 2);
17
+ out[o] = s1 * c2 * c3 + c1 * s2 * s3;
18
+ out[o + 1] = c1 * s2 * c3 - s1 * c2 * s3;
19
+ out[o + 2] = c1 * c2 * s3 + s1 * s2 * c3;
20
+ out[o + 3] = c1 * c2 * c3 - s1 * s2 * s3;
21
+ }
22
+
23
+ /** Column-major T * R * S from a slot at data[o..o+9] into m. */
24
+ export function composeTRS(m: Float32Array, data: Float32Array, o: number): void {
25
+ const x = data[o + 3];
26
+ const y = data[o + 4];
27
+ const z = data[o + 5];
28
+ const w = data[o + 6];
29
+ const sx = data[o + 7];
30
+ const sy = data[o + 8];
31
+ const sz = data[o + 9];
32
+ const x2 = x + x;
33
+ const y2 = y + y;
34
+ const z2 = z + z;
35
+ const xx = x * x2;
36
+ const xy = x * y2;
37
+ const xz = x * z2;
38
+ const yy = y * y2;
39
+ const yz = y * z2;
40
+ const zz = z * z2;
41
+ const wx = w * x2;
42
+ const wy = w * y2;
43
+ const wz = w * z2;
44
+ m[0] = (1 - (yy + zz)) * sx;
45
+ m[1] = (xy + wz) * sx;
46
+ m[2] = (xz - wy) * sx;
47
+ m[3] = 0;
48
+ m[4] = (xy - wz) * sy;
49
+ m[5] = (1 - (xx + zz)) * sy;
50
+ m[6] = (yz + wx) * sy;
51
+ m[7] = 0;
52
+ m[8] = (xz + wy) * sz;
53
+ m[9] = (yz - wx) * sz;
54
+ m[10] = (1 - (xx + yy)) * sz;
55
+ m[11] = 0;
56
+ m[12] = data[o];
57
+ m[13] = data[o + 1];
58
+ m[14] = data[o + 2];
59
+ m[15] = 1;
60
+ }
61
+
62
+ /** out = a(at offset ao) * b, column-major. out must not alias a or b. */
63
+ export function mulMat4(out: Float32Array, a: Float32Array, ao: number, b: Float32Array): void {
64
+ for (let c = 0; c < 4; c++) {
65
+ const b0 = b[c * 4];
66
+ const b1 = b[c * 4 + 1];
67
+ const b2 = b[c * 4 + 2];
68
+ const b3 = b[c * 4 + 3];
69
+ for (let r = 0; r < 4; r++) {
70
+ out[c * 4 + r] = a[ao + r] * b0 + a[ao + 4 + r] * b1 + a[ao + 8 + r] * b2 + a[ao + 12 + r] * b3;
71
+ }
72
+ }
73
+ }
74
+
75
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
76
+
77
+ export class TransformBuffer {
78
+ data: Float32Array;
79
+ mask: Uint32Array;
80
+ parents: Float32Array;
81
+ instances: (FInstance | undefined)[] = [];
82
+ private local = new Float32Array(16);
83
+ private world = new Float32Array(16);
84
+ private slots = 0;
85
+
86
+ constructor(slots = 0) {
87
+ this.data = new Float32Array(0);
88
+ this.mask = new Uint32Array(0);
89
+ this.parents = new Float32Array(0);
90
+ this.ensure(slots);
91
+ }
92
+
93
+ get capacity(): number {
94
+ return this.slots;
95
+ }
96
+
97
+ /** Grows the buffers to hold at least n slots; new slots are identity. */
98
+ ensure(n: number): void {
99
+ if (n <= this.slots) return;
100
+ const data = new Float32Array(n * STRIDE);
101
+ data.set(this.data);
102
+ const parents = new Float32Array(n * 16);
103
+ parents.set(this.parents);
104
+ for (let s = this.slots; s < n; s++) {
105
+ data[s * STRIDE + 6] = 1;
106
+ data[s * STRIDE + 7] = data[s * STRIDE + 8] = data[s * STRIDE + 9] = 1;
107
+ parents.set(IDENTITY, s * 16);
108
+ }
109
+ const mask = new Uint32Array(Math.ceil(n / 32));
110
+ mask.set(this.mask);
111
+ this.data = data;
112
+ this.parents = parents;
113
+ this.mask = mask;
114
+ this.slots = n;
115
+ }
116
+
117
+ markDirty(slot: number): void {
118
+ this.mask[slot >> 5] |= 1 << (slot & 31);
119
+ }
120
+
121
+ isDirty(slot: number): boolean {
122
+ return (this.mask[slot >> 5] & (1 << (slot & 31))) !== 0;
123
+ }
124
+
125
+ pos(slot: number, x: number, y: number, z: number): void {
126
+ const o = slot * STRIDE;
127
+ this.data[o] = x;
128
+ this.data[o + 1] = y;
129
+ this.data[o + 2] = z;
130
+ this.markDirty(slot);
131
+ }
132
+
133
+ rot(slot: number, x: number, y: number, z: number): void {
134
+ eulerToQuat(this.data, slot * STRIDE + 3, x, y, z);
135
+ this.markDirty(slot);
136
+ }
137
+
138
+ scale(slot: number, x: number, y: number, z: number): void {
139
+ const o = slot * STRIDE + 7;
140
+ this.data[o] = x;
141
+ this.data[o + 1] = y;
142
+ this.data[o + 2] = z;
143
+ this.markDirty(slot);
144
+ }
145
+
146
+ setParent(slot: number, matrix: ArrayLike<number>): void {
147
+ this.parents.set(matrix, slot * 16);
148
+ this.markDirty(slot);
149
+ }
150
+
151
+ /** Writes every dirty slot's world matrix to the TransformManager in one transaction. */
152
+ flush(tcm: FTransformManager): number {
153
+ const { mask, data, parents, instances, local, world } = this;
154
+ let n = 0;
155
+ let open = false;
156
+ for (let w = 0; w < mask.length; w++) {
157
+ let bits = mask[w];
158
+ if (bits === 0) continue;
159
+ mask[w] = 0;
160
+ while (bits !== 0) {
161
+ const low = bits & -bits;
162
+ bits ^= low;
163
+ const slot = w * 32 + (31 - Math.clz32(low));
164
+ const inst = instances[slot];
165
+ if (!inst) {
166
+ // Entity not built yet; it re-marks the slot when it appears.
167
+ continue;
168
+ }
169
+ if (!open) {
170
+ tcm.openLocalTransformTransaction();
171
+ open = true;
172
+ }
173
+ composeTRS(local, data, slot * STRIDE);
174
+ mulMat4(world, parents, slot * 16, local);
175
+ tcm.setTransform(inst, world);
176
+ n++;
177
+ }
178
+ }
179
+ if (open) tcm.commitLocalTransformTransaction();
180
+ return n;
181
+ }
182
+ }