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
@@ -0,0 +1,33 @@
1
+ import type { TgpuRoot } from '../core/root/rootTypes.ts';
2
+ export interface AttachAutoResizerOptions {
3
+ root: TgpuRoot;
4
+ canvas: HTMLCanvasElement;
5
+ onResize?: (() => void) | undefined;
6
+ }
7
+ export interface AutoResizer {
8
+ detach: () => void;
9
+ }
10
+ /**
11
+ * Keeps the canvas' internal resolution (`canvas.width` and `canvas.height`) in sync with
12
+ * the physical size it takes up on the screen. The resolution is clamped to what the
13
+ * device supports.
14
+ *
15
+ * @param options.onResize Called right after the canvas has been resized. Changing the canvas
16
+ * resolution clears its contents, so this is a good place to re-render the frame, and to
17
+ * resize any resolution-dependent resources.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const autoResizer = common.attachAutoResizer({
22
+ * root,
23
+ * canvas,
24
+ * onResize() {
25
+ * render();
26
+ * },
27
+ * });
28
+ *
29
+ * // Later, when the canvas is no longer used
30
+ * autoResizer.detach();
31
+ * ```
32
+ */
33
+ export declare function attachAutoResizer({ root, canvas, onResize, }: AttachAutoResizerOptions): AutoResizer;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Returns the physical (device pixel) size of the observed element, falling back to
3
+ * the CSS size multiplied by the device pixel ratio when the browser does not report it.
4
+ */
5
+ function getPhysicalSize(entry) {
6
+ // Not every browser supports `devicePixelContentBoxSize` (e.g. Safari), despite what the types say.
7
+ const dpcb = entry.devicePixelContentBoxSize?.[0];
8
+ if (dpcb) {
9
+ return [dpcb.inlineSize, dpcb.blockSize];
10
+ }
11
+ const dpr = window.devicePixelRatio || 1;
12
+ // Older browsers expose `contentBoxSize` as a single object instead of an array.
13
+ const contentBoxSize = entry.contentBoxSize;
14
+ const cb = Array.isArray(contentBoxSize)
15
+ ? contentBoxSize[0]
16
+ : contentBoxSize;
17
+ if (cb) {
18
+ return [cb.inlineSize * dpr, cb.blockSize * dpr];
19
+ }
20
+ return [entry.contentRect.width * dpr, entry.contentRect.height * dpr];
21
+ }
22
+ function getMaxCanvasSize(root) {
23
+ try {
24
+ return root.device.limits.maxTextureDimension2D;
25
+ }
26
+ catch {
27
+ // Roots that are not backed by a WebGPU device (e.g. the WebGL fallback) don't expose
28
+ // device limits. Falling back to the minimum value guaranteed by WebGPU.
29
+ return 8192;
30
+ }
31
+ }
32
+ /**
33
+ * Keeps the canvas' internal resolution (`canvas.width` and `canvas.height`) in sync with
34
+ * the physical size it takes up on the screen. The resolution is clamped to what the
35
+ * device supports.
36
+ *
37
+ * @param options.onResize Called right after the canvas has been resized. Changing the canvas
38
+ * resolution clears its contents, so this is a good place to re-render the frame, and to
39
+ * resize any resolution-dependent resources.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const autoResizer = common.attachAutoResizer({
44
+ * root,
45
+ * canvas,
46
+ * onResize() {
47
+ * render();
48
+ * },
49
+ * });
50
+ *
51
+ * // Later, when the canvas is no longer used
52
+ * autoResizer.detach();
53
+ * ```
54
+ */
55
+ export function attachAutoResizer({ root, canvas, onResize, }) {
56
+ const maxSize = getMaxCanvasSize(root);
57
+ const observer = new ResizeObserver((entries) => {
58
+ for (const entry of entries) {
59
+ const [width, height] = getPhysicalSize(entry);
60
+ const target = entry.target;
61
+ target.width = Math.max(1, Math.min(Math.round(width), maxSize));
62
+ target.height = Math.max(1, Math.min(Math.round(height), maxSize));
63
+ onResize?.();
64
+ }
65
+ });
66
+ try {
67
+ observer.observe(canvas, { box: 'device-pixel-content-box' });
68
+ }
69
+ catch {
70
+ try {
71
+ observer.observe(canvas, { box: 'content-box' });
72
+ }
73
+ catch {
74
+ // The `box` option is not supported at all
75
+ observer.observe(canvas);
76
+ }
77
+ }
78
+ return {
79
+ detach: () => {
80
+ observer.disconnect();
81
+ },
82
+ };
83
+ }
package/common/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { fullScreenTriangle } from './fullScreenTriangle.ts';
2
2
  export { writeChannels } from './writeChannels.ts';
3
+ export { attachAutoResizer, type AutoResizer, type AttachAutoResizerOptions, } from './attachAutoResizer.ts';
3
4
  export { writeSoA } from './writeSoA.ts';
package/common/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // NOTE: This is a barrel file, internal files should not import things from this file
2
2
  export { fullScreenTriangle } from "./fullScreenTriangle.js";
3
3
  export { writeChannels } from "./writeChannels.js";
4
+ export { attachAutoResizer, } from "./attachAutoResizer.js";
4
5
  export { writeSoA } from "./writeSoA.js";
@@ -4,6 +4,7 @@ import { alignmentOf } from "../data/alignmentOf.js";
4
4
  import { undecorate } from "../data/dataTypes.js";
5
5
  import { offsetsForProps } from "../data/offsets.js";
6
6
  import { sizeOf } from "../data/sizeOf.js";
7
+ import { strideOf } from "../data/schemaMemoryLayout.js";
7
8
  import { isAtomic, isMat, isMat2x2f, isMat3x3f, isWgslArray } from "../data/wgslTypes.js";
8
9
  import { getName } from "../shared/meta.js";
9
10
  function packedSchemaOf(schema) {
@@ -44,7 +45,7 @@ function computeSoAByteLength(arraySchema, soaData) {
44
45
  if (inferredCount === undefined) {
45
46
  return undefined;
46
47
  }
47
- const elementStride = roundUp(sizeOf(structSchema), alignmentOf(structSchema));
48
+ const elementStride = strideOf(arraySchema);
48
49
  return inferredCount * elementStride;
49
50
  }
50
51
  function writePackedValue(target, schema, srcBytes, dstOffset, srcOffset) {
@@ -61,7 +62,7 @@ function writePackedValue(target, schema, srcBytes, dstOffset, srcOffset) {
61
62
  }
62
63
  if (isWgslArray(unpackedSchema)) {
63
64
  const packedElementSize = packedSizeOf(unpackedSchema.elementType);
64
- const gpuElementStride = roundUp(sizeOf(unpackedSchema.elementType), alignmentOf(unpackedSchema.elementType));
65
+ const gpuElementStride = strideOf(unpackedSchema);
65
66
  for (let i = 0; i < unpackedSchema.elementCount; i++) {
66
67
  writePackedValue(target, unpackedSchema.elementType, srcBytes, dstOffset + i * gpuElementStride, srcOffset + i * packedElementSize);
67
68
  }
@@ -71,7 +72,7 @@ function writePackedValue(target, schema, srcBytes, dstOffset, srcOffset) {
71
72
  }
72
73
  function scatterSoA(target, arraySchema, soaData, startOffset, endOffset) {
73
74
  const structSchema = arraySchema.elementType;
74
- const elementStride = roundUp(sizeOf(structSchema), alignmentOf(structSchema));
75
+ const elementStride = strideOf(arraySchema);
75
76
  invariant(startOffset % elementStride === 0, `startOffset (${startOffset}) must be aligned to the element stride (${elementStride})`);
76
77
  const startElement = Math.floor(startOffset / elementStride);
77
78
  const endElement = Math.min(arraySchema.elementCount, Math.ceil(endOffset / elementStride));
@@ -18,7 +18,7 @@ export interface CommandEncoderInternals {
18
18
  *
19
19
  * @example
20
20
  * ```ts
21
- * const encoder = root['~unstable'].createCommandEncoder();
21
+ * const encoder = root.createCommandEncoder();
22
22
  * const pass = encoder.beginRenderPass({
23
23
  * colorAttachments: [{ view: msaaTexture, resolveTarget: context }],
24
24
  * });
@@ -1,12 +1,15 @@
1
- import { type ResolvedSnippet } from '../../data/snippet.ts';
2
- import { $internal, $resolve } from '../../shared/symbols.ts';
3
- import type { ResolutionCtx, SelfResolvable } from '../../types.ts';
1
+ import { Void } from '../../data/wgslTypes.ts';
2
+ import { $gpuValueOf, $internal } from '../../shared/symbols.ts';
3
+ import type { InferGPU } from '../../data/index.ts';
4
4
  /**
5
5
  * Extra declaration that shall be included in final WGSL code,
6
6
  * when resolving objects that use it.
7
7
  */
8
8
  export interface TgpuDeclare {
9
+ readonly [$internal]: true;
9
10
  $uses(dependencyMap: Record<string, unknown>): this;
11
+ readonly $: InferGPU<Void>;
12
+ readonly [$gpuValueOf]: InferGPU<Void>;
10
13
  }
11
14
  /**
12
15
  * Allows defining extra declarations that shall be included in the final WGSL code,
@@ -16,11 +19,11 @@ export interface TgpuDeclare {
16
19
  * It was developed to ensure full compatibility of TypeGPU programs with current and future versions of WGSL.
17
20
  */
18
21
  export declare function declare(declaration: string): TgpuDeclare;
19
- export declare class TgpuDeclareImpl implements TgpuDeclare, SelfResolvable {
22
+ export declare class TgpuDeclareImpl implements TgpuDeclare {
20
23
  #private;
21
- readonly [$internal] = true;
22
24
  constructor(declaration: string);
25
+ [$internal]: true;
26
+ $: InferGPU<Void>;
27
+ readonly [$gpuValueOf]: InferGPU<Void>;
23
28
  $uses(dependencyMap: Record<string, unknown>): this;
24
- [$resolve](ctx: ResolutionCtx): ResolvedSnippet;
25
- toString(): string;
26
29
  }
@@ -1,7 +1,9 @@
1
1
  import { snip } from "../../data/snippet.js";
2
2
  import { Void } from "../../data/wgslTypes.js";
3
- import { $internal, $resolve } from "../../shared/symbols.js";
3
+ import { $gpuValueOf, $internal } from "../../shared/symbols.js";
4
4
  import { replaceExternalsInWgsl } from "../resolve/externals.js";
5
+ import { makeDereferenceable } from "../../tgsl/makeDereferenceable.js";
6
+ import { makeResolvable } from "../../tgsl/makeResolvable.js";
5
7
  /**
6
8
  * Allows defining extra declarations that shall be included in the final WGSL code,
7
9
  * when resolving objects that use them.
@@ -16,12 +18,33 @@ export function declare(declaration) {
16
18
  // Implementation
17
19
  // --------------
18
20
  export class TgpuDeclareImpl {
19
- [$internal] = true;
20
21
  #externals;
21
22
  #declaration;
22
23
  constructor(declaration) {
23
24
  this.#declaration = declaration;
24
25
  }
26
+ static {
27
+ TgpuDeclareImpl.prototype[$internal] = true;
28
+ makeDereferenceable(makeResolvable(TgpuDeclareImpl.prototype, {
29
+ asString() {
30
+ return `declare: ${this.#declaration}`;
31
+ },
32
+ resolve(ctx) {
33
+ const replacedDeclaration = replaceExternalsInWgsl(ctx, this.#externals ?? {}, this.#declaration);
34
+ ctx.addDeclaration(replacedDeclaration);
35
+ return snip('', Void, /* origin */ 'constant');
36
+ },
37
+ }), {
38
+ codegenMode: {
39
+ getBaseSnippet(trackingProxy) {
40
+ return snip(trackingProxy, Void,
41
+ /* origin */ 'constant',
42
+ /* possibleSideEffects */ false);
43
+ },
44
+ },
45
+ normalMode: { get() { } },
46
+ });
47
+ }
25
48
  $uses(dependencyMap) {
26
49
  if (this.#externals !== undefined) {
27
50
  throw new Error("Cannot call '$uses' multiple times. If you wish to override dependencies, use slots or accessors instead.");
@@ -29,12 +52,4 @@ export class TgpuDeclareImpl {
29
52
  this.#externals = dependencyMap;
30
53
  return this;
31
54
  }
32
- [$resolve](ctx) {
33
- const replacedDeclaration = replaceExternalsInWgsl(ctx, this.#externals ?? {}, this.#declaration);
34
- ctx.addDeclaration(replacedDeclaration);
35
- return snip('', Void, /* origin */ 'constant');
36
- }
37
- toString() {
38
- return `declare: ${this.#declaration}`;
39
- }
40
55
  }
@@ -3,9 +3,11 @@ import { $getNameForward, $internal } from '../../shared/symbols.ts';
3
3
  import { type DualFn } from '../../types.ts';
4
4
  type AnyFn = (...args: never[]) => unknown;
5
5
  export type TgpuComptime<T extends AnyFn = AnyFn> = DualFn<T> & TgpuNamable & {
6
+ toString(): string;
6
7
  [$getNameForward]: unknown;
7
8
  [$internal]: {
8
9
  isComptime: true;
10
+ func: T;
9
11
  };
10
12
  };
11
13
  export declare function isComptimeFn(value: unknown): value is TgpuComptime;
@@ -35,32 +35,37 @@ export function comptime(func) {
35
35
  const impl = ((...args) => {
36
36
  return func(...args);
37
37
  });
38
- impl.toString = () => 'comptime';
38
+ Object.setPrototypeOf(impl, ComptimePrototype);
39
39
  impl[$getNameForward] = func;
40
- impl[$gpuCallable] = {
41
- call(ctx, args) {
42
- const comptimeArgs = args.map((s) => asComptime(s));
43
- if (!comptimeArgs.every((s) => s !== undefined)) {
44
- throw new WgslTypeError(`Called comptime function with runtime-known values: ${args
45
- .filter((_, idx) => comptimeArgs[idx] === undefined)
46
- .map((s) => `'${stringifySnippet(s)}'`)
47
- .join(', ')}`);
48
- }
49
- ctx.pushMode(new NormalState());
50
- try {
51
- return coerceToSnippet(func(...comptimeArgs.map((s) => s.value)));
52
- }
53
- finally {
54
- ctx.popMode();
55
- }
56
- },
57
- };
58
- impl.$name = (label) => {
59
- setName(func, label);
60
- return impl;
61
- };
62
40
  Object.defineProperty(impl, $internal, {
63
- value: { isComptime: true },
41
+ value: { isComptime: true, func },
64
42
  });
65
43
  return impl;
66
44
  }
45
+ const ComptimePrototype = {
46
+ toString() {
47
+ return 'comptime';
48
+ },
49
+ $name(label) {
50
+ setName(this[$internal].func, label);
51
+ return this;
52
+ },
53
+ [$gpuCallable](ctx, args) {
54
+ const comptimeArgs = args.map((s) => asComptime(s));
55
+ if (!comptimeArgs.every((s) => s !== undefined)) {
56
+ throw new WgslTypeError(`Called comptime function with runtime-known values: ${args
57
+ .filter((_, idx) => comptimeArgs[idx] === undefined)
58
+ .map((s) => `'${stringifySnippet(s)}'`)
59
+ .join(', ')}`);
60
+ }
61
+ ctx.pushMode(new NormalState());
62
+ try {
63
+ return coerceToSnippet(this[$internal].func.apply(undefined, comptimeArgs.map((s) => s.value)));
64
+ }
65
+ finally {
66
+ ctx.popMode();
67
+ }
68
+ },
69
+ };
70
+ // Comptime functions are still functions, so they should keep `call`, `apply`, `bind`, etc.
71
+ Object.setPrototypeOf(ComptimePrototype, Function.prototype);
@@ -10,46 +10,41 @@ export function callableSchema(options) {
10
10
  });
11
11
  setName(impl, options.name);
12
12
  impl.toString = () => options.name;
13
- impl[$gpuCallable] = {
14
- get strictSignature() {
15
- return undefined;
16
- },
17
- call(ctx, args) {
18
- const argTypes = options.argTypes(...args.map((s) => {
19
- // Dereference implicit pointers
20
- if (isPtr(s.dataType) && s.dataType.implicit) {
21
- return s.dataType.inner;
22
- }
23
- return s.dataType;
24
- }));
25
- const converted = args.map((s, idx) => {
26
- const argType = argTypes[idx];
27
- if (!argType) {
28
- throw new Error('Function called with invalid arguments');
29
- }
30
- return tryConvertSnippet(ctx, s, argType, false);
31
- });
32
- let result;
33
- const comptimeArgs = converted.map((s) => asComptime(s));
34
- if (comptimeArgs.every((s) => s !== undefined)) {
35
- ctx.pushMode(new NormalState());
36
- try {
37
- result = snip(options.normalImpl(...comptimeArgs.map((s) => s.value)), options.schema(),
38
- // Functions give up ownership of their return value
39
- /* origin */ 'constant');
40
- }
41
- finally {
42
- ctx.popMode('normal');
43
- }
13
+ impl[$gpuCallable] = (ctx, args) => {
14
+ const argTypes = options.argTypes(...args.map((s) => {
15
+ // Dereference implicit pointers
16
+ if (isPtr(s.dataType) && s.dataType.implicit) {
17
+ return s.dataType.inner;
44
18
  }
45
- else {
46
- result = options.codegenImpl(ctx, converted);
19
+ return s.dataType;
20
+ }));
21
+ const converted = args.map((s, idx) => {
22
+ const argType = argTypes[idx];
23
+ if (!argType) {
24
+ throw new Error('Function called with invalid arguments');
47
25
  }
48
- if (!args.some((a) => a.possibleSideEffects)) {
49
- return noSideEffects(result);
26
+ return tryConvertSnippet(ctx, s, argType, false);
27
+ });
28
+ let result;
29
+ const comptimeArgs = converted.map((s) => asComptime(s));
30
+ if (comptimeArgs.every((s) => s !== undefined)) {
31
+ ctx.pushMode(new NormalState());
32
+ try {
33
+ result = snip(options.normalImpl(...comptimeArgs.map((s) => s.value)), options.schema(),
34
+ // Functions give up ownership of their return value
35
+ /* origin */ 'constant');
50
36
  }
51
- return result;
52
- },
37
+ finally {
38
+ ctx.popMode('normal');
39
+ }
40
+ }
41
+ else {
42
+ result = options.codegenImpl(ctx, converted);
43
+ }
44
+ if (!args.some((a) => a.possibleSideEffects)) {
45
+ return noSideEffects(result);
46
+ }
47
+ return result;
53
48
  };
54
49
  return impl;
55
50
  }
@@ -1,6 +1,6 @@
1
1
  import { snip } from "../../data/snippet.js";
2
2
  import { setName } from "../../shared/meta.js";
3
- import { $gpuCallable } from "../../shared/symbols.js";
3
+ import { $gpuCallable, $gpuCallableStrictSignature } from "../../shared/symbols.js";
4
4
  import { tryConvertSnippet } from "../../tgsl/conversion.js";
5
5
  import { concretize } from "../../tgsl/generationHelpers.js";
6
6
  import { asComptime, NormalState } from "../../types.js";
@@ -23,55 +23,55 @@ export function dualImpl(options) {
23
23
  setName(impl, options.name);
24
24
  }
25
25
  impl.toString = () => options.name ?? '<unknown>';
26
- impl[$gpuCallable] = {
27
- get strictSignature() {
26
+ Object.defineProperty(impl, $gpuCallableStrictSignature, {
27
+ get() {
28
28
  return typeof options.signature !== 'function' ? options.signature : undefined;
29
29
  },
30
- call(ctx, args) {
31
- const { argTypes, returnType } = typeof options.signature === 'function'
32
- ? options.signature(...args.map((s) => {
33
- // Dereference implicit pointers
34
- if (isPtr(s.dataType) && s.dataType.implicit) {
35
- return s.dataType.inner;
36
- }
37
- return s.dataType;
38
- }))
39
- : options.signature;
40
- const converted = args.map((s, idx) => {
41
- const argType = argTypes[idx];
42
- if (!argType) {
43
- throw new Error('Function called with invalid arguments');
30
+ });
31
+ impl[$gpuCallable] = (ctx, args) => {
32
+ const { argTypes, returnType } = typeof options.signature === 'function'
33
+ ? options.signature(...args.map((s) => {
34
+ // Dereference implicit pointers
35
+ if (isPtr(s.dataType) && s.dataType.implicit) {
36
+ return s.dataType.inner;
44
37
  }
45
- return tryConvertSnippet(ctx, s, argType, !options.ignoreImplicitCastWarning);
46
- });
47
- if (!options.noComptime && typeof options.normalImpl === 'function') {
48
- const comptimeArgs = converted.map((s) => asComptime(s));
49
- if (comptimeArgs.every((s) => s !== undefined)) {
50
- ctx.pushMode(new NormalState());
51
- try {
52
- return snip(options.normalImpl(...comptimeArgs.map((s) => s.value)), returnType,
53
- // Functions give up ownership of their return value
54
- /* origin */ 'constant', options.sideEffects);
55
- }
56
- catch (e) {
57
- // cpuImpl may in some cases be present but implemented only partially.
58
- // In that case, if the MissingCpuImplError is thrown, we fallback to codegenImpl.
59
- // If it is any other error, we just rethrow.
60
- if (!(e instanceof MissingCpuImplError)) {
61
- throw e;
62
- }
63
- }
64
- finally {
65
- ctx.popMode('normal');
38
+ return s.dataType;
39
+ }))
40
+ : options.signature;
41
+ const converted = args.map((s, idx) => {
42
+ const argType = argTypes[idx];
43
+ if (!argType) {
44
+ throw new Error('Function called with invalid arguments');
45
+ }
46
+ return tryConvertSnippet(ctx, s, argType, !options.ignoreImplicitCastWarning);
47
+ });
48
+ if (!options.noComptime && typeof options.normalImpl === 'function') {
49
+ const comptimeArgs = converted.map((s) => asComptime(s));
50
+ if (comptimeArgs.every((s) => s !== undefined)) {
51
+ ctx.pushMode(new NormalState());
52
+ try {
53
+ return snip(options.normalImpl(...comptimeArgs.map((s) => s.value)), returnType,
54
+ // Functions give up ownership of their return value
55
+ /* origin */ 'constant', options.sideEffects);
56
+ }
57
+ catch (e) {
58
+ // cpuImpl may in some cases be present but implemented only partially.
59
+ // In that case, if the MissingCpuImplError is thrown, we fallback to codegenImpl.
60
+ // If it is any other error, we just rethrow.
61
+ if (!(e instanceof MissingCpuImplError)) {
62
+ throw e;
66
63
  }
67
64
  }
65
+ finally {
66
+ ctx.popMode('normal');
67
+ }
68
68
  }
69
- const possibleSideEffects = options.sideEffects || args.some((a) => a.possibleSideEffects);
70
- const concreteReturnType = concretize(returnType);
71
- return snip(options.codegenImpl(ctx, converted, concreteReturnType), concreteReturnType,
72
- // Functions give up ownership of their return value
73
- /* origin */ 'runtime', possibleSideEffects);
74
- },
69
+ }
70
+ const possibleSideEffects = options.sideEffects || args.some((a) => a.possibleSideEffects);
71
+ const concreteReturnType = concretize(returnType);
72
+ return snip(options.codegenImpl(ctx, converted, concreteReturnType), concreteReturnType,
73
+ // Functions give up ownership of their return value
74
+ /* origin */ 'runtime', possibleSideEffects);
75
75
  };
76
76
  return impl;
77
77
  }
@@ -33,9 +33,6 @@ export interface TgpuComputeFn<ComputeIn extends IORecord<AnyComputeBuiltin> = a
33
33
  readonly shell: TgpuComputeFnShellHeader<ComputeIn>;
34
34
  $uses(dependencyMap: Record<string, unknown>): this;
35
35
  }
36
- export interface ComputeFnOptions {
37
- workgroupSize: number[];
38
- }
39
36
  export declare function computeFn(options: {
40
37
  workgroupSize: number[];
41
38
  }): TgpuComputeFnShell<{}>;
@@ -28,12 +28,12 @@ export function fn(argTypesOrCallback, returnType) {
28
28
  return Object.assign(call, shell);
29
29
  }
30
30
  export function isTgpuFn(value) {
31
- return (isMarkedInternal(value) &&
32
- value?.resourceType === 'function');
31
+ return (value?.resourceType === 'function' &&
32
+ isMarkedInternal(value));
33
33
  }
34
34
  export function isGenericFn(value) {
35
- return (isMarkedInternal(value) &&
36
- value?.resourceType === 'generic-function');
35
+ return (value?.resourceType === 'generic-function' &&
36
+ isMarkedInternal(value));
37
37
  }
38
38
  // --------------
39
39
  // Implementation
@@ -47,7 +47,7 @@ export interface TgpuFragmentFnShell<out TIn extends TgpuFragmentFn.In = TgpuFra
47
47
  (implementation: string): TgpuFragmentFn<CleanIO<TIn>, CleanIO<TOut>>;
48
48
  (strings: TemplateStringsArray, ...values: unknown[]): TgpuFragmentFn<CleanIO<TIn>, CleanIO<TOut>>;
49
49
  }
50
- export interface TgpuFragmentFn<in Varying extends TgpuFragmentFn.In = Record<string, never>, out Output extends TgpuFragmentFn.Out = TgpuFragmentFn.Out> extends TgpuNamable {
50
+ export interface TgpuFragmentFn<in Varying extends TgpuFragmentFn.In = never, out Output extends TgpuFragmentFn.Out = TgpuFragmentFn.Out> extends TgpuNamable {
51
51
  readonly [$internal]: true;
52
52
  readonly shell: TgpuFragmentFnShellHeader<Varying, Output>;
53
53
  readonly outputType: IOLayoutToSchema<Output>;
@@ -33,7 +33,7 @@ export interface TgpuVertexFnShell<out TIn extends TgpuVertexFn.In, out TOut ext
33
33
  (implementation: string): TgpuVertexFn<CleanIO<TIn>, CleanIO<TOut>>;
34
34
  (strings: TemplateStringsArray, ...values: unknown[]): TgpuVertexFn<CleanIO<TIn>, CleanIO<TOut>>;
35
35
  }
36
- export interface TgpuVertexFn<in VertexIn extends TgpuVertexFn.In = Record<string, never>, out VertexOut extends TgpuVertexFn.Out = TgpuVertexFn.Out> extends TgpuNamable {
36
+ export interface TgpuVertexFn<in VertexIn extends TgpuVertexFn.In = never, out VertexOut extends TgpuVertexFn.Out = TgpuVertexFn.Out> extends TgpuNamable {
37
37
  readonly [$internal]: true;
38
38
  readonly shell: TgpuVertexFnShellHeader<VertexIn, VertexOut>;
39
39
  $uses(dependencyMap: Record<string, unknown>): this;
@@ -131,7 +131,7 @@ export function requireIndexBuffer(indexBuffer) {
131
131
  }
132
132
  }
133
133
  function warnAboutUnreachableSubmission(core, what) {
134
- logger.warnOnce('suspicious', core, what, `${what} is ignored when recording into a raw GPUCommandEncoder, since there is no submission to report after. Use root['~unstable'].createCommandEncoder() instead.`);
134
+ logger.warnOnce('suspicious', core, what, `${what} is ignored when recording into a raw GPUCommandEncoder, since there is no submission to report after. Use root.createCommandEncoder() instead.`);
135
135
  }
136
136
  /** Returns false when there is no encoder to defer the read to, meaning the output is lost */
137
137
  function queueLogDrain(encoder, logResources) {
@@ -1,6 +1,7 @@
1
1
  import { alignmentOf } from "../../data/alignmentOf.js";
2
2
  import { memoryLayoutOf } from "../../data/offsetUtils.js";
3
3
  import { sizeOf } from "../../data/sizeOf.js";
4
+ import { strideOf } from "../../data/schemaMemoryLayout.js";
4
5
  import { isWgslArray, isWgslStruct } from "../../data/wgslTypes.js";
5
6
  import { invariant } from "../../errors.js";
6
7
  import { roundUp } from "../../mathUtils.js";
@@ -43,7 +44,7 @@ export function warnIfNotUniformAligned(schema) {
43
44
  function checkUniformAlignment(schema) {
44
45
  if (isWgslArray(schema)) {
45
46
  checkUniformAlignment(schema.elementType);
46
- const stride = roundUp(sizeOf(schema.elementType), alignmentOf(schema.elementType));
47
+ const stride = strideOf(schema);
47
48
  if (stride % 16 !== 0) {
48
49
  logger.warn('uniform-schema-misaligned', `\
49
50
  Schema '${getName(schema.elementType) ?? '<unnamed>'}' is used in an array in a uniform buffer, and its stride (${stride}) is not a multiple of 16.
@@ -11,6 +11,10 @@ function isResolvable(value) {
11
11
  */
12
12
  export function mergeFunctionExternals(fnExternals) {
13
13
  const base = fnExternals.pluginProvided ?? fnExternals.userProvided ?? {};
14
+ if (fnExternals.args === undefined && fnExternals.out === undefined) {
15
+ // Nothing to merge in, and consumers never mutate the map
16
+ return base;
17
+ }
14
18
  // avoid calling any of the getters
15
19
  const result = Object.defineProperties({}, Object.getOwnPropertyDescriptors(base));
16
20
  for (const flatExternal of [fnExternals.args, fnExternals.out].filter((e) => e !== undefined)) {
@@ -4,6 +4,10 @@ import { ShelllessRepository } from '../../tgsl/shellless.ts';
4
4
  import type { TgpuLazy, TgpuSlot } from '../slot/slotTypes.ts';
5
5
  type SlotToValueMap = Map<TgpuSlot<unknown>, unknown>;
6
6
  export interface NamespaceInternal {
7
+ /**
8
+ * Global identifiers taken by resolved items. Reserved WGSL words are checked separately,
9
+ * so that creating a namespace doesn't have to copy them.
10
+ */
7
11
  readonly takenGlobalIdentifiers: Set<string>;
8
12
  readonly shelllessRepo: ShelllessRepository;
9
13
  readonly strategy: 'random' | 'strict';
@@ -1,4 +1,3 @@
1
- import { bannedTokens, builtins, templateEnumerants } from "../../nameUtils.js";
2
1
  import { $internal } from "../../shared/symbols.js";
3
2
  import { ShelllessRepository } from "../../tgsl/shellless.js";
4
3
  class NamespaceImpl {
@@ -6,7 +5,7 @@ class NamespaceImpl {
6
5
  constructor(strategy) {
7
6
  this[$internal] = {
8
7
  strategy,
9
- takenGlobalIdentifiers: new Set([...bannedTokens, ...builtins, ...templateEnumerants]),
8
+ takenGlobalIdentifiers: new Set(),
10
9
  shelllessRepo: new ShelllessRepository(),
11
10
  memoizedResolves: new WeakMap(),
12
11
  memoizedLazy: new WeakMap(),