@threenative/three-native 0.3.12 → 0.3.15

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.
@@ -14,6 +14,16 @@ export interface IUpdateFrame {
14
14
  frameId: number;
15
15
  camera?: unknown;
16
16
  scene?: unknown;
17
+ renderer?: unknown;
18
+ }
19
+
20
+ /** What one sync is for: the draw's camera and root, the renderer's frame, and a dispatch's kernels (engine node ids). */
21
+ export interface ISyncFrame {
22
+ camera?: unknown;
23
+ scene?: unknown;
24
+ renderer?: unknown;
25
+ frameId?: number;
26
+ kernels?: readonly number[];
17
27
  }
18
28
 
19
29
  interface IUniformState {
@@ -138,11 +148,17 @@ function referenceValue(property: string, type: string, object: unknown): unknow
138
148
  * Wraps a back end's `uniform` so each uniform node it returns answers `.value` (an accessor on the
139
149
  * node itself: a V8 node has no prototype of its own to carry it) and three's update hooks. `setValues`
140
150
  * writes a node's lanes into the engine. `sync()` runs once per render: the update callbacks first,
141
- * then the edited objects' lanes, each written only when its lanes changed.
151
+ * then the edited objects' lanes, each written only when its lanes changed. With `setMany`, every
152
+ * write of one sync crosses as one call (node i takes `counts[i]` of the packed `lanes`, PRD-828);
153
+ * a `.value` set outside a sync still goes through `setValues` at once. `reads` (PRD-878) asks the engine which
154
+ * of the hooked nodes one draw or dispatch reads, as indices into `hooked`; undefined runs every hook, as a
155
+ * scene's render does.
142
156
  */
143
157
  export function liveUniforms<TNode extends object>(
144
158
  uniform: (value: unknown, type?: unknown) => TNode,
145
159
  setValues: (node: TNode, lanes: readonly number[]) => void,
160
+ setMany?: (nodes: readonly TNode[], counts: readonly number[], lanes: readonly number[]) => void,
161
+ reads?: (frame: ISyncFrame, hooked: readonly TNode[]) => ArrayLike<number> | undefined,
146
162
  ): {
147
163
  uniform: (value: unknown, type?: unknown) => TNode;
148
164
  uniformArray: (
@@ -150,7 +166,7 @@ export function liveUniforms<TNode extends object>(
150
166
  type?: string,
151
167
  ) => { array: unknown[]; element(index: unknown): TNode };
152
168
  reference(property: string, type: string, object?: unknown): TNode;
153
- sync(frame?: { camera?: unknown; scene?: unknown; frameId?: number }): void;
169
+ sync(frame?: ISyncFrame): void;
154
170
  } {
155
171
  const debug = debugRequested();
156
172
  const host = globalThis as {
@@ -268,8 +284,38 @@ export function liveUniforms<TNode extends object>(
268
284
  own(node, value);
269
285
  }
270
286
  };
271
- const updating = new Set<TNode>();
287
+ // Every node with an update callback, in the order its first callback was set (the engine's `reads` indexes it).
288
+ const updating: TNode[] = [];
289
+ // The render hooks alone: a nested render of a frame whose frame hooks all ran walks only these.
290
+ const renders = new Set<TNode>();
291
+ let hookedFrame: number | undefined;
272
292
  let frameId = 0;
293
+ // One sync's writes, sent as one crossing at its end (PRD-828); a write outside a sync goes at once.
294
+ let batching = false;
295
+ const pendingNodes: TNode[] = [];
296
+ const pendingCounts: number[] = [];
297
+ const pendingLanes: number[] = [];
298
+ const clear = () => {
299
+ pendingNodes.length = 0;
300
+ pendingCounts.length = 0;
301
+ pendingLanes.length = 0;
302
+ };
303
+ // A batch that was refused or never sent (a hook threw) counts as not uploaded: the next sync writes each
304
+ // node's current value again, so a `.value` set in between is not overwritten by a stale lane.
305
+ const requeue = () => {
306
+ for (const node of pendingNodes) {
307
+ const state = states.get(node);
308
+ if (state !== undefined) state.lanes = undefined;
309
+ dirty.add(new WeakRef(node));
310
+ }
311
+ clear();
312
+ };
313
+ const flush = () => {
314
+ if (pendingNodes.length === 0 || setMany === undefined) return;
315
+ setMany(pendingNodes, pendingCounts, pendingLanes);
316
+ if (debug) count("uniformWriteCrossings");
317
+ clear();
318
+ };
273
319
  // An unchanged value is not written again: an edited Color or vector is found by its lanes, and a
274
320
  // hook that returns the same number every render costs no engine write.
275
321
  const write = (node: TNode, state: IUniformState, lanes: readonly number[]) => {
@@ -287,13 +333,45 @@ export function liveUniforms<TNode extends object>(
287
333
  // A snapshot for the sink and the state: `lanes` is the state's scratch, refilled by the next
288
334
  // extraction, so a sink that keeps its argument must not see later values.
289
335
  const written = lanes.slice();
290
- setValues(node, written);
336
+ if (batching) {
337
+ pendingNodes.push(node);
338
+ pendingCounts.push(written.length);
339
+ for (const lane of written) pendingLanes.push(lane);
340
+ } else {
341
+ setValues(node, written);
342
+ if (debug) count("uniformWriteCrossings");
343
+ }
291
344
  if (debug) {
292
345
  count("uniformWrites");
293
346
  count("uniformLaneWrites", lanes.length);
294
347
  }
295
348
  state.lanes = written;
296
349
  };
350
+ // One sync's frame: one object, refilled each sync, as three's NodeFrame is one object.
351
+ const frame: IUpdateFrame = { frameId: 0 };
352
+ // Runs one node's update callback for this sync and writes what it returns.
353
+ const updateNode = (node: TNode, rendererFrame: number | undefined): void => {
354
+ const state = states.get(node);
355
+ if (state?.update === undefined) return;
356
+ if (state.updateType === "frame" && rendererFrame !== undefined) {
357
+ if (state.ranFrame === rendererFrame) return;
358
+ state.ranFrame = rendererFrame;
359
+ }
360
+ let next: unknown;
361
+ if (debug) {
362
+ const callbackStart = performance.now();
363
+ count(state.updateType === "frame" ? "uniformFrameCallbacks" : "uniformRenderCallbacks");
364
+ try {
365
+ next = state.update(frame);
366
+ } finally {
367
+ const elapsed = performance.now() - callbackStart;
368
+ count("uniformCallbackMs", elapsed);
369
+ if (state.debugSource !== undefined)
370
+ count(`uniformCallback:${state.debugSource}Ms`, elapsed, state.debugSource);
371
+ }
372
+ } else next = state.update(frame);
373
+ if (next !== undefined) (node as { value: unknown }).value = next;
374
+ };
297
375
  const live = {
298
376
  uniform(value: unknown, type?: unknown): TNode {
299
377
  // A matrix uniform is made by its type name at identity, then given the matrix's elements.
@@ -329,7 +407,10 @@ export function liveUniforms<TNode extends object>(
329
407
  throw new Error(
330
408
  `TN_TSL_UPDATE_UNSUPPORTED: a native uniform updates per frame or render, not per '${updateType}'`,
331
409
  );
332
- if (state.update === undefined) updating.add(node);
410
+ if (state.update === undefined) updating.push(node);
411
+ if (updateType === "render") renders.add(node);
412
+ else renders.delete(node);
413
+ hookedFrame = undefined; // a frame hook added mid-frame runs at the next render
333
414
  state.update = (frame) => callback.call(node, frame, node);
334
415
  state.updateType = updateType;
335
416
  if (debug) {
@@ -372,71 +453,74 @@ export function liveUniforms<TNode extends object>(
372
453
  },
373
454
  /**
374
455
  * three's uniformArray(values): `element(i)` at a constant index is a uniform that reads
375
- * `values[i]` before each render, as UniformArrayNode copies its array per update. ponytail: a
376
- * node index needs an engine uniform array; it is refused by name.
456
+ * `values[i]` before each render, as UniformArrayNode copies its array per update. A node index
457
+ * (a Loop's `i`) selects among those uniforms. ponytail: one select per element on each read; an
458
+ * engine uniform array when a game indexes long arrays.
377
459
  */
378
460
  uniformArray(values: unknown[]) {
379
461
  if (!Array.isArray(values))
380
462
  throw new TypeError("TN_TSL_UNIFORM_ARRAY: uniformArray takes an array");
381
463
  const elements = new Map<number, TNode>();
382
- return {
383
- array: values,
384
- element(index: unknown): TNode {
385
- if (
386
- typeof index !== "number" ||
387
- !Number.isInteger(index) ||
388
- index < 0 ||
389
- index >= values.length
390
- )
391
- throw new RangeError(
392
- `TN_TSL_UNIFORM_ARRAY: element needs a constant index in [0, ${values.length})`,
393
- );
394
- let node = elements.get(index);
395
- if (node === undefined) {
396
- node = live.uniform(values[index]);
397
- // quality-allow: TNode does not expose internal onRenderUpdate hook from WebGPU node system.
398
- const updatable = node as unknown as {
399
- onRenderUpdate: (callback: () => unknown) => void;
400
- };
401
- updatable.onRenderUpdate(() => values[index]);
402
- elements.set(index, node);
403
- }
404
- return node;
405
- },
464
+ type IIndexNode = { equal(k: number): { select(a: TNode, b: TNode): TNode } };
465
+ const element = (index: unknown): TNode => {
466
+ if (
467
+ typeof index === "object" &&
468
+ index !== null &&
469
+ typeof (index as Partial<IIndexNode>).equal === "function" &&
470
+ values.length > 0
471
+ ) {
472
+ let picked = element(values.length - 1);
473
+ for (let k = values.length - 2; k >= 0; k--)
474
+ picked = (index as IIndexNode).equal(k).select(element(k), picked);
475
+ return picked;
476
+ }
477
+ if (
478
+ typeof index !== "number" ||
479
+ !Number.isInteger(index) ||
480
+ index < 0 ||
481
+ index >= values.length
482
+ )
483
+ throw new RangeError(
484
+ `TN_TSL_UNIFORM_ARRAY: element needs a constant index in [0, ${values.length})`,
485
+ );
486
+ let node = elements.get(index);
487
+ if (node === undefined) {
488
+ node = live.uniform(values[index]);
489
+ // quality-allow: TNode does not expose internal onRenderUpdate hook from WebGPU node system.
490
+ const updatable = node as unknown as {
491
+ onRenderUpdate: (callback: () => unknown) => void;
492
+ };
493
+ updatable.onRenderUpdate(() => values[index]);
494
+ elements.set(index, node);
495
+ }
496
+ return node;
406
497
  };
498
+ return { array: values, element };
407
499
  },
408
- sync(extra?: { camera?: unknown; scene?: unknown; frameId?: number }) {
500
+ sync(extra?: ISyncFrame) {
409
501
  // `extra.frameId` is the renderer's frame: every render, target draw and compute of one frame
410
502
  // shares it. The callbacks see this module's own counter, as three's NodeFrame counts renders.
411
503
  const started = debug ? performance.now() : 0;
412
504
  if (debug) count("uniformSyncCalls");
505
+ const outer = !batching;
506
+ batching = setMany !== undefined;
413
507
  try {
414
508
  const rendererFrame = extra?.frameId;
415
- const frame: IUpdateFrame = { ...extra, frameId: ++frameId };
416
- for (const node of updating) {
417
- const state = states.get(node);
418
- if (state?.update === undefined) continue;
419
- if (state.updateType === "frame" && rendererFrame !== undefined) {
420
- if (state.ranFrame === rendererFrame) continue;
421
- state.ranFrame = rendererFrame;
422
- }
423
- let next: unknown;
424
- if (debug) {
425
- const callbackStart = performance.now();
426
- count(
427
- state.updateType === "frame" ? "uniformFrameCallbacks" : "uniformRenderCallbacks",
428
- );
429
- try {
430
- next = state.update(frame);
431
- } finally {
432
- const elapsed = performance.now() - callbackStart;
433
- count("uniformCallbackMs", elapsed);
434
- if (state.debugSource !== undefined)
435
- count(`uniformCallback:${state.debugSource}Ms`, elapsed, state.debugSource);
436
- }
437
- } else next = state.update(frame);
438
- if (next !== undefined) (node as { value: unknown }).value = next;
439
- }
509
+ frame.frameId = ++frameId;
510
+ frame.camera = extra?.camera;
511
+ frame.scene = extra?.scene;
512
+ frame.renderer = extra?.renderer;
513
+ // A nested render of a frame whose frame hooks already ran skips them without walking them.
514
+ const nested = rendererFrame !== undefined && rendererFrame === hookedFrame;
515
+ // A draw of one mesh or a dispatch runs only the hooks its graphs read (the engine answers which).
516
+ const picked = extra === undefined ? undefined : reads?.(extra, updating);
517
+ if (picked !== undefined)
518
+ for (let index = 0; index < picked.length; index += 1)
519
+ updateNode(updating[picked[index] as number] as TNode, rendererFrame);
520
+ else for (const node of nested ? renders : updating) updateNode(node, rendererFrame);
521
+ // Only once every hook returned: one that threw leaves later frame hooks to the next render. A picked
522
+ // sync ran some hooks only, so it does not stand for the frame's.
523
+ if (picked === undefined) hookedFrame = rendererFrame;
440
524
  // Deleted only once written: a sink that throws leaves the rest to retry at the next sync.
441
525
  for (const ref of dirty) {
442
526
  const node = ref.deref();
@@ -455,7 +539,12 @@ export function liveUniforms<TNode extends object>(
455
539
  const state = states.get(node);
456
540
  if (state !== undefined) write(node, state, uniformLanes(state.value, state.scratch));
457
541
  }
542
+ flush();
458
543
  } finally {
544
+ if (outer) {
545
+ batching = false;
546
+ requeue();
547
+ }
459
548
  if (debug) count("uniformSyncMs", performance.now() - started);
460
549
  }
461
550
  },
@@ -73,11 +73,14 @@ export function withUpdateRanges(prototype: object): void {
73
73
  if (cached !== undefined) return cached;
74
74
  const target: IRange[] = [];
75
75
  let snapshot: unknown;
76
+ // The records as the engine last had them: a record edited in place differs from it.
77
+ let mirror = "[]";
76
78
  const refresh = () => {
77
79
  const current = emptied.delete(this) ? "[]" : (read.call(this) as unknown);
78
80
  if (current === snapshot) return;
79
81
  target.splice(0, target.length, ...(JSON.parse(String(current)) as IRange[]));
80
82
  snapshot = current;
83
+ mirror = JSON.stringify(target);
81
84
  };
82
85
  const validate = (ranges: readonly IRange[]) => {
83
86
  for (const range of ranges)
@@ -97,6 +100,7 @@ export function withUpdateRanges(prototype: object): void {
97
100
  clear.call(this);
98
101
  for (const range of target) add.call(this, range.start, range.count);
99
102
  snapshot = undefined;
103
+ mirror = JSON.stringify(target);
100
104
  };
101
105
  const guarded = <T>(change: () => T): T => {
102
106
  refresh();
@@ -117,7 +121,9 @@ export function withUpdateRanges(prototype: object): void {
117
121
  refresh();
118
122
  for (const range of ranges) add.call(owner, range.start, range.count);
119
123
  snapshot = undefined;
120
- return target.push(...ranges);
124
+ const length = target.push(...ranges);
125
+ mirror = JSON.stringify(target);
126
+ return length;
121
127
  };
122
128
  if (typeof key === "string" && MUTATORS.has(key))
123
129
  return (...args: unknown[]) =>
@@ -149,6 +155,26 @@ export function withUpdateRanges(prototype: object): void {
149
155
  return Reflect.getOwnPropertyDescriptor(array, key);
150
156
  },
151
157
  });
158
+ // A record is an ordinary object, as three's is, so an edit in place (`last.count = n`, core's
159
+ // addRange) reaches the engine when needsUpdate publishes it, as the V8 adapter does (PRD-857).
160
+ let holder: object | null = Object.getPrototypeOf(this) as object | null;
161
+ let publish: PropertyDescriptor | undefined;
162
+ while (holder !== null && publish === undefined) {
163
+ publish = Object.getOwnPropertyDescriptor(holder, "needsUpdate");
164
+ holder = Object.getPrototypeOf(holder) as object | null;
165
+ }
166
+ if (publish?.set !== undefined) {
167
+ const set = publish.set;
168
+ const get = publish.get;
169
+ Object.defineProperty(this, "needsUpdate", {
170
+ configurable: true,
171
+ ...(get === undefined ? {} : { get: () => get.call(owner) }),
172
+ set(value: unknown) {
173
+ if (value && JSON.stringify(target) !== mirror) write();
174
+ set.call(owner, value);
175
+ },
176
+ });
177
+ }
152
178
  proxies.set(this, proxy);
153
179
  return proxy;
154
180
  },