@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.
@@ -42,6 +42,17 @@ export interface ITslRuntime {
42
42
  set(material: IEngineRef, path: string, node: number): void;
43
43
  /** three's `uniform.value = x`: the uniform's lanes, with no program change. */
44
44
  setUniform(node: number, lanes: readonly number[]): void;
45
+ /** Many `setUniform`s in one crossing: node i takes `counts[i]` of the packed `lanes` (PRD-828). */
46
+ setUniforms?(nodes: readonly number[], counts: readonly number[], lanes: readonly number[]): void;
47
+ /**
48
+ * PRD-878, `tn_tsl_reads`: which of `candidates` (uniform node ids) a draw of `root` (a mesh and what is under it)
49
+ * or a dispatch of `kernels` reads, as indices into `candidates`.
50
+ */
51
+ reads?(
52
+ root: IEngineRef | undefined,
53
+ kernels: readonly number[],
54
+ candidates: readonly number[],
55
+ ): number[];
45
56
  /** A live post effect's scalar uniform, written first when `value` is given; answers its value. */
46
57
  effectParameter(node: number, name: string, value?: number): number;
47
58
  /** three's RenderPipeline: the post graph the web host draws between scene and output, or none. */
@@ -70,6 +81,7 @@ const FUNCTIONS = [
70
81
  "uv",
71
82
  "texture",
72
83
  "texture3D",
84
+ "cubeTexture",
73
85
  "add",
74
86
  "sub",
75
87
  "mul",
@@ -121,6 +133,8 @@ const FUNCTIONS = [
121
133
  "ivec3",
122
134
  "ivec4",
123
135
  "uvec2",
136
+ "uvec3",
137
+ "uvec4",
124
138
  "bool",
125
139
  "storageTexture",
126
140
  "textureLoad",
@@ -250,6 +264,7 @@ const CONSTANTS = [
250
264
  "materialEmissive",
251
265
  "materialMetalness",
252
266
  "materialRoughness",
267
+ "diffuseColor",
253
268
  "time",
254
269
  "deltaTime",
255
270
  "normalView",
@@ -271,6 +286,10 @@ const CONSTANTS = [
271
286
  /** Node methods the shared table answers, with the receiver passed apart. */
272
287
  const METHODS = [
273
288
  "element",
289
+ "toReadOnly",
290
+ "toWriteOnly",
291
+ "toReadWrite",
292
+ "setSampler",
274
293
  "compute",
275
294
  "add",
276
295
  "sub",
@@ -410,6 +429,7 @@ function takesEngineObject(name: string, index: number): boolean {
410
429
  (index === 0 &&
411
430
  (name === "pmremTexture" ||
412
431
  name === "texture3D" ||
432
+ name === "cubeTexture" ||
413
433
  name === "storageTexture" ||
414
434
  name === "textureStore" ||
415
435
  name === "lightShadowMatrix")) ||
@@ -434,7 +454,8 @@ export function defineTsl(
434
454
  classes?: ConstClasses,
435
455
  ): {
436
456
  exports: Record<string, unknown>;
437
- sync(frame?: INodeFrame): void;
457
+ /** `kernels`: a dispatch's engine node ids, so its sync runs only the hooks they read (PRD-878). */
458
+ sync(frame?: INodeFrame & { kernels?: readonly number[] }): void;
438
459
  } {
439
460
  const released = new FinalizationRegistry<number>((node) => runtime.release(node));
440
461
  // three marks every node with `isNode`; framework code (Atmosphere.radiance) branches on it.
@@ -458,6 +479,9 @@ export function defineTsl(
458
479
  return { kind: "other" };
459
480
  if (typeof value === "number") return { kind: "number", number: value };
460
481
  if (typeof value === "string") return { kind: "string", text: value };
482
+ // setSampler(false) on a storage texture: its flag crosses as 0 or 1.
483
+ if (name === "setSampler" && typeof value === "boolean")
484
+ return { kind: "number", number: value ? 1 : 0 };
461
485
  // texture(engineTexture, uv) samples that texture itself; a plain object names a material map,
462
486
  // and textureLoad also takes a texture node.
463
487
  if (
@@ -599,20 +623,39 @@ export function defineTsl(
599
623
  exports[name] = (...args: unknown[]) => wrap(call(name, null, args));
600
624
  // three's lights([...]) takes one array; each light crosses as its own engine object.
601
625
  exports.lights = (list: readonly unknown[] = []) => wrap(call("lights", null, [...list]));
626
+ // three's transformNormal (accessors/Normal.js): the normal matrix of `matrix`, mat3(m)^-T, times the normal.
627
+ exports.transformNormal = (normal: unknown, matrix: unknown = exports.modelWorldMatrix) => {
628
+ type Chain = {
629
+ inverse(): Chain;
630
+ transpose(): Chain;
631
+ mul(value: unknown): Chain;
632
+ normalize(): Chain;
633
+ };
634
+ return (exports.mat3 as (value: unknown) => Chain)(matrix)
635
+ .inverse()
636
+ .transpose()
637
+ .mul(normal)
638
+ .normalize();
639
+ };
640
+ // three's element(node, index) (ArrayElementNode) is the node method in function form.
641
+ exports.element = (node: unknown, index: unknown) =>
642
+ wrap(call("element", isTslNode(node) ? node[TSL_NODE] : null, [index]));
602
643
  exports.nodeObject = (value: unknown) =>
603
644
  isTslNode(value) ? value : wrap(call("nodeObject", null, [value]));
604
- exports.texture = (initial: unknown, ...args: unknown[]) => {
605
- let value = initial;
606
- const node = wrap(call("texture", null, [value, ...args]));
607
- return Object.defineProperty(node, "value", {
608
- get: () => value,
609
- set: (next: unknown) => {
610
- if (next === value) return;
611
- runtime.release(call("textureValue", node[TSL_NODE], [next]));
612
- value = next;
613
- },
614
- });
615
- };
645
+ // three's TextureNode.value: assigning another texture swaps the one the node samples (ProbeVolume swaps its volume).
646
+ for (const name of ["texture", "texture3D", "cubeTexture"])
647
+ exports[name] = (initial: unknown, ...args: unknown[]) => {
648
+ let value = initial;
649
+ const node = wrap(call(name, null, [value, ...args]));
650
+ return Object.defineProperty(node, "value", {
651
+ get: () => value,
652
+ set: (next: unknown) => {
653
+ if (next === value) return;
654
+ runtime.release(call("textureValue", node[TSL_NODE], [next]));
655
+ value = next;
656
+ },
657
+ });
658
+ };
616
659
  exports.rtt = defineRtt(
617
660
  exports.rtt as Parameters<typeof defineRtt>[0],
618
661
  classes && "Mesh" in classes
@@ -656,7 +699,17 @@ export function defineTsl(
656
699
  return Object.assign(inline, { setLayout: () => inline });
657
700
  };
658
701
  exports.Fn = withFnBuilder(exports.Fn as Parameters<typeof withFnBuilder>[0]);
659
- for (const name of ["atomicAdd", "atomicStore", "textureStore"])
702
+ for (const name of [
703
+ "atomicAdd",
704
+ "atomicSub",
705
+ "atomicMax",
706
+ "atomicMin",
707
+ "atomicAnd",
708
+ "atomicOr",
709
+ "atomicXor",
710
+ "atomicStore",
711
+ "textureStore",
712
+ ])
660
713
  exports[name] = (...args: unknown[]) => {
661
714
  statement(name);
662
715
  return wrap(call(name, null, args));
@@ -828,8 +881,32 @@ export function defineTsl(
828
881
  );
829
882
  return valueUniform((exports[`mat${n}`] as (...columns: ITslNode[]) => ITslNode)(...columns));
830
883
  };
831
- const live = liveUniforms(matrixUniform, (node, lanes) =>
832
- runtime.setUniform(node[TSL_NODE], lanes),
884
+ const setUniforms = runtime.setUniforms?.bind(runtime);
885
+ const engineReads = runtime.reads?.bind(runtime);
886
+ const hookIds: number[] = [];
887
+ const live = liveUniforms(
888
+ matrixUniform,
889
+ (node, lanes) => runtime.setUniform(node[TSL_NODE], lanes),
890
+ setUniforms &&
891
+ ((nodes, counts, lanes) =>
892
+ setUniforms(
893
+ nodes.map((node) => node[TSL_NODE]),
894
+ counts,
895
+ lanes,
896
+ )),
897
+ // A scene's render runs every hook (its fog, background and lights read uniforms no mesh names); a draw of
898
+ // a mesh (a post quad) or a dispatch runs the hooks its graphs read, which the engine answers (PRD-878).
899
+ engineReads &&
900
+ ((frame, hooked) => {
901
+ const root = frame.scene as { isScene?: unknown } | null | undefined;
902
+ if (frame.kernels === undefined && (root == null || root.isScene === true))
903
+ return undefined;
904
+ for (let i = hookIds.length; i < hooked.length; i += 1)
905
+ hookIds.push((hooked[i] as ITslNode)[TSL_NODE]);
906
+ const ref = frame.kernels === undefined ? engineRef(root as object) : undefined;
907
+ if (frame.kernels === undefined && ref === undefined) return undefined;
908
+ return engineReads(ref, frame.kernels ?? [], hookIds);
909
+ }),
833
910
  );
834
911
  exports.uniform = booleanUniforms(live.uniform, (scalar) =>
835
912
  wrap(call("notEqual", scalar[TSL_NODE], [0])),
@@ -311,7 +311,7 @@ export function defineValueViews(host: IValueViewHost): IValueViews {
311
311
  if (read === undefined || write === undefined) return;
312
312
  const heap = runtime.heapF64;
313
313
  const lane = heap
314
- ? (address: number): number => heap()[address / 8] as number
314
+ ? (address: number): number => heap(address + 8)[address / 8] as number
315
315
  : (address: number): number => read(address, 1) as number;
316
316
  if (name === "Quaternion" && binding.fields !== undefined) {
317
317
  const offsets = ["x", "y", "z", "w"].map((key) => binding.fields?.[key]?.[0] ?? 0);
@@ -458,17 +458,33 @@ export function defineValueViews(host: IValueViewHost): IValueViews {
458
458
  // a frame, and a copy call allocates two arrays a read.
459
459
  const refresh = heap
460
460
  ? (address: number, values: number[]): void => {
461
- const memory = heap();
461
+ const memory = heap(address + count * 8);
462
462
  for (let i = 0, at = address / 8; i < count; i++) values[i] = memory[at + i] as number;
463
463
  }
464
464
  : (address: number, values: number[]): void => {
465
465
  const memory = read(address, count) as number[];
466
466
  for (let i = 0; i < count; i++) values[i] = memory[i] as number;
467
467
  };
468
+ // Shared memory (the threads build) never detaches when it grows, so a view onto it is the
469
+ // matrix itself: three's compose wrote 16 trapped elements a call, 49 ms of a laptop load (PRD-860).
470
+ const shared = new WeakMap<object, Float64Array>();
468
471
  Object.defineProperty(accessors, "elements", {
469
472
  configurable: true,
470
473
  get(this: object): number[] {
471
474
  const address = addressOf(this) + offset;
475
+ const memory = heap?.(address + count * 8);
476
+ if (
477
+ typeof SharedArrayBuffer !== "undefined" &&
478
+ memory?.buffer instanceof SharedArrayBuffer
479
+ ) {
480
+ let view = shared.get(this);
481
+ if (view === undefined) {
482
+ view = memory.subarray(address / 8, address / 8 + count);
483
+ shared.set(this, view);
484
+ }
485
+ // quality-allow: three's elements are an indexable number list; a Float64Array is one.
486
+ return view as unknown as number[];
487
+ }
472
488
  let mirror = mirrors.get(this);
473
489
  if (mirror === undefined) {
474
490
  const values = new Array<number>(count);
@@ -13,7 +13,9 @@ import {
13
13
  type TnAbiModule,
14
14
  VALUE,
15
15
  gltfOf,
16
+ heapFor,
16
17
  isRef,
18
+ packedRef,
17
19
  tslOf,
18
20
  } from "./browser-abi-types.js";
19
21
  import { SCALARS, TYPED, type TypedArray } from "./browser-marshal.js";
@@ -36,24 +38,30 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
36
38
  let encoding = "arguments";
37
39
  // The heap's views, made again only when the memory grows: Emscripten replaces HEAPU8 then, so one
38
40
  // identity test per use stands in for reading two `.buffer`s, which every crossing paid (PRD-748).
41
+ // Shared memory can grow from another thread with no replacement here, but it never detaches: an
42
+ // access past `heapBytes` (an engine pointer's `end`) refreshes through `heapFor`.
39
43
  let heap = abi.HEAPU8;
40
44
  let heapBytes = heap.byteLength;
41
45
  let dataView = new DataView(heap.buffer);
42
46
  let words = new Uint32Array(heap.buffer);
43
- const grown = () => {
44
- debug?.add("wasmGrowthEvents", 1, "bridge");
45
- debug?.add("wasmGrowthBytes", Math.max(0, abi.HEAPU8.byteLength - heapBytes), "memory");
46
- heap = abi.HEAPU8;
47
+ const grown = (end: number) => {
48
+ const before = heapBytes;
49
+ heap = heapFor(abi, end);
47
50
  heapBytes = heap.byteLength;
48
51
  dataView = new DataView(heap.buffer);
49
52
  words = new Uint32Array(heap.buffer);
53
+ debug?.add("wasmGrowthEvents", 1, "bridge");
54
+ debug?.add("wasmGrowthBytes", Math.max(0, heapBytes - before), "memory");
50
55
  };
51
- const view = () => {
52
- if (abi.HEAPU8 !== heap) grown();
56
+ const reach = (end: number) => {
57
+ if (end > heapBytes) grown(end);
58
+ };
59
+ const view = (end = 0) => {
60
+ if (end > heapBytes || abi.HEAPU8 !== heap) grown(end);
53
61
  return dataView;
54
62
  };
55
- const wordView = () => {
56
- if (abi.HEAPU8 !== heap) grown();
63
+ const wordView = (end = 0) => {
64
+ if (end > heapBytes || abi.HEAPU8 !== heap) grown(end);
57
65
  return words;
58
66
  };
59
67
  // Each call frees what it allocated, and only that: a callback can run a nested call.
@@ -79,8 +87,8 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
79
87
  debug?.add("bridgeOverflowBytes", aligned, "bridge");
80
88
  }
81
89
  // A call's scratch is a few words (a handle, a value, a diagnostic): word stores beat a fill call.
82
- // `wordView` first: a `_malloc` above may have grown the memory.
83
- const w = wordView();
90
+ // `wordView` first: a `_malloc` above may have grown the memory, on this thread or another.
91
+ const w = wordView(pointer + aligned);
84
92
  if (aligned > 64) heap.fill(0, pointer, pointer + aligned);
85
93
  else for (let at = pointer >>> 2, end = (pointer + aligned) >>> 2; at < end; at++) w[at] = 0;
86
94
  return pointer;
@@ -139,25 +147,19 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
139
147
  return ref;
140
148
  };
141
149
  const writeHandle = (pointer: number, ref: IEngineRef) => {
142
- let packed = ref as Partial<IPackedRef>;
143
- if (packed.w0 === undefined) {
144
- // A ref some other source made: parse its key once and keep the words on it.
145
- const [type = 0, context = 0, index = 0, generation = 0] = ref.key.split(":").map(Number);
146
- packed = Object.isExtensible(ref) ? (ref as IPackedRef) : { ...ref };
147
- Object.assign(packed, { w0: (type | (context << 16)) >>> 0, w1: index, w2: generation });
148
- }
150
+ const packed = packedRef(ref);
149
151
  if ((pointer & 3) === 0) {
150
152
  const at = pointer >>> 2;
151
153
  const w = wordView();
152
- w[at] = packed.w0 as number;
153
- w[at + 1] = packed.w1 as number;
154
- w[at + 2] = packed.w2 as number;
154
+ w[at] = packed.w0;
155
+ w[at + 1] = packed.w1;
156
+ w[at + 2] = packed.w2;
155
157
  return;
156
158
  }
157
159
  const v = view();
158
- v.setUint32(pointer, packed.w0 as number, true);
159
- v.setUint32(pointer + 4, packed.w1 as number, true);
160
- v.setUint32(pointer + 8, packed.w2 as number, true);
160
+ v.setUint32(pointer, packed.w0, true);
161
+ v.setUint32(pointer + 4, packed.w1, true);
162
+ v.setUint32(pointer + 8, packed.w2, true);
161
163
  };
162
164
  const handleOf = (ref: IEngineRef): number => {
163
165
  const pointer = alloc(HANDLE);
@@ -233,7 +235,7 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
233
235
  return pointer;
234
236
  };
235
237
  const readValue = (pointer: number): EngineValue => {
236
- const v = view();
238
+ const v = view(pointer + VALUE);
237
239
  switch (v.getUint32(pointer, true)) {
238
240
  case KIND.undefined:
239
241
  return undefined;
@@ -266,9 +268,9 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
266
268
  }
267
269
  case KIND.numbers: {
268
270
  const at = v.getUint32(pointer + 48, true) / 8;
269
- return Array.from(
270
- abi.HEAPF64.subarray(at, at + Number(v.getBigUint64(pointer + 40, true))),
271
- );
271
+ const count = Number(v.getBigUint64(pointer + 40, true));
272
+ reach((at + count) * 8);
273
+ return Array.from(abi.HEAPF64.subarray(at, at + count));
272
274
  }
273
275
  default:
274
276
  return null;
@@ -328,6 +330,7 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
328
330
  const Typed = SCALARS[scalar ?? -1];
329
331
  if (Typed === undefined)
330
332
  throw new TypeError(`TN_NATIVE_UNSUPPORTED array: scalar ${String(scalar)}`);
333
+ reach((address ?? 0) + (count ?? 0) * Typed.BYTES_PER_ELEMENT);
331
334
  return use(new Typed(abi.HEAPU8.buffer as ArrayBuffer, address ?? 0, count ?? 0));
332
335
  } finally {
333
336
  abi._tnw_attribute_view_release?.(lease);
@@ -398,16 +401,55 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
398
401
  const v = view();
399
402
  return refs.map((_, i) => v.getUint32(out + i * 4, true));
400
403
  }),
401
- readByte: (address) => abi.HEAPU8[address] as number,
402
- readWord: (address) => view().getUint32(address, true),
404
+ // PRD-828: the rig batch, one crossing. Handles are three words each; a rig without an action or
405
+ // a stride body repeats its mixer's handle there, and the flags word says which of the two exist.
406
+ animTick: (batch) => {
407
+ const count = batch.mixers.length;
408
+ if (count === 0) return;
409
+ scoped(() => {
410
+ const triples = alloc(count * 3 * HANDLE);
411
+ for (let i = 0; i < count; i += 1) {
412
+ const at = triples + i * 3 * HANDLE;
413
+ const mixer = batch.mixers[i] as IEngineRef;
414
+ writeHandle(at, mixer);
415
+ writeHandle(at + HANDLE, batch.actions[i] ?? mixer);
416
+ writeHandle(at + 2 * HANDLE, batch.roots[i] ?? mixer);
417
+ }
418
+ const values = alloc(count * 5 * 8);
419
+ const status = alloc(count * 3 * 8);
420
+ const v = view();
421
+ for (let i = 0; i < count * 5; i += 1)
422
+ v.setFloat64(values + i * 8, batch.values[i] as number, true);
423
+ const diag = diagnostic();
424
+ check(
425
+ abi._tn_anim_tick(context, triples, values, count, status, diag),
426
+ diag,
427
+ "tn_anim_tick",
428
+ );
429
+ const after = view();
430
+ for (let i = 0; i < count * 3; i += 1)
431
+ batch.status[i] = after.getFloat64(status + i * 8, true);
432
+ });
433
+ },
434
+ readByte: (address) => {
435
+ reach(address + 1);
436
+ return abi.HEAPU8[address] as number;
437
+ },
438
+ readWord: (address) => view(address + 4).getUint32(address, true),
403
439
  writeDouble: (address, value) => {
440
+ reach(address + 8);
404
441
  abi.HEAPF64[address / 8] = value;
405
442
  },
406
443
  writeByte: (address, value) => {
444
+ reach(address + 1);
407
445
  abi.HEAPU8[address] = value;
408
446
  },
409
- heapF64: () => abi.HEAPF64,
447
+ heapF64: (end) => {
448
+ reach(end);
449
+ return abi.HEAPF64;
450
+ },
410
451
  readDoubles: (address, count) => {
452
+ reach(address + count * 8);
411
453
  const at = address / 8;
412
454
  return count === 1
413
455
  ? (abi.HEAPF64[at] as number)
@@ -0,0 +1,19 @@
1
+ // three's typed BufferAttribute subclasses, ported from three r187 src/core/BufferAttribute.js (MIT).
2
+ // Each one only converts its array: the engine BufferAttribute keeps a Uint8Array, Uint16Array or
3
+ // Uint32Array in its own storage type. Int16BufferAttribute stays unbound: the engine stores an
4
+ // Int16Array as float32, so a normalized Int16 attribute would read wrong on the GPU.
5
+
6
+ type Attribute = new (array: ArrayLike<number>, itemSize: number, normalized?: boolean) => object;
7
+
8
+ /** `Uint16BufferAttribute` is `defineTypedBufferAttribute(BufferAttribute, Uint16Array)`. */
9
+ export function defineTypedBufferAttribute(
10
+ base: Attribute,
11
+ storage: new (array: ArrayLike<number>) => ArrayLike<number>,
12
+ ) {
13
+ return class extends base {
14
+ constructor(array: ArrayLike<number>, itemSize: number, normalized = false) {
15
+ // three's default, explicit: the engine constructor refuses an undefined `normalized`.
16
+ super(new storage(array), itemSize, normalized);
17
+ }
18
+ };
19
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * three's CompressedTexture on the browser back end (PRD-867): BC7 or ETC2 RGBA levels built from
3
+ * three's `mipmaps`, each crossing to the engine once, coarse first, so a streamed finer level goes
4
+ * up alone.
5
+ */
6
+ import {
7
+ type EngineValue,
8
+ type IBrowserRuntime,
9
+ type IEngineRef,
10
+ engineRef,
11
+ } from "./browser-backend.js";
12
+
13
+ type EngineClass = new (...args: unknown[]) => object;
14
+
15
+ /** One of three's `CompressedTexture.mipmaps`: a level's blocks, or null while it is not resident. */
16
+ interface ICompressedLevel {
17
+ data: ArrayLike<number> | null;
18
+ readonly width: number;
19
+ readonly height: number;
20
+ }
21
+
22
+ /**
23
+ * three's CompressedTexture(mipmaps, width, height, format) over the engine's (PRD-867), or undefined
24
+ * when the engine binds none. The engine takes the level count; each level then crosses as one
25
+ * `mipmaps.N.data`, coarse first.
26
+ */
27
+ export function defineCompressedTexture(
28
+ BaseCompressed: EngineClass | undefined,
29
+ runtime: IBrowserRuntime,
30
+ ): unknown {
31
+ if (BaseCompressed === undefined) return undefined;
32
+ const Base: EngineClass = BaseCompressed;
33
+ /** A typed array as the runtime takes it: itself when typed arrays cross, else its numbers. */
34
+ const crossing = (data: ArrayLike<number>): EngineValue =>
35
+ runtime.typedArrays === true && ArrayBuffer.isView(data) && !(data instanceof DataView)
36
+ ? (data as EngineValue)
37
+ : Array.from(data);
38
+ // Each CompressedTexture's `mipmaps`, and the `data` of each level the engine already holds.
39
+ const levels = new WeakMap<object, ICompressedLevel[]>();
40
+ const sent = new WeakMap<object, unknown[]>();
41
+ /** Sends the levels whose `data` changed, coarse first: the engine keeps the finest resident level as the base. */
42
+ const sendLevels = (texture: object): void => {
43
+ const mipmaps = levels.get(texture) ?? [];
44
+ const held = sent.get(texture) ?? [];
45
+ for (let level = mipmaps.length - 1; level >= 0; level -= 1) {
46
+ const data = mipmaps[level]?.data;
47
+ if (data == null || held[level] === data) continue;
48
+ runtime.set(
49
+ engineRef(texture) as IEngineRef,
50
+ `mipmaps.${String(level)}.data`,
51
+ crossing(data),
52
+ );
53
+ held[level] = data;
54
+ }
55
+ sent.set(texture, held);
56
+ };
57
+
58
+ /**
59
+ * three's CompressedTexture(mipmaps, width, height, format) over the engine's (PRD-867): BC7
60
+ * (`RGBA_BPTC_Format`) or ETC2 RGBA (`RGBA_ETC2_EAC_Format`) levels, finest first. A level whose `data`
61
+ * is null is not resident yet: set it and `needsUpdate`, and that level alone goes up, as a stream does.
62
+ */
63
+ function CompressedTexture(
64
+ this: unknown,
65
+ mipmaps: ICompressedLevel[] = [],
66
+ width = 1,
67
+ height = 1,
68
+ format = 1023,
69
+ ) {
70
+ const texture = Reflect.construct(
71
+ Base,
72
+ [mipmaps.length, width, height, format],
73
+ new.target ?? CompressedTexture,
74
+ ) as object;
75
+ levels.set(texture, mipmaps);
76
+ sendLevels(texture);
77
+ return texture;
78
+ }
79
+ {
80
+ CompressedTexture.prototype = BaseCompressed.prototype;
81
+ const needsUpdate = Object.getOwnPropertyDescriptor(
82
+ BaseCompressed.prototype,
83
+ "needsUpdate",
84
+ )?.set;
85
+ if (needsUpdate === undefined)
86
+ throw new TypeError("TN_BROWSER_UNBOUND: CompressedTexture.needsUpdate");
87
+ Object.defineProperties(BaseCompressed.prototype, {
88
+ mipmaps: {
89
+ configurable: true,
90
+ get(this: object) {
91
+ return levels.get(this) ?? [];
92
+ },
93
+ set(this: object, mipmaps: ICompressedLevel[]) {
94
+ levels.set(this, mipmaps);
95
+ },
96
+ },
97
+ image: {
98
+ configurable: true,
99
+ get(this: object) {
100
+ const base = levels.get(this)?.[0];
101
+ return { width: base?.width ?? 0, height: base?.height ?? 0 };
102
+ },
103
+ },
104
+ needsUpdate: {
105
+ configurable: true,
106
+ set(this: object, value: unknown) {
107
+ // A level the engine holds already is not re-sent: after one new level, the engine writes that one.
108
+ if (value) sendLevels(this);
109
+ needsUpdate.call(this, value);
110
+ },
111
+ },
112
+ });
113
+ }
114
+
115
+ return CompressedTexture;
116
+ }
@@ -1,16 +1,30 @@
1
1
  import { PLAYTEST_OBSERVING_GLOBAL, callerOf } from "./bridge-meter.js";
2
2
 
3
- /** Kept local to the bridge so three-native does not depend on core. */
3
+ /**
4
+ * Kept local to the bridge so three-native does not depend on core, and held to core's rule by
5
+ * `scripts/__tests__/launch-flag-parity.spec.ts`: `0` and `false` are off, a named-but-empty value
6
+ * is on, an empty variable is unset, and every seam that names the flag is heard. The two copies
7
+ * disagreed before — core accepted `?tnDebug=true` and this did not — which is drift nobody sees
8
+ * until one layer's telemetry is off while the other's is on.
9
+ */
4
10
  export function debugRequested(): boolean {
5
11
  const host = globalThis as {
6
12
  process?: { env?: Record<string, unknown> };
7
13
  [name: string]: unknown;
8
14
  };
9
- return (
10
- host.process?.env?.TN_DEBUG === "1" ||
11
- /[?&]tnDebug=1(?:&|$)/u.test(globalThis.location?.search ?? "") ||
12
- host.__THREENATIVE_DEBUG__ === true
13
- );
15
+ const values: string[] = [];
16
+ const env = host.process?.env?.TN_DEBUG;
17
+ if (typeof env === "string" && env !== "") values.push(env);
18
+ const search = globalThis.location?.search;
19
+ if (typeof search === "string") {
20
+ const fromQuery = new URLSearchParams(search).get("tnDebug");
21
+ if (fromQuery !== null) values.push(fromQuery);
22
+ }
23
+ const set = host.__THREENATIVE_DEBUG__;
24
+ if (typeof set === "string") values.push(set);
25
+ else if (typeof set === "number") values.push(String(set));
26
+ else if (typeof set === "boolean") values.push(set ? "true" : "false");
27
+ return values.some((value) => value !== "0" && value !== "false");
14
28
  }
15
29
 
16
30
  type DebugSource = { area: string; caller: string; lever?: string; unit?: string };