@threenative/three-native 0.3.11 → 0.3.13

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.
@@ -11,6 +11,7 @@ import {
11
11
  type ConstClasses,
12
12
  booleanUniforms,
13
13
  liveUniforms,
14
+ matrixElements,
14
15
  uniformLanes,
15
16
  withConstValues,
16
17
  } from "./tsl-uniforms.js";
@@ -41,6 +42,17 @@ export interface ITslRuntime {
41
42
  set(material: IEngineRef, path: string, node: number): void;
42
43
  /** three's `uniform.value = x`: the uniform's lanes, with no program change. */
43
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[];
44
56
  /** A live post effect's scalar uniform, written first when `value` is given; answers its value. */
45
57
  effectParameter(node: number, name: string, value?: number): number;
46
58
  /** three's RenderPipeline: the post graph the web host draws between scene and output, or none. */
@@ -69,6 +81,7 @@ const FUNCTIONS = [
69
81
  "uv",
70
82
  "texture",
71
83
  "texture3D",
84
+ "cubeTexture",
72
85
  "add",
73
86
  "sub",
74
87
  "mul",
@@ -117,10 +130,16 @@ const FUNCTIONS = [
117
130
  "nodeObject",
118
131
  "color",
119
132
  "ivec2",
133
+ "ivec3",
134
+ "ivec4",
120
135
  "uvec2",
136
+ "uvec3",
137
+ "uvec4",
138
+ "bool",
121
139
  "storageTexture",
122
140
  "textureLoad",
123
141
  "textureSize",
142
+ "mrt",
124
143
  "reflect",
125
144
  "dFdx",
126
145
  "dFdy",
@@ -144,6 +163,7 @@ const FUNCTIONS = [
144
163
  "struct",
145
164
  "wgslFunction",
146
165
  "lightShadowMatrix",
166
+ "lights",
147
167
  "luminance",
148
168
  "viewZToOrthographicDepth",
149
169
  "viewZToPerspectiveDepth",
@@ -156,7 +176,12 @@ const FUNCTIONS = [
156
176
  "reflector",
157
177
  "transformDirection",
158
178
  "transformNormalToView",
179
+ "getViewPosition",
180
+ "bumpMap",
181
+ "normalMap",
159
182
  "property",
183
+ "varyingProperty",
184
+ "instanceMatrix",
160
185
  "radians",
161
186
  "degrees",
162
187
  "inverseSqrt",
@@ -209,6 +234,7 @@ const FUNCTIONS = [
209
234
  ] as const;
210
235
  /** The inputs TSL exports as values (tn::abi::tslConstants), each built once, when first read. */
211
236
  const CONSTANTS = [
237
+ "modelViewProjection",
212
238
  "viewportLinearDepth",
213
239
  "frameGroup",
214
240
  "renderGroup",
@@ -224,6 +250,9 @@ const CONSTANTS = [
224
250
  "normalWorld",
225
251
  "positionLocal",
226
252
  "positionWorld",
253
+ "positionView",
254
+ "frontFacing",
255
+ "faceDirection",
227
256
  "positionWorldDirection",
228
257
  "normalViewGeometry",
229
258
  "cameraViewMatrix",
@@ -235,6 +264,7 @@ const CONSTANTS = [
235
264
  "materialEmissive",
236
265
  "materialMetalness",
237
266
  "materialRoughness",
267
+ "diffuseColor",
238
268
  "time",
239
269
  "deltaTime",
240
270
  "normalView",
@@ -242,6 +272,9 @@ const CONSTANTS = [
242
272
  "screenCoordinate",
243
273
  "normalGeometry",
244
274
  "tangentGeometry",
275
+ "normalLocal",
276
+ "tangentLocal",
277
+ "positionPrevious",
245
278
  "normalWorldGeometry",
246
279
  "EPSILON",
247
280
  "INFINITY",
@@ -253,6 +286,10 @@ const CONSTANTS = [
253
286
  /** Node methods the shared table answers, with the receiver passed apart. */
254
287
  const METHODS = [
255
288
  "element",
289
+ "toReadOnly",
290
+ "toWriteOnly",
291
+ "toReadWrite",
292
+ "setSampler",
256
293
  "compute",
257
294
  "add",
258
295
  "sub",
@@ -306,6 +343,7 @@ const METHODS = [
306
343
  "smoothstep",
307
344
  "select",
308
345
  "sample",
346
+ "setInterpolation",
309
347
  "__rtt",
310
348
  "oneMinus",
311
349
  "dispose",
@@ -319,6 +357,7 @@ const METHODS = [
319
357
  "flipW",
320
358
  "level",
321
359
  "bias",
360
+ "depth",
322
361
  "transformDirection",
323
362
  "radians",
324
363
  "degrees",
@@ -390,9 +429,11 @@ function takesEngineObject(name: string, index: number): boolean {
390
429
  (index === 0 &&
391
430
  (name === "pmremTexture" ||
392
431
  name === "texture3D" ||
432
+ name === "cubeTexture" ||
393
433
  name === "storageTexture" ||
394
434
  name === "textureStore" ||
395
435
  name === "lightShadowMatrix")) ||
436
+ name === "lights" ||
396
437
  (index < 2 && (name === "reflector" || name === "__rtt"))
397
438
  );
398
439
  }
@@ -413,7 +454,8 @@ export function defineTsl(
413
454
  classes?: ConstClasses,
414
455
  ): {
415
456
  exports: Record<string, unknown>;
416
- 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;
417
459
  } {
418
460
  const released = new FinalizationRegistry<number>((node) => runtime.release(node));
419
461
  // three marks every node with `isNode`; framework code (Atmosphere.radiance) branches on it.
@@ -437,11 +479,17 @@ export function defineTsl(
437
479
  return { kind: "other" };
438
480
  if (typeof value === "number") return { kind: "number", number: value };
439
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 };
440
485
  // texture(engineTexture, uv) samples that texture itself; a plain object names a material map,
441
486
  // and textureLoad also takes a texture node.
442
487
  if (
443
488
  index === 0 &&
444
- (name === "texture" || name === "textureValue") &&
489
+ (name === "texture" ||
490
+ name === "textureValue" ||
491
+ name === "textureLoad" ||
492
+ name === "textureSize") &&
445
493
  typeof value === "object" &&
446
494
  engineRef(value) !== undefined
447
495
  )
@@ -495,7 +543,9 @@ export function defineTsl(
495
543
  const node = (id: number): TslArgValue => ({ kind: "node", node: id });
496
544
  const capture = (form: string, callback: unknown, input?: unknown): number => {
497
545
  if (typeof callback !== "function") throw new TypeError(`TN_TSL ${form}: expected a callback`);
498
- runtime.release(runtime.call("scope:open", null, []));
546
+ runtime.release(
547
+ runtime.call("scope:open", null, form === "Fn" ? [{ kind: "string", text: "Fn" }] : []),
548
+ );
499
549
  depth++;
500
550
  let returned: TslArgValue[] = [];
501
551
  try {
@@ -518,9 +568,8 @@ export function defineTsl(
518
568
  if (depth === 0) throw new TypeError(`TN_TSL ${form}: statement outside Fn`);
519
569
  };
520
570
  prototype.toVar = function (this: ITslNode) {
521
- // Outside a function body there is no stack to declare a variable in (rain's fragment node names its
522
- // terms this way); the expression itself is the value, read where it is used.
523
- if (depth === 0) return this;
571
+ // Outside a function body the engine declares the variable at the top of the program (rain's fragment node
572
+ // names its terms this way; a Fn assigns one handed to it as an `out` argument).
524
573
  return wrap(runtime.call("toVar", this[TSL_NODE], []));
525
574
  };
526
575
  prototype.assign = function (this: ITslNode, value: unknown) {
@@ -572,20 +621,41 @@ export function defineTsl(
572
621
  exports.NodeUpdateType = NodeUpdateType;
573
622
  for (const name of FUNCTIONS)
574
623
  exports[name] = (...args: unknown[]) => wrap(call(name, null, args));
624
+ // three's lights([...]) takes one array; each light crosses as its own engine object.
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]));
575
643
  exports.nodeObject = (value: unknown) =>
576
644
  isTslNode(value) ? value : wrap(call("nodeObject", null, [value]));
577
- exports.texture = (initial: unknown, ...args: unknown[]) => {
578
- let value = initial;
579
- const node = wrap(call("texture", null, [value, ...args]));
580
- return Object.defineProperty(node, "value", {
581
- get: () => value,
582
- set: (next: unknown) => {
583
- if (next === value) return;
584
- runtime.release(call("textureValue", node[TSL_NODE], [next]));
585
- value = next;
586
- },
587
- });
588
- };
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
+ };
589
659
  exports.rtt = defineRtt(
590
660
  exports.rtt as Parameters<typeof defineRtt>[0],
591
661
  classes && "Mesh" in classes
@@ -614,8 +684,13 @@ export function defineTsl(
614
684
  (Array.isArray(first) || first.constructor === Object)
615
685
  ? first
616
686
  : args;
687
+ // As three's nodeObject: a plain object or array (a struct of nodes, a list) passes through unchanged.
617
688
  const asNode = (value: unknown) =>
618
- isTslNode(value) ? value : wrap(call("nodeObject", null, [value]));
689
+ isTslNode(value) ||
690
+ Array.isArray(value) ||
691
+ (typeof value === "object" && value !== null && value.constructor === Object)
692
+ ? value
693
+ : wrap(call("nodeObject", null, [value]));
619
694
  const parameters = Array.isArray(inputs)
620
695
  ? inputs.map(asNode)
621
696
  : Object.fromEntries(Object.entries(inputs).map(([key, value]) => [key, asNode(value)]));
@@ -624,7 +699,17 @@ export function defineTsl(
624
699
  return Object.assign(inline, { setLayout: () => inline });
625
700
  };
626
701
  exports.Fn = withFnBuilder(exports.Fn as Parameters<typeof withFnBuilder>[0]);
627
- 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
+ ])
628
713
  exports[name] = (...args: unknown[]) => {
629
714
  statement(name);
630
715
  return wrap(call(name, null, args));
@@ -634,8 +719,9 @@ export function defineTsl(
634
719
  // quality-allow: the export table is untyped; defineStorageTextures narrows it to the builders it reads.
635
720
  defineStorageTextures(exports as unknown as Parameters<typeof defineStorageTextures>[0]),
636
721
  );
637
- // r185's Break(), Continue() and Return(): a loop or kernel ends early (statements, like atomicAdd).
638
- for (const name of ["Break", "Continue", "Return"])
722
+ // r185's Break(), Continue() and Return(): a loop or kernel ends early (statements, like atomicAdd);
723
+ // Discard(conditional) ends the fragment, under If(conditional) when one is given.
724
+ for (const name of ["Break", "Continue", "Return", "Discard"])
639
725
  exports[name] = (...args: unknown[]) => {
640
726
  statement(name);
641
727
  return wrap(call(name, null, args));
@@ -781,9 +867,46 @@ export function defineTsl(
781
867
  },
782
868
  });
783
869
  }
870
+ // uniform(matrix): the engine takes a matN uniform's first value as a constant matN, built here
871
+ // from the matrix's columns; later edits sync through uniformLanes (the 9 or 16 elements).
872
+ const valueUniform = exports.uniform as (value: unknown, type?: unknown) => ITslNode;
873
+ const vec = (n: number) => exports[`vec${n}`] as (...lanes: number[]) => ITslNode;
874
+ const matrixUniform = (value: unknown, type?: unknown): ITslNode => {
875
+ const elements = matrixElements(value);
876
+ if (elements === undefined)
877
+ return type === undefined ? valueUniform(value) : valueUniform(value, type);
878
+ const n = elements.length === 16 ? 4 : 3;
879
+ const columns = Array.from({ length: n }, (_, c) =>
880
+ vec(n)(...Array.from({ length: n }, (_, r) => elements[c * n + r] as number)),
881
+ );
882
+ return valueUniform((exports[`mat${n}`] as (...columns: ITslNode[]) => ITslNode)(...columns));
883
+ };
884
+ const setUniforms = runtime.setUniforms?.bind(runtime);
885
+ const engineReads = runtime.reads?.bind(runtime);
886
+ const hookIds: number[] = [];
784
887
  const live = liveUniforms(
785
- exports.uniform as (value: unknown, type?: unknown) => ITslNode,
888
+ matrixUniform,
786
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
+ }),
787
910
  );
788
911
  exports.uniform = booleanUniforms(live.uniform, (scalar) =>
789
912
  wrap(call("notEqual", scalar[TSL_NODE], [0])),