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
@@ -6,21 +6,33 @@ export type AnyAttribute<AllowedBuiltins extends Builtin<BuiltinName> = Builtin<
6
6
  export type ExtractAttributes<T> = T extends {
7
7
  readonly attribs: unknown[];
8
8
  } ? T['attribs'] : [];
9
+ /**
10
+ * `TAttribs` without the attributes of type `TType`. An array that is not a tuple is kept as it is.
11
+ */
12
+ type WithoutAttribute<TAttribs extends unknown[], TType> = number extends TAttribs['length'] ? TAttribs : TAttribs extends [infer Head, ...infer Rest] ? Head extends {
13
+ readonly type: TType;
14
+ } ? WithoutAttribute<Rest, TType> : [Head, ...WithoutAttribute<Rest, TType>] : [];
9
15
  /**
10
16
  * Decorates a data-type `TData` with an attribute `TAttrib`.
11
17
  *
12
18
  * - if `TData` is loose
13
19
  * - if `TData` is already `LooseDecorated`
14
- * - Prepend `TAttrib` to the existing attribute tuple.
20
+ * - Prepend `TAttrib` to the existing attribute tuple, replacing an attribute of the same type.
15
21
  * - else
16
22
  * - Wrap `TData` with `LooseDecorated` and a single attribute `[TAttrib]`
17
23
  * - else
18
24
  * - if `TData` is already `Decorated`
19
- * - Prepend `TAttrib` to the existing attribute tuple.
25
+ * - Prepend `TAttrib` to the existing attribute tuple, replacing an attribute of the same type.
20
26
  * - else
21
27
  * - Wrap `TData` with `Decorated` and a single attribute `[TAttrib]`
22
28
  */
23
- export type Decorate<TData extends BaseData, TAttrib extends AnyAttribute> = IsWgslData<TData> extends true ? Decorated<Undecorate<TData>, [TAttrib, ...ExtractAttributes<TData>]> : IsLooseData<TData> extends true ? LooseDecorated<Undecorate<TData>, [TAttrib, ...ExtractAttributes<TData>]> : never;
29
+ export type Decorate<TData extends BaseData, TAttrib extends AnyAttribute> = IsWgslData<TData> extends true ? Decorated<Undecorate<TData>, [
30
+ TAttrib,
31
+ ...WithoutAttribute<ExtractAttributes<TData>, TAttrib['type']>
32
+ ]> : IsLooseData<TData> extends true ? LooseDecorated<Undecorate<TData>, [
33
+ TAttrib,
34
+ ...WithoutAttribute<ExtractAttributes<TData>, TAttrib['type']>
35
+ ]> : never;
24
36
  export type IsBuiltin<T> = ExtractAttributes<T>[number] extends [] ? false : ExtractAttributes<T>[number] extends Builtin<BuiltinName> ? true : false;
25
37
  export type HasCustomLocation<T> = ExtractAttributes<T>[number] extends [] ? false : ExtractAttributes<T>[number] extends Location ? true : false;
26
38
  export declare function attribute(data: BaseData, attrib: AnyAttribute): Decorated | LooseDecorated;
@@ -117,3 +129,4 @@ export declare function interpolate<TInterpolation extends FlatInterpolationType
117
129
  export declare function invariant(data: Decorated<Vec4f, [Builtin<'position'>]>): Decorated<Vec4f, [Builtin<'position'>, Invariant]>;
118
130
  export declare function isBuiltin(value: unknown): value is Decorated<AnyWgslData, AnyAttribute[]> | LooseDecorated<AnyLooseData, AnyAttribute[]>;
119
131
  export declare function getAttributesString<T extends BaseData>(field: T): string;
132
+ export {};
@@ -30,12 +30,21 @@ export const builtinNames = [
30
30
  'subgroup_id',
31
31
  'num_subgroups',
32
32
  ];
33
+ /**
34
+ * WGSL allows one attribute of each kind, so a new decorator replaces an existing one of the same kind.
35
+ */
36
+ function withAttribute(attribs, attrib) {
37
+ return [
38
+ attrib,
39
+ ...attribs.filter((existing) => existing.type !== attrib.type),
40
+ ];
41
+ }
33
42
  export function attribute(data, attrib) {
34
43
  if (isDecorated(data)) {
35
- return new DecoratedImpl(data.inner, [attrib, ...data.attribs]);
44
+ return new DecoratedImpl(data.inner, withAttribute(data.attribs, attrib));
36
45
  }
37
46
  if (isLooseDecorated(data)) {
38
- return new LooseDecoratedImpl(data.inner, [attrib, ...data.attribs]);
47
+ return new LooseDecoratedImpl(data.inner, withAttribute(data.attribs, attrib));
39
48
  }
40
49
  if (isLooseData(data)) {
41
50
  return new LooseDecoratedImpl(data, [attrib]);
@@ -1,9 +1,9 @@
1
1
  import { roundUp } from "../mathUtils.js";
2
2
  import { logger } from "../tgpuLogger.js";
3
- import { alignmentOf } from "./alignmentOf.js";
4
3
  import { isDisarray, isLooseDecorated, isUnstruct } from "./dataTypes.js";
5
4
  import { offsetsForProps } from "./offsets.js";
6
5
  import { sizeOf } from "./sizeOf.js";
6
+ import { strideOf } from "./schemaMemoryLayout.js";
7
7
  import { formatToWGSLType, isPackedData } from "./vertexFormatData.js";
8
8
  import * as wgsl from "./wgslTypes.js";
9
9
  export const EVAL_ALLOWED_IN_ENV = (() => {
@@ -148,7 +148,7 @@ export function buildWriter(node, offsetExpr, valueExpr, depth = 0, partial = fa
148
148
  if (node.elementCount === 0) {
149
149
  throw new Error('Cannot write using a runtime-sized schema.');
150
150
  }
151
- const elementSize = roundUp(sizeOf(node.elementType), alignmentOf(node));
151
+ const elementSize = strideOf(node);
152
152
  const totalSize = node.elementCount * elementSize;
153
153
  const copyLen = partial
154
154
  ? `Math.min(${valueExpr}.byteLength, Math.max(0, endOffset - (${offsetExpr})))`
package/data/dataIO.js CHANGED
@@ -1,15 +1,64 @@
1
1
  import { BufferReader, BufferWriter, getSystemEndianness, } from 'typed-binary';
2
- import alignIO from "./alignIO.js";
3
- import { alignmentOf, customAlignmentOf } from "./alignmentOf.js";
4
2
  import { mat2x2f, mat3x3f, mat4x4f } from "./matrix.js";
3
+ import { offsetsForProps } from "./offsets.js";
5
4
  import { sizeOf } from "./sizeOf.js";
5
+ import { strideOf } from "./schemaMemoryLayout.js";
6
6
  import { vec2f, vec2h, vec2i, vec2u, vec3f, vec3h, vec3i, vec3u, vec4f, vec4h, vec4i, vec4u, } from "./vector.js";
7
7
  import * as wgsl from "./wgslTypes.js";
8
8
  import { getCompiledWriter } from "./compiledIO.js";
9
9
  import { getName } from "../shared/meta.js";
10
- import { roundUp } from "../mathUtils.js";
11
10
  import { logger } from "../tgpuLogger.js";
12
11
  import { readFloat16, writeFloat16 } from "./float16Conversion.js";
12
+ function writeStructLike(output, schema, value) {
13
+ // The parent has placed us at our offset
14
+ const beginning = output.currentByteOffset;
15
+ for (const [key, { offset }] of Object.entries(offsetsForProps(schema))) {
16
+ const property = schema.propTypes[key];
17
+ output.seekTo(beginning + offset);
18
+ writeData(output, property, value[key]);
19
+ }
20
+ output.seekTo(beginning + sizeOf(schema));
21
+ }
22
+ function writeArrayLike(output, schema, value) {
23
+ if (schema.elementCount === 0) {
24
+ throw new Error('Cannot write using a runtime-sized schema.');
25
+ }
26
+ // The parent has placed us at our offset
27
+ const beginning = output.currentByteOffset;
28
+ const stride = strideOf(schema);
29
+ for (let i = 0; i < Math.min(schema.elementCount, value.length); i++) {
30
+ output.seekTo(beginning + i * stride);
31
+ writeData(output, schema.elementType, value[i]);
32
+ }
33
+ output.seekTo(beginning + sizeOf(schema));
34
+ }
35
+ function readStructLike(input, schema) {
36
+ // The parent has placed us at our offset
37
+ const beginning = input.currentByteOffset;
38
+ const result = {};
39
+ for (const [key, { offset }] of Object.entries(offsetsForProps(schema))) {
40
+ input.seekTo(beginning + offset);
41
+ result[key] = readData(input, schema.propTypes[key]);
42
+ }
43
+ input.seekTo(beginning + sizeOf(schema));
44
+ return result;
45
+ }
46
+ function readArrayLike(input, schema) {
47
+ if (schema.elementCount === 0) {
48
+ throw new Error('Cannot read using a runtime-sized schema.');
49
+ }
50
+ // The parent has placed us at our offset
51
+ const beginning = input.currentByteOffset;
52
+ const stride = strideOf(schema);
53
+ const elements = [];
54
+ for (let i = 0; i < schema.elementCount; i++) {
55
+ input.seekTo(beginning + i * stride);
56
+ const value = readData(input, schema.elementType);
57
+ elements.push(value);
58
+ }
59
+ input.seekTo(beginning + sizeOf(schema));
60
+ return elements;
61
+ }
13
62
  const dataWriters = {
14
63
  bool() {
15
64
  throw new Error('Booleans are not host-shareable');
@@ -123,28 +172,8 @@ const dataWriters = {
123
172
  output.writeFloat32(value[i]);
124
173
  }
125
174
  },
126
- struct(output, schema, value) {
127
- const alignment = alignmentOf(schema);
128
- alignIO(output, alignment);
129
- for (const [key, property] of Object.entries(schema.propTypes)) {
130
- alignIO(output, alignmentOf(property));
131
- writeData(output, property, value[key]);
132
- }
133
- alignIO(output, alignment);
134
- },
135
- array(output, schema, value) {
136
- if (schema.elementCount === 0) {
137
- throw new Error('Cannot write using a runtime-sized schema.');
138
- }
139
- const alignment = alignmentOf(schema);
140
- alignIO(output, alignment);
141
- const beginning = output.currentByteOffset;
142
- for (let i = 0; i < Math.min(schema.elementCount, value.length); i++) {
143
- alignIO(output, alignment);
144
- writeData(output, schema.elementType, value[i]);
145
- }
146
- output.seekTo(beginning + sizeOf(schema));
147
- },
175
+ struct: writeStructLike,
176
+ array: writeArrayLike,
148
177
  ptr() {
149
178
  throw new Error('Pointers are not host-shareable');
150
179
  },
@@ -152,8 +181,6 @@ const dataWriters = {
152
181
  dataWriters[schema.inner.type]?.(output, schema, value);
153
182
  },
154
183
  decorated(output, schema, value) {
155
- const alignment = customAlignmentOf(schema);
156
- alignIO(output, alignment);
157
184
  const beginning = output.currentByteOffset;
158
185
  dataWriters[schema.inner?.type]?.(output, schema.inner, value);
159
186
  output.seekTo(beginning + sizeOf(schema));
@@ -344,25 +371,9 @@ const dataWriters = {
344
371
  output.writeUint8(Math.round(value.x * 255));
345
372
  output.writeUint8(Math.round(value.w * 255));
346
373
  },
347
- disarray(output, schema, value) {
348
- const alignment = alignmentOf(schema);
349
- alignIO(output, alignment);
350
- const beginning = output.currentByteOffset;
351
- for (let i = 0; i < Math.min(schema.elementCount, value.length); i++) {
352
- alignIO(output, alignment);
353
- dataWriters[schema.elementType?.type]?.(output, schema.elementType, value[i]);
354
- }
355
- output.seekTo(beginning + sizeOf(schema));
356
- },
357
- unstruct(output, schema, value) {
358
- const propTypes = schema.propTypes;
359
- for (const [key, property] of Object.entries(propTypes)) {
360
- dataWriters[property.type]?.(output, property, value[key]);
361
- }
362
- },
374
+ disarray: writeArrayLike,
375
+ unstruct: writeStructLike,
363
376
  'loose-decorated'(output, schema, value) {
364
- const alignment = customAlignmentOf(schema);
365
- alignIO(output, alignment);
366
377
  const beginning = output.currentByteOffset;
367
378
  const writer = dataWriters[schema.inner?.type];
368
379
  writer?.(output, schema.inner, value);
@@ -478,33 +489,8 @@ const dataReaders = {
478
489
  //
479
490
  input.readFloat32(), input.readFloat32(), input.readFloat32(), input.readFloat32());
480
491
  },
481
- struct(input, schema) {
482
- const alignment = alignmentOf(schema);
483
- alignIO(input, alignment);
484
- const result = {};
485
- const propTypes = schema.propTypes;
486
- for (const [key, property] of Object.entries(propTypes)) {
487
- alignIO(input, alignmentOf(property));
488
- result[key] = readData(input, property);
489
- }
490
- alignIO(input, alignment);
491
- return result;
492
- },
493
- array(input, schema) {
494
- if (schema.elementCount === 0) {
495
- throw new Error('Cannot read using a runtime-sized schema.');
496
- }
497
- const alignment = alignmentOf(schema);
498
- const elements = [];
499
- for (let i = 0; i < schema.elementCount; i++) {
500
- alignIO(input, alignment);
501
- const elementType = schema.elementType;
502
- const value = readData(input, elementType);
503
- elements.push(value);
504
- }
505
- alignIO(input, alignment);
506
- return elements;
507
- },
492
+ struct: readStructLike,
493
+ array: readArrayLike,
508
494
  ptr() {
509
495
  throw new Error('Pointers are not host-shareable');
510
496
  },
@@ -512,8 +498,6 @@ const dataReaders = {
512
498
  return readData(input, schema.inner);
513
499
  },
514
500
  decorated(input, schema) {
515
- const alignment = customAlignmentOf(schema);
516
- alignIO(input, alignment);
517
501
  const beginning = input.currentByteOffset;
518
502
  const value = readData(input, schema.inner);
519
503
  input.seekTo(beginning + sizeOf(schema));
@@ -578,26 +562,9 @@ const dataReaders = {
578
562
  const a = i.readByte() / 255;
579
563
  return vec4f(r, g, b, a);
580
564
  },
581
- unstruct(input, schema) {
582
- const result = {};
583
- const propTypes = schema.propTypes;
584
- for (const [key, property] of Object.entries(propTypes)) {
585
- result[key] = readData(input, property);
586
- }
587
- return result;
588
- },
589
- disarray(input, schema) {
590
- const alignment = alignmentOf(schema);
591
- const elements = [];
592
- for (let i = 0; i < schema.elementCount; i++) {
593
- alignIO(input, alignment);
594
- elements.push(readData(input, schema.elementType));
595
- }
596
- alignIO(input, alignment);
597
- return elements;
598
- },
565
+ unstruct: readStructLike,
566
+ disarray: readArrayLike,
599
567
  'loose-decorated'(input, schema) {
600
- alignIO(input, customAlignmentOf(schema));
601
568
  const beginning = input.currentByteOffset;
602
569
  const value = readData(input, schema.inner);
603
570
  input.seekTo(beginning + sizeOf(schema));
@@ -619,8 +586,7 @@ export function calculateOffsets(options, schema, data) {
619
586
  let naturalSize = undefined;
620
587
  if (wgsl.isWgslArray(schema) && Array.isArray(data)) {
621
588
  const arrayData = data;
622
- naturalSize =
623
- arrayData.length * roundUp(sizeOf(schema.elementType), alignmentOf(schema.elementType));
589
+ naturalSize = arrayData.length * strideOf(schema);
624
590
  }
625
591
  else if (ArrayBuffer.isView(data) || data instanceof ArrayBuffer) {
626
592
  naturalSize = data.byteLength;
@@ -55,8 +55,6 @@ export interface Unstruct<out TProps extends Record<string, wgsl.BaseData> = Rec
55
55
  }[keyof TProps] extends true ? true : false;
56
56
  readonly [$invalidSchemaReason]: 'Unstructs are not host-shareable, use structs instead';
57
57
  }
58
- /** @deprecated Just use `Unstruct` without any type parameters */
59
- export type AnyUnstruct = Unstruct;
60
58
  export interface LooseDecorated<out TInner extends wgsl.BaseData = wgsl.BaseData, out TAttribs extends unknown[] = unknown[]> extends wgsl.BaseData {
61
59
  readonly type: 'loose-decorated';
62
60
  readonly inner: TInner;
package/data/dataTypes.js CHANGED
@@ -36,7 +36,7 @@ export function isLooseData(data) {
36
36
  * isDisarray(d.vec3f) // false
37
37
  */
38
38
  export function isDisarray(schema) {
39
- return isMarkedInternal(schema) && schema?.type === 'disarray';
39
+ return schema?.type === 'disarray' && isMarkedInternal(schema);
40
40
  }
41
41
  /**
42
42
  * Checks whether passed in value is a unstruct schema,
@@ -52,10 +52,10 @@ export function isDisarray(schema) {
52
52
  * isUnstruct(d.vec3f) // false
53
53
  */
54
54
  export function isUnstruct(schema) {
55
- return isMarkedInternal(schema) && schema?.type === 'unstruct';
55
+ return schema?.type === 'unstruct' && isMarkedInternal(schema);
56
56
  }
57
57
  export function isLooseDecorated(value) {
58
- return isMarkedInternal(value) && value?.type === 'loose-decorated';
58
+ return value?.type === 'loose-decorated' && isMarkedInternal(value);
59
59
  }
60
60
  export function getCustomAlignment(data) {
61
61
  return data.attribs?.find(wgsl.isAlignAttrib)
package/data/disarray.js CHANGED
@@ -56,3 +56,5 @@ const DisarrayImpl = {
56
56
  return `disarrayOf(${this.elementType}, ${this.elementCount})`;
57
57
  },
58
58
  };
59
+ // Schemas are still functions, so they should keep `call`, `apply`, `bind`, etc.
60
+ Object.setPrototypeOf(DisarrayImpl, Function.prototype);
@@ -1,11 +1,11 @@
1
- import { roundUp } from "../mathUtils.js";
2
- import { alignmentOf } from "./alignmentOf.js";
3
1
  import { offsetsForProps } from "./offsets.js";
4
2
  import { sizeOf } from "./sizeOf.js";
3
+ import { strideOf } from "./schemaMemoryLayout.js";
5
4
  import { isContiguous } from "./isContiguous.js";
6
5
  import { getLongestContiguousPrefix } from "./getLongestContiguousPrefix.js";
7
6
  import { isMat, isVec, isWgslArray, isWgslStruct } from "./wgslTypes.js";
8
7
  import { isDisarray, isUnstruct, undecorate } from "./dataTypes.js";
8
+ import { isPackedData } from "./vertexFormatData.js";
9
9
  import { vec2f, vec3f, vec4f } from "./vector.js";
10
10
  /**
11
11
  * The absolute byte offset of the node, counted from the start of the root schema.
@@ -42,26 +42,23 @@ function getMarker(target, prop) {
42
42
  }
43
43
  return undefined;
44
44
  }
45
- function throwIfLoose(schema) {
46
- if (isUnstruct(schema) || isDisarray(schema)) {
47
- throw new Error(`memoryLayoutOf: loose schemas are not supported (encountered '${schema.type}').`);
48
- }
49
- }
50
45
  function makeProxy(schema, baseOffset, contiguous) {
51
46
  const unwrapped = undecorate(schema);
52
- throwIfLoose(unwrapped);
53
47
  if (isVec(unwrapped)) {
54
48
  return makeVecProxy(unwrapped, scalarNode(baseOffset, contiguous));
55
49
  }
56
50
  if (isMat(unwrapped)) {
57
51
  return makeMatProxy(unwrapped, scalarNode(baseOffset, contiguous));
58
52
  }
59
- if (isWgslStruct(unwrapped)) {
53
+ if (isWgslStruct(unwrapped) || isUnstruct(unwrapped)) {
60
54
  return makeStructProxy(unwrapped, scalarNode(baseOffset, contiguous));
61
55
  }
62
- if (isWgslArray(unwrapped)) {
56
+ if (isWgslArray(unwrapped) || isDisarray(unwrapped)) {
63
57
  return makeArrayProxy(unwrapped, scalarNode(baseOffset, contiguous));
64
58
  }
59
+ if (isPackedData(unwrapped)) {
60
+ return makePackedProxy(unwrapped, scalarNode(baseOffset, contiguous));
61
+ }
65
62
  return scalarNode(baseOffset, contiguous);
66
63
  }
67
64
  export function createOffsetProxy(schema, baseOffset = 0) {
@@ -104,6 +101,20 @@ function makeVecProxy(vec, parent) {
104
101
  },
105
102
  });
106
103
  }
104
+ function makePackedProxy(packed, parent) {
105
+ return new Proxy(parent, {
106
+ get(t, prop) {
107
+ const marker = getMarker(t, prop);
108
+ if (marker !== undefined) {
109
+ return marker;
110
+ }
111
+ if (typeof prop === 'string' && vecPropToIndex[prop] !== undefined) {
112
+ throw new Error(`memoryLayoutOf: accessing components of packed vertex format '${packed.type}' is not supported.`);
113
+ }
114
+ return undefined;
115
+ },
116
+ });
117
+ }
107
118
  function makeMatProxy(mat, parent) {
108
119
  const [columnCount, columnSchema] = mat.type === 'mat2x2f' ? [2, vec2f] : mat.type === 'mat3x3f' ? [3, vec3f] : [4, vec4f];
109
120
  const elementSize = 4;
@@ -166,8 +177,8 @@ function makeMatProxy(mat, parent) {
166
177
  }
167
178
  function makeArrayProxy(array, parent) {
168
179
  const elementType = array.elementType;
169
- const elementSize = sizeOf(elementType);
170
- const stride = roundUp(elementSize, alignmentOf(elementType));
180
+ const elementSize = sizeOf(undecorate(elementType));
181
+ const stride = strideOf(array);
171
182
  const hasPadding = stride > elementSize;
172
183
  const elementLCP = getLongestContiguousPrefix(elementType);
173
184
  const remainingFromParent = parent[CONTIGUOUS_MARKER];
@@ -287,7 +298,6 @@ function makeStructProxy(struct, parent) {
287
298
  * @returns An object containing the offset and contiguous byte information.
288
299
  */
289
300
  export function memoryLayoutOf(schema, accessor) {
290
- throwIfLoose(undecorate(schema));
291
301
  if (!accessor) {
292
302
  return {
293
303
  offset: 0,
package/data/offsets.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { Measurer } from 'typed-binary';
2
- import { roundUp } from "../mathUtils.js";
3
2
  import alignIO from "./alignIO.js";
4
3
  import { alignmentOf, customAlignmentOf } from "./alignmentOf.js";
5
4
  import { isUnstruct } from "./dataTypes.js";
@@ -29,7 +28,7 @@ export function offsetsForProps(struct) {
29
28
  measurer.add(propSize);
30
29
  }
31
30
  if (lastEntry) {
32
- lastEntry.padding = roundUp(sizeOf(struct), alignmentOf(struct)) - measurer.size;
31
+ lastEntry.padding = sizeOf(struct) - measurer.size;
33
32
  }
34
33
  cachedOffsets.set(struct, offsets);
35
34
  return offsets;
package/data/partialIO.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import { BufferWriter, getSystemEndianness } from 'typed-binary';
2
- import { roundUp } from "../mathUtils.js";
3
- import { alignmentOf } from "./alignmentOf.js";
4
2
  import { getCompiledWriter } from "./compiledIO.js";
5
3
  import { writeData } from "./dataIO.js";
6
4
  import { isDisarray, isUnstruct } from "./dataTypes.js";
7
5
  import { offsetsForProps } from "./offsets.js";
8
6
  import { sizeOf } from "./sizeOf.js";
7
+ import { strideOf } from "./schemaMemoryLayout.js";
9
8
  import { isWgslArray, isWgslStruct } from "./wgslTypes.js";
10
9
  /**
11
10
  * Converts `{idx, value}[]` sparse arrays into `Record<number, T>` format.
@@ -70,7 +69,7 @@ export function getPatchInstructions(schema, data, targetBuffer, validateRange)
70
69
  }
71
70
  if (isWgslArray(node) || isDisarray(node)) {
72
71
  const arrSchema = node;
73
- const elementSize = roundUp(sizeOf(arrSchema.elementType), alignmentOf(arrSchema.elementType));
72
+ const elementSize = strideOf(arrSchema);
74
73
  const elementPadding = elementSize - sizeOf(arrSchema.elementType);
75
74
  if (ArrayBuffer.isView(value)) {
76
75
  const copyLen = Math.min(value.byteLength, arrSchema.elementCount * elementSize);
package/data/ref.js CHANGED
@@ -13,49 +13,47 @@ export const _ref = (() => {
13
13
  setName(impl, 'ref');
14
14
  impl.toString = () => 'ref';
15
15
  impl[$internal] = true;
16
- impl[$gpuCallable] = {
17
- call(ctx, [value]) {
18
- if (value.origin === 'argument') {
19
- throw new WgslTypeError(`d.ref(${stringifySnippet(value)}) is illegal, cannot take a reference of an argument. Copy the value first, and take a reference of the copy.`);
20
- }
21
- if (value.origin === 'constant-immutable-def' || value.origin === 'runtime-immutable-def') {
22
- const typeStr = ctx.resolve(value.dataType).value;
23
- throw new WgslTypeError(`d.ref(${stringifySnippet(value)}) is illegal, cannot take a reference to a constant.
16
+ impl[$gpuCallable] = (ctx, [value]) => {
17
+ if (value.origin === 'argument') {
18
+ throw new WgslTypeError(`d.ref(${stringifySnippet(value)}) is illegal, cannot take a reference of an argument. Copy the value first, and take a reference of the copy.`);
19
+ }
20
+ if (value.origin === 'constant-immutable-def' || value.origin === 'runtime-immutable-def') {
21
+ const typeStr = ctx.resolve(value.dataType).value;
22
+ throw new WgslTypeError(`d.ref(${stringifySnippet(value)}) is illegal, cannot take a reference to a constant.
24
23
  -----
25
24
  - Try 'd.ref(${typeStr}(${stringifySnippet(value)}));' instead to create a new referencable value.
26
25
  -----`);
27
- }
28
- if (isStoredInMemory(value) && isNaturallyEphemeral(value.dataType)) {
29
- const typeStr = ctx.resolve(value.dataType).value;
30
- throw new WgslTypeError(`d.ref(${stringifySnippet(value)}) is illegal, cannot take a reference to a scalar value.
26
+ }
27
+ if (isStoredInMemory(value) && isNaturallyEphemeral(value.dataType)) {
28
+ const typeStr = ctx.resolve(value.dataType).value;
29
+ throw new WgslTypeError(`d.ref(${stringifySnippet(value)}) is illegal, cannot take a reference to a scalar value.
31
30
  -----
32
31
  - Try 'd.ref(${typeStr}(${stringifySnippet(value)}));' instead to create a new referencable scalar.
33
32
  -----`);
34
- }
35
- if (isPtr(value.dataType)) {
36
- // This can happen if we take a reference of an *implicit* pointer, one
37
- // made by assigning a reference to a `const`.
38
- return withDataType(explicitFrom(value.dataType), value);
39
- }
40
- if (value.dataType === UnknownData || isVoid(value.dataType)) {
41
- throw new WgslTypeError(`d.ref(${stringifySnippet(value)}) is illegal, cannot determine the WGSL type of '${stringifySnippet(value)}'.`);
42
- }
43
- /**
44
- * The value is addressable only if the ref was created from a reference (buttery-butter).
45
- *
46
- * @example
47
- * ```ts
48
- * const life = ref(42); // created from a value, has to be stored in a variable
49
- * const boid = ref(layout.$.boids[0]); // created from a reference
50
- * ```
51
- */
52
- const ptrType = createPtrFromOrigin(value.origin, value.dataType) ??
53
- // Values that are not addressable become addressable once stored in a
54
- // function-scope variable (`const life = d.ref(42)`), so that's the type they get.
55
- ptrFn(concretize(value.dataType));
56
- return snip(new RefOperator(value, ptrType), ptrType,
57
- /* origin */ 'runtime', value.possibleSideEffects);
58
- },
33
+ }
34
+ if (isPtr(value.dataType)) {
35
+ // This can happen if we take a reference of an *implicit* pointer, one
36
+ // made by assigning a reference to a `const`.
37
+ return withDataType(explicitFrom(value.dataType), value);
38
+ }
39
+ if (value.dataType === UnknownData || isVoid(value.dataType)) {
40
+ throw new WgslTypeError(`d.ref(${stringifySnippet(value)}) is illegal, cannot determine the WGSL type of '${stringifySnippet(value)}'.`);
41
+ }
42
+ /**
43
+ * The value is addressable only if the ref was created from a reference (buttery-butter).
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * const life = ref(42); // created from a value, has to be stored in a variable
48
+ * const boid = ref(layout.$.boids[0]); // created from a reference
49
+ * ```
50
+ */
51
+ const ptrType = createPtrFromOrigin(value.origin, value.dataType) ??
52
+ // Values that are not addressable become addressable once stored in a
53
+ // function-scope variable (`const life = d.ref(42)`), so that's the type they get.
54
+ ptrFn(concretize(value.dataType));
55
+ return snip(new RefOperator(value, ptrType), ptrType,
56
+ /* origin */ 'runtime', value.possibleSideEffects);
59
57
  };
60
58
  return impl;
61
59
  })();
@@ -32,6 +32,6 @@ export function schemaCallWrapperGPU(ctx, schema, item) {
32
32
  }
33
33
  const callSchema = schema;
34
34
  return item === undefined || item.value === undefined
35
- ? callSchema[$gpuCallable].call(ctx, [])
36
- : callSchema[$gpuCallable].call(ctx, [item]);
35
+ ? callSchema[$gpuCallable](ctx, [])
36
+ : callSchema[$gpuCallable](ctx, [item]);
37
37
  }
@@ -1,8 +1,13 @@
1
- import type { BaseData } from './wgslTypes.ts';
1
+ import type { Disarray } from './dataTypes.ts';
2
+ import type { BaseData, WgslArray } from './wgslTypes.ts';
2
3
  interface SchemaMemoryLayout {
3
4
  isContiguous: boolean;
4
5
  size: number;
5
6
  longestContiguousPrefix: number;
6
7
  }
8
+ /**
9
+ * Returns the distance (in bytes) between the starts of consecutive elements of an array.
10
+ */
11
+ export declare function strideOf(schema: WgslArray | Disarray): number;
7
12
  export declare function getLayoutInfo<T extends keyof SchemaMemoryLayout>(schema: BaseData, key: T): SchemaMemoryLayout[T];
8
13
  export {};