typegpu 0.1.2 → 0.2.0-alpha.0
Sign up to get free protection for your applications and to get access to all the features.
- package/LICENSE.md +21 -0
- package/README.md +1 -1
- package/chunk-5EPBCOO4.js +8 -0
- package/chunk-5EPBCOO4.js.map +1 -0
- package/chunk-SBJR5ZQJ.cjs +8 -0
- package/chunk-SBJR5ZQJ.cjs.map +1 -0
- package/data/index.cjs +1 -7
- package/data/index.cjs.map +1 -1
- package/data/index.d.cts +482 -48
- package/data/index.d.ts +482 -48
- package/data/index.js +1 -7
- package/data/index.js.map +1 -1
- package/index.cjs +51 -1
- package/index.cjs.map +1 -1
- package/index.d.cts +299 -37
- package/index.d.ts +299 -37
- package/index.js +51 -1
- package/index.js.map +1 -1
- package/package.json +7 -1
- package/types-qmW7FFqN.d.cts +880 -0
- package/types-qmW7FFqN.d.ts +880 -0
- package/chunk-3I5VAGHS.js +0 -2
- package/chunk-3I5VAGHS.js.map +0 -1
- package/chunk-PMM3NYJ4.cjs +0 -2
- package/chunk-PMM3NYJ4.cjs.map +0 -1
- package/vector-D5Vx-xhb.d.cts +0 -516
- package/vector-D5Vx-xhb.d.ts +0 -516
package/index.d.ts
CHANGED
@@ -1,40 +1,296 @@
|
|
1
|
+
import { T as TgpuRenderResource, a as TgpuNamable, b as TgpuBuffer, A as AnyTgpuData, O as OmitProps, c as TgpuBufferUsage, U as Uniform, S as Storage, d as TgpuBufferUniform, e as TgpuShaderStage, f as TgpuBufferReadonly, g as TgpuBufferMutable, h as U32, I as I32, F as F32, V as Vec4u, i as Vec4i, j as Vec4f, k as TgpuPlum, E as ExtractPlumValue, l as Unsubscribe, m as TgpuCode, B as BoundTgpuCode, n as Block, v as vecBase, o as vec3f, p as vec3i, q as vec3u } from './types-qmW7FFqN.js';
|
2
|
+
export { r as TgpuData, w as Vertex, s as isUsableAsStorage, t as isUsableAsUniform, u as isUsableAsVertex } from './types-qmW7FFqN.js';
|
1
3
|
import { Parsed } from 'typed-binary';
|
2
|
-
import { A as AnyTgpuData, T as TgpuAllocatable, a as TgpuNamable, b as TgpuPlum, v as vecBase, c as vec3f, d as vec3i, e as vec3u } from './vector-D5Vx-xhb.js';
|
3
|
-
export { f as TgpuData } from './vector-D5Vx-xhb.js';
|
4
4
|
|
5
|
-
|
5
|
+
declare const TgpuSettableTrait: unique symbol;
|
6
|
+
interface TgpuSettable {
|
7
|
+
readonly [TgpuSettableTrait]: true;
|
8
|
+
}
|
9
|
+
|
10
|
+
type PlumListener<T> = (newValue: T) => unknown;
|
11
|
+
|
12
|
+
interface TgpuSampler extends TgpuRenderResource, TgpuNamable {
|
13
|
+
readonly descriptor: GPUSamplerDescriptor;
|
14
|
+
}
|
15
|
+
|
16
|
+
interface Unwrapper {
|
6
17
|
readonly device: GPUDevice;
|
7
|
-
|
18
|
+
unwrap(resource: TgpuBuffer<AnyTgpuData>): GPUBuffer;
|
19
|
+
unwrap(resource: TgpuBindGroupLayout): GPUBindGroupLayout;
|
20
|
+
unwrap(resource: TgpuBindGroup): GPUBindGroup;
|
8
21
|
}
|
9
|
-
|
10
|
-
|
22
|
+
|
23
|
+
type TgpuLayoutEntryBase = {
|
24
|
+
/**
|
25
|
+
* Limits this resource's visibility to specific shader stages.
|
26
|
+
*
|
27
|
+
* By default, each resource is visible to all shader stage types, but
|
28
|
+
* depending on the underlying implementation, this may have performance implications.
|
29
|
+
*
|
30
|
+
* @default ['compute'] for mutable resources
|
31
|
+
* @default ['compute','vertex','fragment'] for everything else
|
32
|
+
*/
|
33
|
+
visibility?: TgpuShaderStage[];
|
34
|
+
};
|
35
|
+
type TgpuLayoutUniform = TgpuLayoutEntryBase & {
|
36
|
+
uniform: AnyTgpuData | ((arrayLength: number) => AnyTgpuData);
|
37
|
+
};
|
38
|
+
type TgpuLayoutStorage = TgpuLayoutEntryBase & {
|
39
|
+
storage: AnyTgpuData | ((arrayLength: number) => AnyTgpuData);
|
40
|
+
/** @default 'readonly' */
|
41
|
+
access?: 'mutable' | 'readonly';
|
42
|
+
};
|
43
|
+
type TgpuLayoutSampler = TgpuLayoutEntryBase & {
|
44
|
+
sampler: GPUSamplerBindingType;
|
45
|
+
};
|
46
|
+
type TgpuLayoutTexture<TSampleType extends GPUTextureSampleType = GPUTextureSampleType> = TgpuLayoutEntryBase & {
|
47
|
+
/**
|
48
|
+
* - 'float' - f32
|
49
|
+
* - 'unfilterable-float' - f32, cannot be used with filtering samplers
|
50
|
+
* - 'depth' - f32
|
51
|
+
* - 'sint' - i32
|
52
|
+
* - 'uint' - u32
|
53
|
+
*/
|
54
|
+
texture: TSampleType;
|
55
|
+
/**
|
56
|
+
* @default '2d'
|
57
|
+
*/
|
58
|
+
viewDimension?: GPUTextureViewDimension;
|
59
|
+
/**
|
60
|
+
* @default false
|
61
|
+
*/
|
62
|
+
multisampled?: boolean;
|
63
|
+
};
|
64
|
+
type TgpuLayoutStorageTexture<TFormat extends GPUTextureFormat = GPUTextureFormat> = TgpuLayoutEntryBase & {
|
65
|
+
storageTexture: TFormat;
|
66
|
+
/** @default 'writeonly' */
|
67
|
+
access?: 'readonly' | 'writeonly' | 'mutable';
|
68
|
+
/** @default '2d' */
|
69
|
+
viewDimension?: GPUTextureViewDimension;
|
70
|
+
};
|
71
|
+
type TgpuLayoutExternalTexture = TgpuLayoutEntryBase & {
|
72
|
+
externalTexture: Record<string, never>;
|
73
|
+
};
|
74
|
+
type TgpuLayoutEntry = TgpuLayoutUniform | TgpuLayoutStorage | TgpuLayoutSampler | TgpuLayoutTexture | TgpuLayoutStorageTexture | TgpuLayoutExternalTexture;
|
75
|
+
type UnwrapRuntimeConstructorInner<T extends AnyTgpuData | ((_: number) => AnyTgpuData)> = T extends AnyTgpuData ? T : T extends (_: number) => infer Return ? Return : never;
|
76
|
+
type UnwrapRuntimeConstructor<T extends AnyTgpuData | ((_: number) => AnyTgpuData)> = T extends unknown ? UnwrapRuntimeConstructorInner<T> : never;
|
77
|
+
interface TgpuBindGroupLayout<Entries extends Record<string, TgpuLayoutEntry | null> = Record<string, TgpuLayoutEntry | null>> extends TgpuNamable {
|
78
|
+
readonly resourceType: 'bind-group-layout';
|
79
|
+
readonly label: string | undefined;
|
80
|
+
readonly entries: Entries;
|
81
|
+
populate(entries: {
|
82
|
+
[K in keyof OmitProps<Entries, null>]: LayoutEntryToInput<Entries[K]>;
|
83
|
+
}): TgpuBindGroup<Entries>;
|
84
|
+
/**
|
85
|
+
* Creates a raw WebGPU resource based on the typed descriptor.
|
86
|
+
* NOTE: This creates a new resource every time, better to use `root.unwrap(...)` instead.
|
87
|
+
* @param unwrapper Used to unwrap any resources that this resource depends on.
|
88
|
+
*/
|
89
|
+
unwrap(unwrapper: Unwrapper): GPUBindGroupLayout;
|
11
90
|
}
|
12
|
-
|
13
|
-
|
14
|
-
|
91
|
+
type StorageUsageForEntry<T extends TgpuLayoutStorage> = T extends {
|
92
|
+
access?: infer Access;
|
93
|
+
} ? 'mutable' | 'readonly' extends Access ? TgpuBufferReadonly<UnwrapRuntimeConstructor<T['storage']>> | TgpuBufferMutable<UnwrapRuntimeConstructor<T['storage']>> : 'readonly' extends Access ? TgpuBufferReadonly<UnwrapRuntimeConstructor<T['storage']>> : 'mutable' extends Access ? TgpuBufferMutable<UnwrapRuntimeConstructor<T['storage']>> : TgpuBufferReadonly<UnwrapRuntimeConstructor<T['storage']>> | TgpuBufferMutable<UnwrapRuntimeConstructor<T['storage']>> : TgpuBufferReadonly<UnwrapRuntimeConstructor<T['storage']>>;
|
94
|
+
type LayoutEntryToInput<T extends TgpuLayoutEntry | null> = T extends TgpuLayoutUniform ? TgpuBufferUsage<UnwrapRuntimeConstructor<T['uniform']>, 'uniform'> | (TgpuBuffer<UnwrapRuntimeConstructor<T['uniform']>> & Uniform) | GPUBuffer : T extends TgpuLayoutStorage ? StorageUsageForEntry<T> | (TgpuBuffer<UnwrapRuntimeConstructor<T['storage']>> & Storage) | GPUBuffer : T extends TgpuLayoutSampler ? GPUSampler : T extends TgpuLayoutTexture ? GPUTextureView : T extends TgpuLayoutStorageTexture ? GPUTextureView : T extends TgpuLayoutExternalTexture ? GPUExternalTexture : never;
|
95
|
+
type BindLayoutEntry<T extends TgpuLayoutEntry | null> = T extends TgpuLayoutUniform ? TgpuBufferUniform<UnwrapRuntimeConstructor<T['uniform']>> : T extends TgpuLayoutStorage ? StorageUsageForEntry<T> : T extends TgpuLayoutSampler ? TgpuSampler : never;
|
96
|
+
type TgpuBindGroup<Entries extends Record<string, TgpuLayoutEntry | null> = Record<string, TgpuLayoutEntry | null>> = {
|
97
|
+
readonly resourceType: 'bind-group';
|
98
|
+
readonly layout: TgpuBindGroupLayout<Entries>;
|
99
|
+
unwrap(unwrapper: Unwrapper): GPUBindGroup;
|
100
|
+
};
|
101
|
+
declare function bindGroupLayout<Entries extends Record<string, TgpuLayoutEntry | null>>(entries: Entries): TgpuBindGroupLayout<Entries>;
|
102
|
+
|
103
|
+
type StorageTextureAccess = 'read' | 'write' | 'read_write';
|
104
|
+
type TextureScalarFormat = U32 | I32 | F32;
|
105
|
+
type TexelFormat = Vec4u | Vec4i | Vec4f;
|
106
|
+
|
107
|
+
type Optional<T> = {
|
108
|
+
[P in keyof T]?: T[P] | undefined;
|
109
|
+
};
|
110
|
+
interface TgpuAnyTextureView extends TgpuRenderResource {
|
111
|
+
readonly descriptor: GPUTextureViewDescriptor;
|
112
|
+
readonly texture: TgpuAnyTexture;
|
113
|
+
readonly dataType: TextureScalarFormat | TexelFormat;
|
114
|
+
readonly access: StorageTextureAccess | undefined;
|
15
115
|
}
|
16
|
-
|
17
|
-
|
18
|
-
|
116
|
+
interface TgpuAnyTexture {
|
117
|
+
readonly descriptor: Omit<GPUTextureDescriptor, 'usage'>;
|
118
|
+
get flags(): GPUTextureUsageFlags;
|
19
119
|
}
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
120
|
+
interface TgpuTextureExternal extends TgpuRenderResource, TgpuNamable {
|
121
|
+
readonly descriptor: Optional<GPUExternalTextureDescriptor>;
|
122
|
+
get source(): HTMLVideoElement | VideoFrame | undefined;
|
123
|
+
}
|
124
|
+
|
125
|
+
type SetPlumAction<T> = T | ((prev: T) => T);
|
126
|
+
interface TgpuRoot extends Unwrapper {
|
127
|
+
/**
|
128
|
+
* The GPU device associated with this root.
|
129
|
+
*/
|
130
|
+
readonly device: GPUDevice;
|
131
|
+
/**
|
132
|
+
* @param typeSchema The type of data that this buffer will hold.
|
133
|
+
* @param initial The initial value of the buffer. (optional)
|
134
|
+
*/
|
135
|
+
createBuffer<TData extends AnyTgpuData>(typeSchema: TData, initial?: Parsed<TData> | TgpuPlum<Parsed<TData>> | undefined): TgpuBuffer<TData>;
|
136
|
+
/**
|
137
|
+
* @param typeSchema The type of data that this buffer will hold.
|
138
|
+
* @param gpuBuffer A vanilla WebGPU buffer.
|
139
|
+
*/
|
140
|
+
createBuffer<TData extends AnyTgpuData>(typeSchema: TData, gpuBuffer: GPUBuffer): TgpuBuffer<TData>;
|
141
|
+
unwrap(resource: TgpuBuffer<AnyTgpuData>): GPUBuffer;
|
142
|
+
unwrap(resource: TgpuBindGroupLayout): GPUBindGroupLayout;
|
143
|
+
unwrap(resource: TgpuBindGroup): GPUBindGroup;
|
28
144
|
destroy(): void;
|
29
145
|
}
|
146
|
+
interface ExperimentalTgpuRoot extends TgpuRoot {
|
147
|
+
readonly jitTranspiler?: JitTranspiler | undefined;
|
148
|
+
/**
|
149
|
+
* The current command encoder. This property will
|
150
|
+
* hold the same value until `flush()` is called.
|
151
|
+
*/
|
152
|
+
readonly commandEncoder: GPUCommandEncoder;
|
153
|
+
readPlum<TPlum extends TgpuPlum>(plum: TPlum): ExtractPlumValue<TPlum>;
|
154
|
+
setPlum<TPlum extends TgpuPlum & TgpuSettable>(plum: TPlum, value: SetPlumAction<ExtractPlumValue<TPlum>>): void;
|
155
|
+
onPlumChange<TValue>(plum: TgpuPlum<TValue>, listener: PlumListener<TValue>): Unsubscribe;
|
156
|
+
setSource(texture: TgpuTextureExternal, source: HTMLVideoElement | VideoFrame): void;
|
157
|
+
isDirty(texture: TgpuTextureExternal): boolean;
|
158
|
+
markClean(texture: TgpuTextureExternal): void;
|
159
|
+
textureFor(view: TgpuAnyTexture | TgpuAnyTextureView): GPUTexture;
|
160
|
+
viewFor(view: TgpuAnyTextureView): GPUTextureView;
|
161
|
+
externalTextureFor(texture: TgpuTextureExternal): GPUExternalTexture;
|
162
|
+
samplerFor(sampler: TgpuSampler): GPUSampler;
|
163
|
+
/**
|
164
|
+
* Causes all commands enqueued by pipelines to be
|
165
|
+
* submitted to the GPU.
|
166
|
+
*/
|
167
|
+
flush(): void;
|
168
|
+
makeRenderPipeline(options: RenderPipelineOptions): RenderPipelineExecutor;
|
169
|
+
makeComputePipeline(options: ComputePipelineOptions): ComputePipelineExecutor;
|
170
|
+
}
|
171
|
+
interface RenderPipelineOptions {
|
172
|
+
vertex: {
|
173
|
+
code: TgpuCode | BoundTgpuCode;
|
174
|
+
output: {
|
175
|
+
[K in symbol]: string;
|
176
|
+
} & {
|
177
|
+
[K in string]: AnyTgpuData;
|
178
|
+
};
|
179
|
+
};
|
180
|
+
fragment: {
|
181
|
+
code: TgpuCode | BoundTgpuCode;
|
182
|
+
target: Iterable<GPUColorTargetState | null>;
|
183
|
+
};
|
184
|
+
primitive: GPUPrimitiveState;
|
185
|
+
externalLayouts?: GPUBindGroupLayout[];
|
186
|
+
label?: string;
|
187
|
+
}
|
188
|
+
interface ComputePipelineOptions {
|
189
|
+
code: TgpuCode | BoundTgpuCode;
|
190
|
+
workgroupSize?: readonly [number, number?, number?];
|
191
|
+
externalLayouts?: GPUBindGroupLayout[];
|
192
|
+
label?: string;
|
193
|
+
}
|
194
|
+
type RenderPipelineExecutorOptions = GPURenderPassDescriptor & {
|
195
|
+
vertexCount: number;
|
196
|
+
instanceCount?: number;
|
197
|
+
firstVertex?: number;
|
198
|
+
firstInstance?: number;
|
199
|
+
externalBindGroups?: GPUBindGroup[];
|
200
|
+
};
|
201
|
+
interface RenderPipelineExecutor {
|
202
|
+
execute(options: RenderPipelineExecutorOptions): void;
|
203
|
+
}
|
204
|
+
type ComputePipelineExecutorOptions = {
|
205
|
+
workgroups?: readonly [number, number?, number?];
|
206
|
+
externalBindGroups?: GPUBindGroup[];
|
207
|
+
};
|
208
|
+
interface ComputePipelineExecutor {
|
209
|
+
execute(options?: ComputePipelineExecutorOptions): void;
|
210
|
+
}
|
211
|
+
|
212
|
+
/**
|
213
|
+
* Information extracted from transpiling a JS function.
|
214
|
+
*/
|
215
|
+
type TranspilationResult = {
|
216
|
+
argNames: string[];
|
217
|
+
body: Block;
|
218
|
+
/**
|
219
|
+
* All identifiers found in the function code that are not declared in the
|
220
|
+
* function itself, or in the block that is accessing that identifier.
|
221
|
+
*/
|
222
|
+
externalNames: string[];
|
223
|
+
};
|
224
|
+
|
225
|
+
/**
|
226
|
+
* Used to transpile JS resources into SMoL on demand.
|
227
|
+
*/
|
228
|
+
interface JitTranspiler {
|
229
|
+
transpileFn(rawJs: string): TranspilationResult;
|
230
|
+
}
|
231
|
+
|
232
|
+
/**
|
233
|
+
* Options passed into {@link init}.
|
234
|
+
*/
|
235
|
+
type InitOptions = {
|
236
|
+
adapter?: GPURequestAdapterOptions | undefined;
|
237
|
+
device?: GPUDeviceDescriptor | undefined;
|
238
|
+
unstable_jitTranspiler?: JitTranspiler | undefined;
|
239
|
+
};
|
240
|
+
/**
|
241
|
+
* Options passed into {@link initFromDevice}.
|
242
|
+
*/
|
243
|
+
type InitFromDeviceOptions = {
|
244
|
+
device: GPUDevice;
|
245
|
+
unstable_jitTranspiler?: JitTranspiler | undefined;
|
246
|
+
};
|
247
|
+
/**
|
248
|
+
* Requests a new GPU device and creates a root around it.
|
249
|
+
* If a specific device should be used instead, use @see initFromDevice.
|
250
|
+
*
|
251
|
+
* @example
|
252
|
+
* When given no options, the function will ask the browser for a suitable GPU device.
|
253
|
+
* ```ts
|
254
|
+
* const root = await tgpu.init();
|
255
|
+
* ```
|
256
|
+
*
|
257
|
+
* @example
|
258
|
+
* If there are specific options that should be used when requesting a device, you can pass those in.
|
259
|
+
* ```ts
|
260
|
+
* const adapterOptions: GPURequestAdapterOptions = ...;
|
261
|
+
* const deviceDescriptor: GPUDeviceDescriptor = ...;
|
262
|
+
* const root = await tgpu.init({ adapter: adapterOptions, device: deviceDescriptor });
|
263
|
+
* ```
|
264
|
+
*/
|
265
|
+
declare function init(options?: InitOptions): Promise<ExperimentalTgpuRoot>;
|
266
|
+
/**
|
267
|
+
* Creates a root from the given device, instead of requesting it like @see init.
|
268
|
+
*
|
269
|
+
* @example
|
270
|
+
* ```ts
|
271
|
+
* const device: GPUDevice = ...;
|
272
|
+
* const root = tgpu.initFromDevice({ device });
|
273
|
+
* ```
|
274
|
+
*/
|
275
|
+
declare function initFromDevice(options: InitFromDeviceOptions): ExperimentalTgpuRoot;
|
276
|
+
|
277
|
+
/**
|
278
|
+
* @deprecated Use the `root.createBuffer` API instead, accessible through `await tgpu.init()`
|
279
|
+
*
|
280
|
+
* @param typeSchema The type of data that this buffer will hold.
|
281
|
+
* @param initial The initial value of the buffer. (optional)
|
282
|
+
*/
|
30
283
|
declare function createBuffer<TData extends AnyTgpuData>(typeSchema: TData, initial?: Parsed<TData> | TgpuPlum<Parsed<TData>> | undefined): TgpuBuffer<TData>;
|
284
|
+
/**
|
285
|
+
* @deprecated Use the `root.createBuffer` API instead, accessible through `await tgpu.init()`
|
286
|
+
*
|
287
|
+
* @param typeSchema The type of data that this buffer will hold.
|
288
|
+
* @param gpuBuffer A vanilla WebGPU buffer.
|
289
|
+
*/
|
31
290
|
declare function createBuffer<TData extends AnyTgpuData>(typeSchema: TData, gpuBuffer: GPUBuffer): TgpuBuffer<TData>;
|
32
|
-
declare function isUsableAsUniform<T extends TgpuBuffer<AnyTgpuData>>(buffer: T): buffer is T & Uniform;
|
33
|
-
declare function isUsableAsStorage<T extends TgpuBuffer<AnyTgpuData>>(buffer: T): buffer is T & Storage;
|
34
|
-
declare function isUsableAsVertex<T extends TgpuBuffer<AnyTgpuData>>(buffer: T): buffer is T & Vertex;
|
35
291
|
|
36
|
-
declare function write<TData extends AnyTgpuData>(buffer: TgpuBuffer<TData
|
37
|
-
declare function read<TData extends AnyTgpuData>(buffer: TgpuBuffer<TData>
|
292
|
+
declare function write<TData extends AnyTgpuData>(buffer: TgpuBuffer<TData>, data: Parsed<TData>): void;
|
293
|
+
declare function read<TData extends AnyTgpuData>(buffer: TgpuBuffer<TData>): Promise<Parsed<TData>>;
|
38
294
|
|
39
295
|
/**
|
40
296
|
* @category Errors
|
@@ -44,16 +300,16 @@ declare class RecursiveDataTypeError extends Error {
|
|
44
300
|
}
|
45
301
|
|
46
302
|
declare const std: {
|
47
|
-
add
|
48
|
-
sub
|
303
|
+
add<T extends vecBase>(lhs: T, rhs: T): T;
|
304
|
+
sub<T extends vecBase>(lhs: T, rhs: T): T;
|
49
305
|
mul: <T extends vecBase>(s: number, v: T) => T;
|
50
|
-
dot
|
306
|
+
dot<T extends vecBase>(lhs: T, rhs: T): number;
|
51
307
|
normalize: <T extends vecBase>(v: T) => T;
|
52
|
-
cross
|
53
|
-
fract
|
54
|
-
length
|
55
|
-
sin
|
56
|
-
cos
|
308
|
+
cross<T extends vec3f | vec3i | vec3u>(a: T, b: T): T;
|
309
|
+
fract(a: number): number;
|
310
|
+
length<T extends vecBase>(vector: T): number;
|
311
|
+
sin(radians: number): number;
|
312
|
+
cos(radians: number): number;
|
57
313
|
};
|
58
314
|
|
59
315
|
/**
|
@@ -61,12 +317,18 @@ declare const std: {
|
|
61
317
|
*/
|
62
318
|
|
63
319
|
declare const tgpu: {
|
64
|
-
|
65
|
-
|
66
|
-
|
320
|
+
/** @deprecated Use `'uniform'` string literal instead. */
|
321
|
+
Uniform: "uniform";
|
322
|
+
/** @deprecated Use `'storage'` string literal instead. */
|
323
|
+
Storage: "storage";
|
324
|
+
/** @deprecated Use `'vertex'` string literal instead. */
|
325
|
+
Vertex: "vertex";
|
326
|
+
bindGroupLayout: typeof bindGroupLayout;
|
327
|
+
init: typeof init;
|
328
|
+
initFromDevice: typeof initFromDevice;
|
67
329
|
createBuffer: typeof createBuffer;
|
68
330
|
read: typeof read;
|
69
331
|
write: typeof write;
|
70
332
|
};
|
71
333
|
|
72
|
-
export { AnyTgpuData, RecursiveDataTypeError, type
|
334
|
+
export { AnyTgpuData, type BindLayoutEntry, type LayoutEntryToInput, RecursiveDataTypeError, Storage, type TgpuBindGroup, type TgpuBindGroupLayout, TgpuBuffer, type TgpuLayoutEntry, type TgpuLayoutSampler, type TgpuLayoutUniform, Uniform, tgpu as default, std, tgpu };
|
package/index.js
CHANGED
@@ -1,2 +1,52 @@
|
|
1
|
-
import{a,d as
|
1
|
+
import{A as Ye,B as g,H as He,P as W,Q as K,R as q,S as V,T as L,U as P,V as D,W as J,X as Y,a as M,b as O,c as Me,d as o,e as ee,f as B,g as Te,h as Oe,i as ct,j as z,l as me,m as G,o as ye,p as ze,q as Ne,r as N,s as te,t as v,u as j,v as je,w as We,x as Ke,y as qe,z as Je}from"./chunk-5EPBCOO4.js";var H=class{constructor(e){this._make=e;o(this,"_map",new WeakMap)}getOrMake(e,...r){if(this._map.has(e))return this._map.get(e);let n=this._make(e,...r);return this._map.set(e,n),n}};var ft=Symbol("This plum's value is sourced from outside the root.");function re(t){return t[ft]===!0}function Xe(t){return t.__brand==="TgpuPlum"}var ne=class{constructor(){o(this,"_stateMap",new WeakMap)}inspect(e){return this._stateMap.get(e)}_getState(e){let r=this._stateMap.get(e);if(!r){let{value:n,dependencies:a}=this._computeAndGatherDependencies(e);r={value:n,dependencies:a,version:0},this._stateMap.set(e,r)}return r}_notifyListeners(e){let r=this._getState(e);if(!r.active)return;let n=[...r.active.listeners];for(let a of n)a(r.value)}_computeAndGatherDependencies(e){let r=new Map,n=a=>{if(!r.has(a)){let i=this._getState(a);r.set(a,i.version)}return this.get(a)};return{value:e.compute(n),dependencies:r}}_recompute(e){let r=this._getState(e);if(r.active)for(let i of r.active.unsubs)i();let{value:n,dependencies:a}=this._computeAndGatherDependencies(e);if(r.dependencies=a,r.active)for(let[i]of r.dependencies)r.active.unsubs.add(this.subscribe(i,()=>{this._recompute(e)}));return Object.is(r.value,n)||(r.value=n,r.version=re(e)?e.version:r.version+1,this._notifyListeners(e)),r.value}get(e){let r=this._getState(e);if(r.active)return r.value;let n=!1;return re(e)?(e.compute(null),n=r.version!==e.version):r.dependencies.size>0&&(n=[...r.dependencies.entries()].some(([a,i])=>(this.get(a),this._getState(a).version!==i))),n?this._recompute(e):r.value}set(e,r){let n=this._getState(e);Object.is(n.value,r)||(n.value=r,n.version++,this._notifyListeners(e))}subscribe(e,r){let n=this._getState(e),a;if(!n.active){let i=new Set;n.active={listeners:new Set,unsubs:i};for(let[u]of n.dependencies)i.add(this.subscribe(u,()=>{this._recompute(e)}));re(e)&&(a=e.subscribe(()=>{this._recompute(e)}))}return n.active.listeners.add(r),()=>{if(n.active&&(n.active.listeners.delete(r),n.active.listeners.size===0)){for(let i of n.active.unsubs)i();a==null||a(),n.active=void 0}}}};var Tt={f32:"float32",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",u32:"uint32",vec2u:"uint32x2",vec3u:"uint32x3",vec4u:"uint32x4",i32:"sint32",vec2i:"sint32x2",vec3i:"sint32x3",vec4i:"sint32x4"};function xe(t){if("expressionCode"in t){let e=t.expressionCode,r=Tt[e];if(!r)throw new Error(`Unsupported vertex format: ${e}`);return r}if("elementType"in t)return xe(t.elementType);throw new Error("Invalid vertex format schema")}function ae(t){return t.type==="sampler"||t.type==="sampler_comparison"}function Qe(t){return!("texture"in t)&&!ae(t)}function ue(t){return"texture"in t}var mt={uniform:"uniform",mutable:"storage",readonly:"read-only-storage"},ie=class{constructor(e,r,n){this.root=e;this.context=r;this.shaderStage=n;o(this,"samplers",[]);o(this,"textureViews",[]);o(this,"externalTextures",[]);o(this,"buffers",[]);o(this,"vertexBuffers",null);o(this,"layout",null);o(this,"bindGroup",null);o(this,"vertexLayout",null);let a=Array.from(r.usedRenderResources);for(let i of a)if(ae(i))this.samplers.push(i);else if(ue(i))this.textureViews.push(i);else if(Qe(i))this.externalTextures.push(i);else throw new Error(`Invalid resource type: ${i}`);this.buffers=Array.from(r.usedBindables)}setVertexBuffers(e){if(this.shaderStage!==GPUShaderStage.VERTEX)throw new Error("Vertex buffers can only be set for vertex shader");this.vertexBuffers=new Map(e.map(({index:r,buffer:n})=>[n,r]))}getBindGroupLayout(){if(this.layout)return this.layout;let e=[];for(let n of this.textureViews)n.access===void 0?e.push({binding:this.context.getIndexFor(n),visibility:this.shaderStage,texture:{}}):e.push({binding:this.context.getIndexFor(n),visibility:this.shaderStage,storageTexture:{format:n.texture.descriptor.format}});for(let n of this.externalTextures)e.push({binding:this.context.getIndexFor(n),visibility:this.shaderStage,externalTexture:{}});for(let n of this.samplers)e.push({binding:this.context.getIndexFor(n),visibility:this.shaderStage,sampler:{}});for(let n of this.buffers)n.usage!=="vertex"&&e.push({binding:this.context.getIndexFor(n),visibility:this.shaderStage,buffer:{type:mt[n.usage]}});let r=this.root.device.createBindGroupLayout({entries:e});return this.layout=r,r}getBindGroup(){if(this.checkBindGroupInvalidation(),this.bindGroup)return this.bindGroup;let e=[];for(let n of this.textureViews)e.push({binding:this.context.getIndexFor(n),resource:this.root.viewFor(n)});for(let n of this.externalTextures)e.push({binding:this.context.getIndexFor(n),resource:this.root.externalTextureFor(n)});for(let n of this.samplers)e.push({binding:this.context.getIndexFor(n),resource:this.root.samplerFor(n)});for(let n of this.buffers)n.usage!=="vertex"&&e.push({binding:this.context.getIndexFor(n),resource:{buffer:n.allocatable.buffer}});let r=this.root.device.createBindGroup({layout:this.getBindGroupLayout(),entries:e});return this.bindGroup=r,r}getBindings(){return{bindGroupLayout:this.getBindGroupLayout(),bindGroup:this.getBindGroup()}}getVertexBufferDescriptors(){if(this.vertexBuffers===null)throw new Error("Vertex buffers not set");if(this.vertexLayout)return this.vertexLayout;let e=[];for(let[r,n]of this.vertexBuffers.entries())e.push(O(M({},r.vertexLayout),{attributes:[{shaderLocation:n,offset:0,format:xe(r.allocatable.dataType)}]}));return this.vertexLayout=e,e}getVertexBuffers(){if(this.vertexBuffers===null)throw new Error("Vertex buffers not set");return this.vertexBuffers.entries()}getVertexBufferIndex(e){var n;let r=(n=this.vertexBuffers)==null?void 0:n.get(e);if(this.vertexBuffers===null||r===void 0)throw new Error("Vertex buffers not set");return r}invalidateBindGroup(){this.bindGroup=null}checkBindGroupInvalidation(){for(let e of this.externalTextures){if(this.root.isDirty(e)){this.invalidateBindGroup(),this.root.markClean(e);continue}e.source instanceof HTMLVideoElement&&this.invalidateBindGroup()}}};var f=class{constructor(e){this.name=e;o(this,"s");this.s=Ne.get(e)}get label(){return this.name}resolve(e){return e.resolve(g`${this.s}`)}},y={vertexIndex:new f("vertex_index"),instanceIndex:new f("instance_index"),position:new f("position"),clipDistances:new f("clip_distances"),frontFacing:new f("front_facing"),fragDepth:new f("frag_depth"),sampleIndex:new f("sample_index"),sampleMask:new f("sample_mask"),fragment:new f("fragment"),localInvocationId:new f("local_invocation_id"),localInvocationIndex:new f("local_invocation_index"),globalInvocationId:new f("global_invocation_id"),workgroupId:new f("workgroup_id"),numWorkgroups:new f("num_workgroups")};var yt={[y.vertexIndex.s]:G,[y.instanceIndex.s]:G,[y.position.s]:D,[y.clipDistances.s]:He(G,8),[y.frontFacing.s]:ye,[y.fragDepth.s]:ye,[y.sampleIndex.s]:G,[y.sampleMask.s]:G,[y.fragment.s]:D,[y.localInvocationId.s]:P,[y.localInvocationIndex.s]:G,[y.globalInvocationId.s]:P,[y.workgroupId.s]:P,[y.numWorkgroups.s]:P};function X(t){let e=yt[t];if(!e)throw new Error(`The symbol ${String(t)} in not a valid 'builtin'`);return e}var S=class{constructor(){o(this,"lastUniqueId",0);o(this,"names",new WeakMap)}nameFor(e){let r=this.names.get(e);if(r===void 0){let n;e.label?(n=e.label.replaceAll(/\s/g,"_"),n=n.replaceAll(/[^\w\d]/g,"")):n="item",r=`${n}_${this.lastUniqueId++}`,this.names.set(e,r)}return r}};function x(t,e){return je(e.value)?t.resolve(e.value):String(e.value)}function xt(t){throw new Error(`'${JSON.stringify(t)}' was not handled by the WGSL generator.`)}function Ze(t,e){return e?{value:"true",dataType:me}:{value:"false",dataType:me}}function et(t,e){return`${t.indent()}{
|
2
|
+
${e.block.map(r=>ve(t,r)).join(`
|
3
|
+
`)}
|
4
|
+
${t.dedent()}}`}function he(t,e){return t.getById(e)}function b(t,e){if(typeof e=="string")return he(t,e);if(typeof e=="boolean")return Ze(t,e);if("x2"in e){let[r,n,a]=e.x2,i=x(t,b(t,r)),u=x(t,b(t,a));return{value:`${i} ${n} ${u}`,dataType:v}}if("."in e){let[r,n]=e["."],a=b(t,r),i=x(t,b(t,n));return j(a.value)||typeof a.value=="object"?i==="value"?{value:x(t,a),dataType:v}:{value:a.value[i],dataType:v}:{value:`${x(t,a)}.${i}`,dataType:v}}if("[]"in e){let[r,n]=e["[]"],a=x(t,b(t,r)),i=x(t,b(t,n));return{value:`${a}[${i}]`,dataType:v}}if("num"in e)return{value:e.num,dataType:v};if("call"in e){let n=b(t,e.call).value,i=e.args.map(u=>b(t,u)).map(u=>x(t,u));return j(n)||typeof n=="function"?{value:n(...i),dataType:v}:{value:`${String(n)}(${i.join(", ")})`,dataType:v}}xt(e)}function ve(t,e){if(typeof e=="string")return`${t.pre}${x(t,he(t,e))};`;if(typeof e=="boolean")return`${t.pre}${x(t,Ze(t,e))};`;if("return"in e)return e.return===null?`${t.pre}return;`:`${t.pre}return ${x(t,b(t,e.return))};`;if("if"in e){let r=x(t,b(t,e.if));t.indent();let n=ve(t,e.do);t.dedent(),t.indent();let a=e.else?ve(t,e.else):void 0;return t.dedent(),a?`${t.pre}if (${r})
|
5
|
+
${n}
|
6
|
+
${t.pre}else
|
7
|
+
${a}`:`${t.pre}if (${r})
|
8
|
+
${n}`}if("let"in e||"const"in e){let r=x(t,he(t,"let"in e?e.let:e.const)),n=e.eq?b(t,e.eq):void 0;if(!n)throw new Error("Cannot create variable without an initial value.");return`${t.pre}var ${r} = ${x(t,n)};`}return"block"in e?et(t,e):`${t.pre}${x(t,b(t,e))};`}function be(t,e){return et(t,e)}var ht={uniform:"uniform",mutable:"storage, read_write",readonly:"storage, read"},Be=class{constructor(e,r,n){this.names=e;this._bindingGroup=r;this.jitTranspiler=n;o(this,"_nextFreeBindingIdx",0);o(this,"_nextFreeVertexBindingIdx",0);o(this,"_usedBindables",new Set);o(this,"_usedRenderResources",new Set);o(this,"_resourceToIndexMap",new WeakMap);o(this,"_vertexBufferToIndexMap",new WeakMap);o(this,"_usedBuiltins",new Set);o(this,"_declarations",[])}get usedBindables(){return this._usedBindables}get usedRenderResources(){return this._usedRenderResources}get declarations(){return this._declarations}get usedBuiltins(){return this._usedBuiltins}reserveBindingEntry(e){this._usedBindables.add(e);let r=this._nextFreeBindingIdx++;return this._resourceToIndexMap.set(e,r),{group:this._bindingGroup,idx:r}}registerVertexEntry(e){this._usedBindables.add(e);let r=this._nextFreeVertexBindingIdx++;this._vertexBufferToIndexMap.set(e,r)}reserveRenderResourceEntry(e){this._usedRenderResources.add(e);let r=this._nextFreeBindingIdx++;return this._resourceToIndexMap.set(e,r),{group:this._bindingGroup,idx:r}}getBindingIndex(e){return this._resourceToIndexMap.get(e)}addDeclaration(e){this._declarations.push(e)}addBuiltin(e){this._usedBuiltins.add(e)}},Pe=class{constructor(){o(this,"_stack",[]);o(this,"_itemDepth",0)}get itemDepth(){return this._itemDepth}get topItem(){let e=this._stack[this._stack.length-1];if(!e||e.type!=="item")throw new Error("Internal error, expected item layer to be on top.");return e}pushItem(){this._itemDepth++,this._stack.push({type:"item",usedSlots:new Set})}pushSlotBindings(e){this._stack.push({type:"slotBinding",bindingMap:new WeakMap(e)})}pushFunctionScope(e,r,n){this._stack.push({type:"functionScope",args:e,returnType:r,externalMap:n})}pop(){let e=this._stack.pop();(e==null?void 0:e.type)==="item"&&this._itemDepth--}readSlot(e){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if((n==null?void 0:n.type)==="item")n.usedSlots.add(e);else if((n==null?void 0:n.type)==="slotBinding"){let a=n.bindingMap.get(e);if(a!==void 0)return a}else if(!((n==null?void 0:n.type)==="functionScope"||(n==null?void 0:n.type)==="blockScope"))throw new Error("Unknown layer type.")}return e.defaultValue}getResourceById(e){for(let r=this._stack.length-1;r>=0;--r){let n=this._stack[r];if((n==null?void 0:n.type)==="functionScope"){let a=n.args.find(u=>u.value===e);if(a!==void 0)return a;let i=n.externalMap[e];if(i!==void 0)return{value:i,dataType:v}}else if((n==null?void 0:n.type)==="blockScope"){let a=n.declarations.get(e);if(a!==void 0)return{value:e,dataType:a}}}}},oe=[""," "," "," "," "," "," "," "," "],we=oe.length-1,Se=class{constructor(){o(this,"identLevel",0)}get pre(){var e;return(e=oe[this.identLevel])!=null?e:oe[we].repeat(this.identLevel/we)+oe[this.identLevel%we]}indent(){let e=this.pre;return this.identLevel++,e}dedent(){return this.identLevel--,this.pre}},_=class{constructor(e){o(this,"_memoizedResolves",new WeakMap);o(this,"_shared");o(this,"_indentController",new Se);o(this,"_itemStateStack",new Pe);var r;this._shared=new Be(e.names,(r=e.bindingGroup)!=null?r:0,e.jitTranspiler)}get usedBindables(){return this._shared.usedBindables}get usedRenderResources(){return this._shared.usedRenderResources}get usedBuiltins(){return this._shared.usedBuiltins}get pre(){return this._indentController.pre}indent(){return this._indentController.indent()}dedent(){return this._indentController.dedent()}getById(e){var r;return(r=this._itemStateStack.getResourceById(e))!=null?r:{value:e,dataType:v}}transpileFn(e){if(!this._shared.jitTranspiler)throw new Error("Tried to execute a tgpu.fn function without providing a JIT transpiler, or transpiling at build time.");return this._shared.jitTranspiler.transpileFn(e)}fnToWgsl(e,r,n,a){let i=r.map((l,d)=>({value:l,dataType:e.argTypes[d]}));this._itemStateStack.pushFunctionScope(i,e.returnType,a);let u=be(this,n);this._itemStateStack.pop();let s=i.map(l=>`${l.value}: ${this.resolve(l.dataType)}`).join(", ");return{head:e.returnType!==void 0?`(${s}) -> ${this.resolve(e.returnType)}`:`(${s})`,body:u}}addDeclaration(e){this._shared.addDeclaration(this.resolve(e))}addBinding(e,r){if(e.usage==="vertex"){this._shared.registerVertexEntry(e);return}let{group:n,idx:a}=this._shared.reserveBindingEntry(e);this.addDeclaration(g`@group(${n}) @binding(${a}) var<${ht[e.usage]}> ${r}: ${e.allocatable.dataType};`)}addRenderResource(e,r){let{group:n,idx:a}=this._shared.reserveRenderResourceEntry(e);if(We(e.type)||qe(e.type)||Ke(e.type)){this.addDeclaration(g`@group(${n}) @binding(${a}) var ${r}: ${e.type};`);return}if(ue(e)){if(e.access!==void 0){this.addDeclaration(g`@group(${n}) @binding(${a}) var ${r}: ${e.type}<${e.texture.descriptor.format}, ${e.access}>;`);return}this.addDeclaration(g`@group(${n}) @binding(${a}) var ${r}: ${e.type}<${e.dataType}>;`);return}throw new Error(`Unsupported resource type: ${e.type}`)}addBuiltin(e){this._shared.addBuiltin(e)}nameFor(e){return this._shared.names.nameFor(e)}readSlot(e){let r=this._itemStateStack.readSlot(e);if(r===void 0)throw new Oe(e);return r}unwrap(e){let r=e;for(;Ye(r);)r=this.readSlot(r);return r}_getOrInstantiate(e){var n;let r=(n=this._memoizedResolves.get(e))!=null?n:[];this._itemStateStack.pushItem();try{for(let u of r)if([...u.slotToValueMap.entries()].every(([l,d])=>this._itemStateStack.readSlot(l)===d))return u.result;let a=e.resolve(this),i=new Map;for(let u of this._itemStateStack.topItem.usedSlots)i.set(u,this._itemStateStack.readSlot(u));return r.push({slotToValueMap:i,result:a}),this._memoizedResolves.set(e,r),a}catch(a){throw a instanceof Te?a.appendToTrace(e):new Te(a,[e])}finally{this._itemStateStack.pop()}}resolve(e,r=[]){if(!j(e))return String(e);let n=!1;r.length>0&&(n=!0,this._itemStateStack.pushSlotBindings(r));try{if(this._itemStateStack.itemDepth===0){let a=ee(()=>this._getOrInstantiate(e));return`${[...this._shared.declarations].join(`
|
9
|
+
|
10
|
+
`)}${a}`}return this._getOrInstantiate(e)}finally{n&&this._itemStateStack.pop()}}getIndexFor(e){let r=this._shared.getBindingIndex(e);if(r===void 0)throw new Error("No index found for item");return r}};var $=class{constructor(e,r){this.root=e;this.rootNode=r}build(e){var a;let r=new _({names:(a=e.nameRegistry)!=null?a:new S,bindingGroup:e.bindingGroup,jitTranspiler:this.root.jitTranspiler}),n=r.resolve(this.rootNode);return{bindGroupResolver:new ie(this.root,r,e.shaderStage),code:n}}};function vt(t){return Object.getOwnPropertySymbols(t).map(r=>{if(ze.get(r)===void 0)throw new Error("Symbol is not a member of `builtin`");return{name:t[r],builtinSymbol:r}})}var se=class{constructor(e,r,n,a){this.root=e;this.vertexRoot=r;this.fragmentRoot=n;this.vertexOutputFormat=a}build(e){var ke,Ie,Ce,Fe;let r=Object.getOwnPropertySymbols(this.vertexOutputFormat).map(p=>{let h=this.vertexOutputFormat[p];if(typeof h!="string")throw new Error("Output names must be strings.");return{symbol:p,name:h}}),n=vt(Object.fromEntries(r.map(({symbol:p,name:h})=>[p,h]))),a=Object.keys(this.vertexOutputFormat).map((p,h)=>{let E=this.vertexOutputFormat[p];if(!E)throw new Error("Output names must be strings.");return{name:p,varInfo:E,index:h}}),i=[...n.map(p=>{var E;let h=(E=this.vertexOutputFormat[p.builtinSymbol])!=null?E:"";return g`
|
11
|
+
@builtin(${N(p.builtinSymbol)}) ${h}: ${X(p.builtinSymbol)},
|
12
|
+
`}),...a.map(({name:p,varInfo:h,index:E})=>g`
|
13
|
+
@location(${E}) ${p}: ${h},
|
14
|
+
`)],u=new _({names:(ke=e.nameRegistry)!=null?ke:new S,bindingGroup:e.bindingGroup,jitTranspiler:this.root.jitTranspiler});u.resolve(this.vertexRoot);let l=Array.from(u.usedBindables).filter(p=>p.usage==="vertex").map((p,h)=>({idx:h,entry:{bindable:p,underlyingType:p.allocatable.dataType}})),d=l.map(p=>g`
|
15
|
+
@location(${p.idx}) ${p.entry.bindable} : ${"expressionCode"in p.entry.underlyingType?p.entry.underlyingType.expressionCode:p.entry.underlyingType.elementType},
|
16
|
+
`),c=[...Array.from(u.usedBuiltins).map(p=>g`
|
17
|
+
@builtin(${N(p)}) ${te(p)}: ${X(p)},
|
18
|
+
`),...d],w=g`
|
19
|
+
struct VertexOutput {
|
20
|
+
${i}
|
21
|
+
};
|
22
|
+
|
23
|
+
@vertex
|
24
|
+
fn main(${c}) -> VertexOutput {
|
25
|
+
${this.vertexRoot}
|
26
|
+
var output: VertexOutput;
|
27
|
+
${n.map(p=>g`
|
28
|
+
output.${p.name} = ${p.name};
|
29
|
+
`)}
|
30
|
+
${a.map(({name:p})=>g`
|
31
|
+
output.${p} = ${p};
|
32
|
+
`)}
|
33
|
+
return output;
|
34
|
+
}
|
35
|
+
`,U=new _({names:(Ie=e.nameRegistry)!=null?Ie:new S,bindingGroup:e.bindingGroup,jitTranspiler:this.root.jitTranspiler});U.resolve(this.fragmentRoot);let Q=Array.from(U.usedBuiltins).map(p=>g`
|
36
|
+
@builtin(${N(p)}) ${te(p)}: ${X(p)},
|
37
|
+
`),Z=a.map(({name:p,varInfo:h},E)=>g`
|
38
|
+
@location(${E}) ${p}: ${h},
|
39
|
+
`),lt=[...Q,...Z],dt=g`
|
40
|
+
@fragment
|
41
|
+
fn main(${lt}) -> @location(0) vec4f {
|
42
|
+
${this.fragmentRoot}
|
43
|
+
}
|
44
|
+
`,$e=new $(this.root,w).build({bindingGroup:e.bindingGroup,shaderStage:GPUShaderStage.VERTEX,nameRegistry:(Ce=e.nameRegistry)!=null?Ce:new S}),gt=new $(this.root,dt).build({bindingGroup:e.bindingGroup+1,shaderStage:GPUShaderStage.FRAGMENT,nameRegistry:(Fe=e.nameRegistry)!=null?Fe:new S});return $e.bindGroupResolver.setVertexBuffers(l.map(p=>({index:p.idx,buffer:p.entry.bindable}))),{vertexProgram:$e,fragmentProgram:gt}}},pe=class{constructor(e,r,n){this.root=e;this.computeRoot=r;this.workgroupSize=n}build(e){var l,d,T,m;let r=new _({names:(l=e.nameRegistry)!=null?l:new S,bindingGroup:e.bindingGroup,jitTranspiler:this.root.jitTranspiler});r.resolve(this.computeRoot);let a=Array.from(r.usedBuiltins).map(c=>g`
|
45
|
+
@builtin(${N(c)}) ${te(c)}: ${X(c)},
|
46
|
+
`),i=`@workgroup_size(${this.workgroupSize[0]}, ${(d=this.workgroupSize[1])!=null?d:1}, ${(T=this.workgroupSize[2])!=null?T:1})`,u=g`
|
47
|
+
@compute ${i}
|
48
|
+
fn main(${a}) {
|
49
|
+
${this.computeRoot}
|
50
|
+
}
|
51
|
+
`;return new $(this.root,u).build({bindingGroup:e.bindingGroup,shaderStage:GPUShaderStage.COMPUTE,nameRegistry:(m=e.nameRegistry)!=null?m:new S})}};import{BufferReader as Ue,BufferWriter as Ee}from"typed-binary";function le(t,e,r){return new De(t,e,r)}function A(t){return t.resourceType==="buffer"}function de(t){return!!t.usableAsUniform}function ge(t){return!!t.usableAsStorage}function bt(t){return!!t.usableAsVertex}var De=class{constructor(e,r,n){this._group=e;this.dataType=r;this.initialOrBuffer=n;o(this,"resourceType","buffer");o(this,"flags",GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC);o(this,"_device",null);o(this,"_buffer",null);o(this,"_destroyed",!1);o(this,"_subscription",null);o(this,"_label");o(this,"initial");o(this,"usableAsUniform",!1);o(this,"usableAsStorage",!1);o(this,"usableAsVertex",!1);Je(n)?this._buffer=n:this.initial=n}get label(){return this._label}get buffer(){if(!this._device)throw new Error("Create this buffer using `root.createBuffer` instead of `tgpu.createBuffer`.");if(this._destroyed)throw new Error("This buffer has been destroyed");if(!this._buffer&&(this._buffer=this._device.createBuffer({size:this.dataType.size,usage:this.flags,mappedAtCreation:!!this.initial}),this.initial)){let e=new Ee(this._buffer.getMappedRange());if(Xe(this.initial)){let r=this._group;if(!r)throw new Error("Create this buffer using `root.createBuffer` instead of `tgpu.createBuffer`.");let n=this.initial;this.dataType.write(e,r.readPlum(n)),this._subscription=r.onPlumChange(n,()=>{this.write(r.readPlum(n))})}else this.dataType.write(e,this.initial);this._buffer.unmap()}return this._buffer}get device(){if(!this._device)throw new Error("This buffer has not been assigned a device. Use .$device(device) to assign a device");return this._device}get destroyed(){return this._destroyed}$name(e){return this._label=e,this}$usage(...e){for(let r of e)this.flags|=r==="uniform"?GPUBufferUsage.UNIFORM:0,this.flags|=r==="storage"?GPUBufferUsage.STORAGE:0,this.flags|=r==="vertex"?GPUBufferUsage.VERTEX:0,this.usableAsUniform=this.usableAsUniform||r==="uniform",this.usableAsStorage=this.usableAsStorage||r==="storage",this.usableAsVertex=this.usableAsVertex||r==="vertex";return this}$addFlags(e){return this.flags|=e,this}$device(e){return this._device=e,this}write(e){let r=this.buffer,n=this.device;if(r.mapState==="mapped"){let i=r.getMappedRange();if(A(e))throw new Error("Cannot copy to a mapped buffer.");this.dataType.write(new Ee(i),e);return}let a=this.dataType.size;if(A(e)){let i=e.buffer;if(this._group)this._group.commandEncoder.copyBufferToBuffer(i,0,r,0,a);else{let u=n.createCommandEncoder();u.copyBufferToBuffer(i,0,r,0,a),n.queue.submit([u.finish()])}}else{this._group&&this._group.flush();let i=new ArrayBuffer(a);this.dataType.write(new Ee(i),e),n.queue.writeBuffer(r,0,i,0,a)}}async read(){this._group&&this._group.flush();let e=this.buffer,r=this.device;if(e.mapState==="mapped"){let u=e.getMappedRange();return this.dataType.read(new Ue(u))}if(e.usage&GPUBufferUsage.MAP_READ){await e.mapAsync(GPUMapMode.READ);let u=e.getMappedRange(),s=this.dataType.read(new Ue(u));return e.unmap(),s}let n=r.createBuffer({size:this.dataType.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=r.createCommandEncoder();a.copyBufferToBuffer(e,0,n,0,this.dataType.size),r.queue.submit([a.finish()]),await r.queue.onSubmittedWorkDone(),await n.mapAsync(GPUMapMode.READ,0,this.dataType.size);let i=this.dataType.read(new Ue(n.getMappedRange()));return n.unmap(),n.destroy(),i}destroy(){var e;this._destroyed||(this._destroyed=!0,this._subscription&&this._subscription(),(e=this._buffer)==null||e.destroy())}toString(){var e;return`buffer:${(e=this._label)!=null?e:"<unnamed>"}`}};function Re(t){return!!t&&t.resourceType==="buffer-usage"}function rt(t){return new _e(t)}function nt(t){return!!t&&t.resourceType==="bind-group-layout"}function at(t){return!!t&&t.resourceType==="bind-group"}var Ge=class t extends Error{constructor(e,r){super(`Bind group '${e!=null?e:"<unnamed>"}' is missing a required binding '${r}'`),Object.setPrototypeOf(this,t.prototype)}},tt=["compute"],k=["compute","vertex","fragment"],_e=class{constructor(e){this.entries=e;o(this,"_label");o(this,"resourceType","bind-group-layout");o(this,"bound",{})}get label(){return this._label}$name(e){return this._label=e,this}unwrap(e){var n;return e.device.createBindGroupLayout({label:(n=this.label)!=null?n:"",entries:Object.values(this.entries).map((a,i)=>{var l,d,T,m;if(a===null)return null;let u=a.visibility,s={binding:i,visibility:0};if("uniform"in a)u=u!=null?u:k,s.buffer={type:"uniform"};else if("storage"in a)u=u!=null?u:a.access==="mutable"?tt:k,s.buffer={type:a.access==="mutable"?"storage":"read-only-storage"};else if("sampler"in a)u=u!=null?u:k,s.sampler={type:a.sampler};else if("texture"in a)u=u!=null?u:k,s.texture={sampleType:a.texture,viewDimension:(l=a.viewDimension)!=null?l:"2d",multisampled:(d=a.multisampled)!=null?d:!1};else if("storageTexture"in a){let c=(T=a.access)!=null?T:"writeonly";u=u!=null?u:c==="readonly"?k:tt,s.storageTexture={format:a.storageTexture,access:{mutable:"read-write",readonly:"read-only",writeonly:"write-only"}[c],viewDimension:(m=a.viewDimension)!=null?m:"2d"}}else"externalTexture"in a&&(u=u!=null?u:k,s.externalTexture={});return u!=null&&u.includes("compute")&&(s.visibility|=GPUShaderStage.COMPUTE),u!=null&&u.includes("vertex")&&(s.visibility|=GPUShaderStage.VERTEX),u!=null&&u.includes("fragment")&&(s.visibility|=GPUShaderStage.FRAGMENT),s}).filter(a=>a!==null)})}populate(e){return new Ae(this,e)}},Ae=class{constructor(e,r){this.layout=e;this.entries=r;o(this,"resourceType","bind-group");for(let n of Object.keys(e.entries))if(e.entries[n]!==null&&!(n in r))throw new Ge(e.label,n)}unwrap(e){var n;return e.device.createBindGroup({label:(n=this.layout.label)!=null?n:"",layout:e.unwrap(this.layout),entries:Object.entries(this.layout.entries).map(([a,i],u)=>{var l;if(i===null)return null;let s=this.entries[a];if(s===void 0)throw new Error(`'${a}' is a resource required to populate bind group layout '${(l=this.layout.label)!=null?l:"<unnamed>"}'.`);if("uniform"in i){let d;if(A(s)){if(!de(s))throw new z(s);d={buffer:e.unwrap(s)}}else if(Re(s)){if(!de(s.allocatable))throw new z(s.allocatable);d={buffer:e.unwrap(s.allocatable)}}else d={buffer:s};return{binding:u,resource:d}}if("storage"in i){let d;if(A(s)){if(!ge(s))throw new z(s);d={buffer:e.unwrap(s)}}else if(Re(s)){if(!ge(s.allocatable))throw new z(s.allocatable);d={buffer:e.unwrap(s.allocatable)}}else d={buffer:s};return{binding:u,resource:d}}if("texture"in i||"storageTexture"in i||"externalTexture"in i||"sampler"in i)return{binding:u,resource:s};throw new Error(`Malformed bind group entry: ${s} (${JSON.stringify(s)})`)}).filter(a=>a!==null)})}};var ce=class{constructor(e,r){this.device=e;this.jitTranspiler=r;o(this,"_buffers",[]);o(this,"_samplers",new WeakMap);o(this,"_textures",new WeakMap);o(this,"_textureViews",new WeakMap);o(this,"_externalTexturesStatus",new WeakMap);o(this,"_unwrappedBindGroupLayouts",new H(e=>e.unwrap(this)));o(this,"_unwrappedBindGroups",new H(e=>e.unwrap(this)));o(this,"_pipelineExecutors",[]);o(this,"_commandEncoder",null);o(this,"_plumStore",new ne)}get commandEncoder(){return this._commandEncoder||(this._commandEncoder=this.device.createCommandEncoder()),this._commandEncoder}createBuffer(e,r){let n=le(this,e,r).$device(this.device);return this._buffers.push(n),n}destroy(){for(let e of this._buffers)e.destroy()}unwrap(e){if(A(e))return e.buffer;if(nt(e))return this._unwrappedBindGroupLayouts.getOrMake(e);if(at(e))return this._unwrappedBindGroups.getOrMake(e);throw new Error(`Unknown resource type: ${e}`)}textureFor(e){let r;"texture"in e?r=e.texture:r=e;let n=this._textures.get(r);if(!n){let a=O(M({},r.descriptor),{usage:r.flags});if(n=this.device.createTexture(a),!n)throw new Error(`Failed to create texture for ${e}`);this._textures.set(r,n)}return n}viewFor(e){let r=this._textureViews.get(e);return r||(r=this.textureFor(e.texture).createView(e.descriptor),this._textureViews.set(e,r)),r}externalTextureFor(e){if(this._externalTexturesStatus.set(e,"clean"),e.descriptor.source===void 0)throw new Error("External texture source needs to be defined before use");return this.device.importExternalTexture(e.descriptor)}samplerFor(e){let r=this._samplers.get(e);if(!r){if(r=this.device.createSampler(e.descriptor),!r)throw new Error(`Failed to create sampler for ${e}`);this._samplers.set(e,r)}return r}setSource(e,r){this._externalTexturesStatus.set(e,"dirty"),e.descriptor.source=r}isDirty(e){return this._externalTexturesStatus.get(e)==="dirty"}markClean(e){this._externalTexturesStatus.set(e,"clean")}readPlum(e){return this._plumStore.get(e)}setPlum(e,r){if(typeof r=="function"){let n=r;this._plumStore.set(e,n(this._plumStore.get(e)))}else this._plumStore.set(e,r)}onPlumChange(e,r){return this._plumStore.subscribe(e,r)}makeRenderPipeline(e){var d,T,m,c,w,U,fe,Q,Z;let{vertexProgram:r,fragmentProgram:n}=new se(this,e.vertex.code,e.fragment.code,e.vertex.output).build({bindingGroup:((d=e.externalLayouts)!=null?d:[]).length}),a=this.device.createShaderModule({code:r.code}),i=this.device.createShaderModule({code:n.code}),u=this.device.createPipelineLayout({label:(T=e.label)!=null?T:"",bindGroupLayouts:[...(m=e.externalLayouts)!=null?m:[],r.bindGroupResolver.getBindGroupLayout(),n.bindGroupResolver.getBindGroupLayout()]}),s=this.device.createRenderPipeline({label:(c=e.label)!=null?c:"",layout:u,vertex:{module:a,buffers:(w=r.bindGroupResolver.getVertexBufferDescriptors())!=null?w:[]},fragment:{module:i,targets:(fe=(U=e.fragment)==null?void 0:U.target)!=null?fe:[]},primitive:e.primitive}),l=new Ve(this,s,r,n,(Z=(Q=e.externalLayouts)==null?void 0:Q.length)!=null?Z:0);return this._pipelineExecutors.push(l),l}makeComputePipeline(e){var s,l,d,T,m;let r=ee(()=>{var c,w;return new pe(this,e.code,(c=e.workgroupSize)!=null?c:[1]).build({bindingGroup:((w=e.externalLayouts)!=null?w:[]).length})}),n=this.device.createShaderModule({code:r.code}),a=this.device.createPipelineLayout({label:(s=e.label)!=null?s:"",bindGroupLayouts:[...(l=e.externalLayouts)!=null?l:[],r.bindGroupResolver.getBindGroupLayout()]}),i=this.device.createComputePipeline({label:(d=e.label)!=null?d:"",layout:a,compute:{module:n}}),u=new Le(this,i,[r],(m=(T=e.externalLayouts)==null?void 0:T.length)!=null?m:0);return this._pipelineExecutors.push(u),u}flush(){this._commandEncoder&&(this.device.queue.submit([this._commandEncoder.finish()]),this._commandEncoder=null)}},Ve=class{constructor(e,r,n,a,i,u){this.root=e;this.pipeline=r;this.vertexProgram=n;this.fragmentProgram=a;this.externalLayoutCount=i;this.label=u}execute(e){var T,m,c;let d=e,{vertexCount:r,instanceCount:n,firstVertex:a,firstInstance:i,externalBindGroups:u}=d,s=Me(d,["vertexCount","instanceCount","firstVertex","firstInstance","externalBindGroups"]);if(((T=u==null?void 0:u.length)!=null?T:0)!==this.externalLayoutCount)throw new Error(`External bind group count doesn't match the external bind group layout configuration. Expected ${this.externalLayoutCount}, got: ${(m=u==null?void 0:u.length)!=null?m:0}`);let l=this.root.commandEncoder.beginRenderPass(O(M({},s),{label:(c=this.label)!=null?c:""}));l.setPipeline(this.pipeline),(u!=null?u:[]).forEach((w,U)=>l.setBindGroup(U,w)),l.setBindGroup((u!=null?u:[]).length,this.vertexProgram.bindGroupResolver.getBindGroup()),l.setBindGroup((u!=null?u:[]).length+1,this.fragmentProgram.bindGroupResolver.getBindGroup());for(let[w,U]of this.vertexProgram.bindGroupResolver.getVertexBuffers())l.setVertexBuffer(U,w.allocatable.buffer);l.draw(r,n,a,i),l.end()}},Le=class{constructor(e,r,n,a,i){this.root=e;this.pipeline=r;this.programs=n;this.externalLayoutCount=a;this.label=i}execute(e){var i,u,s;let{workgroups:r=[1,1],externalBindGroups:n}=e!=null?e:{};if(((i=n==null?void 0:n.length)!=null?i:0)!==this.externalLayoutCount)throw new Error(`External bind group count doesn't match the external bind group layout configuration. Expected ${this.externalLayoutCount}, got: ${(u=n==null?void 0:n.length)!=null?u:0}`);let a=this.root.commandEncoder.beginComputePass({label:(s=this.label)!=null?s:""});a.setPipeline(this.pipeline),(n!=null?n:[]).forEach((l,d)=>a.setBindGroup(d,l)),this.programs.forEach((l,d)=>a.setBindGroup((n!=null?n:[]).length+d,l.bindGroupResolver.getBindGroup())),a.dispatchWorkgroups(...r),a.end()}};async function ut(t){if(!navigator.gpu)throw new Error("WebGPU is not supported by this browser.");let e=await navigator.gpu.requestAdapter(t==null?void 0:t.adapter);if(!e)throw new Error("Could not find a compatible GPU");return new ce(await e.requestDevice(t==null?void 0:t.device),t==null?void 0:t.unstable_jitTranspiler)}function it(t){return new ce(t.device,t.unstable_jitTranspiler)}function ot(t,e){return le(void 0,t,e)}function st(t,e){t.write(e)}async function pt(t){return t.read()}var I=t=>Math.sqrt(t.x**2+t.y**2),C=t=>Math.sqrt(t.x**2+t.y**2+t.z**2),F=t=>Math.sqrt(t.x**2+t.y**2+t.z**2+t.w**2),R={length:{vec2f:I,vec2i:I,vec2u:I,vec3f:C,vec3i:C,vec3u:C,vec4f:F,vec4i:F,vec4u:F},add:{vec2f:(t,e)=>W(t.x+e.x,t.y+e.y),vec2i:(t,e)=>K(t.x+e.x,t.y+e.y),vec2u:(t,e)=>q(t.x+e.x,t.y+e.y),vec3f:(t,e)=>V(t.x+e.x,t.y+e.y,t.z+e.z),vec3i:(t,e)=>L(t.x+e.x,t.y+e.y,t.z+e.z),vec3u:(t,e)=>P(t.x+e.x,t.y+e.y,t.z+e.z),vec4f:(t,e)=>D(t.x+e.x,t.y+e.y,t.z+e.z,t.w+e.w),vec4i:(t,e)=>J(t.x+e.x,t.y+e.y,t.z+e.z,t.w+e.w),vec4u:(t,e)=>Y(t.x+e.x,t.y+e.y,t.z+e.z,t.w+e.w)},sub:{vec2f:(t,e)=>W(t.x-e.x,t.y-e.y),vec2i:(t,e)=>K(t.x-e.x,t.y-e.y),vec2u:(t,e)=>q(t.x-e.x,t.y-e.y),vec3f:(t,e)=>V(t.x-e.x,t.y-e.y,t.z-e.z),vec3i:(t,e)=>L(t.x-e.x,t.y-e.y,t.z-e.z),vec3u:(t,e)=>P(t.x-e.x,t.y-e.y,t.z-e.z),vec4f:(t,e)=>D(t.x-e.x,t.y-e.y,t.z-e.z,t.w-e.w),vec4i:(t,e)=>J(t.x-e.x,t.y-e.y,t.z-e.z,t.w-e.w),vec4u:(t,e)=>Y(t.x-e.x,t.y-e.y,t.z-e.z,t.w-e.w)},mul:{vec2f:(t,e)=>W(t*e.x,t*e.y),vec2i:(t,e)=>K(t*e.x,t*e.y),vec2u:(t,e)=>q(t*e.x,t*e.y),vec3f:(t,e)=>V(t*e.x,t*e.y,t*e.z),vec3i:(t,e)=>L(t*e.x,t*e.y,t*e.z),vec3u:(t,e)=>P(t*e.x,t*e.y,t*e.z),vec4f:(t,e)=>D(t*e.x,t*e.y,t*e.z,t*e.w),vec4i:(t,e)=>J(t*e.x,t*e.y,t*e.z,t*e.w),vec4u:(t,e)=>Y(t*e.x,t*e.y,t*e.z,t*e.w)},dot:{vec2f:(t,e)=>t.x*e.x+t.y*e.y,vec2i:(t,e)=>t.x*e.x+t.y*e.y,vec2u:(t,e)=>t.x*e.x+t.y*e.y,vec3f:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z,vec3i:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z,vec3u:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z,vec4f:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z+t.w*e.w,vec4i:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z+t.w*e.w,vec4u:(t,e)=>t.x*e.x+t.y*e.y+t.z*e.z+t.w*e.w},normalize:{vec2f:t=>{let e=I(t);return W(t.x/e,t.y/e)},vec2i:t=>{let e=I(t);return K(t.x/e,t.y/e)},vec2u:t=>{let e=I(t);return q(t.x/e,t.y/e)},vec3f:t=>{let e=C(t);return V(t.x/e,t.y/e,t.z/e)},vec3i:t=>{let e=C(t);return L(t.x/e,t.y/e,t.z/e)},vec3u:t=>{let e=C(t);return P(t.x/e,t.y/e,t.z/e)},vec4f:t=>{let e=F(t);return D(t.x/e,t.y/e,t.z/e,t.w/e)},vec4i:t=>{let e=F(t);return J(t.x/e,t.y/e,t.z/e,t.w/e)},vec4u:t=>{let e=F(t);return Y(t.x/e,t.y/e,t.z/e,t.w/e)}},cross:{vec3f:(t,e)=>V(t.y*e.z-t.z*e.y,t.z*e.x-t.x*e.z,t.x*e.y-t.y*e.x),vec3i:(t,e)=>L(t.y*e.z-t.z*e.y,t.z*e.x-t.x*e.z,t.x*e.y-t.y*e.x),vec3u:(t,e)=>P(t.y*e.z-t.z*e.y,t.z*e.x-t.x*e.z,t.x*e.y-t.y*e.x)}};var wt={add(t,e){return B()?`(${t} + ${e})`:R.add[t.kind](t,e)},sub(t,e){return B()?`(${t} - ${e})`:R.sub[t.kind](t,e)},mul:(t,e)=>B()?`(${t} * ${e})`:R.mul[e.kind](t,e),dot(t,e){return B()?`dot(${t}, ${e})`:R.dot[t.kind](t,e)},normalize:t=>B()?`normalize(${t})`:R.normalize[t.kind](t),cross(t,e){return B()?`cross(${t}, ${e})`:R.cross[t.kind](t,e)},fract(t){return B()?`fract(${t})`:t-Math.floor(t)},length(t){return B()?`length(${t})`:R.length[t.kind](t)},sin(t){return B()?`sin(${t})`:Math.sin(t)},cos(t){return B()?`cos(${t})`:Math.cos(t)}};var Bt={Uniform:"uniform",Storage:"storage",Vertex:"vertex",bindGroupLayout:rt,init:ut,initFromDevice:it,createBuffer:ot,read:pt,write:st},Yr=Bt;export{ct as RecursiveDataTypeError,Yr as default,ge as isUsableAsStorage,de as isUsableAsUniform,bt as isUsableAsVertex,wt as std,Bt as tgpu};
|
2
52
|
//# sourceMappingURL=index.js.map
|