typegpu 0.10.0 → 0.10.2

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 (263) hide show
  1. package/{chunk-BYypO7fO.js → _virtual/_rolldown/runtime.js} +1 -1
  2. package/builtin.d.ts +50 -0
  3. package/builtin.js +37 -0
  4. package/common/fullScreenTriangle.d.ts +26 -0
  5. package/common/fullScreenTriangle.js +36 -0
  6. package/common/index.d.ts +2 -3
  7. package/common/index.js +3 -4
  8. package/core/buffer/buffer.d.ts +74 -0
  9. package/core/buffer/buffer.js +197 -0
  10. package/core/buffer/bufferShorthand.d.ts +48 -0
  11. package/core/buffer/bufferShorthand.js +49 -0
  12. package/core/buffer/bufferUsage.d.ts +45 -0
  13. package/core/buffer/bufferUsage.js +163 -0
  14. package/core/constant/tgpuConstant.d.ts +28 -0
  15. package/core/constant/tgpuConstant.js +67 -0
  16. package/core/declare/tgpuDeclare.d.ts +18 -0
  17. package/core/declare/tgpuDeclare.js +40 -0
  18. package/core/function/autoIO.d.ts +37 -0
  19. package/core/function/autoIO.js +87 -0
  20. package/core/function/comptime.d.ts +39 -0
  21. package/core/function/comptime.js +51 -0
  22. package/core/function/createCallableSchema.js +42 -0
  23. package/core/function/dualImpl.js +54 -0
  24. package/core/function/extractArgs.js +204 -0
  25. package/core/function/fnCore.js +79 -0
  26. package/core/function/fnTypes.d.ts +34 -0
  27. package/core/function/ioSchema.d.ts +10 -0
  28. package/core/function/ioSchema.js +30 -0
  29. package/core/function/shelllessImpl.d.ts +28 -0
  30. package/core/function/shelllessImpl.js +23 -0
  31. package/core/function/templateUtils.js +13 -0
  32. package/core/function/tgpuComputeFn.d.ts +49 -0
  33. package/core/function/tgpuComputeFn.js +62 -0
  34. package/core/function/tgpuFn.d.ts +52 -0
  35. package/core/function/tgpuFn.js +170 -0
  36. package/core/function/tgpuFragmentFn.d.ts +68 -0
  37. package/core/function/tgpuFragmentFn.js +68 -0
  38. package/core/function/tgpuVertexFn.d.ts +55 -0
  39. package/core/function/tgpuVertexFn.js +65 -0
  40. package/core/pipeline/applyPipelineState.js +37 -0
  41. package/core/pipeline/computePipeline.d.ts +58 -0
  42. package/core/pipeline/computePipeline.js +226 -0
  43. package/core/pipeline/connectAttachmentToShader.js +26 -0
  44. package/core/pipeline/connectTargetsToShader.js +29 -0
  45. package/core/pipeline/limitsOverflow.js +13 -0
  46. package/core/pipeline/renderPipeline.d.ts +266 -0
  47. package/core/pipeline/renderPipeline.js +471 -0
  48. package/core/pipeline/timeable.d.ts +23 -0
  49. package/core/pipeline/timeable.js +61 -0
  50. package/core/pipeline/typeGuards.js +29 -0
  51. package/core/querySet/querySet.d.ts +22 -0
  52. package/core/querySet/querySet.js +103 -0
  53. package/core/rawCodeSnippet/tgpuRawCodeSnippet.d.ts +59 -0
  54. package/core/rawCodeSnippet/tgpuRawCodeSnippet.js +96 -0
  55. package/core/resolve/externals.d.ts +10 -0
  56. package/core/resolve/externals.js +58 -0
  57. package/core/resolve/namespace.d.ts +38 -0
  58. package/core/resolve/namespace.js +41 -0
  59. package/core/resolve/resolveData.js +146 -0
  60. package/core/resolve/stitch.js +25 -0
  61. package/core/resolve/tgpuResolve.d.ts +151 -0
  62. package/core/resolve/tgpuResolve.js +68 -0
  63. package/core/root/configurableImpl.js +18 -0
  64. package/core/root/init.d.ts +69 -0
  65. package/core/root/init.js +457 -0
  66. package/core/root/rootTypes.d.ts +622 -0
  67. package/core/sampler/sampler.d.ts +35 -0
  68. package/core/sampler/sampler.js +116 -0
  69. package/core/simulate/tgpuSimulate.d.ts +36 -0
  70. package/core/simulate/tgpuSimulate.js +76 -0
  71. package/core/slot/accessor.d.ts +13 -0
  72. package/core/slot/accessor.js +97 -0
  73. package/core/slot/internalSlots.js +7 -0
  74. package/core/slot/lazy.d.ts +6 -0
  75. package/core/slot/lazy.js +42 -0
  76. package/core/slot/slot.d.ts +6 -0
  77. package/core/slot/slot.js +40 -0
  78. package/core/slot/slotTypes.d.ts +92 -0
  79. package/core/slot/slotTypes.js +21 -0
  80. package/core/texture/externalTexture.d.ts +12 -0
  81. package/core/texture/externalTexture.js +48 -0
  82. package/core/texture/texture.d.ts +118 -0
  83. package/core/texture/texture.js +312 -0
  84. package/core/texture/textureFormats.d.ts +29 -0
  85. package/core/texture/textureFormats.js +99 -0
  86. package/core/texture/textureProps.d.ts +11 -0
  87. package/core/texture/textureUtils.js +224 -0
  88. package/core/texture/usageExtension.d.ts +21 -0
  89. package/core/texture/usageExtension.js +21 -0
  90. package/core/unroll/tgpuUnroll.d.ts +13 -0
  91. package/core/unroll/tgpuUnroll.js +36 -0
  92. package/core/valueProxyUtils.js +44 -0
  93. package/core/variable/tgpuVariable.d.ts +38 -0
  94. package/core/variable/tgpuVariable.js +101 -0
  95. package/core/vertexLayout/connectAttributesToShader.js +59 -0
  96. package/core/vertexLayout/vertexAttribute.d.ts +29 -0
  97. package/core/vertexLayout/vertexLayout.d.ts +19 -0
  98. package/core/vertexLayout/vertexLayout.js +103 -0
  99. package/data/alignIO.js +15 -0
  100. package/data/alignmentOf.d.ts +10 -0
  101. package/data/alignmentOf.js +88 -0
  102. package/data/array.d.ts +28 -0
  103. package/data/array.js +48 -0
  104. package/data/atomic.d.ts +15 -0
  105. package/data/atomic.js +25 -0
  106. package/data/attributes.d.ts +121 -0
  107. package/data/attributes.js +145 -0
  108. package/data/autoStruct.d.ts +3 -0
  109. package/data/autoStruct.js +83 -0
  110. package/data/compiledIO.js +231 -0
  111. package/data/dataIO.js +549 -0
  112. package/data/dataTypes.d.ts +115 -0
  113. package/data/dataTypes.js +97 -0
  114. package/data/deepEqual.d.ts +25 -0
  115. package/data/deepEqual.js +58 -0
  116. package/data/disarray.d.ts +34 -0
  117. package/data/disarray.js +52 -0
  118. package/data/getLongestContiguousPrefix.d.ts +10 -0
  119. package/data/getLongestContiguousPrefix.js +15 -0
  120. package/data/index.d.ts +26 -4
  121. package/data/index.js +27 -7
  122. package/data/instanceToSchema.d.ts +33 -0
  123. package/data/isContiguous.d.ts +10 -0
  124. package/data/isContiguous.js +15 -0
  125. package/data/matrix.d.ts +126 -0
  126. package/data/matrix.js +517 -0
  127. package/data/numberOps.js +24 -0
  128. package/data/numeric.d.ts +81 -0
  129. package/data/numeric.js +234 -0
  130. package/data/offsetUtils.d.ts +33 -0
  131. package/data/offsetUtils.js +167 -0
  132. package/data/offsets.js +36 -0
  133. package/data/partialIO.js +68 -0
  134. package/data/ptr.d.ts +12 -0
  135. package/data/ptr.js +46 -0
  136. package/data/ref.d.ts +37 -0
  137. package/data/ref.js +96 -0
  138. package/data/sampler.d.ts +107 -0
  139. package/data/sampler.js +26 -0
  140. package/data/schemaCallWrapper.js +32 -0
  141. package/data/schemaMemoryLayout.js +200 -0
  142. package/data/sizeOf.d.ts +10 -0
  143. package/data/sizeOf.js +15 -0
  144. package/data/snippet.d.ts +26 -0
  145. package/data/snippet.js +61 -0
  146. package/data/struct.d.ts +17 -0
  147. package/data/struct.js +46 -0
  148. package/data/texture.d.ts +292 -0
  149. package/{texture-Dg5ybJro.js → data/texture.js} +6 -3
  150. package/data/unstruct.d.ts +24 -0
  151. package/data/unstruct.js +43 -0
  152. package/data/vector.d.ts +191 -0
  153. package/data/vector.js +247 -0
  154. package/data/vectorImpl.js +516 -0
  155. package/data/vectorOps.js +664 -0
  156. package/data/vertexFormatData.d.ts +190 -0
  157. package/data/vertexFormatData.js +110 -0
  158. package/data/wgslTypes.d.ts +896 -0
  159. package/data/wgslTypes.js +215 -0
  160. package/errors.d.ts +44 -0
  161. package/errors.js +128 -0
  162. package/execMode.js +51 -0
  163. package/extension.d.ts +11 -0
  164. package/extension.js +18 -0
  165. package/getGPUValue.js +9 -0
  166. package/index.d.ts +40 -243
  167. package/index.js +19 -6318
  168. package/indexNamedExports.d.ts +38 -0
  169. package/mathUtils.js +13 -0
  170. package/memo.js +22 -0
  171. package/nameRegistry.d.ts +30 -0
  172. package/nameRegistry.js +449 -0
  173. package/package.js +5 -0
  174. package/package.json +23 -23
  175. package/resolutionCtx.d.ts +29 -0
  176. package/resolutionCtx.js +546 -0
  177. package/shared/env.js +13 -0
  178. package/shared/generators.js +14 -0
  179. package/shared/meta.d.ts +39 -0
  180. package/shared/meta.js +63 -0
  181. package/shared/repr.d.ts +108 -0
  182. package/shared/stringify.js +22 -0
  183. package/shared/symbols.d.ts +61 -0
  184. package/shared/symbols.js +71 -0
  185. package/shared/utilityTypes.d.ts +29 -0
  186. package/shared/utilityTypes.js +7 -0
  187. package/shared/vertexFormat.d.ts +70 -0
  188. package/shared/vertexFormat.js +64 -0
  189. package/std/array.d.ts +7 -0
  190. package/std/array.js +27 -0
  191. package/std/atomic.d.ts +19 -0
  192. package/std/atomic.js +113 -0
  193. package/std/bitcast.d.ts +10 -0
  194. package/std/bitcast.js +43 -0
  195. package/std/boolean.d.ts +127 -0
  196. package/std/boolean.js +274 -0
  197. package/std/derivative.d.ts +16 -0
  198. package/std/derivative.js +89 -0
  199. package/std/discard.d.ts +6 -0
  200. package/std/discard.js +16 -0
  201. package/std/extensions.d.ts +8 -0
  202. package/std/extensions.js +14 -0
  203. package/std/index.d.ts +15 -3
  204. package/std/index.js +16 -5
  205. package/std/matrix.d.ts +41 -0
  206. package/std/matrix.js +87 -0
  207. package/std/numeric.d.ts +254 -0
  208. package/std/numeric.js +847 -0
  209. package/std/operators.d.ts +48 -0
  210. package/std/operators.js +153 -0
  211. package/std/packing.d.ts +26 -0
  212. package/std/packing.js +86 -0
  213. package/std/subgroup.d.ts +47 -0
  214. package/std/subgroup.js +220 -0
  215. package/std/texture.d.ts +108 -0
  216. package/std/texture.js +197 -0
  217. package/tgpu.js +44 -0
  218. package/tgpuBindGroupLayout.d.ts +161 -0
  219. package/tgpuBindGroupLayout.js +271 -0
  220. package/tgpuUnstable.d.ts +48 -0
  221. package/tgpuUnstable.js +66 -0
  222. package/tgsl/accessIndex.js +45 -0
  223. package/tgsl/accessProp.js +113 -0
  224. package/tgsl/consoleLog/deserializers.js +117 -0
  225. package/tgsl/consoleLog/logGenerator.js +86 -0
  226. package/tgsl/consoleLog/serializers.js +225 -0
  227. package/tgsl/consoleLog/types.d.ts +54 -0
  228. package/tgsl/consoleLog/types.js +12 -0
  229. package/tgsl/conversion.js +200 -0
  230. package/tgsl/forOfUtils.js +45 -0
  231. package/tgsl/generationHelpers.d.ts +37 -0
  232. package/tgsl/generationHelpers.js +67 -0
  233. package/tgsl/math.js +45 -0
  234. package/tgsl/shaderGenerator.d.ts +18 -0
  235. package/tgsl/shellless.d.ts +11 -0
  236. package/tgsl/shellless.js +53 -0
  237. package/tgsl/wgslGenerator.js +585 -0
  238. package/types.d.ts +255 -0
  239. package/types.js +43 -0
  240. package/unwrapper.d.ts +27 -0
  241. package/wgslExtensions.d.ts +5 -0
  242. package/wgslExtensions.js +18 -0
  243. package/builtin-ClEnM-Ye.js +0 -818
  244. package/builtin-ClEnM-Ye.js.map +0 -1
  245. package/common/index.d.ts.map +0 -1
  246. package/common/index.js.map +0 -1
  247. package/data/index.d.ts.map +0 -1
  248. package/data/index.js.map +0 -1
  249. package/deepEqual-yZXvaV2C.js +0 -413
  250. package/deepEqual-yZXvaV2C.js.map +0 -1
  251. package/extensions-0SFbU9FH.js +0 -2032
  252. package/extensions-0SFbU9FH.js.map +0 -1
  253. package/fullScreenTriangle-MdLGaAMR.js +0 -543
  254. package/fullScreenTriangle-MdLGaAMR.js.map +0 -1
  255. package/index.d.ts.map +0 -1
  256. package/index.js.map +0 -1
  257. package/indexNamedExports-Cdy7USiY.d.ts +0 -5696
  258. package/indexNamedExports-Cdy7USiY.d.ts.map +0 -1
  259. package/operators-HTxa_0k9.js +0 -4156
  260. package/operators-HTxa_0k9.js.map +0 -1
  261. package/std/index.d.ts.map +0 -1
  262. package/std/index.js.map +0 -1
  263. package/texture-Dg5ybJro.js.map +0 -1
@@ -0,0 +1,224 @@
1
+ import { getEffectiveSampleTypes, getTextureFormatInfo } from "./textureFormats.js";
2
+
3
+ //#region src/core/texture/textureUtils.ts
4
+ function getImageSourceDimensions(source) {
5
+ const { videoWidth, videoHeight } = source;
6
+ if (videoWidth && videoHeight) return {
7
+ width: videoWidth,
8
+ height: videoHeight
9
+ };
10
+ const { naturalWidth, naturalHeight } = source;
11
+ if (naturalWidth && naturalHeight) return {
12
+ width: naturalWidth,
13
+ height: naturalHeight
14
+ };
15
+ const { codedWidth, codedHeight } = source;
16
+ if (codedWidth && codedHeight) return {
17
+ width: codedWidth,
18
+ height: codedHeight
19
+ };
20
+ const { width, height } = source;
21
+ if (width && height) return {
22
+ width,
23
+ height
24
+ };
25
+ throw new Error("Cannot determine dimensions of the provided image source.");
26
+ }
27
+ const FULLSCREEN_VERTEX_SHADER = `
28
+ struct VertexOutput {
29
+ @builtin(position) pos: vec4f,
30
+ @location(0) uv: vec2f,
31
+ }
32
+
33
+ @vertex
34
+ fn vs_main(@builtin(vertex_index) i: u32) -> VertexOutput {
35
+ const pos = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
36
+ const uv = array(vec2f(0, 1), vec2f(2, 1), vec2f(0, -1));
37
+ return VertexOutput(vec4f(pos[i], 0, 1), uv[i]);
38
+ }`;
39
+ const SAMPLE_FRAGMENT_SHADER = `
40
+ @group(0) @binding(0) var src: texture_2d<f32>;
41
+ @group(0) @binding(1) var samp: sampler;
42
+
43
+ @fragment
44
+ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
45
+ return textureSample(src, samp, uv);
46
+ }`;
47
+ const GATHER_FRAGMENT_SHADER = `
48
+ @group(0) @binding(0) var src: texture_2d<f32>;
49
+ @group(0) @binding(1) var samp: sampler;
50
+
51
+ @fragment
52
+ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
53
+ let r = textureGather(0, src, samp, uv);
54
+ let g = textureGather(1, src, samp, uv);
55
+ let b = textureGather(2, src, samp, uv);
56
+ let a = textureGather(3, src, samp, uv);
57
+ return vec4f(dot(r, vec4f(0.25)), dot(g, vec4f(0.25)), dot(b, vec4f(0.25)), dot(a, vec4f(0.25)));
58
+ }`;
59
+ const blitCache = /* @__PURE__ */ new WeakMap();
60
+ function getOrCreateDeviceCache(device) {
61
+ let cache = blitCache.get(device);
62
+ if (!cache) {
63
+ cache = {
64
+ vertexModule: device.createShaderModule({ code: FULLSCREEN_VERTEX_SHADER }),
65
+ filterableResources: /* @__PURE__ */ new Map(),
66
+ layoutResources: /* @__PURE__ */ new Map()
67
+ };
68
+ blitCache.set(device, cache);
69
+ }
70
+ return cache;
71
+ }
72
+ function getBlitResources(device, filterable, sampleType) {
73
+ const cache = getOrCreateDeviceCache(device);
74
+ let filterableRes = cache.filterableResources.get(filterable);
75
+ if (!filterableRes) {
76
+ filterableRes = {
77
+ fragmentModule: device.createShaderModule({ code: filterable ? SAMPLE_FRAGMENT_SHADER : GATHER_FRAGMENT_SHADER }),
78
+ sampler: device.createSampler(filterable ? {
79
+ magFilter: "linear",
80
+ minFilter: "linear"
81
+ } : {})
82
+ };
83
+ cache.filterableResources.set(filterable, filterableRes);
84
+ }
85
+ const layoutKey = `${filterable}:${sampleType}`;
86
+ let layoutRes = cache.layoutResources.get(layoutKey);
87
+ if (!layoutRes) {
88
+ const bindGroupLayout = device.createBindGroupLayout({ entries: [{
89
+ binding: 0,
90
+ visibility: GPUShaderStage.FRAGMENT,
91
+ texture: { sampleType }
92
+ }, {
93
+ binding: 1,
94
+ visibility: GPUShaderStage.FRAGMENT,
95
+ sampler: { type: filterable ? "filtering" : "non-filtering" }
96
+ }] });
97
+ layoutRes = {
98
+ bindGroupLayout,
99
+ pipelineLayout: device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout] })
100
+ };
101
+ cache.layoutResources.set(layoutKey, layoutRes);
102
+ }
103
+ return {
104
+ vertexModule: cache.vertexModule,
105
+ ...filterableRes,
106
+ ...layoutRes
107
+ };
108
+ }
109
+ function blit(options) {
110
+ const { device, source, destination, format, filterable, sampleType } = options;
111
+ const resources = getBlitResources(device, filterable, sampleType);
112
+ const pipeline = device.createRenderPipeline({
113
+ layout: resources.pipelineLayout,
114
+ vertex: { module: resources.vertexModule },
115
+ fragment: {
116
+ module: resources.fragmentModule,
117
+ targets: [{ format }]
118
+ },
119
+ primitive: { topology: "triangle-list" }
120
+ });
121
+ const bindGroup = device.createBindGroup({
122
+ layout: resources.bindGroupLayout,
123
+ entries: [{
124
+ binding: 0,
125
+ resource: source
126
+ }, {
127
+ binding: 1,
128
+ resource: resources.sampler
129
+ }]
130
+ });
131
+ const ownEncoder = !options.encoder;
132
+ const encoder = options.encoder ?? device.createCommandEncoder();
133
+ const pass = encoder.beginRenderPass({ colorAttachments: [{
134
+ view: destination,
135
+ loadOp: "clear",
136
+ storeOp: "store"
137
+ }] });
138
+ pass.setPipeline(pipeline);
139
+ pass.setBindGroup(0, bindGroup);
140
+ pass.draw(3);
141
+ pass.end();
142
+ if (ownEncoder) device.queue.submit([encoder.finish()]);
143
+ }
144
+ function clearTextureUtilsCache(device) {
145
+ blitCache.delete(device);
146
+ }
147
+ function validateBlitFormat(device, format, operation) {
148
+ const info = getTextureFormatInfo(format);
149
+ const effectiveSampleTypes = getEffectiveSampleTypes(device, format);
150
+ const isFloat = effectiveSampleTypes.includes("float");
151
+ const isUnfilterableFloat = effectiveSampleTypes.includes("unfilterable-float");
152
+ if (!isFloat && !isUnfilterableFloat) throw new Error(`Cannot ${operation} for format '${format}': only float formats are supported.`);
153
+ if (!info.canRenderAttachment) throw new Error(`Cannot ${operation} for format '${format}': format does not support render attachments.`);
154
+ return {
155
+ filterable: isFloat,
156
+ sampleType: isFloat ? "float" : "unfilterable-float"
157
+ };
158
+ }
159
+ function generateTextureMipmaps(device, texture, baseMipLevel = 0, mipLevels) {
160
+ if (texture.dimension !== "2d") throw new Error("Mipmap generation only supports 2D textures.");
161
+ const { filterable, sampleType } = validateBlitFormat(device, texture.format, "generate mipmaps");
162
+ const levels = mipLevels ?? texture.mipLevelCount - baseMipLevel;
163
+ for (let layer = 0; layer < texture.depthOrArrayLayers; layer++) for (let mip = baseMipLevel; mip < baseMipLevel + levels - 1; mip++) {
164
+ const viewOptions = (level) => ({
165
+ dimension: "2d",
166
+ baseMipLevel: level,
167
+ mipLevelCount: 1,
168
+ baseArrayLayer: layer,
169
+ arrayLayerCount: 1
170
+ });
171
+ blit({
172
+ device,
173
+ source: texture.createView(viewOptions(mip)),
174
+ destination: texture.createView(viewOptions(mip + 1)),
175
+ format: texture.format,
176
+ filterable,
177
+ sampleType
178
+ });
179
+ }
180
+ }
181
+ function resampleImage(device, targetTexture, image, layer = 0) {
182
+ if (targetTexture.dimension !== "2d") throw new Error("Resampling only supports 2D textures.");
183
+ const { filterable } = validateBlitFormat(device, targetTexture.format, "resample");
184
+ const { width, height } = getImageSourceDimensions(image);
185
+ const inputTexture = device.createTexture({
186
+ size: [width, height],
187
+ format: "rgba8unorm",
188
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT
189
+ });
190
+ device.queue.copyExternalImageToTexture({ source: image }, { texture: inputTexture }, [width, height]);
191
+ const renderTexture = device.createTexture({
192
+ size: [targetTexture.width, targetTexture.height],
193
+ format: targetTexture.format,
194
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
195
+ });
196
+ const encoder = device.createCommandEncoder();
197
+ blit({
198
+ device,
199
+ source: inputTexture.createView(),
200
+ destination: renderTexture.createView(),
201
+ format: targetTexture.format,
202
+ filterable,
203
+ sampleType: "float",
204
+ encoder
205
+ });
206
+ encoder.copyTextureToTexture({ texture: renderTexture }, {
207
+ texture: targetTexture,
208
+ origin: {
209
+ x: 0,
210
+ y: 0,
211
+ z: layer
212
+ }
213
+ }, {
214
+ width: targetTexture.width,
215
+ height: targetTexture.height,
216
+ depthOrArrayLayers: 1
217
+ });
218
+ device.queue.submit([encoder.finish()]);
219
+ inputTexture.destroy();
220
+ renderTexture.destroy();
221
+ }
222
+
223
+ //#endregion
224
+ export { clearTextureUtilsCache, generateTextureMipmaps, getImageSourceDimensions, resampleImage };
@@ -0,0 +1,21 @@
1
+ import { StorageFlag } from "../../extension.js";
2
+ import { TextureProps } from "./textureProps.js";
3
+ import { StorageTextureFormats } from "./textureFormats.js";
4
+
5
+ //#region src/core/texture/usageExtension.d.ts
6
+ interface SampledFlag {
7
+ usableAsSampled: true;
8
+ }
9
+ interface RenderFlag {
10
+ usableAsRender: true;
11
+ }
12
+ type LiteralToExtensionMap = {
13
+ storage: StorageFlag;
14
+ sampled: SampledFlag;
15
+ render: RenderFlag;
16
+ };
17
+ type AllowedUsages<TProps extends TextureProps> = 'sampled' | 'render' | (TProps['format'] extends StorageTextureFormats ? 'storage' : never);
18
+ declare function isUsableAsSampled<T>(value: T): value is T & SampledFlag;
19
+ declare function isUsableAsRender<T>(value: T): value is T & RenderFlag;
20
+ //#endregion
21
+ export { AllowedUsages, LiteralToExtensionMap, RenderFlag, SampledFlag, isUsableAsRender, isUsableAsSampled };
@@ -0,0 +1,21 @@
1
+ import { getName } from "../../shared/meta.js";
2
+
3
+ //#region src/core/texture/usageExtension.ts
4
+ function isUsableAsSampled(value) {
5
+ return !!value?.usableAsSampled;
6
+ }
7
+ function isUsableAsRender(value) {
8
+ return !!value?.usableAsRender;
9
+ }
10
+ /**
11
+ * @category Errors
12
+ */
13
+ var NotSampledError = class NotSampledError extends Error {
14
+ constructor(value) {
15
+ super(`Resource '${getName(value) ?? "<unnamed>"}' cannot be bound as 'sampled'. Use .$usage('sampled') to allow it.`);
16
+ Object.setPrototypeOf(this, NotSampledError.prototype);
17
+ }
18
+ };
19
+
20
+ //#endregion
21
+ export { NotSampledError, isUsableAsRender, isUsableAsSampled };
@@ -0,0 +1,13 @@
1
+ import { $internal } from "../../shared/symbols.js";
2
+ import "../../data/snippet.js";
3
+ import { GPUCallable } from "../../types.js";
4
+
5
+ //#region src/core/unroll/tgpuUnroll.d.ts
6
+ /**
7
+ * Marks an iterable to be unrolled by the wgslGenerator.
8
+ */
9
+ declare const unroll: (<T extends Iterable<unknown>>(value: T) => T) & GPUCallable<[value: Iterable<unknown>]> & {
10
+ [$internal]: true;
11
+ };
12
+ //#endregion
13
+ export { unroll };
@@ -0,0 +1,36 @@
1
+ import { $gpuCallable, $internal, $resolve } from "../../shared/symbols.js";
2
+ import { setName } from "../../shared/meta.js";
3
+ import { snip } from "../../data/snippet.js";
4
+ import { stitch } from "../resolve/stitch.js";
5
+
6
+ //#region src/core/unroll/tgpuUnroll.ts
7
+ /**
8
+ * The result of calling `tgpu.unroll(...)`. The code responsible for
9
+ * generating shader code can check if the value of a snippet is
10
+ * an instance of `UnrollableIterable`, and act accordingly.
11
+ */
12
+ var UnrollableIterable = class {
13
+ [$internal] = true;
14
+ constructor(snippet) {
15
+ this.snippet = snippet;
16
+ }
17
+ [$resolve](_ctx) {
18
+ return snip(stitch`${this.snippet}`, this.snippet.dataType, this.snippet.origin);
19
+ }
20
+ };
21
+ /**
22
+ * Marks an iterable to be unrolled by the wgslGenerator.
23
+ */
24
+ const unroll = (() => {
25
+ const impl = ((value) => value);
26
+ setName(impl, "unroll");
27
+ impl.toString = () => "unroll";
28
+ impl[$internal] = true;
29
+ impl[$gpuCallable] = { call(_ctx, [value]) {
30
+ return snip(new UnrollableIterable(value), value.dataType, value.origin);
31
+ } };
32
+ return impl;
33
+ })();
34
+
35
+ //#endregion
36
+ export { UnrollableIterable, unroll };
@@ -0,0 +1,44 @@
1
+ import { $internal, $ownSnippet, $resolve } from "../shared/symbols.js";
2
+ import { getOwnSnippet } from "../types.js";
3
+ import { getGPUValue } from "../getGPUValue.js";
4
+ import { accessProp } from "../tgsl/accessProp.js";
5
+ import { accessIndex } from "../tgsl/accessIndex.js";
6
+
7
+ //#region src/core/valueProxyUtils.ts
8
+ const valueProxyHandler = { get(target, prop) {
9
+ if (prop in target) return Reflect.get(target, prop);
10
+ if (prop === "toString" || prop === Symbol.toStringTag || prop === Symbol.toPrimitive) return () => target.toString();
11
+ if (typeof prop === "symbol") return;
12
+ const targetSnippet = getOwnSnippet(target);
13
+ const index = Number(prop);
14
+ if (!Number.isNaN(index)) {
15
+ const accessed = accessIndex(targetSnippet, index);
16
+ if (!accessed) return;
17
+ return new Proxy({
18
+ [$internal]: true,
19
+ [$resolve]: (ctx) => ctx.resolve(accessed.value, accessed.dataType),
20
+ [$ownSnippet]: accessed,
21
+ toString: () => `${String(target)}[${prop}]`
22
+ }, valueProxyHandler);
23
+ }
24
+ const accessed = accessProp(targetSnippet, String(prop));
25
+ if (!accessed) return;
26
+ return new Proxy({
27
+ [$internal]: true,
28
+ [$resolve]: (ctx) => ctx.resolve(accessed.value, accessed.dataType),
29
+ [$ownSnippet]: accessed,
30
+ toString: () => `${String(target)}.${prop}`
31
+ }, valueProxyHandler);
32
+ } };
33
+ function getGpuValueRecursively(value) {
34
+ let unwrapped = value;
35
+ while (true) {
36
+ const gpuValue = getGPUValue(unwrapped);
37
+ if (!gpuValue) break;
38
+ unwrapped = gpuValue;
39
+ }
40
+ return unwrapped;
41
+ }
42
+
43
+ //#endregion
44
+ export { getGpuValueRecursively, valueProxyHandler };
@@ -0,0 +1,38 @@
1
+ import { TgpuNamable } from "../../shared/meta.js";
2
+ import { $gpuValueOf, $internal } from "../../shared/symbols.js";
3
+ import { BaseData } from "../../data/wgslTypes.js";
4
+ import { InferGPU } from "../../shared/repr.js";
5
+ import { AnyData } from "../../data/dataTypes.js";
6
+
7
+ //#region src/core/variable/tgpuVariable.d.ts
8
+ type VariableScope = 'private' | 'workgroup';
9
+ interface TgpuVar<TScope extends VariableScope = VariableScope, TDataType extends BaseData = BaseData> extends TgpuNamable {
10
+ readonly resourceType: 'var';
11
+ readonly [$gpuValueOf]: InferGPU<TDataType>;
12
+ /**
13
+ * @deprecated Use `.$` instead, works the same way.
14
+ */
15
+ value: InferGPU<TDataType>;
16
+ $: InferGPU<TDataType>;
17
+ readonly [$internal]: {
18
+ /** Makes it differentiable on the type level. Does not exist at runtime. */dataType?: TDataType; /** Makes it differentiable on the type level. Does not exist at runtime. */
19
+ scope?: TScope;
20
+ };
21
+ }
22
+ /**
23
+ * Defines a variable scoped to each entry function (private).
24
+ *
25
+ * @param dataType The schema of the held data's type
26
+ * @param initialValue If not provided, the variable will be initialized to the dataType's "zero-value".
27
+ */
28
+ declare function privateVar<TDataType extends AnyData>(dataType: TDataType, initialValue?: InferGPU<TDataType>): TgpuVar<'private', TDataType>;
29
+ /**
30
+ * Defines a variable scoped to the whole workgroup, shared between entry functions
31
+ * of the same invocation.
32
+ *
33
+ * @param dataType The schema of the held data's type
34
+ */
35
+ declare function workgroupVar<TDataType extends AnyData>(dataType: TDataType): TgpuVar<'workgroup', TDataType>;
36
+ declare function isVariable(value: unknown): value is TgpuVar;
37
+ //#endregion
38
+ export { TgpuVar, VariableScope, isVariable, privateVar, workgroupVar };
@@ -0,0 +1,101 @@
1
+ import { $gpuValueOf, $internal, $ownSnippet, $resolve } from "../../shared/symbols.js";
2
+ import { getName, setName } from "../../shared/meta.js";
3
+ import { isNaturallyEphemeral } from "../../data/wgslTypes.js";
4
+ import { snip } from "../../data/snippet.js";
5
+ import { IllegalVarAccessError } from "../../errors.js";
6
+ import { getExecMode, isInsideTgpuFn } from "../../execMode.js";
7
+ import { assertExhaustive } from "../../shared/utilityTypes.js";
8
+ import { valueProxyHandler } from "../valueProxyUtils.js";
9
+
10
+ //#region src/core/variable/tgpuVariable.ts
11
+ /**
12
+ * Defines a variable scoped to each entry function (private).
13
+ *
14
+ * @param dataType The schema of the held data's type
15
+ * @param initialValue If not provided, the variable will be initialized to the dataType's "zero-value".
16
+ */
17
+ function privateVar(dataType, initialValue) {
18
+ return new TgpuVarImpl("private", dataType, initialValue);
19
+ }
20
+ /**
21
+ * Defines a variable scoped to the whole workgroup, shared between entry functions
22
+ * of the same invocation.
23
+ *
24
+ * @param dataType The schema of the held data's type
25
+ */
26
+ function workgroupVar(dataType) {
27
+ return new TgpuVarImpl("workgroup", dataType);
28
+ }
29
+ function isVariable(value) {
30
+ return value instanceof TgpuVarImpl;
31
+ }
32
+ var TgpuVarImpl = class {
33
+ [$internal] = {};
34
+ resourceType;
35
+ #scope;
36
+ #dataType;
37
+ #initialValue;
38
+ constructor(scope, dataType, initialValue) {
39
+ this.resourceType = "var";
40
+ this.#scope = scope;
41
+ this.#dataType = dataType;
42
+ this.#initialValue = initialValue;
43
+ }
44
+ [$resolve](ctx) {
45
+ const id = ctx.getUniqueName(this);
46
+ const pre = `var<${this.#scope}> ${id}: ${ctx.resolve(this.#dataType).value}`;
47
+ if (this.#initialValue) ctx.addDeclaration(`${pre} = ${ctx.resolve(this.#initialValue, this.#dataType).value};`);
48
+ else ctx.addDeclaration(`${pre};`);
49
+ return snip(id, this.#dataType, isNaturallyEphemeral(this.#dataType) ? "runtime" : this.#scope);
50
+ }
51
+ $name(label) {
52
+ setName(this, label);
53
+ return this;
54
+ }
55
+ toString() {
56
+ return `var:${getName(this) ?? "<unnamed>"}`;
57
+ }
58
+ get [$gpuValueOf]() {
59
+ const dataType = this.#dataType;
60
+ const origin = isNaturallyEphemeral(dataType) ? "runtime" : this.#scope;
61
+ return new Proxy({
62
+ [$internal]: true,
63
+ get [$ownSnippet]() {
64
+ return snip(this, dataType, origin);
65
+ },
66
+ [$resolve]: (ctx) => ctx.resolve(this),
67
+ toString: () => `var:${getName(this) ?? "<unnamed>"}.$`
68
+ }, valueProxyHandler);
69
+ }
70
+ get $() {
71
+ const mode = getExecMode();
72
+ const insideTgpuFn = isInsideTgpuFn();
73
+ if (mode.type === "normal") throw new IllegalVarAccessError(insideTgpuFn ? `Cannot access variable '${getName(this) ?? "<unnamed>"}'. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation` : "TypeGPU variables are inaccessible during normal JS execution. If you wanted to simulate GPU behavior, try `tgpu.simulate()`");
74
+ if (mode.type === "codegen") return this[$gpuValueOf];
75
+ if (mode.type === "simulate") {
76
+ if (!mode.vars[this.#scope].has(this)) mode.vars[this.#scope].set(this, this.#initialValue);
77
+ return mode.vars[this.#scope].get(this);
78
+ }
79
+ return assertExhaustive(mode, "tgpuVariable.ts#TgpuVarImpl/$");
80
+ }
81
+ set $(value) {
82
+ const mode = getExecMode();
83
+ const insideTgpuFn = isInsideTgpuFn();
84
+ if (mode.type === "normal") throw new IllegalVarAccessError(insideTgpuFn ? `Cannot access ${String(this)}. TypeGPU functions that depends on GPU resources need to be part of a compute dispatch, draw call or simulation` : "TypeGPU variables are inaccessible during normal JS execution. If you wanted to simulate GPU behavior, try `tgpu.simulate()`");
85
+ if (mode.type === "codegen") throw new Error("Unreachable tgpuVariable.ts#TgpuVarImpl/$");
86
+ if (mode.type === "simulate") {
87
+ mode.vars[this.#scope].set(this, value);
88
+ return;
89
+ }
90
+ assertExhaustive(mode, "tgpuVariable.ts#TgpuVarImpl/$");
91
+ }
92
+ get value() {
93
+ return this.$;
94
+ }
95
+ set value(v) {
96
+ this.$ = v;
97
+ }
98
+ };
99
+
100
+ //#endregion
101
+ export { isVariable, privateVar, workgroupVar };
@@ -0,0 +1,59 @@
1
+ import { getCustomLocation, isData } from "../../data/dataTypes.js";
2
+ import { isBuiltin } from "../../data/attributes.js";
3
+
4
+ //#region src/core/vertexLayout/connectAttributesToShader.ts
5
+ function isAttribute(value) {
6
+ return typeof value?.format === "string";
7
+ }
8
+ function connectAttributesToShader(shaderInputLayout, attributes) {
9
+ const usedVertexLayouts = [];
10
+ if (isData(shaderInputLayout)) {
11
+ if (!isAttribute(attributes)) throw new Error("Shader expected a single attribute, not a record of attributes to be passed in.");
12
+ usedVertexLayouts.push(attributes._layout);
13
+ return {
14
+ usedVertexLayouts,
15
+ bufferDefinitions: [{
16
+ arrayStride: attributes._layout.stride,
17
+ stepMode: attributes._layout.stepMode,
18
+ attributes: [{
19
+ format: attributes.format,
20
+ offset: attributes.offset,
21
+ shaderLocation: getCustomLocation(shaderInputLayout) ?? 0
22
+ }]
23
+ }]
24
+ };
25
+ }
26
+ const bufferDefinitions = [];
27
+ const layoutToAttribListMap = /* @__PURE__ */ new WeakMap();
28
+ let nextShaderLocation = 0;
29
+ for (const [key, member] of Object.entries(shaderInputLayout)) {
30
+ if (isBuiltin(member)) continue;
31
+ const matchingAttribute = attributes[key];
32
+ if (!matchingAttribute) throw new Error(`An attribute by the name of '${key}' was not provided to the shader.`);
33
+ const layout = matchingAttribute._layout;
34
+ let attribList = layoutToAttribListMap.get(layout);
35
+ if (!attribList) {
36
+ usedVertexLayouts.push(layout);
37
+ attribList = [];
38
+ bufferDefinitions.push({
39
+ arrayStride: layout.stride,
40
+ stepMode: layout.stepMode,
41
+ attributes: attribList
42
+ });
43
+ layoutToAttribListMap.set(layout, attribList);
44
+ }
45
+ nextShaderLocation = getCustomLocation(member) ?? nextShaderLocation;
46
+ attribList.push({
47
+ format: matchingAttribute.format,
48
+ offset: matchingAttribute.offset,
49
+ shaderLocation: nextShaderLocation++
50
+ });
51
+ }
52
+ return {
53
+ usedVertexLayouts,
54
+ bufferDefinitions
55
+ };
56
+ }
57
+
58
+ //#endregion
59
+ export { connectAttributesToShader, isAttribute };
@@ -0,0 +1,29 @@
1
+ import { KindToAcceptedAttribMap, KindToDefaultFormatMap, TgpuVertexAttrib, VertexFormat } from "../../shared/vertexFormat.js";
2
+ import { FormatToWGSLType } from "../../data/vertexFormatData.js";
3
+ import { Decorated, WgslArray, WgslStruct } from "../../data/wgslTypes.js";
4
+ import { Disarray, LooseDecorated, Unstruct } from "../../data/dataTypes.js";
5
+
6
+ //#region src/core/vertexLayout/vertexAttribute.d.ts
7
+ /**
8
+ * The array can hold T, where T is a single/multi-component numeric, or a struct with members of type T.
9
+ * Examples of valid array members:
10
+ * - Vec3f,
11
+ * - unorm8x2
12
+ * - WgslStruct<{ a: Vec3f, b: unorm8x2 }>
13
+ * - WgslStruct<{ nested: WgslStruct<{ a: Vec3f }> }>
14
+ */
15
+ type DataToContainedAttribs<T> = T extends WgslStruct | Unstruct ? { [Key in keyof T['propTypes']]: DataToContainedAttribs<T['propTypes'][Key]> } : T extends {
16
+ type: VertexFormat;
17
+ } ? TgpuVertexAttrib<T['type']> : T extends {
18
+ type: keyof KindToDefaultFormatMap;
19
+ } ? TgpuVertexAttrib<KindToDefaultFormatMap[T['type']]> : T extends Decorated<infer TInner> ? DataToContainedAttribs<TInner> : T extends LooseDecorated<infer TInner> ? DataToContainedAttribs<TInner> : never;
20
+ /**
21
+ * Interprets an array as a set of vertex attributes.
22
+ */
23
+ type ArrayToContainedAttribs<T extends WgslArray | Disarray> = DataToContainedAttribs<T['elementType']>;
24
+ type LayoutToAllowedAttribs<T> = T extends {
25
+ type: keyof KindToAcceptedAttribMap;
26
+ } ? KindToAcceptedAttribMap[T['type']] : T extends Record<string, unknown> ? { [Key in keyof T]: LayoutToAllowedAttribs<T[Key]> } : never;
27
+ type AttribRecordToDefaultDataTypes<T extends Record<string, TgpuVertexAttrib>> = { [Key in keyof T]: FormatToWGSLType<T[Key]['format']> };
28
+ //#endregion
29
+ export { ArrayToContainedAttribs, AttribRecordToDefaultDataTypes, LayoutToAllowedAttribs };
@@ -0,0 +1,19 @@
1
+ import { TgpuNamable } from "../../shared/meta.js";
2
+ import { $internal } from "../../shared/symbols.js";
3
+ import { ArrayToContainedAttribs } from "./vertexAttribute.js";
4
+ import { WgslArray } from "../../data/wgslTypes.js";
5
+ import { Disarray } from "../../data/dataTypes.js";
6
+
7
+ //#region src/core/vertexLayout/vertexLayout.d.ts
8
+ interface TgpuVertexLayout<TData extends WgslArray | Disarray = WgslArray | Disarray> extends TgpuNamable {
9
+ readonly [$internal]: true;
10
+ readonly resourceType: 'vertex-layout';
11
+ readonly stride: number;
12
+ readonly stepMode: 'vertex' | 'instance';
13
+ readonly attrib: ArrayToContainedAttribs<TData>;
14
+ readonly vertexLayout: GPUVertexBufferLayout;
15
+ schemaForCount(n: number): TData;
16
+ }
17
+ declare function vertexLayout<TData extends WgslArray | Disarray>(schemaForCount: (count: number) => TData, stepMode?: 'vertex' | 'instance'): TgpuVertexLayout<TData>;
18
+ //#endregion
19
+ export { TgpuVertexLayout, vertexLayout };