typegpu 0.12.8 → 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 (119) 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 +45 -44
  13. package/core/function/tgpuComputeFn.d.ts +0 -3
  14. package/core/function/tgpuFn.d.ts +1 -0
  15. package/core/function/tgpuFn.js +14 -4
  16. package/core/function/tgpuFragmentFn.d.ts +1 -1
  17. package/core/function/tgpuVertexFn.d.ts +1 -1
  18. package/core/pipeline/computePipeline.js +5 -2
  19. package/core/pipeline/drawState.js +1 -1
  20. package/core/pipeline/renderPipeline.js +5 -2
  21. package/core/pipeline/webgpuLimitations.js +11 -3
  22. package/core/resolve/externals.js +4 -0
  23. package/core/resolve/namespace.d.ts +4 -0
  24. package/core/resolve/namespace.js +1 -2
  25. package/core/resolve/stitch.js +13 -8
  26. package/core/root/init.d.ts +3 -3
  27. package/core/root/init.js +12 -13
  28. package/core/root/rootTypes.d.ts +44 -37
  29. package/core/slot/accessor.js +4 -4
  30. package/core/texture/texture.d.ts +3 -3
  31. package/core/texture/texture.js +60 -44
  32. package/core/texture/textureFormats.d.ts +4 -3
  33. package/core/texture/textureFormats.js +17 -6
  34. package/core/texture/textureWrite.d.ts +9 -0
  35. package/core/texture/textureWrite.js +21 -0
  36. package/core/unroll/tgpuUnroll.js +2 -4
  37. package/core/vertexLayout/vertexAttribute.d.ts +1 -4
  38. package/core/vertexLayout/vertexLayout.js +11 -30
  39. package/data/alignmentOf.d.ts +1 -1
  40. package/data/alignmentOf.js +5 -12
  41. package/data/array.js +34 -2
  42. package/data/attributes.d.ts +16 -3
  43. package/data/attributes.js +11 -2
  44. package/data/compiledIO.js +3 -3
  45. package/data/dataIO.js +77 -111
  46. package/data/dataTypes.d.ts +0 -2
  47. package/data/dataTypes.js +3 -3
  48. package/data/disarray.js +2 -0
  49. package/data/index.d.ts +4 -3
  50. package/data/index.js +3 -2
  51. package/data/offsetUtils.js +23 -13
  52. package/data/offsets.js +1 -2
  53. package/data/partialIO.js +2 -3
  54. package/data/ref.js +35 -37
  55. package/data/schemaCallWrapper.js +2 -2
  56. package/data/schemaMemoryLayout.d.ts +6 -1
  57. package/data/schemaMemoryLayout.js +23 -14
  58. package/data/schemasEqual.d.ts +37 -0
  59. package/data/schemasEqual.js +122 -0
  60. package/data/sizeOf.d.ts +1 -1
  61. package/data/sizeOf.js +2 -3
  62. package/data/snippet.d.ts +1 -1
  63. package/data/struct.js +27 -1
  64. package/data/unstruct.js +2 -0
  65. package/data/vectorImpl.js +45 -21
  66. package/data/vertexFormatData.js +7 -9
  67. package/data/wgslTypes.d.ts +28 -13
  68. package/data/wgslTypes.js +33 -39
  69. package/extension.d.ts +0 -4
  70. package/package.json +2 -2
  71. package/resolutionCtx.d.ts +1 -1
  72. package/resolutionCtx.js +26 -7
  73. package/serial/restore.d.ts +4 -3
  74. package/serial/restore.js +2 -1
  75. package/shared/meta.js +1 -1
  76. package/shared/symbols.d.ts +5 -0
  77. package/shared/symbols.js +6 -1
  78. package/shared/utilityTypes.d.ts +0 -6
  79. package/std/bitcast.d.ts +1 -1
  80. package/std/comptime.d.ts +67 -0
  81. package/std/comptime.js +88 -0
  82. package/std/environment.js +2 -4
  83. package/std/index.d.ts +2 -0
  84. package/std/index.js +2 -0
  85. package/std/matrix.js +5 -5
  86. package/std/numeric.d.ts +2 -1
  87. package/std/numeric.js +47 -10
  88. package/std/typeOf.d.ts +31 -0
  89. package/std/typeOf.js +54 -0
  90. package/tgpu.d.ts +1 -1
  91. package/tgpu.js +1 -1
  92. package/tgpuBindGroupLayout.d.ts +6 -3
  93. package/tgpuBindGroupLayout.js +15 -2
  94. package/tgpuLogger.d.ts +3 -0
  95. package/tgpuLogger.js +3 -0
  96. package/tgpuUnstableNamespace.d.ts +1 -0
  97. package/tgpuUnstableNamespace.js +5 -0
  98. package/tgsl/accessIndex.js +10 -7
  99. package/tgsl/accessProp.js +5 -57
  100. package/tgsl/consoleLog/serializers.d.ts +1 -8
  101. package/tgsl/consoleLog/serializers.js +53 -37
  102. package/tgsl/consoleLog/types.d.ts +1 -1
  103. package/tgsl/conversion.js +21 -0
  104. package/tgsl/forOfUtils.js +1 -1
  105. package/tgsl/generationHelpers.d.ts +0 -1
  106. package/tgsl/generationHelpers.js +1 -4
  107. package/tgsl/shaderGenerator.d.ts +5 -0
  108. package/tgsl/shellless.js +3 -20
  109. package/tgsl/swizzle.d.ts +24 -0
  110. package/tgsl/swizzle.js +112 -0
  111. package/tgsl/wgslGenerator.d.ts +13 -3
  112. package/tgsl/wgslGenerator.js +150 -152
  113. package/types.d.ts +10 -10
  114. package/types.js +1 -1
  115. package/unwrapper.d.ts +2 -2
  116. package/data/deepEqual.d.ts +0 -21
  117. package/data/deepEqual.js +0 -93
  118. package/taskQueue.d.ts +0 -6
  119. package/taskQueue.js +0 -30
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) => {
@@ -26,16 +28,19 @@ const variadicUnifySignature = (...args) => {
26
28
  returnType: uargs[0],
27
29
  };
28
30
  };
29
- export const unifyRestrictedSignature = (restrict) => (...args) => {
30
- const uargs = unify(args, restrict);
31
- if (!uargs) {
32
- throw new SignatureNotSupportedError(args, restrict);
33
- }
34
- return {
35
- argTypes: uargs,
36
- returnType: uargs[0],
31
+ /*#__NO_SIDE_EFFECTS__*/
32
+ export function unifyRestrictedSignature(restrict) {
33
+ return (...args) => {
34
+ const uargs = unify(args, restrict);
35
+ if (!uargs) {
36
+ throw new SignatureNotSupportedError(args, restrict);
37
+ }
38
+ return {
39
+ argTypes: uargs,
40
+ returnType: uargs[0],
41
+ };
37
42
  };
38
- };
43
+ }
39
44
  function variadicReduce(fn) {
40
45
  return (fst, ...rest) => {
41
46
  let acc = fst;
@@ -653,6 +658,38 @@ export const pow = dualImpl({
653
658
  codegenImpl: (_ctx, [lhs, rhs]) => stitch `pow(${lhs}, ${rhs})`,
654
659
  sideEffects: false,
655
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
+ });
656
693
  function cpuQuantizeToF16(_value) {
657
694
  throw new Error('Unreachable code. The function is only used for the type.');
658
695
  }
@@ -0,0 +1,31 @@
1
+ import type { AnyData } from '../data/dataTypes.ts';
2
+ import type { GPUCallable } from '../types.ts';
3
+ interface TypeOf extends GPUCallable {
4
+ (arg: unknown): AnyData | undefined;
5
+ }
6
+ /**
7
+ * Returns the type of an expression, the one it will have during shader execution. That information can
8
+ * be used to introspect or specialize the shader. It will return `undefined` if the expression cannot
9
+ * be represented in shader code, or if the type is unknown at the point where the query is made.
10
+ *
11
+ * The returned value is only known at shader-generation time and has no WGSL representation, so it
12
+ * cannot be stored in a variable (e.g. `const t = std.typeOf(a)` throws). Consume it immediately,
13
+ * e.g. by comparing it (`std.typeOf(a) === d.f32`) or passing it to a comptime function.
14
+ *
15
+ * @example
16
+ * function double(value: number) {
17
+ * 'use gpu';
18
+ * if (std.typeOf(value) === d.f32) {
19
+ * return value * 2;
20
+ * }
21
+ * return value << 1;
22
+ * }
23
+ *
24
+ * function main() {
25
+ * 'use gpu';
26
+ * double(1.5); // generates double(f32), which multiplies by 2
27
+ * double(1); // generates double(i32), which shifts left by 1
28
+ * }
29
+ */
30
+ export declare const typeOf: TypeOf;
31
+ export {};
package/std/typeOf.js ADDED
@@ -0,0 +1,54 @@
1
+ import { isWgslData } from "../data/wgslTypes.js";
2
+ import { setName } from "../shared/meta.js";
3
+ import { $gpuCallable, $internal } from "../shared/symbols.js";
4
+ import { coerceToSnippet } from "../tgsl/generationHelpers.js";
5
+ /**
6
+ * Returns the type of an expression, the one it will have during shader execution. That information can
7
+ * be used to introspect or specialize the shader. It will return `undefined` if the expression cannot
8
+ * be represented in shader code, or if the type is unknown at the point where the query is made.
9
+ *
10
+ * The returned value is only known at shader-generation time and has no WGSL representation, so it
11
+ * cannot be stored in a variable (e.g. `const t = std.typeOf(a)` throws). Consume it immediately,
12
+ * e.g. by comparing it (`std.typeOf(a) === d.f32`) or passing it to a comptime function.
13
+ *
14
+ * @example
15
+ * function double(value: number) {
16
+ * 'use gpu';
17
+ * if (std.typeOf(value) === d.f32) {
18
+ * return value * 2;
19
+ * }
20
+ * return value << 1;
21
+ * }
22
+ *
23
+ * function main() {
24
+ * 'use gpu';
25
+ * double(1.5); // generates double(f32), which multiplies by 2
26
+ * double(1); // generates double(i32), which shifts left by 1
27
+ * }
28
+ */
29
+ export const typeOf = (() => {
30
+ const impl = (() => {
31
+ // Deducing the WGSL type of a value at comptime is near-impossible with
32
+ // the current comptime type flowing. We can lift this restriction once it
33
+ // becomes more capable.
34
+ throw new Error('std.typeOf() cannot be called in JS, it can only be used in the GPU context. You can use std.isBeingTranspiled() to branch off and provide a fallback.');
35
+ });
36
+ setName(impl, 'typeOf');
37
+ impl.toString = () => 'typeOf';
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);
50
+ };
51
+ // Mark as internal
52
+ Object.defineProperty(impl, $internal, { value: true });
53
+ return impl;
54
+ })();
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)}`);
package/tgpuLogger.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  declare const warningTypes: readonly ["deprecated", "suspicious", "fallback", "precision-loss", "implicit-conversion", "webgpu-feature-missing", "webgpu-limits-exceeded", "log-limit-exceeded", "external-omitted", "uniform-schema-misaligned"];
2
2
  type WarningType = (typeof warningTypes)[number];
3
3
  interface Logger {
4
+ /** Lets callers skip computing what a warning needs when it wouldn't be shown anyway. */
5
+ isEnabled(type: WarningType): boolean;
4
6
  warn(type: WarningType, ...args: unknown[]): void;
5
7
  warnOnce(type: WarningType, key: object, tag: string, ...args: unknown[]): void;
6
8
  }
@@ -26,6 +28,7 @@ export declare class TgpuLogger implements Logger, Warn {
26
28
  constructor(prod: boolean);
27
29
  disable(type: WarningType): void;
28
30
  reset(): void;
31
+ isEnabled(type: WarningType): boolean;
29
32
  warn(type: WarningType, ...args: unknown[]): void;
30
33
  warnOnce(type: WarningType, key: object, tag: string, ...args: unknown[]): void;
31
34
  }
package/tgpuLogger.js CHANGED
@@ -35,6 +35,9 @@ export class TgpuLogger {
35
35
  reset() {
36
36
  this.#enabledWarnings = new Set(this.#initialEnabledWarnings);
37
37
  }
38
+ isEnabled(type) {
39
+ return this.#enabledWarnings.has(type);
40
+ }
38
41
  warn(type, ...args) {
39
42
  if (this.#enabledWarnings.has(type)) {
40
43
  console.warn(`⚠️ [${type}] `, ...args);
@@ -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) {
@@ -1,13 +1,7 @@
1
1
  import type { TgpuMutable } from '../../core/buffer/bufferBinding.ts';
2
2
  import { type TgpuFn } from '../../core/function/tgpuFn.ts';
3
- import { type AnyWgslData, type Atomic, type U32, type Void, type WgslArray } from '../../data/wgslTypes.ts';
3
+ import { type AnyWgslData, type Atomic, type U32, type WgslArray } from '../../data/wgslTypes.ts';
4
4
  import type { LogGeneratorOptions, SerializedLogCallData } from './types.ts';
5
- type SerializerMap = {
6
- [K in AnyWgslData['type']]?: TgpuFn<(args_0: Extract<AnyWgslData, {
7
- type: K;
8
- }>) => Void>;
9
- };
10
- export declare const serializerMap: SerializerMap;
11
5
  /**
12
6
  * Creates a TGPU function that serializes data to the log buffer.
13
7
  *
@@ -18,4 +12,3 @@ export declare const serializerMap: SerializerMap;
18
12
  * @param logOptions - Configuration options
19
13
  */
20
14
  export declare function createLoggingFunction(id: number, dataTypes: AnyWgslData[], dataBuffer: TgpuMutable<WgslArray<SerializedLogCallData>>, indexBuffer: TgpuMutable<Atomic<U32>>, logOptions: Required<LogGeneratorOptions>): TgpuFn;
21
- export {};
@@ -7,111 +7,116 @@ import { sizeOf } from "../../data/sizeOf.js";
7
7
  import { vec2b, vec2f, vec2h, vec2i, vec2u, vec3b, vec3f, vec3h, vec3i, vec3u, vec4b, vec4f, vec4h, vec4i, vec4u, } from "../../data/vector.js";
8
8
  import { isWgslArray, isWgslStruct, } from "../../data/wgslTypes.js";
9
9
  import { getName } from "../../shared/meta.js";
10
- const dataBlockIndex = privateVar(u32, 0).$name('dataBlockIndex');
11
- const dataByteIndex = privateVar(u32, 0).$name('dataByteIndex');
12
- const dataBufferSlot = slot().$name('dataBuffer');
13
- const nextByteIndex = fn([], u32) `() {
10
+ /**
11
+ * The serializers are only needed when shaders log something, so they're created on first use
12
+ * instead of on import (creating them is not free, and most apps never log from shaders).
13
+ */
14
+ function createSerializerState() {
15
+ const dataBlockIndex = privateVar(u32, 0).$name('dataBlockIndex');
16
+ const dataByteIndex = privateVar(u32, 0).$name('dataByteIndex');
17
+ const dataBufferSlot = slot().$name('dataBuffer');
18
+ const nextByteIndex = fn([], u32) `() {
14
19
  let i = dataByteIndex;
15
20
  dataByteIndex = dataByteIndex + 1u;
16
21
  return i;
17
22
  }`
18
- .$uses({ dataByteIndex })
19
- .$name('nextByteIndex');
20
- const nextU32 = 'dataBuffer[dataBlockIndex].serializedData[nextByteIndex()]';
21
- export const serializerMap = {
22
- f32: fn([f32]) `(n) {
23
+ .$uses({ dataByteIndex })
24
+ .$name('nextByteIndex');
25
+ const nextU32 = 'dataBuffer[dataBlockIndex].serializedData[nextByteIndex()]';
26
+ const serializerMap = {
27
+ f32: fn([f32]) `(n) {
23
28
  ${nextU32} = bitcast<u32>(n);
24
29
  }`,
25
- f16: fn([f16]) `(n) {
30
+ f16: fn([f16]) `(n) {
26
31
  ${nextU32} = pack2x16float(vec2f(f32(n), 0.0));
27
32
  }`,
28
- i32: fn([i32]) `(n) {
33
+ i32: fn([i32]) `(n) {
29
34
  ${nextU32} = bitcast<u32>(n);
30
35
  }`,
31
- u32: fn([u32]) `(n) {
36
+ u32: fn([u32]) `(n) {
32
37
  ${nextU32} = n;
33
38
  }`,
34
- bool: fn([bool]) `(b) {
39
+ bool: fn([bool]) `(b) {
35
40
  ${nextU32} = u32(b);
36
41
  }`,
37
- vec2f: fn([vec2f]) `(v) {
42
+ vec2f: fn([vec2f]) `(v) {
38
43
  ${nextU32} = bitcast<u32>(v.x);
39
44
  ${nextU32} = bitcast<u32>(v.y);
40
45
  }`,
41
- vec3f: fn([vec3f]) `(v) {
46
+ vec3f: fn([vec3f]) `(v) {
42
47
  ${nextU32} = bitcast<u32>(v.x);
43
48
  ${nextU32} = bitcast<u32>(v.y);
44
49
  ${nextU32} = bitcast<u32>(v.z);
45
50
  }`,
46
- vec4f: fn([vec4f]) `(v) {
51
+ vec4f: fn([vec4f]) `(v) {
47
52
  ${nextU32} = bitcast<u32>(v.x);
48
53
  ${nextU32} = bitcast<u32>(v.y);
49
54
  ${nextU32} = bitcast<u32>(v.z);
50
55
  ${nextU32} = bitcast<u32>(v.w);
51
56
  }`,
52
- vec2h: fn([vec2h]) `(v) {
57
+ vec2h: fn([vec2h]) `(v) {
53
58
  ${nextU32} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
54
59
  }`,
55
- vec3h: fn([vec3h]) `(v) {
60
+ vec3h: fn([vec3h]) `(v) {
56
61
  ${nextU32} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
57
62
  ${nextU32} = pack2x16float(vec2f(f32(v.z), 0.0));
58
63
  }`,
59
- vec4h: fn([vec4h]) `(v) {
64
+ vec4h: fn([vec4h]) `(v) {
60
65
  ${nextU32} = pack2x16float(vec2f(f32(v.x), f32(v.y)));
61
66
  ${nextU32} = pack2x16float(vec2f(f32(v.z), f32(v.w)));
62
67
  }`,
63
- vec2i: fn([vec2i]) `(v) {
68
+ vec2i: fn([vec2i]) `(v) {
64
69
  ${nextU32} = bitcast<u32>(v.x);
65
70
  ${nextU32} = bitcast<u32>(v.y);
66
71
  }`,
67
- vec3i: fn([vec3i]) `(v) {
72
+ vec3i: fn([vec3i]) `(v) {
68
73
  ${nextU32} = bitcast<u32>(v.x);
69
74
  ${nextU32} = bitcast<u32>(v.y);
70
75
  ${nextU32} = bitcast<u32>(v.z);
71
76
  }`,
72
- vec4i: fn([vec4i]) `(v) {
77
+ vec4i: fn([vec4i]) `(v) {
73
78
  ${nextU32} = bitcast<u32>(v.x);
74
79
  ${nextU32} = bitcast<u32>(v.y);
75
80
  ${nextU32} = bitcast<u32>(v.z);
76
81
  ${nextU32} = bitcast<u32>(v.w);
77
82
  }`,
78
- vec2u: fn([vec2u]) `(v) {
83
+ vec2u: fn([vec2u]) `(v) {
79
84
  ${nextU32} = v.x;
80
85
  ${nextU32} = v.y;
81
86
  }`,
82
- vec3u: fn([vec3u]) `(v) {
87
+ vec3u: fn([vec3u]) `(v) {
83
88
  ${nextU32} = v.x;
84
89
  ${nextU32} = v.y;
85
90
  ${nextU32} = v.z;
86
91
  }`,
87
- vec4u: fn([vec4u]) `(v) {
92
+ vec4u: fn([vec4u]) `(v) {
88
93
  ${nextU32} = v.x;
89
94
  ${nextU32} = v.y;
90
95
  ${nextU32} = v.z;
91
96
  ${nextU32} = v.w;
92
97
  }`,
93
- 'vec2<bool>': fn([vec2b]) `(v) {
98
+ 'vec2<bool>': fn([vec2b]) `(v) {
94
99
  ${nextU32} = u32(v.x);
95
100
  ${nextU32} = u32(v.y);
96
101
  }`,
97
- 'vec3<bool>': fn([vec3b]) `(v) {
102
+ 'vec3<bool>': fn([vec3b]) `(v) {
98
103
  ${nextU32} = u32(v.x);
99
104
  ${nextU32} = u32(v.y);
100
105
  ${nextU32} = u32(v.z);
101
106
  }`,
102
- 'vec4<bool>': fn([vec4b]) `(v) {
107
+ 'vec4<bool>': fn([vec4b]) `(v) {
103
108
  ${nextU32} = u32(v.x);
104
109
  ${nextU32} = u32(v.y);
105
110
  ${nextU32} = u32(v.z);
106
111
  ${nextU32} = u32(v.w);
107
112
  }`,
108
- mat2x2f: fn([mat2x2f]) `(m) {
113
+ mat2x2f: fn([mat2x2f]) `(m) {
109
114
  ${nextU32} = bitcast<u32>(m[0][0]);
110
115
  ${nextU32} = bitcast<u32>(m[0][1]);
111
116
  ${nextU32} = bitcast<u32>(m[1][0]);
112
117
  ${nextU32} = bitcast<u32>(m[1][1]);
113
118
  }`,
114
- mat3x3f: fn([mat3x3f]) `(m) {
119
+ mat3x3f: fn([mat3x3f]) `(m) {
115
120
  ${nextU32} = bitcast<u32>(m[0][0]);
116
121
  ${nextU32} = bitcast<u32>(m[0][1]);
117
122
  ${nextU32} = bitcast<u32>(m[0][2]);
@@ -125,7 +130,7 @@ export const serializerMap = {
125
130
  ${nextU32} = bitcast<u32>(m[2][2]);
126
131
  ${nextU32} = 0u;
127
132
  }`,
128
- mat4x4f: fn([mat4x4f]) `(m) {
133
+ mat4x4f: fn([mat4x4f]) `(m) {
129
134
  ${nextU32} = bitcast<u32>(m[0][0]);
130
135
  ${nextU32} = bitcast<u32>(m[0][1]);
131
136
  ${nextU32} = bitcast<u32>(m[0][2]);
@@ -143,12 +148,21 @@ export const serializerMap = {
143
148
  ${nextU32} = bitcast<u32>(m[3][2]);
144
149
  ${nextU32} = bitcast<u32>(m[3][3]);
145
150
  }`,
146
- };
147
- // rename the functions and add externals
148
- for (const [name, serializer] of Object.entries(serializerMap)) {
149
- serializer
150
- .$name(`serialize${name[0].toLocaleUpperCase()}${name.slice(1)}`)
151
- .$uses({ dataBlockIndex, nextByteIndex, dataBuffer: dataBufferSlot });
151
+ };
152
+ // rename the functions and add externals
153
+ for (const [name, serializer] of Object.entries(serializerMap)) {
154
+ serializer
155
+ .$name(`serialize${name[0].toLocaleUpperCase()}${name.slice(1)}`)
156
+ .$uses({ dataBlockIndex, nextByteIndex, dataBuffer: dataBufferSlot });
157
+ }
158
+ return { dataBlockIndex, dataByteIndex, dataBufferSlot, serializerMap };
159
+ }
160
+ let serializerState;
161
+ function getSerializerState() {
162
+ if (!serializerState) {
163
+ serializerState = createSerializerState();
164
+ }
165
+ return serializerState;
152
166
  }
153
167
  // -------
154
168
  // Helpers
@@ -165,6 +179,7 @@ function generateHeader(argTypes) {
165
179
  * @param dataBuffer - A buffer to store serialized log call data (a necessary external for the returned function)
166
180
  */
167
181
  function getSerializer(dataType, dataBuffer) {
182
+ const { serializerMap, dataBufferSlot } = getSerializerState();
168
183
  const maybeSerializer = serializerMap[dataType.type];
169
184
  if (maybeSerializer) {
170
185
  return maybeSerializer.with(dataBufferSlot, dataBuffer);
@@ -221,6 +236,7 @@ export function createLoggingFunction(id, dataTypes, dataBuffer, indexBuffer, lo
221
236
  if (serializedSize > logOptions.logSizeLimit) {
222
237
  throw new Error(`Logged data needs to fit in ${logOptions.logSizeLimit} bytes (one of the logs requires ${serializedSize} bytes). Consider increasing the limit by passing appropriate options to tgpu.init().`);
223
238
  }
239
+ const { dataBlockIndex, dataByteIndex } = getSerializerState();
224
240
  const compoundSerializer = createCompoundSerializer(dataTypes, dataBuffer).$name(`log${id}serializer`);
225
241
  const header = generateHeader(dataTypes);
226
242
  return fn(dataTypes) `${header} {
@@ -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
  }