typegpu 0.12.8 → 0.12.9

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.
@@ -11,6 +11,7 @@ export class MissingCpuImplError extends Error {
11
11
  this.name = this.constructor.name;
12
12
  }
13
13
  }
14
+ /*#__NO_SIDE_EFFECTS__*/
14
15
  export function dualImpl(options) {
15
16
  const impl = ((...args) => {
16
17
  if (typeof options.normalImpl === 'string') {
@@ -19,6 +19,7 @@ type TgpuFnShellHeader<Args extends BaseData[], Return extends BaseData> = {
19
19
  * Describes a function signature (its arguments and return type).
20
20
  * Allows creating tgpu functions by calling this shell
21
21
  * and passing the implementation (as WGSL string or JS function) as the argument.
22
+ * An already shelled function is reused when its argument and return schemas match.
22
23
  */
23
24
  export type TgpuFnShell<Args extends BaseData[], Return extends BaseData> = TgpuFnShellHeader<Args, Return> & (<T extends (...args: InferArgs<Args>) => InferGPU<Return>>(implementation: T) => TgpuFn<Prettify<InheritArgNames<(...args: Args) => Return, T>>['result']>) & ((implementation: string) => TgpuFn<(...args: Args) => Return>) & ((strings: TemplateStringsArray, ...values: unknown[]) => TgpuFn<(...args: Args) => Return>);
24
25
  interface TgpuFnBase<ImplSchema extends AnyFn> extends TgpuNamable, Withable<TgpuFn<ImplSchema>> {
@@ -1,4 +1,5 @@
1
1
  import { schemaCallWrapper } from "../../data/schemaCallWrapper.js";
2
+ import { schemasEqualNominally } from "../../data/schemasEqual.js";
2
3
  import { Void } from "../../data/wgslTypes.js";
3
4
  import { ExecutionError } from "../../errors.js";
4
5
  import { provideInsideTgpuFn } from "../../execMode.js";
@@ -44,6 +45,15 @@ function bindingsOf(transform) {
44
45
  return transform(new ConfigurableImpl([])).bindings;
45
46
  }
46
47
  function createFn(shell, _implementation) {
48
+ if (isTgpuFn(_implementation)) {
49
+ const innerShell = _implementation.shell;
50
+ if (!schemasEqualNominally(innerShell.returnType, shell.returnType) ||
51
+ innerShell.argTypes.length !== shell.argTypes.length ||
52
+ !shell.argTypes.every((type, index) => schemasEqualNominally(type, innerShell.argTypes[index]))) {
53
+ throw new Error('Cannot wrap a shelled function with a different signature');
54
+ }
55
+ return _implementation;
56
+ }
47
57
  let pairs = [];
48
58
  // Unwrapping generic functions
49
59
  let implementation;
@@ -41,6 +41,7 @@ export function INTERNAL_restoreComputePipeline(soul, ctx) {
41
41
  }
42
42
  class TgpuComputePipelineImpl {
43
43
  [$internal];
44
+ #unbound;
44
45
  [$soul];
45
46
  resourceType = 'compute-pipeline';
46
47
  [$getNameForward];
@@ -86,7 +87,9 @@ class TgpuComputePipelineImpl {
86
87
  with(first, resource) {
87
88
  const internals = this[$internal];
88
89
  if (isTgpuComputePass(first)) {
89
- return this.#withPriors({ pass: first, encoder: undefined });
90
+ const bound = this.#withPriors({ pass: first, encoder: undefined });
91
+ bound.#unbound = this.#unbound ?? this;
92
+ return bound;
90
93
  }
91
94
  if (isTgpuCommandEncoder(first)) {
92
95
  return this.#withPriors({ pass: undefined, encoder: first });
@@ -157,7 +160,7 @@ class TgpuComputePipelineImpl {
157
160
  #execute(dispatch) {
158
161
  const { core, priors, root } = this[$internal];
159
162
  if (priors.pass) {
160
- emitComputeDispatch(root, priors.pass[$internal], this, dispatch);
163
+ emitComputeDispatch(root, priors.pass[$internal], this.#unbound ?? this, dispatch);
161
164
  return;
162
165
  }
163
166
  const encoder = priors.encoder ?? INTERNAL_createCommandEncoder(root);
@@ -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
@@ -34,8 +34,15 @@ function requiredAlignOf(schema) {
34
34
  * See https://www.w3.org/TR/WGSL/#address-space-layout-constraints
35
35
  */
36
36
  export function warnIfNotUniformAligned(schema) {
37
+ if (!logger.isEnabled('uniform-schema-misaligned')) {
38
+ // Silenced by default in production, and computing memory layouts isn't free
39
+ return;
40
+ }
41
+ checkUniformAlignment(schema);
42
+ }
43
+ function checkUniformAlignment(schema) {
37
44
  if (isWgslArray(schema)) {
38
- warnIfNotUniformAligned(schema.elementType);
45
+ checkUniformAlignment(schema.elementType);
39
46
  const stride = roundUp(sizeOf(schema.elementType), alignmentOf(schema.elementType));
40
47
  if (stride % 16 !== 0) {
41
48
  logger.warn('uniform-schema-misaligned', `\
@@ -45,7 +52,7 @@ To address this, put the element schema in a struct and wrap the prop in 'd.alig
45
52
  }
46
53
  }
47
54
  if (isWgslStruct(schema)) {
48
- Object.values(schema.propTypes).forEach(warnIfNotUniformAligned);
55
+ Object.values(schema.propTypes).forEach(checkUniformAlignment);
49
56
  Object.entries(schema.propTypes).forEach(([key, value]) => {
50
57
  const offset = memoryLayoutOf(schema, (schema) => schema[key]).offset;
51
58
  const requiredAlignment = requiredAlignOf(value);
@@ -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 {
@@ -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,
@@ -152,6 +152,7 @@ export interface TgpuTextureRenderView {
152
152
  readonly descriptor: TgpuTextureViewDescriptor;
153
153
  }
154
154
  export declare function INTERNAL_createTexture(props: TextureProps, root: ExperimentalTgpuRoot, rawTexture?: GPUTexture): TgpuTexture<TextureProps>;
155
+ export declare function INTERNAL_restoreTextureView(soul: TgpuTextureViewSoul): TgpuTextureView | TgpuTextureRenderView;
155
156
  export declare function isTexture(value: unknown): value is TgpuTexture;
156
157
  export declare function isTextureView(value: unknown): value is TgpuTextureView;
157
158
  export declare class TgpuLaidOutTextureViewImpl<T extends WgslTexture | WgslStorageTexture> implements TgpuTextureView<T>, SelfResolvable {
@@ -174,6 +175,6 @@ export declare class TgpuTextureRenderViewImpl implements TgpuTextureRenderView
174
175
  readonly [$internal]: TextureViewInternals;
175
176
  readonly [$soul]: TgpuTextureViewSoul<'render'>;
176
177
  readonly resourceType: "texture-view";
177
- constructor(baseTexture: TgpuTexture, descriptor?: TgpuTextureViewDescriptor);
178
+ constructor(soul: TgpuTextureViewSoul<'render'>);
178
179
  get descriptor(): TgpuTextureViewDescriptor;
179
180
  }
@@ -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,10 +131,15 @@ 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
145
  const [width, height, depth] = mipLevelSize(this.props, mip);
@@ -268,15 +280,9 @@ class TgpuFixedTextureViewImpl {
268
280
  [$internal];
269
281
  [$soul];
270
282
  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
- };
283
+ constructor(soul) {
284
+ this[$soul] = { ...soul };
285
+ const { texture, schema, descriptor } = soul;
280
286
  this[$internal] = {
281
287
  unwrap: () => {
282
288
  const soul = this[$soul];
@@ -292,8 +298,7 @@ class TgpuFixedTextureViewImpl {
292
298
  }
293
299
  return soul.raw;
294
300
  },
295
- format: descriptor?.format ??
296
- (isWgslStorageTexture(schema) ? schema.format : baseTexture.props.format),
301
+ format: descriptor?.format ?? (isWgslStorageTexture(schema) ? schema.format : texture.props.format),
297
302
  aspect: descriptor?.aspect,
298
303
  };
299
304
  }
@@ -397,15 +402,9 @@ export class TgpuTextureRenderViewImpl {
397
402
  [$internal];
398
403
  [$soul];
399
404
  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
- };
405
+ constructor(soul) {
406
+ this[$soul] = { ...soul };
407
+ const { texture, descriptor } = soul;
409
408
  this[$internal] = {
410
409
  unwrap: () => {
411
410
  const soul = this[$soul];
@@ -417,8 +416,8 @@ export class TgpuTextureRenderViewImpl {
417
416
  }
418
417
  return soul.raw;
419
418
  },
420
- format: descriptor.format ?? baseTexture.props.format,
421
- aspect: descriptor.aspect,
419
+ format: descriptor?.format ?? texture.props.format,
420
+ aspect: descriptor?.aspect,
422
421
  };
423
422
  }
424
423
  get descriptor() {
@@ -112,7 +112,7 @@ const vertexFormatValueTransform = {
112
112
  const specialPackedFormats = {
113
113
  'unorm10-10-10-2': {
114
114
  writeFunction: 'setUint32',
115
- generator: (offsetExpr, valueExpr) => `output.setUint32(${offsetExpr}, ((${valueExpr}.x*1023&0x3FF)<<22)|((${valueExpr}.y*1023&0x3FF)<<12)|((${valueExpr}.z*1023&0x3FF)<<2)|(${valueExpr}.w*3&3), littleEndian);\n`,
115
+ generator: (offsetExpr, valueExpr) => `output.setUint32(${offsetExpr}, ((Math.round(${valueExpr}.x*1023)&0x3FF)<<22)|((Math.round(${valueExpr}.y*1023)&0x3FF)<<12)|((Math.round(${valueExpr}.z*1023)&0x3FF)<<2)|(Math.round(${valueExpr}.w*3)&3), littleEndian);\n`,
116
116
  },
117
117
  'unorm8x4-bgra': {
118
118
  writeFunction: 'setUint8',
package/data/dataIO.js CHANGED
@@ -238,17 +238,17 @@ const dataWriters = {
238
238
  output.writeInt16(value.w);
239
239
  },
240
240
  unorm16(output, _, value) {
241
- output.writeUint16(value * 65535);
241
+ output.writeUint16(Math.round(value * 65535));
242
242
  },
243
243
  unorm16x2(output, _, value) {
244
- output.writeUint16(value.x * 65535);
245
- output.writeUint16(value.y * 65535);
244
+ output.writeUint16(Math.round(value.x * 65535));
245
+ output.writeUint16(Math.round(value.y * 65535));
246
246
  },
247
247
  unorm16x4(output, _, value) {
248
- output.writeUint16(value.x * 65535);
249
- output.writeUint16(value.y * 65535);
250
- output.writeUint16(value.z * 65535);
251
- output.writeUint16(value.w * 65535);
248
+ output.writeUint16(Math.round(value.x * 65535));
249
+ output.writeUint16(Math.round(value.y * 65535));
250
+ output.writeUint16(Math.round(value.z * 65535));
251
+ output.writeUint16(Math.round(value.w * 65535));
252
252
  },
253
253
  snorm16(output, _, value) {
254
254
  output.writeInt16(Math.round(value * 32767));
@@ -332,17 +332,17 @@ const dataWriters = {
332
332
  },
333
333
  'unorm10-10-10-2'(output, _, value) {
334
334
  let packed = 0;
335
- packed |= ((value.x * 1023) & 1023) << 22; // r (10 bits)
336
- packed |= ((value.y * 1023) & 1023) << 12; // g (10 bits)
337
- packed |= ((value.z * 1023) & 1023) << 2; // b (10 bits)
338
- packed |= (value.w * 3) & 3; // a (2 bits)
335
+ packed |= (Math.round(value.x * 1023) & 1023) << 22; // r (10 bits)
336
+ packed |= (Math.round(value.y * 1023) & 1023) << 12; // g (10 bits)
337
+ packed |= (Math.round(value.z * 1023) & 1023) << 2; // b (10 bits)
338
+ packed |= Math.round(value.w * 3) & 3; // a (2 bits)
339
339
  output.writeUint32(packed);
340
340
  },
341
341
  'unorm8x4-bgra'(output, _, value) {
342
- output.writeUint8(value.z * 255);
343
- output.writeUint8(value.y * 255);
344
- output.writeUint8(value.x * 255);
345
- output.writeUint8(value.w * 255);
342
+ output.writeUint8(Math.round(value.z * 255));
343
+ output.writeUint8(Math.round(value.y * 255));
344
+ output.writeUint8(Math.round(value.x * 255));
345
+ output.writeUint8(Math.round(value.w * 255));
346
346
  },
347
347
  disarray(output, schema, value) {
348
348
  const alignment = alignmentOf(schema);
@@ -565,7 +565,7 @@ const dataReaders = {
565
565
  sint32x4: (i) => vec4i(i.readInt32(), i.readInt32(), i.readInt32(), i.readInt32()),
566
566
  'unorm10-10-10-2'(i) {
567
567
  const packed = i.readUint32();
568
- const r = (packed >> 22) / 1023;
568
+ const r = (packed >>> 22) / 1023;
569
569
  const g = ((packed >> 12) & 1023) / 1023;
570
570
  const b = ((packed >> 2) & 1023) / 1023;
571
571
  const a = (packed & 3) / 3;
package/data/index.d.ts CHANGED
@@ -19,9 +19,9 @@ export declare const vec4u: import("./wgslTypes.ts").Vec4u;
19
19
  export declare const mat2x2f: import("./wgslTypes.ts").Mat2x2f;
20
20
  export declare const mat3x3f: import("./wgslTypes.ts").Mat3x3f;
21
21
  export declare const mat4x4f: import("./wgslTypes.ts").Mat4x4f;
22
- export { bool, f16, f32, i32, u16, u32 } from './numeric.ts';
22
+ export { abstractFloat, abstractInt, bool, f16, f32, i32, u16, u32 } from './numeric.ts';
23
23
  export { isAlignAttrib, isAtomic, isBuiltinAttrib, isDecorated, isInterpolateAttrib, isInvariantAttrib, isLocationAttrib, isPtr, isSizeAttrib, isWgslArray, isWgslData, isWgslStruct, Void, } from './wgslTypes.ts';
24
- export type { Align, AnyVecInstance, AnyWgslData, AnyWgslStruct, Atomic, atomicI32, atomicU32, BaseData, BaseData as BaseWgslData, Bool, Builtin, Decorated, F16, F32, I32, Interpolate, Invariant, Location, m2x2f, m3x3f, m4x4f, Mat2x2f, Mat3x3f, Mat4x4f, matBase, Ptr, Size, StorableData, U16, U32, v2b, v2f, v2h, v2i, v2u, v3b, v3f, v3h, v3i, v3u, v4b, v4f, v4h, v4i, v4u, Vec2b, Vec2f, Vec2h, Vec2i, Vec2u, Vec3b, Vec3f, Vec3h, Vec3i, Vec3u, Vec4b, Vec4f, Vec4h, Vec4i, Vec4u, vecBase, WgslArray, WgslStruct, } from './wgslTypes.ts';
24
+ export type { AbstractFloat, AbstractInt, Align, AnyVecInstance, AnyWgslData, AnyWgslStruct, Atomic, atomicI32, atomicU32, BaseData, BaseData as BaseWgslData, Bool, Builtin, Decorated, F16, F32, I32, Interpolate, Invariant, Location, m2x2f, m3x3f, m4x4f, Mat2x2f, Mat3x3f, Mat4x4f, matBase, Ptr, Size, StorableData, U16, U32, v2b, v2f, v2h, v2i, v2u, v3b, v3f, v3h, v3i, v3u, v4b, v4f, v4h, v4i, v4u, Vec2b, Vec2f, Vec2h, Vec2i, Vec2u, Vec3b, Vec3f, Vec3h, Vec3i, Vec3u, Vec4b, Vec4f, Vec4h, Vec4i, Vec4u, vecBase, WgslArray, WgslStruct, } from './wgslTypes.ts';
25
25
  export { struct } from './struct.ts';
26
26
  export { arrayOf } from './array.ts';
27
27
  export { ptrFn, ptrHandle, ptrPrivate, ptrStorage, ptrUniform, ptrWorkgroup } from './ptr.ts';
@@ -42,6 +42,7 @@ export { PUBLIC_getLongestContiguousPrefix as getLongestContiguousPrefix } from
42
42
  export { memoryLayoutOf } from './offsetUtils.ts';
43
43
  export { PUBLIC_alignmentOf as alignmentOf } from './alignmentOf.ts';
44
44
  export { builtin } from '../builtin.ts';
45
- export { deepEqual } from './deepEqual.ts';
45
+ export { schemasEqualStructurally, schemasEqualNominally,
46
+ /** @deprecated Use `schemasEqualStructurally` instead */ schemasEqualStructurally as deepEqual, } from './schemasEqual.ts';
46
47
  export type { AnyBuiltin, BuiltinClipDistances, BuiltinFragDepth, BuiltinFrontFacing, BuiltinGlobalInvocationId, BuiltinGlobalInvocationIndex, BuiltinInstanceIndex, BuiltinLocalInvocationId, BuiltinLocalInvocationIndex, BuiltinNumSubgroups, BuiltinNumWorkgroups, BuiltinPosition, BuiltinPrimitiveIndex, BuiltinSampleIndex, BuiltinSampleMask, BuiltinSubgroupId, BuiltinSubgroupInvocationId, BuiltinSubgroupSize, BuiltinVertexIndex, BuiltinWorkgroupId, BuiltinWorkgroupIndex, } from '../builtin.ts';
47
48
  export type { Infer, InferGPU, InferInput, InferPartial, InferPatch, MemIdentity, } from '../shared/repr.ts';
package/data/index.js CHANGED
@@ -23,7 +23,7 @@ import { mat2x2f as _mat2x2f, mat3x3f as _mat3x3f, mat4x4f as _mat4x4f } from ".
23
23
  export const mat2x2f = (() => (assignInfixOperators(), _mat2x2f))();
24
24
  export const mat3x3f = (() => (assignInfixOperators(), _mat3x3f))();
25
25
  export const mat4x4f = (() => (assignInfixOperators(), _mat4x4f))();
26
- export { bool, f16, f32, i32, u16, u32 } from "./numeric.js";
26
+ export { abstractFloat, abstractInt, bool, f16, f32, i32, u16, u32 } from "./numeric.js";
27
27
  export { isAlignAttrib, isAtomic, isBuiltinAttrib, isDecorated, isInterpolateAttrib, isInvariantAttrib, isLocationAttrib, isPtr, isSizeAttrib, isWgslArray, isWgslData, isWgslStruct, Void, } from "./wgslTypes.js";
28
28
  export { struct } from "./struct.js";
29
29
  export { arrayOf } from "./array.js";
@@ -44,4 +44,5 @@ export { PUBLIC_getLongestContiguousPrefix as getLongestContiguousPrefix } from
44
44
  export { memoryLayoutOf } from "./offsetUtils.js";
45
45
  export { PUBLIC_alignmentOf as alignmentOf } from "./alignmentOf.js";
46
46
  export { builtin } from "../builtin.js";
47
- export { deepEqual } from "./deepEqual.js";
47
+ export { schemasEqualStructurally, schemasEqualNominally,
48
+ /** @deprecated Use `schemasEqualStructurally` instead */ schemasEqualStructurally as deepEqual, } from "./schemasEqual.js";
@@ -0,0 +1,37 @@
1
+ import type { AnyData } from './dataTypes.ts';
2
+ /**
3
+ * Performs a structural comparison of two TypeGPU data schemas. This
4
+ * means two struct definitions are considered equal when they have the
5
+ * same properties. Use `schemasEqualNominally` for a nominal comparison.
6
+ *
7
+ * @param a The first data schema to compare.
8
+ * @param b The second data schema to compare.
9
+ * @returns `true` if the schemas are structurally equal, `false` otherwise.
10
+ *
11
+ * @example
12
+ * import { vec3f, struct, schemasEqualStructurally } from 'typegpu/data';
13
+ *
14
+ * console.log(schemasEqualStructurally(struct({ a: vec3f }), struct({ a: vec3f }))); // true
15
+ * console.log(schemasEqualStructurally(struct({ a: vec3f }), struct({ b: vec3f }))); // false
16
+ */
17
+ export declare const schemasEqualStructurally: import("../indexNamedExports.ts").TgpuComptime<(a: AnyData, b: AnyData) => boolean>;
18
+ /**
19
+ * Performs a nominal comparison of two TypeGPU data schemas. This
20
+ * means two struct definitions are only considered equal when they
21
+ * have the same object identity. Use `schemasEqualStructurally` for
22
+ * a structural comparison.
23
+ *
24
+ * @param a The first data schema to compare.
25
+ * @param b The second data schema to compare.
26
+ * @returns `true` if the schemas are nominally equal, `false` otherwise.
27
+ *
28
+ * @example
29
+ * import { vec3f, struct, schemasEqualNominally } from 'typegpu/data';
30
+ *
31
+ * const struct1 = struct({ a: vec3f });
32
+ * const struct2 = struct({ a: vec3f });
33
+ *
34
+ * console.log(schemasEqualNominally(d.arrayOf(struct1, 2), d.arrayOf(struct1, 2))); // true
35
+ * console.log(schemasEqualNominally(struct1, struct2)); // false
36
+ */
37
+ export declare const schemasEqualNominally: import("../indexNamedExports.ts").TgpuComptime<(a: AnyData, b: AnyData) => boolean>;
@@ -0,0 +1,131 @@
1
+ import { comptime } from "../core/function/comptime.js";
2
+ import { isDisarray, isLooseDecorated, isUnstruct } from "./dataTypes.js";
3
+ import { isWgslStorageTexture, isWgslTexture } from "./texture.js";
4
+ import { isAtomic, isDecorated, isPtr, isWgslArray, isWgslStruct } from "./wgslTypes.js";
5
+ /**
6
+ * Performs a structural comparison of two TypeGPU data schemas. This
7
+ * means two struct definitions are considered equal when they have the
8
+ * same properties. Use `schemasEqualNominally` for a nominal comparison.
9
+ *
10
+ * @param a The first data schema to compare.
11
+ * @param b The second data schema to compare.
12
+ * @returns `true` if the schemas are structurally equal, `false` otherwise.
13
+ *
14
+ * @example
15
+ * import { vec3f, struct, schemasEqualStructurally } from 'typegpu/data';
16
+ *
17
+ * console.log(schemasEqualStructurally(struct({ a: vec3f }), struct({ a: vec3f }))); // true
18
+ * console.log(schemasEqualStructurally(struct({ a: vec3f }), struct({ b: vec3f }))); // false
19
+ */
20
+ export const schemasEqualStructurally = comptime((a, b) => schemasEqual(a, b, true)).$name('schemasEqualStructurally');
21
+ /**
22
+ * Performs a nominal comparison of two TypeGPU data schemas. This
23
+ * means two struct definitions are only considered equal when they
24
+ * have the same object identity. Use `schemasEqualStructurally` for
25
+ * a structural comparison.
26
+ *
27
+ * @param a The first data schema to compare.
28
+ * @param b The second data schema to compare.
29
+ * @returns `true` if the schemas are nominally equal, `false` otherwise.
30
+ *
31
+ * @example
32
+ * import { vec3f, struct, schemasEqualNominally } from 'typegpu/data';
33
+ *
34
+ * const struct1 = struct({ a: vec3f });
35
+ * const struct2 = struct({ a: vec3f });
36
+ *
37
+ * console.log(schemasEqualNominally(d.arrayOf(struct1, 2), d.arrayOf(struct1, 2))); // true
38
+ * console.log(schemasEqualNominally(struct1, struct2)); // false
39
+ */
40
+ export const schemasEqualNominally = comptime((a, b) => schemasEqual(a, b, false)).$name('schemasEqualNominally');
41
+ function schemasEqual(a, b, structural) {
42
+ if (a === b) {
43
+ return true;
44
+ }
45
+ if (a.type !== b.type) {
46
+ return false;
47
+ }
48
+ if ((isWgslStruct(a) && isWgslStruct(b)) || (isUnstruct(a) && isUnstruct(b))) {
49
+ if (!structural) {
50
+ // With nominal typing, structs are only considered equal when they
51
+ // generate the same declaration, i.e. have the same object identity.
52
+ // If they didn't pass the previous condition, then they're not equal
53
+ return false;
54
+ }
55
+ const aProps = a.propTypes;
56
+ const bProps = b.propTypes;
57
+ const aKeys = Object.keys(aProps);
58
+ const bKeys = Object.keys(bProps);
59
+ if (aKeys.length !== bKeys.length) {
60
+ return false;
61
+ }
62
+ for (let i = 0; i < aKeys.length; i++) {
63
+ const keyA = aKeys[i];
64
+ const keyB = bKeys[i];
65
+ if (keyA !== keyB ||
66
+ !keyA ||
67
+ !keyB ||
68
+ !schemasEqual(aProps[keyA], bProps[keyB], structural)) {
69
+ return false;
70
+ }
71
+ }
72
+ return true;
73
+ }
74
+ if ((isWgslArray(a) && isWgslArray(b)) || (isDisarray(a) && isDisarray(b))) {
75
+ return (a.elementCount === b.elementCount &&
76
+ schemasEqual(a.elementType, b.elementType, structural));
77
+ }
78
+ if (isPtr(a) && isPtr(b)) {
79
+ return (a.addressSpace === b.addressSpace &&
80
+ a.access === b.access &&
81
+ a.implicit === b.implicit &&
82
+ schemasEqual(a.inner, b.inner, structural));
83
+ }
84
+ if (isAtomic(a) && isAtomic(b)) {
85
+ return schemasEqual(a.inner, b.inner, structural);
86
+ }
87
+ if (isWgslTexture(a) && isWgslTexture(b)) {
88
+ // Dimension and multisampling are already encoded in the type
89
+ return schemasEqual(a.sampleType, b.sampleType, structural);
90
+ }
91
+ if (isWgslStorageTexture(a) && isWgslStorageTexture(b)) {
92
+ // Dimension is already encoded in the type
93
+ return a.format === b.format && a.access === b.access;
94
+ }
95
+ if ((isDecorated(a) && isDecorated(b)) || (isLooseDecorated(a) && isLooseDecorated(b))) {
96
+ if (!schemasEqual(a.inner, b.inner, structural)) {
97
+ return false;
98
+ }
99
+ // Attribute order carries no meaning, so we compare attributes by type.
100
+ // Only the first (outermost) attribute of each type is effective.
101
+ const attribsA = effectiveAttribs(a.attribs);
102
+ const attribsB = effectiveAttribs(b.attribs);
103
+ if (attribsA.size !== attribsB.size) {
104
+ return false;
105
+ }
106
+ for (const [type, attrA] of attribsA) {
107
+ const attrB = attribsB.get(type);
108
+ if (!attrB) {
109
+ return false;
110
+ }
111
+ const paramsA = attrA.params ?? [];
112
+ const paramsB = attrB.params ?? [];
113
+ if (paramsA.length !== paramsB.length ||
114
+ paramsA.some((param, idx) => param !== paramsB[idx])) {
115
+ return false;
116
+ }
117
+ }
118
+ return true;
119
+ }
120
+ // All other types have been checked for equality at the start
121
+ return true;
122
+ }
123
+ function effectiveAttribs(attribs) {
124
+ const result = new Map();
125
+ for (const attrib of attribs) {
126
+ if (!result.has(attrib.type)) {
127
+ result.set(attrib.type, attrib);
128
+ }
129
+ }
130
+ return result;
131
+ }