typegpu 0.12.9 → 0.12.10

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 (98) hide show
  1. package/common/attachAutoResizer.d.ts +33 -0
  2. package/common/attachAutoResizer.js +83 -0
  3. package/common/index.d.ts +1 -0
  4. package/common/index.js +1 -0
  5. package/common/writeSoA.js +4 -3
  6. package/core/commandEncoder/commandEncoder.d.ts +1 -1
  7. package/core/declare/tgpuDeclare.d.ts +10 -7
  8. package/core/declare/tgpuDeclare.js +25 -10
  9. package/core/function/comptime.d.ts +2 -0
  10. package/core/function/comptime.js +29 -24
  11. package/core/function/createCallableSchema.js +32 -37
  12. package/core/function/dualImpl.js +44 -44
  13. package/core/function/tgpuComputeFn.d.ts +0 -3
  14. package/core/function/tgpuFn.js +4 -4
  15. package/core/function/tgpuFragmentFn.d.ts +1 -1
  16. package/core/function/tgpuVertexFn.d.ts +1 -1
  17. package/core/pipeline/drawState.js +1 -1
  18. package/core/pipeline/webgpuLimitations.js +2 -1
  19. package/core/resolve/externals.js +4 -0
  20. package/core/resolve/namespace.d.ts +4 -0
  21. package/core/resolve/namespace.js +1 -2
  22. package/core/resolve/stitch.js +13 -8
  23. package/core/root/rootTypes.d.ts +40 -36
  24. package/core/slot/accessor.js +1 -1
  25. package/core/texture/texture.d.ts +1 -2
  26. package/core/texture/texture.js +37 -20
  27. package/core/texture/textureFormats.d.ts +4 -3
  28. package/core/texture/textureFormats.js +17 -6
  29. package/core/texture/textureWrite.d.ts +9 -0
  30. package/core/texture/textureWrite.js +21 -0
  31. package/core/unroll/tgpuUnroll.js +2 -4
  32. package/core/vertexLayout/vertexAttribute.d.ts +1 -4
  33. package/core/vertexLayout/vertexLayout.js +11 -30
  34. package/data/alignmentOf.d.ts +1 -1
  35. package/data/alignmentOf.js +5 -12
  36. package/data/array.js +34 -2
  37. package/data/attributes.d.ts +16 -3
  38. package/data/attributes.js +11 -2
  39. package/data/compiledIO.js +2 -2
  40. package/data/dataIO.js +61 -95
  41. package/data/dataTypes.d.ts +0 -2
  42. package/data/dataTypes.js +3 -3
  43. package/data/disarray.js +2 -0
  44. package/data/offsetUtils.js +23 -13
  45. package/data/offsets.js +1 -2
  46. package/data/partialIO.js +2 -3
  47. package/data/ref.js +35 -37
  48. package/data/schemaCallWrapper.js +2 -2
  49. package/data/schemaMemoryLayout.d.ts +6 -1
  50. package/data/schemaMemoryLayout.js +23 -14
  51. package/data/schemasEqual.js +6 -15
  52. package/data/sizeOf.d.ts +1 -1
  53. package/data/sizeOf.js +2 -3
  54. package/data/snippet.d.ts +1 -1
  55. package/data/struct.js +25 -1
  56. package/data/unstruct.js +2 -0
  57. package/data/vectorImpl.js +45 -21
  58. package/data/vertexFormatData.js +7 -9
  59. package/data/wgslTypes.d.ts +27 -12
  60. package/data/wgslTypes.js +33 -39
  61. package/extension.d.ts +0 -4
  62. package/package.json +1 -1
  63. package/resolutionCtx.d.ts +1 -1
  64. package/resolutionCtx.js +26 -7
  65. package/serial/restore.d.ts +1 -1
  66. package/shared/meta.js +1 -1
  67. package/shared/symbols.d.ts +5 -0
  68. package/shared/symbols.js +6 -1
  69. package/shared/utilityTypes.d.ts +0 -6
  70. package/std/bitcast.d.ts +1 -1
  71. package/std/comptime.js +10 -12
  72. package/std/environment.js +2 -4
  73. package/std/matrix.js +5 -5
  74. package/std/numeric.d.ts +1 -0
  75. package/std/numeric.js +35 -1
  76. package/std/typeOf.js +12 -14
  77. package/tgpu.d.ts +1 -1
  78. package/tgpu.js +1 -1
  79. package/tgpuBindGroupLayout.d.ts +6 -3
  80. package/tgpuBindGroupLayout.js +15 -2
  81. package/tgpuUnstableNamespace.d.ts +1 -0
  82. package/tgpuUnstableNamespace.js +5 -0
  83. package/tgsl/accessIndex.js +10 -7
  84. package/tgsl/accessProp.js +5 -57
  85. package/tgsl/consoleLog/types.d.ts +1 -1
  86. package/tgsl/conversion.js +21 -0
  87. package/tgsl/forOfUtils.js +1 -1
  88. package/tgsl/generationHelpers.d.ts +0 -1
  89. package/tgsl/generationHelpers.js +1 -4
  90. package/tgsl/shaderGenerator.d.ts +5 -0
  91. package/tgsl/swizzle.d.ts +24 -0
  92. package/tgsl/swizzle.js +112 -0
  93. package/tgsl/wgslGenerator.d.ts +13 -3
  94. package/tgsl/wgslGenerator.js +149 -151
  95. package/types.d.ts +10 -10
  96. package/types.js +1 -1
  97. package/taskQueue.d.ts +0 -6
  98. package/taskQueue.js +0 -30
package/resolutionCtx.js CHANGED
@@ -24,7 +24,7 @@ import { isShelllessImpl } from "./core/function/shelllessImpl.js";
24
24
  import { isTgpuFn } from "./core/function/tgpuFn.js";
25
25
  import { AutoStruct } from "./data/autoStruct.js";
26
26
  import { EntryInputRouter } from "./core/function/entryInputRouter.js";
27
- import { validateIdentifier, sanitizePrimer, bannedTokens } from "./nameUtils.js";
27
+ import { validateIdentifier, sanitizePrimer, bannedTokens, builtins, templateEnumerants, } from "./nameUtils.js";
28
28
  import { minify } from "./minify.js";
29
29
  /**
30
30
  * Inserted into bind group entry definitions that belong
@@ -88,6 +88,7 @@ class ItemStateStackImpl {
88
88
  argAccess,
89
89
  returnType,
90
90
  externalMap,
91
+ externalSnippets: new Map(),
91
92
  reportedReturnTypes: new Set(),
92
93
  placeholderForVariable: new Map(),
93
94
  modifiedVariables: new Set(),
@@ -144,12 +145,18 @@ class ItemStateStackImpl {
144
145
  if (access) {
145
146
  return access();
146
147
  }
148
+ const cached = layer.externalSnippets.get(id);
149
+ if (cached) {
150
+ return cached;
151
+ }
147
152
  if (Object.hasOwn(layer.externalMap, id)) {
148
153
  const external = layer.externalMap[id];
149
154
  if (isNamable(external) && getName(external) === undefined) {
150
155
  setName(external, id.replaceAll('.', '_'));
151
156
  }
152
- return coerceToSnippet(external);
157
+ const snippet = coerceToSnippet(external);
158
+ layer.externalSnippets.set(id, snippet);
159
+ return snippet;
153
160
  }
154
161
  return undefined;
155
162
  }
@@ -359,7 +366,10 @@ export class ResolutionCtxImpl {
359
366
  return bannedTokens.has(name);
360
367
  }
361
368
  isIdentifierTaken(name, scope) {
362
- return (this.#namespaceInternal.takenGlobalIdentifiers.has(name) ||
369
+ return (bannedTokens.has(name) ||
370
+ builtins.has(name) ||
371
+ templateEnumerants.has(name) ||
372
+ this.#namespaceInternal.takenGlobalIdentifiers.has(name) ||
363
373
  (scope === 'block'
364
374
  ? this._itemStateStack.isIdentifierTakenLocally(name)
365
375
  : this._itemStateStack.isIdentifierTakenInCallStack(name)));
@@ -700,14 +710,24 @@ export class ResolutionCtxImpl {
700
710
  }
701
711
  return maybeEventual;
702
712
  }
713
+ /**
714
+ * Whether every slot in the map currently has a value equal to the one recorded in it.
715
+ */
716
+ #slotsHaveValues(slotToValueMap) {
717
+ for (const [slot, expectedValue] of slotToValueMap) {
718
+ if (!slot.areEqual(this._itemStateStack.readSlot(slot), expectedValue)) {
719
+ return false;
720
+ }
721
+ }
722
+ return true;
723
+ }
703
724
  _getOrCompute(lazy) {
704
725
  // All memoized versions of `lazy`
705
726
  const instances = this.#namespaceInternal.memoizedLazy.get(lazy) ?? [];
706
727
  this._itemStateStack.pushItem();
707
728
  try {
708
729
  for (const instance of instances) {
709
- const slotValuePairs = [...instance.slotToValueMap.entries()];
710
- if (slotValuePairs.every(([slot, expectedValue]) => slot.areEqual(this._itemStateStack.readSlot(slot), expectedValue))) {
730
+ if (this.#slotsHaveValues(instance.slotToValueMap)) {
711
731
  return instance.result;
712
732
  }
713
733
  }
@@ -749,8 +769,7 @@ export class ResolutionCtxImpl {
749
769
  this._itemStateStack.pushItem();
750
770
  try {
751
771
  for (const instance of instances) {
752
- const slotValuePairs = [...instance.slotToValueMap.entries()];
753
- if (slotValuePairs.every(([slot, expectedValue]) => slot.areEqual(this._itemStateStack.readSlot(slot), expectedValue))) {
772
+ if (this.#slotsHaveValues(instance.slotToValueMap)) {
754
773
  return instance.result;
755
774
  }
756
775
  }
@@ -20,7 +20,7 @@ import type { RestoreContext } from './types.ts';
20
20
  /** Every soul that can cross a device boundary, discriminated by `type` */
21
21
  export type TgpuResourceSoul = TgpuBufferSoul | TgpuBufferBindingSoul | TgpuTextureSoul | TgpuTextureViewSoul | TgpuSamplerSoul | TgpuQuerySetSoul | TgpuBindGroupLayoutSoul | TgpuBindGroupSoul | TgpuVertexLayoutSoul | TgpuConstSoul | TgpuImmediateVarSoul | TgpuSlotSoul | TgpuAccessorSoul | TgpuComputePipelineSoul | TgpuRenderPipelineSoul | TgpuGuardedComputePipelineSoul | TgpuRootSoul;
22
22
  type Restorer<TSoul extends TgpuSoul> = (soul: TSoul, ctx: RestoreContext) => unknown;
23
- declare function restoreBufferBinding(soul: TgpuBufferBindingSoul): TgpuBufferBindingImpl<"uniform" | "mutable" | "readonly", BaseData>;
23
+ declare function restoreBufferBinding(soul: TgpuBufferBindingSoul): TgpuBufferBindingImpl<"uniform" | "readonly" | "mutable", BaseData>;
24
24
  /**
25
25
  * The one place a soul turns back into a resource. Importing this module opts
26
26
  * into every restorer, so it is kept out of the resources themselves
package/shared/meta.js CHANGED
@@ -1,4 +1,4 @@
1
- const version = "0.12.9";
1
+ const version = "0.12.10";
2
2
  import { DEV, TEST } from "./env.js";
3
3
  import { $getNameForward, $soul, isMarkedInternal } from "./symbols.js";
4
4
  import { normalizeMetadata } from "./normalizeMetadata.js";
@@ -33,6 +33,11 @@ export declare const $cast: unique symbol;
33
33
  * Can be called on the GPU
34
34
  */
35
35
  export declare const $gpuCallable: unique symbol;
36
+ /**
37
+ * Optional strict signature metadata for GPU-callable values, used for argument
38
+ * type hints and validation.
39
+ */
40
+ export declare const $gpuCallableStrictSignature: unique symbol;
36
41
  /**
37
42
  * Type token for the inferred (CPU & GPU) representation of a resource
38
43
  */
package/shared/symbols.js CHANGED
@@ -1,4 +1,4 @@
1
- const version = "0.12.9";
1
+ const version = "0.12.10";
2
2
  export const $internal = Symbol(`typegpu:${version}:$internal`);
3
3
  /** A plain record of all definitional state of a resource, surviving transfer between runtimes */
4
4
  export const $soul = Symbol(`typegpu:${version}:$soul`);
@@ -34,6 +34,11 @@ export const $cast = Symbol(`typegpu:${version}:$cast`);
34
34
  * Can be called on the GPU
35
35
  */
36
36
  export const $gpuCallable = Symbol(`typegpu:${version}:$gpuCallable`);
37
+ /**
38
+ * Optional strict signature metadata for GPU-callable values, used for argument
39
+ * type hints and validation.
40
+ */
41
+ export const $gpuCallableStrictSignature = Symbol(`typegpu:${version}:$gpuCallableStrictSignature`);
37
42
  //
38
43
  // Type tokens
39
44
  //
@@ -15,12 +15,6 @@ export type WithDefaults<TPartial, TDefaults> = Omit<TDefaults, keyof TPartial>
15
15
  export type OmitProps<T extends Record<string, unknown>, Prop> = Pick<T, {
16
16
  [Key in keyof T]: T[Key] extends Prop ? never : Key;
17
17
  }[keyof T]>;
18
- /**
19
- * Removes properties from record type that equal `Prop`
20
- */
21
- export type OmitPropsExact<T extends Record<string, unknown>, Prop> = Pick<T, {
22
- [Key in keyof T]: [T[Key], Prop] extends [Prop, T[Key]] ? never : Key;
23
- }[keyof T]>;
24
18
  export type NullableToOptional<T> = {
25
19
  [K in keyof T as T[K] extends null ? K : never]?: T[K];
26
20
  } & {
package/std/bitcast.d.ts CHANGED
@@ -188,6 +188,6 @@ declare function getBitcast<FromType extends keyof typeof casts, ToType extends
188
188
  readonly vec4i: (value: v4u) => v4i;
189
189
  readonly vec4u: (value: v4u) => v4u;
190
190
  };
191
- }[FromType][(ToType & "bool") | (ToType & "f32") | (ToType & "f16") | (ToType & "i32") | (ToType & "u32") | (ToType & "u16") | (ToType & "vec2f") | (ToType & "vec2h") | (ToType & "vec2i") | (ToType & "vec2u") | (ToType & "vec2<bool>") | (ToType & "vec3f") | (ToType & "vec3h") | (ToType & "vec3i") | (ToType & "vec3u") | (ToType & "vec3<bool>") | (ToType & "vec4f") | (ToType & "vec4h") | (ToType & "vec4i") | (ToType & "vec4u") | (ToType & "vec4<bool>") | (ToType & "mat2x2f") | (ToType & "mat3x3f") | (ToType & "mat4x4f") | (ToType & "struct") | (ToType & "array") | (ToType & "ptr") | (ToType & "atomic") | (ToType & "decorated") | (ToType & "abstractInt") | (ToType & "abstractFloat") | (ToType & "void") | (ToType & ("texture_1d" | "texture_2d" | "texture_multisampled_2d" | "texture_depth_2d" | "texture_depth_multisampled_2d" | "texture_2d_array" | "texture_depth_2d_array" | "texture_cube" | "texture_depth_cube" | "texture_cube_array" | "texture_depth_cube_array" | "texture_3d")) | (ToType & ("texture_storage_1d" | "texture_storage_2d" | "texture_storage_2d_array" | "texture_storage_3d")) | (ToType & "texture_external") | (ToType & "sampler") | (ToType & "sampler_comparison")];
191
+ }[FromType][(ToType & "abstractFloat") | (ToType & "abstractInt") | (ToType & "f32") | (ToType & "i32") | (ToType & "bool") | (ToType & "f16") | (ToType & "u32") | (ToType & "u16") | (ToType & "vec2f") | (ToType & "vec2h") | (ToType & "vec2i") | (ToType & "vec2u") | (ToType & "vec2<bool>") | (ToType & "vec3f") | (ToType & "vec3h") | (ToType & "vec3i") | (ToType & "vec3u") | (ToType & "vec3<bool>") | (ToType & "vec4f") | (ToType & "vec4h") | (ToType & "vec4i") | (ToType & "vec4u") | (ToType & "vec4<bool>") | (ToType & "mat2x2f") | (ToType & "mat3x3f") | (ToType & "mat4x4f") | (ToType & "struct") | (ToType & "array") | (ToType & "ptr") | (ToType & "atomic") | (ToType & "decorated") | (ToType & "void") | (ToType & ("texture_1d" | "texture_2d" | "texture_2d_array" | "texture_3d" | "texture_cube" | "texture_cube_array" | "texture_multisampled_2d" | "texture_depth_multisampled_2d" | "texture_depth_2d" | "texture_depth_2d_array" | "texture_depth_cube" | "texture_depth_cube_array")) | (ToType & ("texture_storage_1d" | "texture_storage_2d" | "texture_storage_2d_array" | "texture_storage_3d")) | (ToType & "texture_external") | (ToType & "sampler") | (ToType & "sampler_comparison")];
192
192
  export declare const bitcast: import("../indexNamedExports.ts").TgpuComptime<typeof getBitcast>;
193
193
  export {};
package/std/comptime.js CHANGED
@@ -73,18 +73,16 @@ export const isKnownAtComptime = /* @__PURE__ */ (() => {
73
73
  const impl = ((_value) => true);
74
74
  impl.toString = () => 'isKnownAtComptime';
75
75
  setName(impl, 'isKnownAtComptime');
76
- impl[$gpuCallable] = {
77
- call(_ctx, [value]) {
78
- if (!value) {
79
- throw new WgslTypeError('`std.isKnownAtComptime` was called without any arguments');
80
- }
81
- if (value.possibleSideEffects) {
82
- throw new WgslTypeError('`std.isKnownAtComptime` received an argument with possible side effects. The expression is never emitted into the shader, so its side effects would silently not happen, and a side-effectful expression is never known at comptime anyway, so the result would always be `false`. Remove the check, and run the side effect as a separate statement if it is needed.');
83
- }
84
- return snip(asComptime(value) !== undefined, bool,
85
- /* origin */ 'constant',
86
- /* possibleSideEffects */ false);
87
- },
76
+ impl[$gpuCallable] = (_ctx, [value]) => {
77
+ if (!value) {
78
+ throw new WgslTypeError('`std.isKnownAtComptime` was called without any arguments');
79
+ }
80
+ if (value.possibleSideEffects) {
81
+ throw new WgslTypeError('`std.isKnownAtComptime` received an argument with possible side effects. The expression is never emitted into the shader, so its side effects would silently not happen, and a side-effectful expression is never known at comptime anyway, so the result would always be `false`. Remove the check, and run the side effect as a separate statement if it is needed.');
82
+ }
83
+ return snip(asComptime(value) !== undefined, bool,
84
+ /* origin */ 'constant',
85
+ /* possibleSideEffects */ false);
88
86
  };
89
87
  return impl;
90
88
  })();
@@ -5,10 +5,8 @@ import { $gpuCallable } from "../shared/symbols.js";
5
5
  import { coerceToSnippet } from "../tgsl/generationHelpers.js";
6
6
  const impl = (() => false);
7
7
  impl.toString = () => 'isBeingTranspiled';
8
- impl[$gpuCallable] = {
9
- call(_ctx, _args) {
10
- return coerceToSnippet(true);
11
- },
8
+ impl[$gpuCallable] = (_ctx, _args) => {
9
+ return coerceToSnippet(true);
12
10
  };
13
11
  /**
14
12
  * Returns `true` when the direct callee is being transpiled for GPU, otherwise `false`.
package/std/matrix.js CHANGED
@@ -5,11 +5,11 @@ import { mul } from "./operators.js";
5
5
  import { $gpuCallable } from "../shared/symbols.js";
6
6
  import { vec3f } from "../data/vector.js";
7
7
  import { f32 } from "../data/numeric.js";
8
- const gpuTranslation4 = translation4[$gpuCallable].call.bind(translation4);
9
- const gpuScaling4 = scaling4[$gpuCallable].call.bind(scaling4);
10
- const gpuRotationX4 = rotationX4[$gpuCallable].call.bind(rotationX4);
11
- const gpuRotationY4 = rotationY4[$gpuCallable].call.bind(rotationY4);
12
- const gpuRotationZ4 = rotationZ4[$gpuCallable].call.bind(rotationZ4);
8
+ const gpuTranslation4 = translation4[$gpuCallable].bind(translation4);
9
+ const gpuScaling4 = scaling4[$gpuCallable].bind(scaling4);
10
+ const gpuRotationX4 = rotationX4[$gpuCallable].bind(rotationX4);
11
+ const gpuRotationY4 = rotationY4[$gpuCallable].bind(rotationY4);
12
+ const gpuRotationZ4 = rotationZ4[$gpuCallable].bind(rotationZ4);
13
13
  /**
14
14
  * Translates the given 4-by-4 matrix by the given vector.
15
15
  * @param {m4x4f} matrix - The matrix to be modified.
package/std/numeric.d.ts CHANGED
@@ -206,6 +206,7 @@ export declare const normalize: import("../types.ts").DualFn<(<T extends AnyFloa
206
206
  declare function powCpu(base: number, exponent: number): number;
207
207
  declare function powCpu<T extends AnyFloatVecInstance>(base: T, exponent: T): T;
208
208
  export declare const pow: import("../types.ts").DualFn<typeof powCpu>;
209
+ export declare const powOperator: import("../types.ts").DualFn<typeof powCpu>;
209
210
  declare function cpuQuantizeToF16(value: number): number;
210
211
  declare function cpuQuantizeToF16<T extends AnyFloat32VecInstance>(value: T): T;
211
212
  export declare const quantizeToF16: import("../types.ts").DualFn<typeof cpuQuantizeToF16>;
package/std/numeric.js CHANGED
@@ -3,14 +3,16 @@ import { stitch } from "../core/resolve/stitch.js";
3
3
  import { mat2x2f, mat3x3f, mat4x4f } from "../data/matrix.js";
4
4
  import { clampScalar, smoothstepScalar } from "../data/numberOps.js";
5
5
  import { abstractFloat, abstractInt, f16, f32, i32, u32 } from "../data/numeric.js";
6
+ import { snip, withValue } from "../data/snippet.js";
6
7
  import { abstruct } from "../data/struct.js";
7
8
  import { vec2f, vec2h, vec2i, vec2u, vec3f, vec3h, vec3i, vec3u, vec4f, vec4h, vec4i, vec4u, } from "../data/vector.js";
8
9
  import { VectorOps } from "../data/vectorOps.js";
9
10
  import { floatKind, matrixKind, numericKind, signedKind, crossKind, assertEqualKinds, assertKind, upCast, generalizeFn, } from "../data/generalizeFn.js";
10
- import { isHalfPrecisionSchema, WORKAROUND_getSchema, } from "../data/wgslTypes.js";
11
+ import { isHalfPrecisionSchema, isVecInstance, WORKAROUND_getSchema, } from "../data/wgslTypes.js";
11
12
  import { SignatureNotSupportedError } from "../errors.js";
12
13
  import { assertExhaustive } from "../shared/utilityTypes.js";
13
14
  import { unify } from "../tgsl/conversion.js";
15
+ import { asComptime } from "../types.js";
14
16
  import { mul, sub } from "./operators.js";
15
17
  // helpers
16
18
  const unaryIdentitySignature = (arg) => {
@@ -656,6 +658,38 @@ export const pow = dualImpl({
656
658
  codegenImpl: (_ctx, [lhs, rhs]) => stitch `pow(${lhs}, ${rhs})`,
657
659
  sideEffects: false,
658
660
  });
661
+ export const powOperator = dualImpl({
662
+ name: 'pow',
663
+ signature: unifyRestrictedSignature(anyFloat),
664
+ normalImpl: powCpu,
665
+ codegenImpl: (ctx, [lhs, rhs], returnType) => {
666
+ const call = (name, ...args) => snip(ctx.gen.emitCall(name, [], args), returnType, 'runtime', args.some((a) => a.possibleSideEffects));
667
+ const exponent = (asComptime(rhs)?.value ?? NaN);
668
+ const k = isVecInstance(exponent) && exponent.every((e) => e === exponent[0]) ? exponent[0] : exponent;
669
+ if (typeof k !== 'number' || !Number.isInteger(k)) {
670
+ return ctx.gen.emitCall('pow', [], [lhs, rhs]);
671
+ }
672
+ if (lhs.possibleSideEffects) {
673
+ // The forms below repeat or drop the base, so only these evaluate it exactly once
674
+ return ctx.gen.emitCall('pow', [], [k % 2 === 0 ? call('abs', lhs) : lhs, rhs]);
675
+ }
676
+ if (k === 0) {
677
+ return ctx.resolveSnippet(withValue(generalizeFn(() => 1, [exponent]), rhs)).value;
678
+ }
679
+ if (k === 1) {
680
+ return ctx.resolveSnippet(lhs).value;
681
+ }
682
+ if (k === 2) {
683
+ return ctx.gen.emitBinaryOp(lhs, '*', lhs);
684
+ }
685
+ const magnitude = call('pow', call('abs', lhs), rhs);
686
+ if (k % 2 === 0) {
687
+ return magnitude.value;
688
+ }
689
+ return ctx.gen.emitBinaryOp(call('sign', lhs), '*', magnitude);
690
+ },
691
+ sideEffects: false,
692
+ });
659
693
  function cpuQuantizeToF16(_value) {
660
694
  throw new Error('Unreachable code. The function is only used for the type.');
661
695
  }
package/std/typeOf.js CHANGED
@@ -35,20 +35,18 @@ export const typeOf = (() => {
35
35
  });
36
36
  setName(impl, 'typeOf');
37
37
  impl.toString = () => 'typeOf';
38
- impl[$gpuCallable] = {
39
- call(_ctx, args) {
40
- const [arg] = args;
41
- if (!arg || args.length > 1) {
42
- throw new Error(`std.typeOf() expects exactly one argument, got ${args.length}`);
43
- }
44
- const type = arg.dataType;
45
- // Only public data types are exposed. Unknown types and internal types
46
- // (e.g. AutoStruct, EntryInputRouter) must not leak to the user.
47
- if (!isWgslData(type)) {
48
- return coerceToSnippet(undefined);
49
- }
50
- return coerceToSnippet(type);
51
- },
38
+ impl[$gpuCallable] = (_ctx, args) => {
39
+ const [arg] = args;
40
+ if (!arg || args.length > 1) {
41
+ throw new Error(`std.typeOf() expects exactly one argument, got ${args.length}`);
42
+ }
43
+ const type = arg.dataType;
44
+ // Only public data types are exposed. Unknown types and internal types
45
+ // (e.g. AutoStruct, EntryInputRouter) must not leak to the user.
46
+ if (!isWgslData(type)) {
47
+ return coerceToSnippet(undefined);
48
+ }
49
+ return coerceToSnippet(type);
52
50
  };
53
51
  // Mark as internal
54
52
  Object.defineProperty(impl, $internal, { value: true });
package/tgpu.d.ts CHANGED
@@ -13,4 +13,4 @@ export { computeFn } from './core/function/tgpuComputeFn.ts';
13
13
  export { fragmentFn } from './core/function/tgpuFragmentFn.ts';
14
14
  export { vertexFn } from './core/function/tgpuVertexFn.ts';
15
15
  export { unroll } from './core/unroll/tgpuUnroll.ts';
16
- export * as '~unstable' from './tgpuUnstable.ts';
16
+ export { unstable as '~unstable' } from './tgpuUnstableNamespace.ts';
package/tgpu.js CHANGED
@@ -14,4 +14,4 @@ export { computeFn } from "./core/function/tgpuComputeFn.js";
14
14
  export { fragmentFn } from "./core/function/tgpuFragmentFn.js";
15
15
  export { vertexFn } from "./core/function/tgpuVertexFn.js";
16
16
  export { unroll } from "./core/unroll/tgpuUnroll.js";
17
- export * as '~unstable' from "./tgpuUnstable.js";
17
+ export { unstable as '~unstable' } from "./tgpuUnstableNamespace.js";
@@ -2,10 +2,10 @@ import { type TgpuBuffer, type UniformFlag } from './core/buffer/buffer.ts';
2
2
  import { type TgpuComparisonSampler, type TgpuSampler } from './core/sampler/sampler.ts';
3
3
  import { type PropsForSchema, type TgpuTexture, type TgpuTextureView } from './core/texture/texture.ts';
4
4
  import { type SampledFlag } from './core/texture/usageExtension.ts';
5
- import { type WgslExternalTexture, type WgslStorageTexture, type WgslTexture } from './data/texture.ts';
5
+ import { type WgslExternalTexture, type WgslStorageTexture, type WgslTexture, type WgslTexture2d } from './data/texture.ts';
6
6
  import type { TgpuRoot } from './core/root/rootTypes.ts';
7
7
  import type { RestoreContext } from './serial/types.ts';
8
- import type { BaseData } from './data/wgslTypes.ts';
8
+ import type { BaseData, F32 } from './data/wgslTypes.ts';
9
9
  import { type StorageFlag } from './extension.ts';
10
10
  import type { TgpuNamable } from './shared/meta.ts';
11
11
  import type { InferGPU, MemIdentity } from './shared/repr.ts';
@@ -105,7 +105,10 @@ export interface TgpuBindGroupLayout<Entries extends Record<string, TgpuLayoutEn
105
105
  }
106
106
  export type LayoutEntryToInput<T extends TgpuLayoutEntry | null> = TgpuLayoutEntry | null extends T ? TgpuBuffer<BaseData> | TgpuBufferBinding<BaseData> | GPUBuffer | TgpuSampler | GPUSampler | TgpuComparisonSampler | TgpuTexture | GPUTextureView | GPUExternalTexture : T extends TgpuLayoutUniform ? (TgpuBuffer<MemIdentity<UnwrapRuntimeConstructor<T['uniform']>>> & UniformFlag) | TgpuUniform<MemIdentity<UnwrapRuntimeConstructor<T['uniform']>>> | GPUBuffer : T extends TgpuLayoutStorage ? (TgpuBuffer<MemIdentity<UnwrapRuntimeConstructor<T['storage']>>> & StorageFlag) | (T extends {
107
107
  access: 'mutable';
108
- } ? TgpuMutable<MemIdentity<UnwrapRuntimeConstructor<T['storage']>>> : TgpuReadonly<MemIdentity<UnwrapRuntimeConstructor<T['storage']>>>) | GPUBuffer : T extends TgpuLayoutSampler ? TgpuSampler | GPUSampler : T extends TgpuLayoutComparisonSampler ? TgpuComparisonSampler | GPUSampler : T extends TgpuLayoutTexture ? GPUTextureView | GPUTexture | (SampledFlag & TgpuTexture<Prettify<PropsForSchema<T['texture']>>>) | TgpuTextureView<WgslTexture> : T extends TgpuLayoutStorageTexture ? GPUTextureView | GPUTexture | (StorageFlag & TgpuTexture<Prettify<PropsForSchema<T['storageTexture']>>>) | TgpuTextureView<WgslStorageTexture> : T extends TgpuLayoutExternalTexture ? GPUExternalTexture : never;
108
+ } ? TgpuMutable<MemIdentity<UnwrapRuntimeConstructor<T['storage']>>> : TgpuReadonly<MemIdentity<UnwrapRuntimeConstructor<T['storage']>>>) | GPUBuffer : T extends TgpuLayoutSampler ? TgpuSampler | GPUSampler : T extends TgpuLayoutComparisonSampler ? TgpuComparisonSampler | GPUSampler : T extends TgpuLayoutTexture ? GPUTextureView | GPUTexture | (SampledFlag & TgpuTexture<Prettify<PropsForSchema<T['texture']>>>) | TgpuTextureView<WgslTexture> : T extends TgpuLayoutStorageTexture ? GPUTextureView | GPUTexture | (StorageFlag & TgpuTexture<Prettify<PropsForSchema<T['storageTexture']>>>) | TgpuTextureView<WgslStorageTexture> : T extends TgpuLayoutExternalTexture ? GPUExternalTexture | GPUTextureView | GPUTexture | (SampledFlag & TgpuTexture<{
109
+ size: readonly number[];
110
+ format: 'rgba8unorm' | 'bgra8unorm' | 'rgba16float';
111
+ }>) | TgpuTextureView<WgslTexture2d<F32>> : never;
109
112
  export type InferLayoutEntry<T extends TgpuLayoutEntry | null> = T extends TgpuLayoutUniform ? InferGPU<T['uniform']> : T extends TgpuLayoutStorage ? InferGPU<UnwrapRuntimeConstructor<T['storage']>> : T extends TgpuLayoutSampler ? InferGPU<WgslSampler> : T extends TgpuLayoutComparisonSampler ? InferGPU<WgslComparisonSampler> : T extends TgpuLayoutTexture<infer TSchema> ? InferGPU<TSchema> : T extends TgpuLayoutStorageTexture<infer TSchema> ? InferGPU<TSchema> : T extends TgpuLayoutExternalTexture ? InferGPU<T['externalTexture']> : never;
110
113
  export type ExtractBindGroupInputFromLayout<T extends Record<string, TgpuLayoutEntry | null>> = NullableToOptional<{
111
114
  [K in keyof T]: LayoutEntryToInput<T[K]>;
@@ -5,7 +5,7 @@ import { comparisonSampler as wgslComparisonSampler, sampler as wgslSampler, } f
5
5
  import { TgpuExternalTextureImpl } from "./core/texture/externalTexture.js";
6
6
  import { isTexture, isTextureView, TgpuLaidOutTextureViewImpl, } from "./core/texture/texture.js";
7
7
  import { isUsableAsSampled, NotSampledError, } from "./core/texture/usageExtension.js";
8
- import {} from "./data/texture.js";
8
+ import { texture2d, } from "./data/texture.js";
9
9
  import { invariant, NotUniformError } from "./errors.js";
10
10
  import { NotStorageError } from "./extension.js";
11
11
  import { getName, setName } from "./shared/meta.js";
@@ -338,9 +338,22 @@ export class TgpuBindGroupImpl {
338
338
  };
339
339
  }
340
340
  if ('externalTexture' in entry) {
341
+ let resource;
342
+ if (isTexture(value)) {
343
+ if (!isUsableAsSampled(value)) {
344
+ throw new NotSampledError(value);
345
+ }
346
+ resource = unwrapper.unwrap(value.createView(texture2d(), { mipLevelCount: 1 }));
347
+ }
348
+ else if (isTextureView(value)) {
349
+ resource = unwrapper.unwrap(value);
350
+ }
351
+ else {
352
+ resource = value;
353
+ }
341
354
  return {
342
355
  binding: idx,
343
- resource: value,
356
+ resource,
344
357
  };
345
358
  }
346
359
  throw new Error(`Malformed bind group entry: ${safeStringify(value)}`);
@@ -0,0 +1 @@
1
+ export * as unstable from './tgpuUnstable.ts';
@@ -0,0 +1,5 @@
1
+ // NOTE: This is a barrel file, internal files should not import things from this file
2
+ // Re-exported under the '~unstable' string name by `tgpu.ts`. Babel's CommonJS transform
3
+ // (used by React Native's Metro) emits invalid code for `export * as '~unstable' from ...`
4
+ // (`exports.~unstable = ...`), but handles named re-exports with string names correctly.
5
+ export * as unstable from "./tgpuUnstable.js";
@@ -8,6 +8,7 @@ import { isPtr, isVec, isWgslArray } from "../data/wgslTypes.js";
8
8
  import { asComptime } from "../types.js";
9
9
  import { accessProp } from "./accessProp.js";
10
10
  import { ArrayExpression, coerceToSnippet } from "./generationHelpers.js";
11
+ import { Swizzle } from "./swizzle.js";
11
12
  const indexableTypeToResult = {
12
13
  mat2x2f: vec2f,
13
14
  mat3x3f: vec3f,
@@ -32,6 +33,7 @@ function deriveIndexAccessOrigin(targetOrigin, indexOrigin) {
32
33
  export function accessIndex(target, indexArg) {
33
34
  const index = typeof indexArg === 'number' ? coerceToSnippet(indexArg) : indexArg;
34
35
  const knownIndex = asComptime(index);
36
+ const possibleSideEffects = target.possibleSideEffects || index.possibleSideEffects;
35
37
  // array
36
38
  if (isWgslArray(target.dataType) || isDisarray(target.dataType)) {
37
39
  const elementType = target.dataType.elementType;
@@ -44,15 +46,16 @@ export function accessIndex(target, indexArg) {
44
46
  ? // oxlint-disable-next-line typescript/no-explicit-any -- it's fine, it's there
45
47
  knownTarget.value[knownIndex.value]
46
48
  : stitch `${target}[${index}]`, elementType,
47
- /* origin */ origin, target.possibleSideEffects || index.possibleSideEffects);
49
+ /* origin */ origin, possibleSideEffects);
48
50
  }
49
51
  // vector
50
52
  if (isVec(target.dataType)) {
51
- const knownTarget = knownIndex && asComptime(target);
52
- return snip(knownTarget && knownIndex
53
- ? // oxlint-disable-next-line typescript/no-explicit-any -- it's fine, it's there
54
- knownTarget.value[knownIndex.value]
55
- : stitch `${target}[${index}]`, target.dataType.primitive, deriveIndexAccessOrigin(target.origin, index.origin), target.possibleSideEffects || index.possibleSideEffects);
53
+ const comptimeIndex = knownIndex?.value;
54
+ if (typeof comptimeIndex === 'number' || typeof comptimeIndex === 'string') {
55
+ const swizzle = new Swizzle(target, comptimeIndex);
56
+ return snip(swizzle, swizzle.dataType, swizzle.origin, possibleSideEffects);
57
+ }
58
+ return snip(stitch `${target}[${index}]`, target.dataType.primitive, deriveIndexAccessOrigin(target.origin, index.origin), possibleSideEffects);
56
59
  }
57
60
  if (isPtr(target.dataType)) {
58
61
  // Sometimes values that are typed as pointers aren't instances of `d.ref`, so we
@@ -62,7 +65,7 @@ export function accessIndex(target, indexArg) {
62
65
  // matrix.columns
63
66
  if (target.value instanceof MatrixColumnsAccess) {
64
67
  const propType = indexableTypeToResult[target.value.matrix.dataType.type];
65
- return snip(stitch `${target.value.matrix}[${index}]`, propType, deriveIndexAccessOrigin(target.origin, index.origin), target.possibleSideEffects || index.possibleSideEffects);
68
+ return snip(stitch `${target.value.matrix}[${index}]`, propType, deriveIndexAccessOrigin(target.origin, index.origin), possibleSideEffects);
66
69
  }
67
70
  // matrix
68
71
  if (target.dataType.type in indexableTypeToResult) {
@@ -3,13 +3,13 @@ import { AutoStruct } from "../data/autoStruct.js";
3
3
  import { EntryInputRouter } from "../core/function/entryInputRouter.js";
4
4
  import { isUnstruct, UnknownData } from "../data/dataTypes.js";
5
5
  import { MatrixColumnsAccess } from "../data/matrixColumnsAccess.js";
6
- import { bool, f16, f32, i32, u32 } from "../data/numeric.js";
6
+ import { u32 } from "../data/numeric.js";
7
7
  import { derefSnippet } from "../data/ref.js";
8
8
  import { isSnippet, snip } from "../data/snippet.js";
9
- import { vec2b, vec2f, vec2h, vec2i, vec2u, vec3b, vec3f, vec3h, vec3i, vec3u, vec4b, vec4f, vec4h, vec4i, vec4u, } from "../data/vector.js";
10
9
  import { isMat, isPtr, isVec, isWgslArray, isWgslStruct, } from "../data/wgslTypes.js";
11
10
  import { asComptime } from "../types.js";
12
11
  import { coerceToSnippet, numericLiteralToSnippet } from "./generationHelpers.js";
12
+ import { isValidSwizzle, Swizzle } from "./swizzle.js";
13
13
  import { InfixDispatch, infixOperators } from "./infixDispatch.js";
14
14
  import { accessStructProp } from "./accessStructProp.js";
15
15
  import { getName, isNamable, setName } from "../shared/meta.js";
@@ -30,38 +30,6 @@ const infixKinds = [
30
30
  'mat3x3f',
31
31
  'mat4x4f',
32
32
  ];
33
- const swizzleLenToType = {
34
- f: {
35
- 1: f32,
36
- 2: vec2f,
37
- 3: vec3f,
38
- 4: vec4f,
39
- },
40
- h: {
41
- 1: f16,
42
- 2: vec2h,
43
- 3: vec3h,
44
- 4: vec4h,
45
- },
46
- i: {
47
- 1: i32,
48
- 2: vec2i,
49
- 3: vec3i,
50
- 4: vec4i,
51
- },
52
- u: {
53
- 1: u32,
54
- 2: vec2u,
55
- 3: vec3u,
56
- 4: vec4u,
57
- },
58
- b: {
59
- 1: bool,
60
- 2: vec2b,
61
- 3: vec3b,
62
- 4: vec4b,
63
- },
64
- };
65
33
  export function accessProp(target, propName) {
66
34
  if (infixKinds.includes(target.dataType.type) && propName in infixOperators) {
67
35
  const operator = infixOperators[propName];
@@ -117,29 +85,9 @@ export function accessProp(target, propName) {
117
85
  return snip(target.dataType.type, UnknownData, 'constant', /* possibleSideEffects */ false);
118
86
  }
119
87
  }
120
- const propLength = propName.length;
121
- if (isVec(target.dataType) &&
122
- propLength >= 1 &&
123
- propLength <= 4 &&
124
- /^[xyzw]+$|^[rgba]+$/.test(propName)) {
125
- const swizzleTypeChar = target.dataType.type.includes('bool')
126
- ? 'b'
127
- : target.dataType.type[4];
128
- const swizzleType = swizzleLenToType[swizzleTypeChar][propLength];
129
- if (!swizzleType) {
130
- return undefined;
131
- }
132
- const knownTarget = asComptime(target);
133
- return snip(knownTarget
134
- ? // oxlint-disable-next-line typescript/no-explicit-any -- it's fine, the prop is there
135
- knownTarget.value[propName]
136
- : stitch `${target}.${propName}`, swizzleType,
137
- // Swizzling creates new vectors (unless they're on the lhs of an assignment, but that's not yet supported in WGSL)
138
- /* origin */ propLength === 1
139
- ? target.origin
140
- : target.origin === 'constant' || target.origin === 'constant-immutable-def'
141
- ? 'constant'
142
- : 'runtime', target.possibleSideEffects);
88
+ if (isVec(target.dataType) && isValidSwizzle(propName)) {
89
+ const swizzle = new Swizzle(target, propName);
90
+ return snip(swizzle, swizzle.dataType, swizzle.origin, target.possibleSideEffects);
143
91
  }
144
92
  const knownTarget = asComptime(target);
145
93
  if (knownTarget) {
@@ -50,6 +50,6 @@ export interface LogResources {
50
50
  logIdToMeta: Map<number, LogMeta>;
51
51
  }
52
52
  export interface LogGenerator {
53
- generateLog(ctx: ResolutionCtx, op: SupportedLogOp, args: Snippet[]): Snippet;
53
+ generateLog(ctx: ResolutionCtx, op: SupportedLogOp, args: readonly Snippet[]): Snippet;
54
54
  get logResources(): LogResources | undefined;
55
55
  }
@@ -102,7 +102,28 @@ function getImplicitConversionRank(src, dest) {
102
102
  }
103
103
  return INFINITE_RANK;
104
104
  }
105
+ /**
106
+ * Conversion ranks only depend on immutable facts about the two schemas (their type tags,
107
+ * identity, inner types and pointer flags), so they're computed once per pair. Callers must
108
+ * treat the returned info as read-only.
109
+ */
110
+ const autoRankCache = new WeakMap();
111
+ const implicitRankCache = new WeakMap();
105
112
  function getConversionRank(src, dest, allowImplicit) {
113
+ const cache = allowImplicit ? implicitRankCache : autoRankCache;
114
+ let byDest = cache.get(src);
115
+ if (!byDest) {
116
+ byDest = new WeakMap();
117
+ cache.set(src, byDest);
118
+ }
119
+ let rank = byDest.get(dest);
120
+ if (!rank) {
121
+ rank = computeConversionRank(src, dest, allowImplicit);
122
+ byDest.set(dest, rank);
123
+ }
124
+ return rank;
125
+ }
126
+ function computeConversionRank(src, dest, allowImplicit) {
106
127
  const autoRank = getAutoConversionRank(src, dest);
107
128
  if (autoRank.rank < Number.POSITIVE_INFINITY) {
108
129
  return autoRank;
@@ -72,7 +72,7 @@ You can wrap iterable with \`tgpu.unroll(...)\`. If iterable is known at comptim
72
72
  ...defaults,
73
73
  end: dataType.elementCount > 0
74
74
  ? snip(dataType.elementCount, u32, 'constant', false)
75
- : arrayLength[$gpuCallable].call(ctx, [iterableSnippet]),
75
+ : arrayLength[$gpuCallable](ctx, [iterableSnippet]),
76
76
  };
77
77
  }
78
78
  if (wgsl.isVec(dataType)) {
@@ -5,7 +5,6 @@ import { $comptimeValueOf, $internal, $resolve } from '../shared/symbols.ts';
5
5
  export declare function numericLiteralToSnippet(value: number): Snippet;
6
6
  export declare function concretize<T extends BaseData>(type: T): T | F32 | I32;
7
7
  export declare function concretizeSnippet(snippet: Snippet): Snippet;
8
- export declare function concretizeSnippets(args: Snippet[]): Snippet[];
9
8
  export declare function coerceToSnippet(value: unknown): Snippet;
10
9
  /**
11
10
  * Intermediate representation for WGSL array expressions.
@@ -1,7 +1,7 @@
1
1
  import { UnknownData } from "../data/dataTypes.js";
2
2
  import { abstractFloat, abstractInt, bool, f32, i32 } from "../data/numeric.js";
3
3
  import { isRef } from "../data/ref.js";
4
- import { isStoredInMemory, isSnippet, snip, withDataType } from "../data/snippet.js";
4
+ import { isSnippet, isStoredInMemory, snip, withDataType } from "../data/snippet.js";
5
5
  import { isMatInstance, isNaturallyEphemeral, isVecInstance, WORKAROUND_getSchema, } from "../data/wgslTypes.js";
6
6
  import { asComptime, getOwnSnippet, } from "../types.js";
7
7
  import { WgslTypeError } from "../errors.js";
@@ -34,9 +34,6 @@ export function concretize(type) {
34
34
  export function concretizeSnippet(snippet) {
35
35
  return withDataType(concretize(snippet.dataType), snippet);
36
36
  }
37
- export function concretizeSnippets(args) {
38
- return args.map(concretizeSnippet);
39
- }
40
37
  export function coerceToSnippet(value) {
41
38
  if (isSnippet(value)) {
42
39
  // Already a snippet