webgpu-computed 0.0.6 → 0.0.8

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.
package/README.zh-CN.md DELETED
@@ -1,385 +0,0 @@
1
- # webgpu-computed
2
-
3
- 一个简化的 WebGPU 计算库,封装了繁琐的初始化和缓冲区管理,让开发者专注于 WGSL 着色器逻辑。
4
-
5
- ## 特性
6
-
7
- - 🚀 简化 WebGPU 初始化
8
- - 📦 自动缓冲区管理和布局计算
9
- - 🔧 支持复杂数据结构(向量、矩阵)
10
- - ⚡ 高性能 GPU 计算
11
- - 📚 内置常用 WGSL 函数
12
- - ✅ 支持Node
13
-
14
- ## 安装
15
-
16
- ```bash
17
- npm install webgpu-computed
18
- ```
19
-
20
- ## 快速开始
21
-
22
- ### 1. 初始化 WebGPU
23
-
24
- 在使用任何计算功能前,需要先初始化 WebGPU 环境:
25
-
26
- ```javascript
27
- import { GpuComputed } from 'webgpu-computed';
28
-
29
- // 初始化 WebGPU
30
- await GpuComputed.init();
31
- // node 环境使用完请调用:
32
- // GpuComputed.destroy()
33
- ```
34
-
35
- ### 2. 执行简单计算
36
-
37
- 以下是一个简单的向量加法示例:
38
-
39
- ```javascript
40
- import { GpuComputed } from 'webgpu-computed';
41
-
42
- // 准备数据
43
- const data = {
44
- inputA: [1.0, 2.0, 3.0, 4.0],
45
- inputB: [0.5, 1.5, 2.5, 3.5],
46
- output: new Array(4).fill(0) // 输出缓冲区
47
- };
48
-
49
- // WGSL 计算代码
50
- const code = `
51
- output[index] = inputA[index] + inputB[index];
52
- `;
53
-
54
- // 执行计算
55
- const results = await GpuComputed.computed({
56
- code,
57
- data,
58
- workgroupCount: [1] // 工作组数量
59
- });
60
-
61
- console.log(results); // [[1.5, 3.5, 5.5, 7.5]]
62
- ```
63
-
64
- ### 3. 使用复杂数据结构
65
-
66
- 库支持向量和矩阵类型:
67
-
68
- ```javascript
69
- const data = {
70
- positions: [
71
- { pos: [1.0, 2.0, 3.0], vel: [0.1, 0.2, 0.3] },
72
- { pos: [4.0, 5.0, 6.0], vel: [0.4, 0.5, 0.6] }
73
- ],
74
- output: new Array(2).fill({ pos: [0,0,0], vel: [0,0,0] })
75
- };
76
-
77
- const code = `
78
- output[index].pos = positions[index].pos + positions[index].vel;
79
- output[index].vel = positions[index].vel * 2.0;
80
- `;
81
-
82
- const results = await GpuComputed.computed({
83
- code,
84
- data,
85
- workgroupCount: [1]
86
- });
87
- ```
88
-
89
- ## API 参考
90
-
91
- ### GpuComputed 类
92
-
93
- #### 静态方法
94
-
95
- ##### `GpuComputed.init()`
96
-
97
- 初始化 WebGPU 环境。必须在使用其他功能前调用。
98
-
99
- **返回值**: `Promise<void>`
100
-
101
- **抛出**: 如果浏览器不支持 WebGPU 或获取适配器/设备失败
102
-
103
- ##### `GpuComputed.computed(options)`
104
-
105
- 执行 GPU 计算任务。
106
-
107
- **参数**:
108
-
109
- - `code` (string): WGSL 计算代码
110
- - `data` (object): 输入/输出数据对象
111
- - `workgroupCount` (array): 工作组数量 [x, y?, z?]
112
- - `workgroupSize` (array, 可选): 工作组大小,默认 [32, 1, 1]
113
- - `globalInvocationIdName` (string, 可选): 全局调用 ID 变量名,默认 "grid"
114
- - `workgroupIndexName` (string, 可选): 工作组索引变量名,默认 "index"
115
- - `synchronize` (array, 可选): 需要同步回 CPU 的缓冲区名称数组
116
- - `beforeCodes` (array, 可选): 计算函数前的 WGSL 代码片段
117
- - `onSuccess` (function, 可选): 计算成功回调函数
118
-
119
- **返回值**: `Promise<Array<Float32Array>>` - 同步缓冲区的数据
120
-
121
- ### 数据类型
122
-
123
- 支持以下 WGSL 类型:
124
-
125
- - `f32`: 单精度浮点数
126
- - `vec2`: 二维向量
127
- - `vec3`: 三维向量
128
- - `vec4`: 四维向量
129
- - `mat3x3`: 3x3 矩阵
130
- - `mat4x4`: 4x4 矩阵
131
-
132
- ### 内置 WGSL 函数
133
-
134
- 库提供了一些常用的 WGSL 辅助函数:
135
-
136
- #### 四元数旋转
137
-
138
- ```wgsl
139
- fn quat_rotate(q: vec4<f32>, v: vec3<f32>) -> vec3<f32>
140
- ```
141
-
142
- 使用示例:
143
-
144
- ```javascript
145
- import { WGSL_Fun } from 'webgpu-computed';
146
-
147
- await GpuComputed.computed({
148
- code: "",
149
- data: {....},
150
- beforeCodes:[WGSL_Fun.quat_rotate]
151
- })
152
-
153
- ```
154
-
155
- #### 点在 OBB 中的检测
156
-
157
- ```wgsl
158
- fn point_in_obb(point: vec3<f32>, center: vec3<f32>, halfSize: vec3<f32>, quat: vec4<f32>) -> bool
159
- ```
160
-
161
- ## 高级用法
162
-
163
- ### 自定义工作组配置
164
-
165
- ```javascript
166
- await GpuComputed.computed({
167
- code: '...',
168
- data: {...},
169
- workgroupCount: [4, 4], // 16 个工作组
170
- workgroupSize: [16, 16], // 每个工作组 256 个线程
171
- });
172
- ```
173
-
174
- ### 同步数据回 CPU
175
-
176
- ```javascript
177
- const results = await GpuComputed.computed({
178
- code: '...',
179
- data: {...},
180
- synchronize: ['output'], // 指定需要同步的缓冲区
181
- workgroupCount: [1]
182
- });
183
-
184
- // results 包含同步回的数据
185
- ```
186
-
187
- ### 回调函数
188
-
189
- ```javascript
190
- await GpuComputed.computed({
191
- code: '...',
192
- data: {...},
193
- workgroupCount: [1],
194
- onSuccess: ({ code, bufferInfoList, results }) => {
195
- console.log('计算完成', results);
196
- }
197
- });
198
- ```
199
-
200
- ## 浏览器支持
201
-
202
- - Chrome 113+
203
- - Edge 113+
204
- - Firefox (部分支持)
205
- - Safari (部分支持)
206
-
207
- 确保浏览器支持 WebGPU API。
208
-
209
- ## 示例项目
210
-
211
- ```js
212
- import { GpuComputed } from "webgpu-computed"
213
-
214
- // 1. 初始化 WebGPU
215
- console.log('初始化 WebGPU...');
216
- await GpuComputed.init();
217
- console.log('WebGPU 初始化成功');
218
-
219
- // 2. 简单数组计算示例
220
- console.log('\n=== 简单数组计算 ===');
221
- const simpleData = {
222
- inputA: [1.0, 2.0, 3.0, 4.0],
223
- inputB: [0.5, 1.5, 2.5, 3.5],
224
- output: new Array(4).fill(0)
225
- };
226
-
227
- const simpleCode = `
228
- output[index] = inputA[index] + inputB[index];
229
- `;
230
-
231
- const simpleResults = await GpuComputed.computed({
232
- code: simpleCode,
233
- data: simpleData,
234
- workgroupCount: [1],
235
- synchronize: ['output']
236
- });
237
-
238
- console.log('简单计算结果:', simpleResults[0]); // [1.5, 3.5, 5.5, 7.5]
239
-
240
- // 3. 复杂数据结构示例(结构体)
241
- console.log('\n=== 复杂数据结构计算 ===');
242
- const complexData = {
243
- particles: [
244
- { position: [1.0, 2.0, 3.0], velocity: [0.1, 0.2, 0.3], mass: 1.0 },
245
- { position: [4.0, 5.0, 6.0], velocity: [0.4, 0.5, 0.6], mass: 2.0 }
246
- ],
247
- output: [
248
- { position: [0, 0, 0], velocity: [0, 0, 0], mass: 0 },
249
- { position: [0, 0, 0], velocity: [0, 0, 0], mass: 0 }
250
- ]
251
- };
252
-
253
- const complexCode = `
254
- output[index].position = particles[index].position + particles[index].velocity;
255
- output[index].velocity = particles[index].velocity * 2.0;
256
- output[index].mass = particles[index].mass * 1.5;
257
- `;
258
-
259
- const complexResults = await GpuComputed.computed({
260
- code: complexCode,
261
- data: complexData,
262
- workgroupCount: [1],
263
- synchronize: ['output']
264
- });
265
-
266
- console.log('复杂计算结果:', complexResults[0]);
267
-
268
- // 4. 使用内置 WGSL 函数示例
269
- console.log('\n=== 使用内置 WGSL 函数 ===');
270
- const wgslFunData = {
271
- points: [
272
- {
273
- x: 1.0, y: 0.0, z: 0.0
274
- },
275
- {
276
- x: 0.0, y: 1.0, z: 0.0
277
- },
278
- {
279
- x: -1.0, y: 0.0, z: 0.0
280
- }
281
- ],
282
- obbCenter: [0.0, 0.0, 0.0],
283
- obbHalfSize: [2.0, 2.0, 2.0],
284
- obbRotation: [0.0, 0.0, 0.0, 1.0], // 单位四元数,无旋转
285
- results: new Array(3).fill(0)
286
- };
287
-
288
- const wgslFunCode = `
289
- let point = vec3(points[index].x, points[index].y, points[index].z);
290
- let center = vec3<f32>(obbCenter[0], obbCenter[1], obbCenter[2]);
291
- let halfSize = vec3<f32>(obbHalfSize[0], obbHalfSize[1], obbHalfSize[2]);
292
- let quat = vec4<f32>(obbRotation[0], obbRotation[1], obbRotation[2], obbRotation[3]);
293
-
294
- if (point_in_obb(point, center, halfSize, quat)) {
295
- results[index] = 1.0;
296
- } else {
297
- results[index] = 0.0;
298
- }
299
- `;
300
-
301
- const wgslFunResults = await GpuComputed.computed({
302
- code: wgslFunCode,
303
- data: wgslFunData,
304
- workgroupCount: [1],
305
- beforeCodes: [WGSL_Fun.quat_rotate, WGSL_Fun.point_in_obb, /** 可添加自己的函数代码 */],
306
- synchronize: ['results']
307
- });
308
-
309
- console.log('OBB 检测结果:', wgslFunResults[0]); // [1, 1, 1] 所有点都在 OBB 内
310
-
311
- // 5. 自定义工作组配置示例
312
- console.log('\n=== 自定义工作组配置 ===');
313
- const largeData = {
314
- largeArray: new Array(1024).fill(0).map((_, i) => i * 1.0),
315
- output: new Array(1024).fill(0)
316
- };
317
-
318
- const largeCode = `
319
- output[index] = largeArray[index] * 2.0;
320
- `;
321
-
322
- const largeResults = await GpuComputed.computed({
323
- code: largeCode,
324
- data: largeData,
325
- workgroupCount: [32], // 32 个工作组
326
- workgroupSize: [32, 1, 1], // 每个工作组 32 个线程,总共 1024 个线程
327
- synchronize: ['output']
328
- });
329
-
330
- console.log('大数组计算结果 (前10个):', largeResults[0].slice(0, 10));
331
-
332
- // 6. 使用回调函数示例
333
- console.log('\n=== 使用回调函数 ===');
334
- const callbackData = {
335
- values: [10.0, 20.0, 30.0],
336
- squares: new Array(3).fill(0)
337
- };
338
-
339
- const callbackCode = `
340
- squares[index] = values[index] * values[index];
341
- `;
342
-
343
- await GpuComputed.computed({
344
- code: callbackCode,
345
- data: callbackData,
346
- workgroupCount: [1],
347
- synchronize: ['squares'],
348
- onSuccess: ({ code, bufferInfoList, results }) => {
349
- console.log('回调函数触发,计算平方结果:', results[0]); // [100, 400, 900]
350
- }
351
- });
352
-
353
- // 7. 多维工作组示例
354
- console.log('\n=== 多维工作组 ===');
355
- const matrixData = {
356
- matrixA: new Array(16).fill(0).map((_, i) => i * 1.0),
357
- matrixB: new Array(16).fill(0).map((_, i) => (i + 1) * 1.0),
358
- result: new Array(16).fill(0)
359
- };
360
-
361
- const matrixCode = `
362
- let x = index % 4u;
363
- let y = index / 4u;
364
- let idx = y * 4u + x;
365
- result[idx] = matrixA[idx] + matrixB[idx];
366
- `;
367
-
368
- const matrixResults = await GpuComputed.computed({
369
- code: matrixCode,
370
- data: matrixData,
371
- workgroupCount: [4, 4], // 4x4 工作组网格
372
- workgroupSize: [1, 1, 1], // 每个工作组 1 个线程
373
- synchronize: ['result']
374
- });
375
-
376
- console.log('矩阵计算结果:', matrixResults[0]);
377
-
378
- console.log('\n所有功能示例运行完成!');
379
- ```
380
-
381
- ## 许可证
382
-
383
- ISC License
384
-
385
- ---
package/src/index.d.ts DELETED
@@ -1,77 +0,0 @@
1
- declare type BufferType = {
2
- buffer: number[];
3
- stride: number;
4
- layout: {
5
- name: string;
6
- type: ValueType;
7
- offset: number;
8
- size: number;
9
- }[];
10
- count: number;
11
- };
12
-
13
- export declare class GpuComputed {
14
- constructor();
15
- static init(): Promise<void>;
16
- static destroy(): void;
17
- getDevice(): Promise<{
18
- adapter: GPUAdapter;
19
- device: GPUDevice;
20
- }>;
21
- createPipeline(code: string, buffers: Record<string, BufferType | number[]>): Promise<{
22
- pipeline: GPUComputePipeline;
23
- group: GPUBindGroup;
24
- device: GPUDevice;
25
- bufferInfoList: {
26
- name: string;
27
- buffer: GPUBuffer;
28
- float32Array: Float32Array<ArrayBuffer>;
29
- groupLayoutItem: GPUBindGroupLayoutEntry;
30
- groupItem: {
31
- binding: number;
32
- resource: {
33
- buffer: GPUBuffer;
34
- };
35
- };
36
- }[];
37
- }>;
38
- private buildCode;
39
- private buildBuffer;
40
- computed(opt: {
41
- code: string;
42
- data: Record<string, any[]>;
43
- onSuccess?: (opt: {
44
- code: string;
45
- bufferInfoList: any[];
46
- results: any;
47
- }) => void;
48
- } & OptionType): Promise<number[][]>;
49
- static instance: GpuComputed;
50
- static get computed(): (opt: {
51
- code: string;
52
- data: Record<string, any[]>;
53
- onSuccess?: (opt: {
54
- code: string;
55
- bufferInfoList: any[];
56
- results: any;
57
- }) => void;
58
- } & OptionType) => Promise<number[][]>;
59
- }
60
-
61
- declare type OptionType = {
62
- workgroupSize?: [number, number, number];
63
- workgroupCount: [number, number?, number?];
64
- globalInvocationIdName?: string;
65
- workgroupIndexName?: string;
66
- synchronize?: string[];
67
- beforeCodes?: string[];
68
- };
69
-
70
- declare type ValueType = "f32" | "vec2" | "vec3" | "vec4" | "mat3x3" | "mat4x4";
71
-
72
- export declare const WGSL_Fun: Readonly<{
73
- quat_rotate: "\n fn quat_rotate(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> {\n // q.xyz = vector part, q.w = scalar part\n let t = 2.0 * cross(q.xyz, v);\n return v + q.w * t + cross(q.xyz, t);\n }\n ";
74
- point_in_obb: "\n fn point_in_obb(\n point: vec3<f32>,\n center: vec3<f32>,\n halfSize: vec3<f32>,\n quat: vec4<f32>\n ) -> bool {\n // 世界空间 → OBB 局部空间\n let local = point - center;\n\n // 逆旋转(共轭四元数)\n let invQuat = vec4<f32>(-quat.xyz, quat.w);\n let pLocal = quat_rotate(invQuat, local);\n\n // AABB 判断\n return all(abs(pLocal) <= halfSize);\n }\n ";
75
- }>;
76
-
77
- export { }