-
Notifications
You must be signed in to change notification settings - Fork 356
Expand file tree
/
Copy pathmain.ts
More file actions
367 lines (329 loc) · 9.84 KB
/
main.ts
File metadata and controls
367 lines (329 loc) · 9.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import { GUI } from 'dat.gui';
import animometerWGSL from './animometer.wgsl';
import { quitIfWebGPUNotAvailable } from '../util';
const canvas = document.querySelector('canvas') as HTMLCanvasElement;
const adapter = await navigator.gpu?.requestAdapter({
featureLevel: 'compatibility',
});
const device = await adapter?.requestDevice();
quitIfWebGPUNotAvailable(adapter, device);
const perfDisplayContainer = document.createElement('div');
perfDisplayContainer.style.color = 'white';
perfDisplayContainer.style.background = 'black';
perfDisplayContainer.style.position = 'absolute';
perfDisplayContainer.style.top = '10px';
perfDisplayContainer.style.left = '10px';
const perfDisplay = document.createElement('pre');
perfDisplayContainer.appendChild(perfDisplay);
if (canvas.parentNode) {
canvas.parentNode.appendChild(perfDisplayContainer);
} else {
console.error('canvas.parentNode is null');
}
const params = new URLSearchParams(window.location.search);
const settings = {
numTriangles: Number(params.get('numTriangles')) || 20000,
renderBundles: Boolean(params.get('renderBundles')),
dynamicOffsets: Boolean(params.get('dynamicOffsets')),
};
const context = canvas.getContext('webgpu') as GPUCanvasContext;
const devicePixelRatio = window.devicePixelRatio;
canvas.width = canvas.clientWidth * devicePixelRatio;
canvas.height = canvas.clientHeight * devicePixelRatio;
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format: presentationFormat,
usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT,
});
const timeBindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: {
type: 'uniform',
minBindingSize: 4,
},
},
],
});
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: {
type: 'uniform',
minBindingSize: 20,
},
},
],
});
const dynamicBindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: {
type: 'uniform',
hasDynamicOffset: true,
minBindingSize: 20,
},
},
],
});
const vec4Size = 4 * Float32Array.BYTES_PER_ELEMENT;
const pipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [timeBindGroupLayout, bindGroupLayout],
});
const dynamicPipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [timeBindGroupLayout, dynamicBindGroupLayout],
});
const shaderModule = device.createShaderModule({
code: animometerWGSL,
});
const pipelineDesc: GPURenderPipelineDescriptor = {
layout: 'auto',
vertex: {
module: shaderModule,
buffers: [
{
// vertex buffer
arrayStride: 2 * vec4Size,
stepMode: 'vertex',
attributes: [
{
// vertex positions
shaderLocation: 0,
offset: 0,
format: 'float32x4',
},
{
// vertex colors
shaderLocation: 1,
offset: vec4Size,
format: 'float32x4',
},
],
},
],
},
fragment: {
module: shaderModule,
targets: [
{
format: presentationFormat,
},
],
},
primitive: {
topology: 'triangle-list',
frontFace: 'ccw',
cullMode: 'none',
},
};
const pipeline = device.createRenderPipeline({
...pipelineDesc,
layout: pipelineLayout,
});
const dynamicPipeline = device.createRenderPipeline({
...pipelineDesc,
layout: dynamicPipelineLayout,
});
const vertexBuffer = device.createBuffer({
size: 2 * 3 * vec4Size,
usage: GPUBufferUsage.VERTEX,
mappedAtCreation: true,
});
// prettier-ignore
new Float32Array(vertexBuffer.getMappedRange()).set([
// position data /**/ color data
0, 0.1, 0, 1, /**/ 1, 0, 0, 1,
-0.1, -0.1, 0, 1, /**/ 0, 1, 0, 1,
0.1, -0.1, 0, 1, /**/ 0, 0, 1, 1,
]);
vertexBuffer.unmap();
function configure() {
const numTriangles = settings.numTriangles;
const uniformBytes = 5 * Float32Array.BYTES_PER_ELEMENT;
const alignedUniformBytes = Math.ceil(uniformBytes / 256) * 256;
const alignedUniformFloats =
alignedUniformBytes / Float32Array.BYTES_PER_ELEMENT;
const uniformBuffer = device.createBuffer({
size: numTriangles * alignedUniformBytes + Float32Array.BYTES_PER_ELEMENT,
usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM,
});
const uniformBufferData = new Float32Array(
numTriangles * alignedUniformFloats
);
const bindGroups = new Array(numTriangles);
for (let i = 0; i < numTriangles; ++i) {
uniformBufferData[alignedUniformFloats * i + 0] = Math.random() * 0.2 + 0.2; // scale
uniformBufferData[alignedUniformFloats * i + 1] =
0.9 * 2 * (Math.random() - 0.5); // offsetX
uniformBufferData[alignedUniformFloats * i + 2] =
0.9 * 2 * (Math.random() - 0.5); // offsetY
uniformBufferData[alignedUniformFloats * i + 3] = Math.random() * 1.5 + 0.5; // scalar
uniformBufferData[alignedUniformFloats * i + 4] = Math.random() * 10; // scalarOffset
bindGroups[i] = device.createBindGroup({
layout: bindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: uniformBuffer,
offset: i * alignedUniformBytes,
size: 6 * Float32Array.BYTES_PER_ELEMENT,
},
},
],
});
}
const dynamicBindGroup = device.createBindGroup({
layout: dynamicBindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: uniformBuffer,
offset: 0,
size: 6 * Float32Array.BYTES_PER_ELEMENT,
},
},
],
});
const timeOffset = numTriangles * alignedUniformBytes;
const timeBindGroup = device.createBindGroup({
layout: timeBindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: uniformBuffer,
offset: timeOffset,
size: Float32Array.BYTES_PER_ELEMENT,
},
},
],
});
// writeBuffer too large may OOM. TODO: The browser should internally chunk uploads.
const maxMappingLength = (14 * 1024 * 1024) / Float32Array.BYTES_PER_ELEMENT;
for (
let offset = 0;
offset < uniformBufferData.length;
offset += maxMappingLength
) {
const uploadCount = Math.min(
uniformBufferData.length - offset,
maxMappingLength
);
device.queue.writeBuffer(
uniformBuffer,
offset * Float32Array.BYTES_PER_ELEMENT,
uniformBufferData.buffer,
uniformBufferData.byteOffset + offset * Float32Array.BYTES_PER_ELEMENT,
uploadCount * Float32Array.BYTES_PER_ELEMENT
);
}
function recordRenderPass(
passEncoder: GPURenderBundleEncoder | GPURenderPassEncoder
) {
if (settings.dynamicOffsets) {
passEncoder.setPipeline(dynamicPipeline);
} else {
passEncoder.setPipeline(pipeline);
}
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.setBindGroup(0, timeBindGroup);
const dynamicOffsets = [0];
for (let i = 0; i < numTriangles; ++i) {
if (settings.dynamicOffsets) {
dynamicOffsets[0] = i * alignedUniformBytes;
passEncoder.setBindGroup(1, dynamicBindGroup, dynamicOffsets);
} else {
passEncoder.setBindGroup(1, bindGroups[i]);
}
passEncoder.draw(3);
}
}
let startTime: number | undefined = undefined;
const uniformTime = new Float32Array([0]);
const renderPassDescriptor = {
colorAttachments: [
{
view: undefined as GPUTextureView, // Assigned later
clearValue: [0, 0, 0, 1],
loadOp: 'clear' as const,
storeOp: 'store' as const,
},
],
};
const renderBundleEncoder = device.createRenderBundleEncoder({
colorFormats: [presentationFormat],
});
recordRenderPass(renderBundleEncoder);
const renderBundle = renderBundleEncoder.finish();
return function doDraw(timestamp: number) {
if (startTime === undefined) {
startTime = timestamp;
}
uniformTime[0] = (timestamp - startTime) / 1000;
device.queue.writeBuffer(uniformBuffer, timeOffset, uniformTime.buffer);
renderPassDescriptor.colorAttachments[0].view = context.getCurrentTexture();
const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
if (settings.renderBundles) {
passEncoder.executeBundles([renderBundle]);
} else {
recordRenderPass(passEncoder);
}
passEncoder.end();
device.queue.submit([commandEncoder.finish()]);
};
}
let doDraw = configure();
const updateSettings = () => {
doDraw = configure();
};
const gui = new GUI();
gui
.add(settings, 'numTriangles', 0, 200000)
.step(1)
.onFinishChange(updateSettings);
gui.add(settings, 'renderBundles');
gui.add(settings, 'dynamicOffsets');
let previousFrameTimestamp: number | undefined = undefined;
let jsTimeAvg: number | undefined = undefined;
let frameTimeAvg: number | undefined = undefined;
let updateDisplay = true;
function frame(timestamp: number) {
let frameTime = 0;
if (previousFrameTimestamp !== undefined) {
frameTime = timestamp - previousFrameTimestamp;
}
previousFrameTimestamp = timestamp;
const start = performance.now();
doDraw(timestamp);
const jsTime = performance.now() - start;
if (frameTimeAvg === undefined) {
frameTimeAvg = frameTime;
}
if (jsTimeAvg === undefined) {
jsTimeAvg = jsTime;
}
const w = 0.2;
frameTimeAvg = (1 - w) * frameTimeAvg + w * frameTime;
jsTimeAvg = (1 - w) * jsTimeAvg + w * jsTime;
if (updateDisplay) {
perfDisplay.innerHTML = `Avg Javascript: ${jsTimeAvg.toFixed(
2
)} ms\nAvg Frame: ${frameTimeAvg.toFixed(2)} ms`;
updateDisplay = false;
setTimeout(() => {
updateDisplay = true;
}, 100);
}
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);