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
@@ -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;
@@ -380,6 +380,44 @@ export interface TgpuRoot extends Unwrapper, WithBinding {
380
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>>;
381
381
  createSampler(props: WgslSamplerProps): TgpuFixedSampler;
382
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;
383
421
  /**
384
422
  * Creates a query set for collecting timestamps or occlusion queries.
385
423
  *
@@ -450,43 +488,9 @@ export interface ExperimentalTgpuRoot extends Omit<TgpuRoot, 'with'>, Withable_D
450
488
  readonly shaderGeneratorClass?: ShaderGeneratorClass | undefined;
451
489
  /** @deprecated Use `root.createTexture` instead. */
452
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>>;
453
- /**
454
- * Creates a {@link TgpuCommandEncoder} for batching multiple render/compute
455
- * passes (and draws within them) into a single submission.
456
- *
457
- * @example
458
- * ```ts
459
- * const encoder = root['~unstable'].createCommandEncoder();
460
- * const pass = encoder.beginRenderPass({
461
- * colorAttachments: [{ view: msaaTexture, resolveTarget: context }],
462
- * });
463
- * scenePipeline.with(pass).draw(vertexCount);
464
- * skyPipeline.with(pass).draw(3);
465
- * pass.end();
466
- * encoder.submit();
467
- * ```
468
- */
491
+ /** @deprecated This feature is now stable, use {@link TgpuRoot.createCommandEncoder | root.createCommandEncoder}. */
469
492
  createCommandEncoder(descriptor?: GPUCommandEncoderDescriptor): TgpuCommandEncoder;
470
- /**
471
- * Creates a {@link TgpuRenderBundleEncoder} for recording draw commands into
472
- * a {@link GPURenderBundle}. Call `finish()` on the encoder to obtain the
473
- * bundle, replayable in a render pass via `pass.executeBundles`.
474
- *
475
- * The caller is responsible for ensuring that the `descriptor` (e.g.
476
- * `colorFormats`, `depthStencilFormat`) is compatible with the render pass
477
- * in which the bundle will be executed.
478
- *
479
- * @param descriptor - Describes the formats the bundle must be compatible with.
480
- *
481
- * @example
482
- * ```ts
483
- * const bundleEncoder = root['~unstable'].createRenderBundleEncoder({
484
- * colorFormats: ['rgba8unorm'],
485
- * });
486
- * scenePipeline.with(bundleEncoder).draw(vertexCount);
487
- * const bundle = bundleEncoder.finish();
488
- * ```
489
- */
493
+ /** @deprecated This feature is now stable, use {@link TgpuRoot.createRenderBundleEncoder | root.createRenderBundleEncoder}. */
490
494
  createRenderBundleEncoder(descriptor: GPURenderBundleEncoderDescriptor): TgpuRenderBundleEncoder;
491
495
  /** @deprecated Use `root.createSampler` instead. */
492
496
  createSampler(props: WgslSamplerProps): TgpuFixedSampler;
@@ -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
  /**
@@ -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 {
@@ -142,12 +142,12 @@ class TgpuTextureImpl {
142
142
  });
143
143
  }
144
144
  #clearMipLevel(mip = 0) {
145
- const [width, height, depth] = mipLevelSize(this.props, mip);
146
- const texelSize = this.#formatInfo.texelSize;
147
- if (texelSize === 'non-copyable') {
148
- 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.`);
149
148
  }
150
- 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);
151
151
  }
152
152
  clear(colorOrMipLevel = 'all', mipLevel = 'all') {
153
153
  const mipLevels = (level) => level === 'all' ? [...Array(this.props.mipLevelCount ?? 1).keys()] : [level];
@@ -212,17 +212,22 @@ class TgpuTextureImpl {
212
212
  }
213
213
  }
214
214
  #writeBufferData(source, options) {
215
- const texelSize = this.#formatInfo.texelSize;
216
- if (texelSize === 'non-copyable') {
217
- throw new Error(`Cannot write to texture with format '${this.props.format}': this format does not support copy operations.`);
218
- }
219
215
  const mipLevel = options.mipLevel ?? 0;
220
216
  const [mipWidth, mipHeight, mipDepth] = mipLevelSize(this.props, mipLevel);
221
217
  const origin = origin3d(options.origin);
222
218
  const width = options.size?.[0] ?? mipWidth - origin.x;
223
219
  const height = options.size?.[1] ?? mipHeight - origin.y;
224
220
  const depth = options.size?.[2] ?? mipDepth - origin.z;
225
- 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;
226
231
  if (source.byteLength !== expectedSize) {
227
232
  throw new Error(`Buffer size mismatch. Expected ${expectedSize} bytes for mip level ${mipLevel}, got ${source.byteLength} bytes.`);
228
233
  }
@@ -231,9 +236,9 @@ class TgpuTextureImpl {
231
236
  mipLevel,
232
237
  origin,
233
238
  }, source, {
234
- bytesPerRow: texelSize * width,
235
- rowsPerImage: height,
236
- }, [width, height, depth]);
239
+ bytesPerRow,
240
+ rowsPerImage,
241
+ }, [options.size?.[0] ?? extent[0], options.size?.[1] ?? extent[1], depth]);
237
242
  }
238
243
  copyFrom(source, options) {
239
244
  if (source.props.format !== this.props.format) {
@@ -247,16 +252,16 @@ class TgpuTextureImpl {
247
252
  }
248
253
  const sourceMipLevel = options?.sourceMipLevel ?? 0;
249
254
  const sourceOrigin = origin3d(options?.sourceOrigin);
250
- const [sourceWidth, sourceHeight, sourceDepth] = mipLevelSize(source.props, sourceMipLevel);
255
+ const { extent } = getTextureCopyLayout(mipLevelSize(source.props, sourceMipLevel), this.#formatInfo);
251
256
  const commandEncoder = this[$soul].device.createCommandEncoder();
252
257
  commandEncoder.copyTextureToTexture({ texture: source[$internal].materialize(), mipLevel: sourceMipLevel, origin: sourceOrigin }, {
253
258
  texture: this[$internal].materialize(),
254
259
  mipLevel: options?.mipLevel ?? 0,
255
260
  origin: origin3d(options?.origin),
256
261
  }, [
257
- options?.size?.[0] ?? sourceWidth - sourceOrigin.x,
258
- options?.size?.[1] ?? sourceHeight - sourceOrigin.y,
259
- 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,
260
265
  ]);
261
266
  this[$soul].device.queue.submit([commandEncoder.finish()]);
262
267
  }
@@ -312,9 +317,14 @@ class TgpuFixedTextureViewImpl {
312
317
  }
313
318
  return this;
314
319
  }
320
+ // Created once, since shader code can access a view many times
321
+ #valueProxy;
315
322
  get [$gpuValueOf]() {
323
+ if (this.#valueProxy) {
324
+ return this.#valueProxy;
325
+ }
316
326
  const schema = this.schema;
317
- return new Proxy({
327
+ this.#valueProxy = new Proxy({
318
328
  [$internal]: true,
319
329
  get [$ownSnippet]() {
320
330
  return snip(this, schema, /* origin */ 'handle', false);
@@ -323,6 +333,7 @@ class TgpuFixedTextureViewImpl {
323
333
  [$resolve]: (ctx) => ctx.resolve(this),
324
334
  toString: () => `${this.toString()}.$`,
325
335
  }, valueProxyHandler);
336
+ return this.#valueProxy;
326
337
  }
327
338
  get $() {
328
339
  if (inCodegenMode()) {
@@ -375,9 +386,14 @@ export class TgpuLaidOutTextureViewImpl {
375
386
  ctx.addDeclaration(`@group(${group}) @binding(${this.#membership.idx}) var ${id}: ${ctx.resolve(this.schema).value};`, id);
376
387
  return snip(id, this.schema, /* origin */ 'handle');
377
388
  }
389
+ // Created once, since shader code can access a view many times
390
+ #valueProxy;
378
391
  get [$gpuValueOf]() {
392
+ if (this.#valueProxy) {
393
+ return this.#valueProxy;
394
+ }
379
395
  const schema = this.schema;
380
- return new Proxy({
396
+ this.#valueProxy = new Proxy({
381
397
  [$internal]: true,
382
398
  get [$ownSnippet]() {
383
399
  return snip(this, schema, /* origin */ 'handle', false);
@@ -386,6 +402,7 @@ export class TgpuLaidOutTextureViewImpl {
386
402
  [$resolve]: (ctx) => ctx.resolve(this),
387
403
  toString: () => `${this.toString()}.$`,
388
404
  }, valueProxyHandler);
405
+ return this.#valueProxy;
389
406
  }
390
407
  get $() {
391
408
  if (inCodegenMode()) {
@@ -33,14 +33,15 @@ export type AspectInfo = {
33
33
  export type TextureFormatInfo = {
34
34
  readonly channelType: F32 | I32 | U32;
35
35
  readonly vectorType: Vec4f | Vec4i | Vec4u;
36
- readonly texelSize: number | 'non-copyable';
36
+ readonly texelBlockSize: number | 'non-copyable';
37
+ readonly blockDimensions: readonly [number, number];
37
38
  readonly sampleTypes: readonly GPUTextureSampleType[];
38
39
  readonly canRenderAttachment: boolean;
39
40
  readonly depthAspect?: AspectInfo & {
40
- readonly texelSize: number | 'non-copyable';
41
+ readonly texelBlockSize: number | 'non-copyable';
41
42
  };
42
43
  readonly stencilAspect?: AspectInfo & {
43
- readonly texelSize: number;
44
+ readonly texelBlockSize: number;
44
45
  };
45
46
  };
46
47
  export declare function getTextureFormatInfo(format: GPUTextureFormat): TextureFormatInfo;
@@ -4,25 +4,25 @@ const DEPTH_ASPECT_NON_COPYABLE = {
4
4
  channelType: f32,
5
5
  vectorType: vec4f,
6
6
  sampleTypes: ['depth', 'unfilterable-float'],
7
- texelSize: 'non-copyable',
7
+ texelBlockSize: 'non-copyable',
8
8
  };
9
9
  const DEPTH_ASPECT_16 = {
10
10
  channelType: f32,
11
11
  vectorType: vec4f,
12
12
  sampleTypes: ['depth', 'unfilterable-float'],
13
- texelSize: 2,
13
+ texelBlockSize: 2,
14
14
  };
15
15
  const DEPTH_ASPECT_32 = {
16
16
  channelType: f32,
17
17
  vectorType: vec4f,
18
18
  sampleTypes: ['depth', 'unfilterable-float'],
19
- texelSize: 4,
19
+ texelBlockSize: 4,
20
20
  };
21
21
  const STENCIL_ASPECT = {
22
22
  channelType: u32,
23
23
  vectorType: vec4u,
24
24
  sampleTypes: ['uint'],
25
- texelSize: 1,
25
+ texelBlockSize: 1,
26
26
  };
27
27
  const formatInfoCache = new Map();
28
28
  export function getTextureFormatInfo(format) {
@@ -40,7 +40,8 @@ function createFormatInfo(format) {
40
40
  return {
41
41
  channelType,
42
42
  vectorType: channelType === u32 ? vec4u : channelType === i32 ? vec4i : vec4f,
43
- texelSize: parseTexelSize(format),
43
+ texelBlockSize: parseTexelBlockSize(format),
44
+ blockDimensions: parseBlockDimensions(format),
44
45
  sampleTypes: parseSampleTypes(format),
45
46
  canRenderAttachment: canRenderAttachment(format),
46
47
  ...(depthAspect && { depthAspect }),
@@ -78,7 +79,7 @@ function parseChannelType(format) {
78
79
  return i32;
79
80
  return f32;
80
81
  }
81
- function parseTexelSize(format) {
82
+ function parseTexelBlockSize(format) {
82
83
  // Standard formats: channel count encoded in prefix length (r=1, rg=2, rgba/bgra=4)
83
84
  const [, channels, bits] = format.match(/^(rgba|bgra|rg|r)(8|16|32)/) ?? [];
84
85
  if (channels && bits) {
@@ -106,6 +107,16 @@ function parseTexelSize(format) {
106
107
  // Packed 32-bit (rgb9e5ufloat, rgb10a2unorm, rgb10a2uint, rg11b10ufloat)
107
108
  return 4;
108
109
  }
110
+ function parseBlockDimensions(format) {
111
+ const astc = /^astc-(\d+)x(\d+)-/.exec(format);
112
+ if (astc) {
113
+ return [Number(astc[1]), Number(astc[2])];
114
+ }
115
+ if (format.startsWith('bc') || format.startsWith('etc2-') || format.startsWith('eac-')) {
116
+ return [4, 4];
117
+ }
118
+ return [1, 1];
119
+ }
109
120
  function parseSampleTypes(format) {
110
121
  if (format === 'stencil8')
111
122
  return ['uint'];
@@ -1,3 +1,4 @@
1
+ import type { TextureFormatInfo } from './textureFormats.ts';
1
2
  import type { TextureProps } from './textureProps.ts';
2
3
  export type TextureWriteFit = 'stretch' | 'clip';
3
4
  export type TextureWriteOptions = {
@@ -54,6 +55,14 @@ export declare function origin3d([x, y, z]?: readonly (number | undefined)[]): {
54
55
  z: number;
55
56
  };
56
57
  export declare function mipLevelSize({ size, dimension }: TextureShape, mipLevel: number): [number, number, number];
58
+ export declare function getTextureCopyLayout([width, height, depth]: readonly [number, number, number], { blockDimensions: [blockWidth, blockHeight], texelBlockSize, }: Pick<TextureFormatInfo, 'blockDimensions' | 'texelBlockSize'>): {
59
+ extent: [number, number, number];
60
+ dataLayout: {
61
+ bytesPerRow: number;
62
+ rowsPerImage: number;
63
+ byteSize: number;
64
+ } | undefined;
65
+ };
57
66
  /** The size of the written region: `size`, or the rest of the mip level past `origin` */
58
67
  export declare function writeRegionSize(texture: TextureShape, options: TextureWriteOptions): [number, number];
59
68
  export declare function sameSize(a: readonly number[], b: readonly number[]): boolean;
@@ -5,6 +5,27 @@ export function mipLevelSize({ size, dimension }, mipLevel) {
5
5
  const scale = (value = 1) => Math.max(1, value >> mipLevel);
6
6
  return [scale(size[0]), scale(size[1]), dimension === '3d' ? scale(size[2]) : (size[2] ?? 1)];
7
7
  }
8
+ export function getTextureCopyLayout([width, height, depth], { blockDimensions: [blockWidth, blockHeight], texelBlockSize, }) {
9
+ const blocksAcross = Math.ceil(width / blockWidth);
10
+ const blockRows = Math.ceil(height / blockHeight);
11
+ const extent = [
12
+ blocksAcross * blockWidth,
13
+ blockRows * blockHeight,
14
+ depth,
15
+ ];
16
+ if (texelBlockSize === 'non-copyable') {
17
+ return { extent, dataLayout: undefined };
18
+ }
19
+ const bytesPerRow = blocksAcross * texelBlockSize;
20
+ return {
21
+ extent,
22
+ dataLayout: {
23
+ bytesPerRow,
24
+ rowsPerImage: blockRows,
25
+ byteSize: bytesPerRow * blockRows * depth,
26
+ },
27
+ };
28
+ }
8
29
  /** The size of the written region: `size`, or the rest of the mip level past `origin` */
9
30
  export function writeRegionSize(texture, options) {
10
31
  const [mipWidth, mipHeight] = mipLevelSize(texture, options.mipLevel ?? 0);
@@ -84,10 +84,8 @@ export const unroll = (() => {
84
84
  setName(impl, 'unroll');
85
85
  impl.toString = () => 'unroll';
86
86
  impl[$internal] = true;
87
- impl[$gpuCallable] = {
88
- call(_ctx, [value]) {
89
- return withValue(new UnrollableIterable(value), value);
90
- },
87
+ impl[$gpuCallable] = (_ctx, [value]) => {
88
+ return withValue(new UnrollableIterable(value), value);
91
89
  };
92
90
  return impl;
93
91
  })();
@@ -1,5 +1,5 @@
1
1
  import type { Disarray, LooseDecorated, Unstruct } from '../../data/dataTypes.ts';
2
- import type { FormatToAcceptedData, FormatToWGSLType } from '../../data/vertexFormatData.ts';
2
+ import type { FormatToWGSLType } from '../../data/vertexFormatData.ts';
3
3
  import type { Decorated, WgslArray, WgslStruct } from '../../data/wgslTypes.ts';
4
4
  import type { KindToAcceptedAttribMap, KindToDefaultFormatMap, TgpuVertexAttrib, VertexFormat } from '../../shared/vertexFormat.ts';
5
5
  /**
@@ -29,6 +29,3 @@ export type LayoutToAllowedAttribs<T> = T extends {
29
29
  export type AttribRecordToDefaultDataTypes<T extends Record<string, TgpuVertexAttrib>> = {
30
30
  [Key in keyof T]: FormatToWGSLType<T[Key]['format']>;
31
31
  };
32
- export type AttribRecordToAcceptedDataTypes<T extends Record<string, TgpuVertexAttrib>> = {
33
- [Key in keyof T]: FormatToAcceptedData[T[Key]['format']];
34
- };
@@ -1,8 +1,7 @@
1
- import { alignmentOf, customAlignmentOf } from "../../data/alignmentOf.js";
2
1
  import { getCustomLocation, isLooseDecorated, isUnstruct } from "../../data/dataTypes.js";
3
- import { sizeOf } from "../../data/sizeOf.js";
2
+ import { offsetsForProps } from "../../data/offsets.js";
3
+ import { strideOf } from "../../data/schemaMemoryLayout.js";
4
4
  import { isDecorated, isWgslStruct } from "../../data/wgslTypes.js";
5
- import { roundUp } from "../../mathUtils.js";
6
5
  import { setName } from "../../shared/meta.js";
7
6
  import { $internal, $soul } from "../../shared/symbols.js";
8
7
  import { kindToDefaultFormatMap, vertexFormats, } from "../../shared/vertexFormat.js";
@@ -22,33 +21,15 @@ function dataToContainedAttribs(layout, data, offset, customLocationMap, key) {
22
21
  if (customLocation !== undefined) {
23
22
  customLocationMap[key ?? defaultAttribEntry] = customLocation;
24
23
  }
25
- return dataToContainedAttribs(layout, data.inner, roundUp(offset, customAlignmentOf(data)), customLocationMap);
24
+ // passing offset unchanged because the parent already applied alignment
25
+ return dataToContainedAttribs(layout, data.inner, offset, customLocationMap);
26
26
  }
27
- if (isWgslStruct(data)) {
28
- let memberOffset = offset;
29
- const propTypes = data.propTypes;
30
- return Object.fromEntries(Object.entries(propTypes).map(([key, value]) => {
31
- memberOffset = roundUp(memberOffset, alignmentOf(value));
32
- const attrib = [
33
- key,
34
- dataToContainedAttribs(layout, value, memberOffset, customLocationMap, key),
35
- ];
36
- memberOffset += sizeOf(value);
37
- return attrib;
38
- }));
39
- }
40
- if (isUnstruct(data)) {
41
- let memberOffset = offset;
42
- const propTypes = data.propTypes;
43
- return Object.fromEntries(Object.entries(propTypes).map(([key, value]) => {
44
- memberOffset = roundUp(memberOffset, customAlignmentOf(value));
45
- const attrib = [
46
- key,
47
- dataToContainedAttribs(layout, value, memberOffset, customLocationMap, key),
48
- ];
49
- memberOffset += sizeOf(value);
50
- return attrib;
51
- }));
27
+ if (isWgslStruct(data) || isUnstruct(data)) {
28
+ const offsets = offsetsForProps(data);
29
+ return Object.fromEntries(Object.entries(data.propTypes).map(([key, value]) => [
30
+ key,
31
+ dataToContainedAttribs(layout, value, offset + offsets[key].offset, customLocationMap, key),
32
+ ]));
52
33
  }
53
34
  if ('type' in data && typeof data.type === 'string') {
54
35
  if (vertexFormats.includes(data.type)) {
@@ -89,7 +70,7 @@ class TgpuVertexLayoutImpl {
89
70
  stepMode,
90
71
  label: undefined,
91
72
  };
92
- this.stride = roundUp(sizeOf(arraySchema.elementType), alignmentOf(arraySchema));
73
+ this.stride = strideOf(arraySchema);
93
74
  this.attrib = dataToContainedAttribs(this, arraySchema.elementType, 0, this.#customLocationMap);
94
75
  }
95
76
  get stepMode() {
@@ -5,4 +5,4 @@ export declare function customAlignmentOf(data: BaseData): number;
5
5
  /**
6
6
  * Returns the alignment (in bytes) of data represented by the `schema`.
7
7
  */
8
- export declare function PUBLIC_alignmentOf(schema: AnyData): number;
8
+ export declare const PUBLIC_alignmentOf: import("../indexNamedExports.ts").TgpuComptime<(schema: AnyData) => number>;
@@ -1,3 +1,4 @@
1
+ import { comptime } from "../core/function/comptime.js";
1
2
  import { safeStringify } from "../shared/stringify.js";
2
3
  import { getCustomAlignment, isDisarray, isLooseDecorated, isUnstruct, } from "./dataTypes.js";
3
4
  import { packedFormats } from "./vertexFormatData.js";
@@ -43,13 +44,8 @@ function computeAlignment(data) {
43
44
  if (isWgslArray(data)) {
44
45
  return alignmentOf(data.elementType);
45
46
  }
46
- if (isUnstruct(data)) {
47
- // A loose struct is aligned to its first property.
48
- const firstProp = Object.values(data.propTypes)[0];
49
- return firstProp ? (getCustomAlignment(firstProp) ?? 1) : 1;
50
- }
51
- if (isDisarray(data)) {
52
- return getCustomAlignment(data.elementType) ?? 1;
47
+ if (isUnstruct(data) || isDisarray(data)) {
48
+ return customAlignmentOf(data);
53
49
  }
54
50
  if (isDecorated(data) || isLooseDecorated(data)) {
55
51
  return getCustomAlignment(data) ?? alignmentOf(data.inner);
@@ -60,8 +56,7 @@ function computeAlignment(data) {
60
56
  throw new Error(`Cannot determine alignment of data: ${safeStringify(data)}`);
61
57
  }
62
58
  function computeCustomAlignment(data) {
63
- if (isUnstruct(data)) {
64
- // A loose struct is aligned to its first property.
59
+ if (isUnstruct(data) || isWgslStruct(data)) {
65
60
  const firstProp = Object.values(data.propTypes)[0];
66
61
  return firstProp ? customAlignmentOf(firstProp) : 1;
67
62
  }
@@ -98,6 +93,4 @@ export function customAlignmentOf(data) {
98
93
  /**
99
94
  * Returns the alignment (in bytes) of data represented by the `schema`.
100
95
  */
101
- export function PUBLIC_alignmentOf(schema) {
102
- return alignmentOf(schema);
103
- }
96
+ export const PUBLIC_alignmentOf = comptime((schema) => alignmentOf(schema));
package/data/array.js CHANGED
@@ -1,7 +1,11 @@
1
1
  import { comptime } from "../core/function/comptime.js";
2
- import { $internal } from "../shared/symbols.js";
2
+ import { WgslTypeError } from "../errors.js";
3
+ import { $gpuCallable, $gpuCallableStrictSignature, $internal } from "../shared/symbols.js";
4
+ import { tryConvertSnippet } from "../tgsl/conversion.js";
5
+ import { ArrayExpression } from "../tgsl/generationHelpers.js";
3
6
  import { schemaCallWrapper } from "./schemaCallWrapper.js";
4
7
  import { sizeOf } from "./sizeOf.js";
8
+ import { fallthroughCopyOrigin, snip } from "./snippet.js";
5
9
  import { isDecorated, isLocationAttrib } from "./wgslTypes.js";
6
10
  /**
7
11
  * Creates an array schema that can be used to construct gpu buffers.
@@ -57,9 +61,37 @@ function cpu_arrayOf(elementType, elementCount) {
57
61
  return arraySchema;
58
62
  }
59
63
  const WgslArrayImpl = {
60
- [$internal]: true,
64
+ [$internal]: {},
61
65
  type: 'array',
62
66
  toString() {
63
67
  return `arrayOf(${String(this.elementType)}, ${this.elementCount})`;
64
68
  },
69
+ get [$gpuCallableStrictSignature]() {
70
+ return { argTypes: [this], returnType: this };
71
+ },
72
+ [$gpuCallable](ctx, args) {
73
+ // Array schema call.
74
+ if (args.length > 1) {
75
+ throw new WgslTypeError('Array schemas should always be called with at most 1 argument');
76
+ }
77
+ // No arguments `array<...>()`, resolve array type and return.
78
+ if (!args[0]) {
79
+ // The schema becomes the data type.
80
+ return ctx.gen.typeInstantiation(this, []);
81
+ }
82
+ const arg = tryConvertSnippet(ctx, args[0], this);
83
+ // `d.arrayOf(...)([...])`.
84
+ // We don't resolve the ArrayExpression object itself to
85
+ // avoid reference checks (we're copying so it's fine)
86
+ if (arg.value instanceof ArrayExpression) {
87
+ return ctx.gen.typeInstantiation(this, arg.value.elements);
88
+ }
89
+ // `d.arrayOf(...)(otherArr)`.
90
+ // We just let the argument resolve everything.
91
+ return snip(ctx.resolveSnippet(arg).value, this,
92
+ // A new array, so not a reference.
93
+ /* origin */ fallthroughCopyOrigin(arg.origin), arg.possibleSideEffects);
94
+ },
65
95
  };
96
+ // Schemas are still functions, so they should keep `call`, `apply`, `bind`, etc.
97
+ Object.setPrototypeOf(WgslArrayImpl, Function.prototype);