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
@@ -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) {
@@ -56,6 +56,7 @@ export function INTERNAL_restoreRenderPipeline(soul, ctx) {
56
56
  }
57
57
  class TgpuRenderPipelineImpl {
58
58
  [$internal];
59
+ #unbound;
59
60
  [$soul];
60
61
  resourceType = 'render-pipeline';
61
62
  [$getNameForward];
@@ -110,7 +111,9 @@ class TgpuRenderPipelineImpl {
110
111
  with(first, resource) {
111
112
  const internals = this[$internal];
112
113
  if (isTgpuRenderCommands(first)) {
113
- return this.#withPriors({ pass: first, encoder: undefined });
114
+ const bound = this.#withPriors({ pass: first, encoder: undefined });
115
+ bound.#unbound = this.#unbound ?? this;
116
+ return bound;
114
117
  }
115
118
  if (isTgpuCommandEncoder(first)) {
116
119
  return this.#withPriors({ pass: undefined, encoder: first });
@@ -235,7 +238,7 @@ class TgpuRenderPipelineImpl {
235
238
  #execute(usesIndexBuffer, emit) {
236
239
  const { core, priors, root } = this[$internal];
237
240
  if (priors.pass) {
238
- emitRenderDraw(root, priors.pass[$internal], this, usesIndexBuffer, emit);
241
+ emitRenderDraw(root, priors.pass[$internal], this.#unbound ?? this, usesIndexBuffer, emit);
239
242
  return;
240
243
  }
241
244
  // checked up front so a rejected draw never leaves a half-recorded pass behind
@@ -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";
@@ -34,9 +35,16 @@ function requiredAlignOf(schema) {
34
35
  * See https://www.w3.org/TR/WGSL/#address-space-layout-constraints
35
36
  */
36
37
  export function warnIfNotUniformAligned(schema) {
38
+ if (!logger.isEnabled('uniform-schema-misaligned')) {
39
+ // Silenced by default in production, and computing memory layouts isn't free
40
+ return;
41
+ }
42
+ checkUniformAlignment(schema);
43
+ }
44
+ function checkUniformAlignment(schema) {
37
45
  if (isWgslArray(schema)) {
38
- warnIfNotUniformAligned(schema.elementType);
39
- const stride = roundUp(sizeOf(schema.elementType), alignmentOf(schema.elementType));
46
+ checkUniformAlignment(schema.elementType);
47
+ const stride = strideOf(schema);
40
48
  if (stride % 16 !== 0) {
41
49
  logger.warn('uniform-schema-misaligned', `\
42
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.
@@ -45,7 +53,7 @@ To address this, put the element schema in a struct and wrap the prop in 'd.alig
45
53
  }
46
54
  }
47
55
  if (isWgslStruct(schema)) {
48
- Object.values(schema.propTypes).forEach(warnIfNotUniformAligned);
56
+ Object.values(schema.propTypes).forEach(checkUniformAlignment);
49
57
  Object.entries(schema.propTypes).forEach(([key, value]) => {
50
58
  const offset = memoryLayoutOf(schema, (schema) => schema[key]).offset;
51
59
  const requiredAlignment = requiredAlignOf(value);
@@ -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(),
@@ -1,26 +1,31 @@
1
1
  import { isSnippet } from "../../data/snippet.js";
2
2
  import { getResolutionCtx } from "../../execMode.js";
3
+ function resolvePart(ctx, part) {
4
+ return isSnippet(part) ? ctx.resolveSnippet(part).value : part;
5
+ }
3
6
  /**
4
7
  * "The reverse of snipping"
5
8
  * Injects resolved snippets into a template string.
6
9
  */
7
10
  export function stitch(strings, ...snippets) {
8
11
  const ctx = getResolutionCtx();
9
- function resolveSnippet(maybeSnippet) {
10
- return isSnippet(maybeSnippet) ? ctx.resolveSnippet(maybeSnippet).value : maybeSnippet;
11
- }
12
12
  let result = '';
13
13
  for (let i = 0; i < strings.length; ++i) {
14
14
  result += strings[i];
15
15
  const snippet = snippets[i];
16
16
  if (Array.isArray(snippet)) {
17
- result += snippet
18
- .filter((s) => s !== undefined)
19
- .map(resolveSnippet)
20
- .join(', ');
17
+ // Joining the defined elements with ', '
18
+ let first = true;
19
+ for (const element of snippet) {
20
+ if (element === undefined) {
21
+ continue;
22
+ }
23
+ result += (first ? '' : ', ') + resolvePart(ctx, element);
24
+ first = false;
25
+ }
21
26
  }
22
27
  else if (snippet) {
23
- result += resolveSnippet(snippet);
28
+ result += resolvePart(ctx, snippet);
24
29
  }
25
30
  }
26
31
  return result;
@@ -1,5 +1,5 @@
1
1
  import { type TgpuQuerySet } from '../querySet/querySet.ts';
2
- import type { v3u, Vec3u } from '../../data/wgslTypes.ts';
2
+ import type { v3u } from '../../data/wgslTypes.ts';
3
3
  import { $getNameForward, $internal, $soul } from '../../shared/symbols.ts';
4
4
  import type { TgpuBindGroup } from '../../tgpuBindGroupLayout.ts';
5
5
  import type { LogGeneratorOptions } from '../../tgsl/consoleLog/types.ts';
@@ -12,7 +12,7 @@ export declare class TgpuGuardedComputePipelineImpl<TArgs extends number[]> impl
12
12
  #private;
13
13
  readonly resourceType = "guarded-compute-pipeline";
14
14
  readonly [$soul]: TgpuGuardedComputePipelineSoul;
15
- constructor(root: ExperimentalTgpuRoot, pipeline: TgpuComputePipeline, sizeUniform: TgpuUniform<Vec3u>, workgroupSize: v3u);
15
+ constructor(root: ExperimentalTgpuRoot, pipeline: TgpuComputePipeline, size: TgpuGuardedComputePipelineSoul['size'], workgroupSize: v3u);
16
16
  with(bindGroup: TgpuBindGroup): TgpuGuardedComputePipeline<TArgs>;
17
17
  withPerformanceCallback(callback: (start: bigint, end: bigint) => void | Promise<void>): TgpuGuardedComputePipeline<TArgs>;
18
18
  withTimestampWrites(options: {
@@ -24,7 +24,7 @@ export declare class TgpuGuardedComputePipelineImpl<TArgs extends number[]> impl
24
24
  initAsync(): Promise<void>;
25
25
  initSync(): void;
26
26
  get pipeline(): TgpuComputePipeline;
27
- get sizeUniform(): TgpuUniform<Vec3u>;
27
+ get sizeUniform(): TgpuUniform<import("../../data/wgslTypes.ts").Vec3u>;
28
28
  [$internal]: boolean;
29
29
  get [$getNameForward](): TgpuComputePipeline;
30
30
  $name(label: string): this;
package/core/root/init.js CHANGED
@@ -44,15 +44,13 @@ export class TgpuGuardedComputePipelineImpl {
44
44
  resourceType = 'guarded-compute-pipeline';
45
45
  [$soul];
46
46
  #root;
47
- #lastSize;
48
- constructor(root, pipeline, sizeUniform, workgroupSize) {
47
+ constructor(root, pipeline, size, workgroupSize) {
49
48
  this.#root = root;
50
- this.#lastSize = vec3u();
51
49
  this[$soul] = {
52
50
  type: 'guarded-compute-pipeline',
53
51
  device: root.device,
54
52
  pipeline,
55
- sizeUniform,
53
+ size,
56
54
  workgroupSize,
57
55
  label: undefined,
58
56
  };
@@ -61,22 +59,23 @@ export class TgpuGuardedComputePipelineImpl {
61
59
  if (!isBindGroup(bindGroup)) {
62
60
  throw new Error('Guarded pipelines only accept bind groups in .with(). To record into passes or encoders, use a regular compute pipeline.');
63
61
  }
64
- return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.with(bindGroup), this[$soul].sizeUniform, this[$soul].workgroupSize);
62
+ return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.with(bindGroup), this[$soul].size, this[$soul].workgroupSize);
65
63
  }
66
64
  withPerformanceCallback(callback) {
67
- return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.withPerformanceCallback(callback), this[$soul].sizeUniform, this[$soul].workgroupSize);
65
+ return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.withPerformanceCallback(callback), this[$soul].size, this[$soul].workgroupSize);
68
66
  }
69
67
  withTimestampWrites(options) {
70
- return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.withTimestampWrites(options), this[$soul].sizeUniform, this[$soul].workgroupSize);
68
+ return new TgpuGuardedComputePipelineImpl(this.#root, this[$soul].pipeline.withTimestampWrites(options), this[$soul].size, this[$soul].workgroupSize);
71
69
  }
72
70
  dispatchThreads(...threads) {
73
71
  const sanitizedSize = toVec3(threads);
74
72
  const workgroupCount = ceil(vec3f(sanitizedSize).div(vec3f(this[$soul].workgroupSize)));
75
- if (!allEq(sanitizedSize, this.#lastSize)) {
73
+ const { size } = this[$soul];
74
+ if (!allEq(sanitizedSize, size.lastValue)) {
76
75
  // Only updating the size if it has changed from the last
77
76
  // invocation. This removes the need for flushing.
78
- this.#lastSize = sanitizedSize;
79
- this[$soul].sizeUniform.write(sanitizedSize);
77
+ size.lastValue = sanitizedSize;
78
+ size.uniform.write(sanitizedSize);
80
79
  }
81
80
  this[$soul].pipeline.dispatchWorkgroups(workgroupCount.x, workgroupCount.y, workgroupCount.z);
82
81
  }
@@ -90,7 +89,7 @@ export class TgpuGuardedComputePipelineImpl {
90
89
  return this[$soul].pipeline;
91
90
  }
92
91
  get sizeUniform() {
93
- return this[$soul].sizeUniform;
92
+ return this[$soul].size.uniform;
94
93
  }
95
94
  [$internal] = true;
96
95
  get [$getNameForward]() {
@@ -105,7 +104,7 @@ export function INTERNAL_restoreRoot(soul, ctx) {
105
104
  return ctx.getRoot(soul.device);
106
105
  }
107
106
  export function INTERNAL_restoreGuardedComputePipeline(soul, ctx) {
108
- return new TgpuGuardedComputePipelineImpl(ctx.getRoot(soul.device), soul.pipeline, soul.sizeUniform, soul.workgroupSize);
107
+ return new TgpuGuardedComputePipelineImpl(ctx.getRoot(soul.device), soul.pipeline, soul.size, soul.workgroupSize);
109
108
  }
110
109
  class WithBindingImpl {
111
110
  #getRoot;
@@ -154,7 +153,7 @@ class WithBindingImpl {
154
153
  }`.$uses({ sizeUniform, wrappedCallback });
155
154
  // NOTE: in certain setups, unplugin can run on package typegpu, so we have to avoid auto-naming triggering here
156
155
  const pipeline = (() => this.createComputePipeline({ compute: mainCompute }))();
157
- return new TgpuGuardedComputePipelineImpl(root, pipeline, sizeUniform, workgroupSize);
156
+ return new TgpuGuardedComputePipelineImpl(root, pipeline, { uniform: sizeUniform, lastValue: vec3u() }, workgroupSize);
158
157
  }
159
158
  pipe(transform) {
160
159
  const newCfg = transform(new ConfigurableImpl([]));
@@ -37,7 +37,10 @@ export interface TgpuRootSoul extends TgpuSoul<'root'> {
37
37
  export interface TgpuGuardedComputePipelineSoul extends TgpuSoul<'guarded-compute-pipeline'> {
38
38
  readonly device: GPUDevice;
39
39
  readonly pipeline: TgpuComputePipeline;
40
- readonly sizeUniform: TgpuUniform<Vec3u>;
40
+ readonly size: {
41
+ uniform: TgpuUniform<Vec3u>;
42
+ lastValue: v3u;
43
+ };
41
44
  readonly workgroupSize: v3u;
42
45
  }
43
46
  export interface TgpuGuardedComputePipeline<TArgs extends number[] = number[]> extends TgpuNamable {
@@ -377,6 +380,44 @@ export interface TgpuRoot extends Unwrapper, WithBinding {
377
380
  createTexture<TWidth extends number, THeight extends number, TDepth extends number, TSize extends readonly [TWidth] | readonly [TWidth, THeight] | readonly [TWidth, THeight, TDepth], TFormat extends GPUTextureFormat, TMipLevelCount extends number, TSampleCount extends number, TViewFormats extends GPUTextureFormat[], TDimension extends GPUTextureDimension>(props: CreateTextureOptions<TSize, TFormat, TMipLevelCount, TSampleCount, TViewFormats, TDimension>): TgpuTexture<CreateTextureResult<TSize, TFormat, TMipLevelCount, TSampleCount, TViewFormats, TDimension>>;
378
381
  createSampler(props: WgslSamplerProps): TgpuFixedSampler;
379
382
  createComparisonSampler(props: WgslComparisonSamplerProps): TgpuFixedComparisonSampler;
383
+ /**
384
+ * Creates a {@link TgpuCommandEncoder} for batching multiple render/compute
385
+ * passes (and draws within them) into a single submission.
386
+ *
387
+ * @example
388
+ * ```ts
389
+ * const encoder = root.createCommandEncoder();
390
+ * const pass = encoder.beginRenderPass({
391
+ * colorAttachments: [{ view: msaaTexture, resolveTarget: context }],
392
+ * });
393
+ * scenePipeline.with(pass).draw(vertexCount);
394
+ * skyPipeline.with(pass).draw(3);
395
+ * pass.end();
396
+ * encoder.submit();
397
+ * ```
398
+ */
399
+ createCommandEncoder(descriptor?: GPUCommandEncoderDescriptor): TgpuCommandEncoder;
400
+ /**
401
+ * Creates a {@link TgpuRenderBundleEncoder} for recording draw commands into
402
+ * a {@link GPURenderBundle}. Call `finish()` on the encoder to obtain the
403
+ * bundle, replayable in a render pass via `pass.executeBundles`.
404
+ *
405
+ * The caller is responsible for ensuring that the `descriptor` (e.g.
406
+ * `colorFormats`, `depthStencilFormat`) is compatible with the render pass
407
+ * in which the bundle will be executed.
408
+ *
409
+ * @param descriptor - Describes the formats the bundle must be compatible with.
410
+ *
411
+ * @example
412
+ * ```ts
413
+ * const bundleEncoder = root.createRenderBundleEncoder({
414
+ * colorFormats: ['rgba8unorm'],
415
+ * });
416
+ * scenePipeline.with(bundleEncoder).draw(vertexCount);
417
+ * const bundle = bundleEncoder.finish();
418
+ * ```
419
+ */
420
+ createRenderBundleEncoder(descriptor: GPURenderBundleEncoderDescriptor): TgpuRenderBundleEncoder;
380
421
  /**
381
422
  * Creates a query set for collecting timestamps or occlusion queries.
382
423
  *
@@ -447,43 +488,9 @@ export interface ExperimentalTgpuRoot extends Omit<TgpuRoot, 'with'>, Withable_D
447
488
  readonly shaderGeneratorClass?: ShaderGeneratorClass | undefined;
448
489
  /** @deprecated Use `root.createTexture` instead. */
449
490
  createTexture<TWidth extends number, THeight extends number, TDepth extends number, TSize extends readonly [TWidth] | readonly [TWidth, THeight] | readonly [TWidth, THeight, TDepth], TFormat extends GPUTextureFormat, TMipLevelCount extends number, TSampleCount extends number, TViewFormats extends GPUTextureFormat[], TDimension extends GPUTextureDimension>(props: CreateTextureOptions<TSize, TFormat, TMipLevelCount, TSampleCount, TViewFormats, TDimension>): TgpuTexture<CreateTextureResult<TSize, TFormat, TMipLevelCount, TSampleCount, TViewFormats, TDimension>>;
450
- /**
451
- * Creates a {@link TgpuCommandEncoder} for batching multiple render/compute
452
- * passes (and draws within them) into a single submission.
453
- *
454
- * @example
455
- * ```ts
456
- * const encoder = root['~unstable'].createCommandEncoder();
457
- * const pass = encoder.beginRenderPass({
458
- * colorAttachments: [{ view: msaaTexture, resolveTarget: context }],
459
- * });
460
- * scenePipeline.with(pass).draw(vertexCount);
461
- * skyPipeline.with(pass).draw(3);
462
- * pass.end();
463
- * encoder.submit();
464
- * ```
465
- */
491
+ /** @deprecated This feature is now stable, use {@link TgpuRoot.createCommandEncoder | root.createCommandEncoder}. */
466
492
  createCommandEncoder(descriptor?: GPUCommandEncoderDescriptor): TgpuCommandEncoder;
467
- /**
468
- * Creates a {@link TgpuRenderBundleEncoder} for recording draw commands into
469
- * a {@link GPURenderBundle}. Call `finish()` on the encoder to obtain the
470
- * bundle, replayable in a render pass via `pass.executeBundles`.
471
- *
472
- * The caller is responsible for ensuring that the `descriptor` (e.g.
473
- * `colorFormats`, `depthStencilFormat`) is compatible with the render pass
474
- * in which the bundle will be executed.
475
- *
476
- * @param descriptor - Describes the formats the bundle must be compatible with.
477
- *
478
- * @example
479
- * ```ts
480
- * const bundleEncoder = root['~unstable'].createRenderBundleEncoder({
481
- * colorFormats: ['rgba8unorm'],
482
- * });
483
- * scenePipeline.with(bundleEncoder).draw(vertexCount);
484
- * const bundle = bundleEncoder.finish();
485
- * ```
486
- */
493
+ /** @deprecated This feature is now stable, use {@link TgpuRoot.createRenderBundleEncoder | root.createRenderBundleEncoder}. */
487
494
  createRenderBundleEncoder(descriptor: GPURenderBundleEncoderDescriptor): TgpuRenderBundleEncoder;
488
495
  /** @deprecated Use `root.createSampler` instead. */
489
496
  createSampler(props: WgslSamplerProps): TgpuFixedSampler;
@@ -1,7 +1,7 @@
1
1
  import { isData, undecorate } from "../../data/dataTypes.js";
2
2
  import { schemaCallWrapper } from "../../data/schemaCallWrapper.js";
3
3
  import { isSnippet, snip } from "../../data/snippet.js";
4
- import { deepEqual } from "../../data/deepEqual.js";
4
+ import { schemasEqualStructurally } from "../../data/schemasEqual.js";
5
5
  import { arrayOf } from "../../data/array.js";
6
6
  import { UnknownData } from "../../data/dataTypes.js";
7
7
  import { isAbstract, isWgslArray } from "../../data/wgslTypes.js";
@@ -54,9 +54,9 @@ function matchesSchema(accessorSchema, providedType) {
54
54
  const expected = undecorate(accessorSchema);
55
55
  const provided = undecorate(providedType);
56
56
  if (isWgslArray(expected) && expected.elementCount === 0 && isWgslArray(provided)) {
57
- return deepEqual(expected.elementType, provided.elementType);
57
+ return schemasEqualStructurally(expected.elementType, provided.elementType);
58
58
  }
59
- return deepEqual(expected, provided);
59
+ return schemasEqualStructurally(expected, provided);
60
60
  }
61
61
  /**
62
62
  * Values with a concrete WGSL type (buffers, variables, GPU functions, ...) are used as-is,
@@ -101,7 +101,7 @@ function createUnvalidatedAccessorSnippet(accessor) {
101
101
  return ownSnippet;
102
102
  }
103
103
  if (isGPUCallable(value)) {
104
- const result = value[$gpuCallable].call(ctx, []);
104
+ const result = value[$gpuCallable](ctx, []);
105
105
  if (result.dataType !== UnknownData && !isAbstract(result.dataType)) {
106
106
  return result;
107
107
  }
@@ -1,7 +1,7 @@
1
1
  import { type TextureSchemaForDescriptor, type WgslStorageTexture, type WgslTexture } from '../../data/texture.ts';
2
2
  import type { StorageFlag } from '../../extension.ts';
3
3
  import { type ResolvedSnippet } from '../../data/snippet.ts';
4
- import type { F32, Vec4f, Vec4i, Vec4u } from '../../data/wgslTypes.ts';
4
+ import type { F32 } from '../../data/wgslTypes.ts';
5
5
  import type { TgpuNamable } from '../../shared/meta.ts';
6
6
  import type { Infer, ValidateTextureViewSchema } from '../../shared/repr.ts';
7
7
  import { type TextureFormats, type ViewDimensionToDimension } from './textureFormats.ts';
@@ -38,7 +38,6 @@ type TextureViewInternals = {
38
38
  readonly format?: GPUTextureFormat | undefined;
39
39
  readonly aspect?: GPUTextureAspect | undefined;
40
40
  };
41
- export type TexelData = Vec4u | Vec4i | Vec4f;
42
41
  export type { TextureBlobWriteOptions, TextureChannel, TextureCopyOptions, TextureRawWriteOptions, TextureWriteFit, TextureWriteOptions, } from './textureWrite.ts';
43
42
  type TgpuTextureViewDescriptor = {
44
43
  /**
@@ -152,6 +151,7 @@ export interface TgpuTextureRenderView {
152
151
  readonly descriptor: TgpuTextureViewDescriptor;
153
152
  }
154
153
  export declare function INTERNAL_createTexture(props: TextureProps, root: ExperimentalTgpuRoot, rawTexture?: GPUTexture): TgpuTexture<TextureProps>;
154
+ export declare function INTERNAL_restoreTextureView(soul: TgpuTextureViewSoul): TgpuTextureView | TgpuTextureRenderView;
155
155
  export declare function isTexture(value: unknown): value is TgpuTexture;
156
156
  export declare function isTextureView(value: unknown): value is TgpuTextureView;
157
157
  export declare class TgpuLaidOutTextureViewImpl<T extends WgslTexture | WgslStorageTexture> implements TgpuTextureView<T>, SelfResolvable {
@@ -174,6 +174,6 @@ export declare class TgpuTextureRenderViewImpl implements TgpuTextureRenderView
174
174
  readonly [$internal]: TextureViewInternals;
175
175
  readonly [$soul]: TgpuTextureViewSoul<'render'>;
176
176
  readonly resourceType: "texture-view";
177
- constructor(baseTexture: TgpuTexture, descriptor?: TgpuTextureViewDescriptor);
177
+ constructor(soul: TgpuTextureViewSoul<'render'>);
178
178
  get descriptor(): TgpuTextureViewDescriptor;
179
179
  }
@@ -7,7 +7,7 @@ import { $gpuValueOf, $internal, $ownSnippet, $comptimeValueOf, $repr, $resolve,
7
7
  import { runtimeOnly } from "../../types.js";
8
8
  import { valueProxyHandler } from "../valueProxyUtils.js";
9
9
  import { clearTextureWithColor, generateTextureMipmaps, writeImages } from "./textureUtils.js";
10
- import { mipLevelSize, origin3d, resolveImageWrite, writeRegionSize, } from "./textureWrite.js";
10
+ import { getTextureCopyLayout, mipLevelSize, origin3d, resolveImageWrite, writeRegionSize, } from "./textureWrite.js";
11
11
  import { logger } from "../../tgpuLogger.js";
12
12
  function getDescriptorForProps(props) {
13
13
  return {
@@ -19,6 +19,13 @@ function getDescriptorForProps(props) {
19
19
  export function INTERNAL_createTexture(props, root, rawTexture) {
20
20
  return new TgpuTextureImpl(props, root, rawTexture);
21
21
  }
22
+ export function INTERNAL_restoreTextureView(soul) {
23
+ const { schema } = soul;
24
+ const descriptor = soul.descriptor;
25
+ return schema === 'render'
26
+ ? new TgpuTextureRenderViewImpl({ ...soul, schema, descriptor })
27
+ : new TgpuFixedTextureViewImpl({ ...soul, schema });
28
+ }
22
29
  export function isTexture(value) {
23
30
  return value?.resourceType === 'texture' && !!value[$internal];
24
31
  }
@@ -124,18 +131,23 @@ class TgpuTextureImpl {
124
131
  return this;
125
132
  }
126
133
  createView(schema, viewDescriptor) {
134
+ const descriptor = viewDescriptor;
135
+ const soul = { type: 'texture-view', texture: this, descriptor };
127
136
  if (schema === 'render') {
128
- return new TgpuTextureRenderViewImpl(this, viewDescriptor);
137
+ return new TgpuTextureRenderViewImpl({ ...soul, schema });
129
138
  }
130
- return new TgpuFixedTextureViewImpl(schema ?? textureDescriptorToSchema(getDescriptorForProps(this.props)), this, viewDescriptor);
139
+ return new TgpuFixedTextureViewImpl({
140
+ ...soul,
141
+ schema: schema ?? textureDescriptorToSchema(getDescriptorForProps(this.props)),
142
+ });
131
143
  }
132
144
  #clearMipLevel(mip = 0) {
133
- const [width, height, depth] = mipLevelSize(this.props, mip);
134
- const texelSize = this.#formatInfo.texelSize;
135
- if (texelSize === 'non-copyable') {
136
- throw new Error(`Cannot clear texture with format '${this.props.format}': this format does not support copy operations.`);
145
+ const { extent, dataLayout } = getTextureCopyLayout(mipLevelSize(this.props, mip), this.#formatInfo);
146
+ if (!dataLayout) {
147
+ throw new Error(`Cannot clear texture with format '${this.props.format}': this format has no defined byte layout.`);
137
148
  }
138
- this[$soul].device.queue.writeTexture({ texture: this[$internal].materialize(), mipLevel: mip }, new Uint8Array(width * height * depth * texelSize), { bytesPerRow: texelSize * width, rowsPerImage: height }, [width, height, depth]);
149
+ const { bytesPerRow, rowsPerImage, byteSize } = dataLayout;
150
+ this[$soul].device.queue.writeTexture({ texture: this[$internal].materialize(), mipLevel: mip }, new Uint8Array(byteSize), { bytesPerRow, rowsPerImage }, extent);
139
151
  }
140
152
  clear(colorOrMipLevel = 'all', mipLevel = 'all') {
141
153
  const mipLevels = (level) => level === 'all' ? [...Array(this.props.mipLevelCount ?? 1).keys()] : [level];
@@ -200,17 +212,22 @@ class TgpuTextureImpl {
200
212
  }
201
213
  }
202
214
  #writeBufferData(source, options) {
203
- const texelSize = this.#formatInfo.texelSize;
204
- if (texelSize === 'non-copyable') {
205
- throw new Error(`Cannot write to texture with format '${this.props.format}': this format does not support copy operations.`);
206
- }
207
215
  const mipLevel = options.mipLevel ?? 0;
208
216
  const [mipWidth, mipHeight, mipDepth] = mipLevelSize(this.props, mipLevel);
209
217
  const origin = origin3d(options.origin);
210
218
  const width = options.size?.[0] ?? mipWidth - origin.x;
211
219
  const height = options.size?.[1] ?? mipHeight - origin.y;
212
220
  const depth = options.size?.[2] ?? mipDepth - origin.z;
213
- const expectedSize = width * height * depth * texelSize;
221
+ const { extent, dataLayout } = getTextureCopyLayout([width, height, depth], this.#formatInfo);
222
+ if (!dataLayout) {
223
+ throw new Error(`Cannot write raw data to texture with format '${this.props.format}': this format has no defined byte layout.`);
224
+ }
225
+ const [blockWidth, blockHeight] = this.#formatInfo.blockDimensions;
226
+ if ((options.size?.[0] !== undefined && width % blockWidth !== 0) ||
227
+ (options.size?.[1] !== undefined && height % blockHeight !== 0)) {
228
+ throw new Error(`Write size ${width}x${height} is not a multiple of the ${blockWidth}x${blockHeight} block size of format '${this.props.format}'.`);
229
+ }
230
+ const { bytesPerRow, rowsPerImage, byteSize: expectedSize } = dataLayout;
214
231
  if (source.byteLength !== expectedSize) {
215
232
  throw new Error(`Buffer size mismatch. Expected ${expectedSize} bytes for mip level ${mipLevel}, got ${source.byteLength} bytes.`);
216
233
  }
@@ -219,9 +236,9 @@ class TgpuTextureImpl {
219
236
  mipLevel,
220
237
  origin,
221
238
  }, source, {
222
- bytesPerRow: texelSize * width,
223
- rowsPerImage: height,
224
- }, [width, height, depth]);
239
+ bytesPerRow,
240
+ rowsPerImage,
241
+ }, [options.size?.[0] ?? extent[0], options.size?.[1] ?? extent[1], depth]);
225
242
  }
226
243
  copyFrom(source, options) {
227
244
  if (source.props.format !== this.props.format) {
@@ -235,16 +252,16 @@ class TgpuTextureImpl {
235
252
  }
236
253
  const sourceMipLevel = options?.sourceMipLevel ?? 0;
237
254
  const sourceOrigin = origin3d(options?.sourceOrigin);
238
- const [sourceWidth, sourceHeight, sourceDepth] = mipLevelSize(source.props, sourceMipLevel);
255
+ const { extent } = getTextureCopyLayout(mipLevelSize(source.props, sourceMipLevel), this.#formatInfo);
239
256
  const commandEncoder = this[$soul].device.createCommandEncoder();
240
257
  commandEncoder.copyTextureToTexture({ texture: source[$internal].materialize(), mipLevel: sourceMipLevel, origin: sourceOrigin }, {
241
258
  texture: this[$internal].materialize(),
242
259
  mipLevel: options?.mipLevel ?? 0,
243
260
  origin: origin3d(options?.origin),
244
261
  }, [
245
- options?.size?.[0] ?? sourceWidth - sourceOrigin.x,
246
- options?.size?.[1] ?? sourceHeight - sourceOrigin.y,
247
- options?.size?.[2] ?? sourceDepth - sourceOrigin.z,
262
+ options?.size?.[0] ?? extent[0] - sourceOrigin.x,
263
+ options?.size?.[1] ?? extent[1] - sourceOrigin.y,
264
+ options?.size?.[2] ?? extent[2] - sourceOrigin.z,
248
265
  ]);
249
266
  this[$soul].device.queue.submit([commandEncoder.finish()]);
250
267
  }
@@ -268,15 +285,9 @@ class TgpuFixedTextureViewImpl {
268
285
  [$internal];
269
286
  [$soul];
270
287
  resourceType = 'texture-view';
271
- constructor(schema, baseTexture, descriptor) {
272
- this[$soul] = {
273
- type: 'texture-view',
274
- texture: baseTexture,
275
- schema,
276
- descriptor,
277
- raw: undefined,
278
- label: undefined,
279
- };
288
+ constructor(soul) {
289
+ this[$soul] = { ...soul };
290
+ const { texture, schema, descriptor } = soul;
280
291
  this[$internal] = {
281
292
  unwrap: () => {
282
293
  const soul = this[$soul];
@@ -292,8 +303,7 @@ class TgpuFixedTextureViewImpl {
292
303
  }
293
304
  return soul.raw;
294
305
  },
295
- format: descriptor?.format ??
296
- (isWgslStorageTexture(schema) ? schema.format : baseTexture.props.format),
306
+ format: descriptor?.format ?? (isWgslStorageTexture(schema) ? schema.format : texture.props.format),
297
307
  aspect: descriptor?.aspect,
298
308
  };
299
309
  }
@@ -307,9 +317,14 @@ class TgpuFixedTextureViewImpl {
307
317
  }
308
318
  return this;
309
319
  }
320
+ // Created once, since shader code can access a view many times
321
+ #valueProxy;
310
322
  get [$gpuValueOf]() {
323
+ if (this.#valueProxy) {
324
+ return this.#valueProxy;
325
+ }
311
326
  const schema = this.schema;
312
- return new Proxy({
327
+ this.#valueProxy = new Proxy({
313
328
  [$internal]: true,
314
329
  get [$ownSnippet]() {
315
330
  return snip(this, schema, /* origin */ 'handle', false);
@@ -318,6 +333,7 @@ class TgpuFixedTextureViewImpl {
318
333
  [$resolve]: (ctx) => ctx.resolve(this),
319
334
  toString: () => `${this.toString()}.$`,
320
335
  }, valueProxyHandler);
336
+ return this.#valueProxy;
321
337
  }
322
338
  get $() {
323
339
  if (inCodegenMode()) {
@@ -370,9 +386,14 @@ export class TgpuLaidOutTextureViewImpl {
370
386
  ctx.addDeclaration(`@group(${group}) @binding(${this.#membership.idx}) var ${id}: ${ctx.resolve(this.schema).value};`, id);
371
387
  return snip(id, this.schema, /* origin */ 'handle');
372
388
  }
389
+ // Created once, since shader code can access a view many times
390
+ #valueProxy;
373
391
  get [$gpuValueOf]() {
392
+ if (this.#valueProxy) {
393
+ return this.#valueProxy;
394
+ }
374
395
  const schema = this.schema;
375
- return new Proxy({
396
+ this.#valueProxy = new Proxy({
376
397
  [$internal]: true,
377
398
  get [$ownSnippet]() {
378
399
  return snip(this, schema, /* origin */ 'handle', false);
@@ -381,6 +402,7 @@ export class TgpuLaidOutTextureViewImpl {
381
402
  [$resolve]: (ctx) => ctx.resolve(this),
382
403
  toString: () => `${this.toString()}.$`,
383
404
  }, valueProxyHandler);
405
+ return this.#valueProxy;
384
406
  }
385
407
  get $() {
386
408
  if (inCodegenMode()) {
@@ -397,15 +419,9 @@ export class TgpuTextureRenderViewImpl {
397
419
  [$internal];
398
420
  [$soul];
399
421
  resourceType = 'texture-view';
400
- constructor(baseTexture, descriptor = {}) {
401
- this[$soul] = {
402
- type: 'texture-view',
403
- texture: baseTexture,
404
- schema: 'render',
405
- descriptor,
406
- raw: undefined,
407
- label: undefined,
408
- };
422
+ constructor(soul) {
423
+ this[$soul] = { ...soul };
424
+ const { texture, descriptor } = soul;
409
425
  this[$internal] = {
410
426
  unwrap: () => {
411
427
  const soul = this[$soul];
@@ -417,8 +433,8 @@ export class TgpuTextureRenderViewImpl {
417
433
  }
418
434
  return soul.raw;
419
435
  },
420
- format: descriptor.format ?? baseTexture.props.format,
421
- aspect: descriptor.aspect,
436
+ format: descriptor?.format ?? texture.props.format,
437
+ aspect: descriptor?.aspect,
422
438
  };
423
439
  }
424
440
  get descriptor() {