-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathp5.RendererWebGPU.js
More file actions
3886 lines (3415 loc) · 133 KB
/
p5.RendererWebGPU.js
File metadata and controls
3886 lines (3415 loc) · 133 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module 3D
* @submodule p5.strands
* @for p5
*/
import * as constants from '../core/constants';
import { getStrokeDefs } from '../webgl/enums';
import { DataType, INSTANCE_ID_VARYING_NAME } from '../strands/ir_types.js';
import { colorVertexShader, colorFragmentShader } from './shaders/color';
import { lineVertexShader, lineFragmentShader} from './shaders/line';
import { materialVertexShader, materialFragmentShader } from './shaders/material';
import { fontVertexShader, fontFragmentShader } from './shaders/font';
import { blitVertexShader, blitFragmentShader } from './shaders/blit';
import { wgslBackend } from './strands_wgslBackend';
import noiseWGSL from './shaders/functions/noise3DWGSL';
import { baseFilterVertexShader, baseFilterFragmentShader } from './shaders/filters/base';
import { imageLightVertexShader, imageLightDiffusedFragmentShader, imageLightSpecularFragmentShader } from './shaders/imageLight';
import { baseComputeShader } from './shaders/compute';
const FRAME_STATE = {
PENDING: 0,
UNPROMOTED: 1,
PROMOTED: 2
};
function rendererWebGPU(p5, fn) {
const { lineDefs } = getStrokeDefs((n, v, t) => `const ${n}: ${t} = ${v};\n`);
// RendererWebGPU depends on these other classes being set up prior,
// as it is optimized for being in a standalone build, not core
const {
Renderer3D,
Shader,
Texture,
MipmapTexture,
Image,
Camera,
RGBA,
} = p5;
class StorageBuffer {
constructor(buffer, size, renderer, schema = null) {
this._isStorageBuffer = true;
this.buffer = buffer;
this.size = size;
this._renderer = renderer;
this._schema = schema;
}
/**
* Updates the data in the buffer with new values. The new data must be in
* the same format as the data originally passed to
* <a href="#/p5/createStorage">`createStorage()`</a>.
*
* ```js example
* let particles;
* let computeShader;
* let displayShader;
* let instance;
* const numParticles = 100;
*
* async function setup() {
* await createCanvas(100, 100, WEBGPU);
* particles = createStorage(makeParticles(width / 2, height / 2));
* computeShader = buildComputeShader(simulate);
* displayShader = buildMaterialShader(display);
* instance = buildGeometry(drawParticle);
* describe('100 orange particles shooting outward.');
* }
*
* function makeParticles(x, y) {
* let data = [];
* for (let i = 0; i < numParticles; i++) {
* let angle = (i / numParticles) * TWO_PI;
* let speed = random(0.5, 2);
* data.push({
* position: createVector(x, y),
* velocity: createVector(cos(angle) * speed, sin(angle) * speed),
* });
* }
* return data;
* }
*
* function drawParticle() {
* sphere(2);
* }
*
* function simulate() {
* let data = uniformStorage(particles);
* let idx = index.x;
* data[idx].position = data[idx].position + data[idx].velocity;
* }
*
* function display() {
* let data = uniformStorage(particles);
* worldInputs.begin();
* let pos = data[instanceID()].position;
* worldInputs.position.xy += pos - [width / 2, height / 2];
* worldInputs.end();
* }
*
* function draw() {
* background(30);
* if (frameCount % 60 === 0) {
* particles.update(makeParticles(random(width), random(height)));
* }
* compute(computeShader, numParticles);
* noStroke();
* fill(255, 200, 50);
* shader(displayShader);
* model(instance, numParticles);
* }
* ```
*
* @method update
* @for p5.StorageBuffer
* @beta
* @webgpu
* @webgpuOnly
* @param {Number[]|Float32Array|Object[]} data The new data to write into the buffer.
*/
update(data) {
const device = this._renderer.device;
if (this._schema !== null) {
// Buffer was created with a struct array
if (
!Array.isArray(data) ||
data.length === 0 ||
typeof data[0] !== 'object' ||
Array.isArray(data[0])
) {
throw new Error(
'update() expects an array of objects matching the original struct format'
);
}
const newSchema = this._renderer._inferStructSchema(data[0]);
if (newSchema.structBody !== this._schema.structBody) {
throw new Error(
`update() data structure doesn't match the original.\n` +
` Expected: ${this._schema.structBody}\n` +
` Got: ${newSchema.structBody}`
);
}
const packed = this._renderer._packStructArray(data, this._schema);
if (packed.byteLength > this.size) {
throw new Error(
`update() data (${packed.byteLength} bytes) exceeds buffer size (${this.size} bytes)`
);
}
device.queue.writeBuffer(this.buffer, 0, packed);
} else {
// Buffer was created with a float array
let floatData;
if (data instanceof Float32Array) {
floatData = data;
} else if (Array.isArray(data)) {
floatData = new Float32Array(data);
} else {
throw new Error(
'update() expects a Float32Array or array of numbers for this buffer'
);
}
if (floatData.byteLength > this.size) {
throw new Error(
`update() data (${floatData.byteLength} bytes) exceeds buffer size (${this.size} bytes)`
);
}
device.queue.writeBuffer(this.buffer, 0, floatData);
}
}
}
/**
* A block of data that shaders can read from, and compute shaders can also
* write to. This is only available in WebGPU mode.
*
* Note: <a href="#/p5/createStorage">`createStorage()`</a> is the recommended
* way to create an instance of this class.
*
* @class p5.StorageBuffer
* @beta
* @webgpu
* @webgpuOnly
*/
p5.StorageBuffer = StorageBuffer;
class RendererWebGPU extends Renderer3D {
constructor(pInst, w, h, isMainCanvas, elt) {
super(pInst, w, h, isMainCanvas, elt)
// Used to group draws into one big render pass
this.activeRenderPass = null;
this.activeRenderPassEncoder = null;
this.activeShaderOptions = null;
this.activeShader = null;
this.samplers = new Map();
// Some uniforms update every frame, like model matrices and sometimes colors.
// The fastest way to handle these is to use mapped memory. We'll batch those
// into bigger buffers with dynamic offsets, separate from the usual system
// where bind groups have their own little buffers that get cached when they
// are unchanged
this.uniformBufferAlignment = 256;
this.activeUniformBuffers = [];
this.currentUniformBuffer = undefined;
this.uniformBufferPool = [];
this.resettingUniformBuffers = [];
this.dynamicEntryOffsets = new Uint32Array(64);
// Cache for current frame's canvas texture view
this.currentCanvasColorTexture = null;
this.currentCanvasColorTextureView = null;
// Single reusable staging buffer for pixel reading
this.pixelReadBuffer = null;
this.pixelReadBufferSize = 0;
this.strandsBackend = wgslBackend;
// Registry to track all shaders for uniform data pooling
this._shadersWithPools = [];
// Registry to track geometries with buffer pools
this._geometriesWithPools = [];
// Flag to track if any draws have happened that need queue submission
this._hasPendingDraws = false;
this._pendingCommandEncoders = [];
// Queue of callbacks to run after next submit (mainly for safe texture deletion)
this._postSubmitCallbacks = [];
// Retired buffers to destroy at end of frame
this._retiredBuffers = [];
// Storage buffers for compute shaders
this._storageBuffers = new Set();
// 2D canvas for pixel reading fallback
this._pixelReadCanvas = null;
this._pixelReadCtx = null;
this.mainFramebuffer = null;
this._frameState = FRAME_STATE.PENDING;
this.finalCamera = new Camera(this);
this.finalCamera._computeCameraDefaultSettings();
this.finalCamera._setDefaultCamera();
this.depthFormat = 'depth24plus-stencil8';
this.depthTexture = null;
this.depthTextureView = null;
}
async setupContext() {
this._setAttributeDefaults(this._pInst);
await this._initContext();
}
_setAttributeDefaults(pInst) {
const defaults = {
forceFallbackAdapter: false,
powerPreference: 'high-performance',
};
if (pInst._webgpuAttributes === null) {
pInst._webgpuAttributes = defaults;
} else {
pInst._webgpuAttributes = Object.assign(defaults, pInst._webgpuAttributes);
}
return;
}
async _initContext() {
this.adapter = await navigator.gpu?.requestAdapter(this._webgpuAttributes);
this.device = await this.adapter?.requestDevice({
// Todo: check support
requiredFeatures: ['depth32float-stencil8']
});
if (!this.device) {
throw new Error('Your browser does not support WebGPU.');
}
this.queue = this.device.queue;
this.drawingContext = this.canvas.getContext('webgpu');
this.presentationFormat = navigator.gpu.getPreferredCanvasFormat();
this.drawingContext.configure({
device: this.device,
format: this.presentationFormat,
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
alphaMode: 'premultiplied',
});
// TODO disablable stencil
this.mainFramebuffer = this.createFramebuffer({ _useCanvasFormat: true });
this._updateSize();
this._update();
this.flushDraw();
}
async _setAttributes(key, value) {
if (typeof this._pInst._webgpuAttributes === "undefined") {
console.log(
"You are trying to use setAttributes on a p5.Graphics object " +
"that does not use a WebGPU renderer."
);
return;
}
let unchanged = true;
if (typeof value !== "undefined") {
//first time modifying the attributes
if (this._pInst._webgpuAttributes === null) {
this._pInst._webgpuAttributes = {};
}
if (this._pInst._webgpuAttributes[key] !== value) {
//changing value of previously altered attribute
this._webgpuAttributes[key] = value;
unchanged = false;
}
//setting all attributes with some change
} else if (key instanceof Object) {
if (this._pInst._webgpuAttributes !== key) {
this._pInst._webgpuAttributes = key;
unchanged = false;
}
}
//@todo_FES
if (!this.isP3D || unchanged) {
return;
}
if (!this._pInst._setupDone) {
if (this.geometryBufferCache.numCached() > 0) {
p5._friendlyError(
"Sorry, Could not set the attributes, you need to call setAttributes() " +
"before calling the other drawing methods in setup()"
);
return;
}
}
await this._resetContext(null, null, RendererWebGPU);
if (this.states.curCamera) {
this.states.curCamera._renderer = this._renderer;
}
}
_updateSize() {
if (!this.device || !this.depthFormat) return;
if (this.depthTexture && this.depthTexture.destroy) {
this.flushDraw();
const textureToDestroy = this.depthTexture;
this._postSubmitCallbacks.push(() => textureToDestroy.destroy());
this.depthTextureView = null;
}
this.depthTexture = this.device.createTexture({
size: {
width: Math.ceil(this.width * this._pixelDensity),
height: Math.ceil(this.height * this._pixelDensity),
depthOrArrayLayers: 1,
},
format: this.depthFormat,
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
});
this.depthTextureView = this.depthTexture.createView();
// Clear the main canvas after resize
this.clear();
}
_getCanvasColorTextureView() {
const canvasTexture = this.drawingContext.getCurrentTexture();
// If texture changed (new frame), update cache
if (this.currentCanvasColorTexture !== canvasTexture) {
this.currentCanvasColorTexture = canvasTexture;
this.currentCanvasColorTextureView = canvasTexture.createView();
}
return this.currentCanvasColorTextureView;
}
_beginActiveRenderPass() {
if (this.activeRenderPass) return;
// Use framebuffer texture if active, otherwise use canvas texture
const activeFramebuffer = this.activeFramebuffer();
const colorAttachment = {
view: activeFramebuffer
? (activeFramebuffer.aaColorTexture
? activeFramebuffer.aaColorTextureView
: activeFramebuffer.colorTextureView)
: this._getCanvasColorTextureView(),
loadOp: "load",
storeOp: "store",
// If using multisampled texture, resolve to non-multisampled texture
resolveTarget: activeFramebuffer && activeFramebuffer.aaColorTexture
? activeFramebuffer.colorTextureView
: undefined,
};
// Use framebuffer depth texture if active, otherwise use canvas depth texture
const depthTextureView = activeFramebuffer
? (activeFramebuffer.aaDepthTexture
? activeFramebuffer.aaDepthTextureView
: activeFramebuffer.depthTextureView)
: this.depthTextureView;
const renderPassDescriptor = {
colorAttachments: [colorAttachment],
depthStencilAttachment: depthTextureView
? {
view: depthTextureView,
depthLoadOp: "load",
depthStoreOp: "store",
depthClearValue: 1.0,
stencilLoadOp: "load",
stencilStoreOp: "store",
depthReadOnly: false,
stencilReadOnly: false,
}
: undefined,
};
const commandEncoder = this.device.createCommandEncoder();
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
this.activeRenderPassEncoder = commandEncoder;
this.activeRenderPass = passEncoder;
}
_finishActiveRenderPass() {
if (!this.activeRenderPass) return;
const commandEncoder = this.activeRenderPassEncoder;
const passEncoder = this.activeRenderPass;
passEncoder.end();
// Store the command encoder for later submission
this._pendingCommandEncoders.push(commandEncoder.finish());
this.activeRenderPassEncoder = null;
this.activeRenderPass = null;
this.activeShader = null;
this.activeShaderOptions = null;
}
clear(...args) {
if (!this.device || !this.drawingContext) return;
const _r = args[0] || 0;
const _g = args[1] || 0;
const _b = args[2] || 0;
const _a = args[3] || 0;
// If PENDING and no custom framebuffer, clear means stay UNPROMOTED
if (this._frameState === FRAME_STATE.PENDING && !this.activeFramebuffer()) {
this._frameState = FRAME_STATE.UNPROMOTED;
}
this._finishActiveRenderPass();
const commandEncoder = this.device.createCommandEncoder();
// Use framebuffer texture if active, otherwise use canvas texture
const activeFramebuffer = this.activeFramebuffer();
const colorAttachment = {
view: activeFramebuffer
? (activeFramebuffer.aaColorTexture
? activeFramebuffer.aaColorTextureView
: activeFramebuffer.colorTextureView)
: this._getCanvasColorTextureView(),
clearValue: { r: _r * _a, g: _g * _a, b: _b * _a, a: _a },
loadOp: 'clear',
storeOp: 'store',
// If using multisampled texture, resolve to non-multisampled texture
resolveTarget: activeFramebuffer && activeFramebuffer.aaColorTexture
? activeFramebuffer.colorTextureView
: undefined,
};
// Use framebuffer depth texture if active, otherwise use canvas depth texture
const depthTextureView = activeFramebuffer
? (activeFramebuffer.aaDepthTexture
? activeFramebuffer.aaDepthTextureView
: activeFramebuffer.depthTextureView)
: this.depthTextureView;
const depthAttachment = depthTextureView
? {
view: depthTextureView,
depthClearValue: 1.0,
depthLoadOp: 'clear',
depthStoreOp: 'store',
stencilLoadOp: 'load',
stencilStoreOp: 'store',
}
: undefined;
const renderPassDescriptor = {
colorAttachments: [colorAttachment],
...(depthAttachment ? { depthStencilAttachment: depthAttachment } : {}),
};
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.end();
this._pendingCommandEncoders.push(commandEncoder.finish());
this._hasPendingDraws = true;
}
/**
* Resets all depth information so that nothing previously drawn will
* occlude anything subsequently drawn.
*/
clearDepth(depth = 1) {
if (!this.device || !this.depthTextureView) return;
this._finishActiveRenderPass();
const commandEncoder = this.device.createCommandEncoder();
// Use framebuffer texture if active, otherwise use canvas texture
const activeFramebuffer = this.activeFramebuffer();
// Use framebuffer depth texture if active, otherwise use canvas depth texture
const depthTextureView = activeFramebuffer
? (activeFramebuffer.aaDepthTexture
? activeFramebuffer.aaDepthTextureView
: activeFramebuffer.depthTextureView)
: this.depthTextureView;
if (!depthTextureView) {
// No depth buffer to clear
return;
}
const depthAttachment = {
view: depthTextureView,
depthClearValue: depth,
depthLoadOp: 'clear',
depthStoreOp: 'store',
stencilLoadOp: 'load',
stencilStoreOp: 'store',
};
const renderPassDescriptor = {
colorAttachments: [], // No color attachments, we're only clearing depth
depthStencilAttachment: depthAttachment,
};
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.end();
this._pendingCommandEncoders.push(commandEncoder.finish());
this._hasPendingDraws = true;
}
_prepareBuffer(renderBuffer, geometry, shader) {
const attr = shader.attributes[renderBuffer.attr];
if (!attr) return;
const { src, dst, size, map } = renderBuffer;
const device = this.device;
const buffers = this._getOrMakeCachedBuffers(geometry);
let srcData = geometry[src];
if (!srcData || srcData.length === 0) {
if (renderBuffer.default) {
srcData = geometry[src] = renderBuffer.default(geometry);
srcData.isDefault = true;
} else {
return;
}
}
// Check if we already have a buffer for this data
let existingBuffer = buffers[dst];
const needsNewBuffer = !existingBuffer;
// Only create new buffer and write data if buffer doesn't exist or data is dirty
if (needsNewBuffer || geometry.dirtyFlags[src] !== false) {
const raw = map ? map(srcData) : srcData;
const typed = this._normalizeBufferData(raw, Float32Array);
// Get pooled buffer (may reuse existing or create new)
const pooledBufferInfo = this._getVertexBufferFromPool(geometry, dst, typed.byteLength);
// Create a copy of the data to avoid conflicts when geometry arrays are reset
const dataCopy = new typed.constructor(typed);
pooledBufferInfo.dataCopy = dataCopy;
// Write the data to the pooled buffer
device.queue.writeBuffer(pooledBufferInfo.buffer, 0, dataCopy);
// Update the buffers cache to use the pooled buffer
buffers[dst] = pooledBufferInfo.buffer;
geometry.dirtyFlags[src] = false;
}
shader.enableAttrib(attr, size);
}
_disableRemainingAttributes(shader) {}
_enableAttrib(attr) {
// TODO: is this necessary?
const loc = attr.location;
if (!this.registerEnabled.has(loc)) {
// TODO
this.registerEnabled.add(loc);
}
}
_ensureGeometryBuffers(buffers, indices, indexType) {
if (!indices) return;
const device = this.device;
const buffer = device.createBuffer({
size: Math.ceil((indices.length * indexType.BYTES_PER_ELEMENT) / 4) * 4,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
});
// Write index data to buffer
const mapping = new indexType(buffer.getMappedRange());
mapping.set(indices);
buffer.unmap();
buffers.indexBuffer = buffer;
buffers.indexBufferType = indexType === Uint32Array ? 'uint32' : 'uint16';
}
_freeBuffers(buffers) {
const destroyIfExists = (buf) => {
if (buf && buf.destroy) {
buf.destroy();
}
};
destroyIfExists(buffers.indexBuffer);
const freeDefs = (defs) => {
for (const def of defs) {
destroyIfExists(buffers[def.dst]);
buffers[def.dst] = null;
}
};
freeDefs(this.buffers.stroke);
freeDefs(this.buffers.fill);
freeDefs(this.buffers.user);
}
_getValidSampleCount(requestedCount) {
// WebGPU supports sample counts of 1, 4 (and sometimes 8)
if (requestedCount <= 1) return 1;
if (requestedCount <= 4) return 4;
return 4; // Cap at 4 for broader compatibility
}
_shaderOptions({ mode, compute, workgroupSize }) {
if (compute) return { compute: true, workgroupSize };
const activeFramebuffer = this.activeFramebuffer();
const format = activeFramebuffer ?
this._getWebGPUColorFormat(activeFramebuffer) :
this.presentationFormat;
const requestedSampleCount = activeFramebuffer ?
(activeFramebuffer.antialias ? activeFramebuffer.antialiasSamples : 1) :
1; // No MSAA needed when blitting already-antialiased textures to canvas
const sampleCount = this._getValidSampleCount(requestedSampleCount);
const depthFormat = activeFramebuffer && activeFramebuffer.useDepth ?
this._getWebGPUDepthFormat(activeFramebuffer) :
this.depthFormat;
const drawTarget = this.drawTarget();
const clipping = this._clipping;
const clipApplied = drawTarget._isClipApplied;
return {
topology: mode === constants.TRIANGLE_STRIP ? 'triangle-strip' : 'triangle-list',
blendMode: this.states.curBlendMode,
sampleCount,
format,
depthFormat,
clipping,
clipApplied,
}
}
_shaderOptionsDifferent(newOptions) {
if (!this.activeShaderOptions) return true;
for (const key in this.activeShaderOptions) {
if (this.activeShaderOptions[key] !== newOptions[key]) return true;
}
return false;
}
_initShader(shader) {
const device = this.device;
if (shader.shaderType === 'compute') {
// Compute shader initialization
shader.computeModule = device.createShaderModule({ code: shader.computeSrc() });
shader._computePipelineCache = null;
shader._workgroupSize = null;
// Create compute pipeline (deferred until first compute() call)
shader.getPipeline = ({ workgroupSize }) => {
if (!shader._computePipelineCache) {
shader._computePipelineCache = device.createComputePipeline({
layout: shader._pipelineLayout,
compute: {
module: shader.computeModule,
entryPoint: 'main'
}
});
shader._workgroupSize = workgroupSize;
}
return shader._computePipelineCache;
};
return;
}
// Render shader initialization
shader.vertModule = device.createShaderModule({ code: shader.vertSrc() });
shader.fragModule = device.createShaderModule({ code: shader.fragSrc() });
shader._pipelineCache = new Map();
shader.getPipeline = ({ topology, blendMode, sampleCount, format, depthFormat, clipping, clipApplied }) => {
const key = `${topology}_${blendMode}_${sampleCount}_${format}_${depthFormat}_${clipping}_${clipApplied}`;
if (!shader._pipelineCache.has(key)) {
const pipeline = device.createRenderPipeline({
layout: shader._pipelineLayout,
vertex: {
module: shader.vertModule,
entryPoint: 'main',
buffers: this._getVertexLayout(shader),
},
fragment: {
module: shader.fragModule,
entryPoint: 'main',
targets: [{
format,
blend: this._getBlendState(blendMode),
}],
},
primitive: { topology },
multisample: { count: sampleCount },
depthStencil: {
format: depthFormat,
depthWriteEnabled: !clipping,
depthCompare: 'less-equal',
stencilFront: {
compare: clipping ? 'always' : (clipApplied ? 'not-equal' : 'always'),
failOp: 'keep',
depthFailOp: 'keep',
passOp: clipping ? 'replace' : 'keep',
},
stencilBack: {
compare: clipping ? 'always' : (clipApplied ? 'not-equal' : 'always'),
failOp: 'keep',
depthFailOp: 'keep',
passOp: clipping ? 'replace' : 'keep',
},
stencilReadMask: 0xFF,
stencilWriteMask: clipping ? 0xFF : 0x00,
},
});
shader._pipelineCache.set(key, pipeline);
}
return shader._pipelineCache.get(key);
}
}
_finalizeShader(shader) {
// Per-group buffer pools. We will pull from these when we draw multiple
// times using the shader in a render pass. These are per group instead of
// global so that we can reuse the last used buffer when uniform values
// don't change.
shader._uniformBufferGroups = [];
shader.buffersDirty = new Set();
for (const group of shader._uniformGroups) {
// Calculate the size needed for this group's uniforms
const groupUniforms = Object.values(group.uniforms);
const rawSize = Math.max(
0,
...groupUniforms.map(u => u.offsetEnd)
);
const alignedSize = Math.ceil(rawSize / 16) * 16;
shader._uniformBufferGroups.push({
group: group.group,
binding: group.binding,
cacheKey: group.group * 1000 + group.binding,
varName: group.varName,
structType: group.structType,
uniforms: groupUniforms,
size: alignedSize,
bufferPool: [],
nextBufferPool: [],
dynamic: groupUniforms.some(u => u.name.startsWith('uModel')),
buffersInUse: new Set(),
currentBuffer: null, // For caching
});
}
// Register this shader in our registry for pool cleanup
this._shadersWithPools.push(shader);
const bindGroupLayouts = new Map(); // group index -> bindGroupLayout
const groupEntries = new Map(); // group index -> array of entries
// Add all uniform group bindings to group 0
const structEntries = new Map();
for (const bufferGroup of shader._uniformBufferGroups) {
const entries = structEntries.get(bufferGroup.group) || [];
entries.push({
bufferGroup,
binding: bufferGroup.binding,
visibility: shader.shaderType === 'compute'
? GPUShaderStage.COMPUTE
: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
buffer: { type: 'uniform', hasDynamicOffset: bufferGroup.dynamic },
});
structEntries.set(bufferGroup.group, entries);
}
for (const [group, entries] of structEntries.entries()) {
entries.sort((a, b) => a.binding - b.binding);
groupEntries.set(group, entries);
}
// Add the variable amount of samplers and texture bindings that can come after
for (const sampler of shader.samplers) {
const group = sampler.group;
const entries = groupEntries.get(group) || [];
if (!['sampler', 'texture_2d<f32>'].includes(sampler.type)) {
throw new Error(`Unsupported texture type: ${sampler.type}`);
}
entries.push({
binding: sampler.binding,
visibility: sampler.visibility,
sampler: sampler.type === 'sampler'
? { type: 'filtering' }
: undefined,
texture: sampler.type === 'texture_2d<f32>'
? { sampleType: 'float', viewDimension: '2d' }
: undefined,
uniform: sampler,
});
entries.sort((a, b) => a.binding - b.binding);
groupEntries.set(group, entries);
}
// Add storage buffer bindings
for (const storage of shader._storageBuffers || []) {
const group = storage.group;
const entries = groupEntries.get(group) || [];
entries.push({
binding: storage.binding,
visibility: storage.visibility,
buffer: {
type: storage.accessMode === 'read' ? 'read-only-storage' : 'storage'
},
storage: storage,
});
entries.sort((a, b) => a.binding - b.binding);
groupEntries.set(group, entries);
}
// Create layouts and bind groups
const groupEntriesArr = [];
for (const [group, entries] of groupEntries) {
const layout = this.device.createBindGroupLayout({ entries });
bindGroupLayouts.set(group, layout);
groupEntriesArr.push([group, entries]);
}
shader._groupEntries = groupEntriesArr;
shader._bindGroupLayouts = [...bindGroupLayouts.values()];
// Reuse bind groups if they don't change
shader._cachedBindGroup = {};
// Remember which dynamic buffer we last used, so that we can
// possibly cache bind groups if unchanged
shader._lastDynamicBuffer = {};
shader._pipelineLayout = this.device.createPipelineLayout({
bindGroupLayouts: shader._bindGroupLayouts,
});
shader._compiled = true;
}
_getBlendState(mode) {
switch (mode) {
case constants.BLEND:
return {
color: {
operation: 'add',
srcFactor: 'one',
dstFactor: 'one-minus-src-alpha'
},
alpha: {
operation: 'add',
srcFactor: 'one',
dstFactor: 'one-minus-src-alpha'
}
};
case constants.ADD:
return {
color: {
operation: 'add',
srcFactor: 'one',
dstFactor: 'one'
},
alpha: {
operation: 'add',
srcFactor: 'one',
dstFactor: 'one'
}
};
case constants.REMOVE:
return {
color: {
operation: 'add',
srcFactor: 'zero',
dstFactor: 'one-minus-src-alpha'
},
alpha: {
operation: 'add',
srcFactor: 'zero',
dstFactor: 'one-minus-src-alpha'
}
};
case constants.MULTIPLY:
return {
color: {
operation: 'add',
srcFactor: 'dst-color',
dstFactor: 'one-minus-src-alpha'
},
alpha: {
operation: 'add',
srcFactor: 'dst-alpha',
dstFactor: 'one-minus-src-alpha'
}
};
case constants.SCREEN:
return {
color: {
operation: 'add',
srcFactor: 'one',
dstFactor: 'one-minus-src-color'
},
alpha: {
operation: 'add',
srcFactor: 'one',
dstFactor: 'one-minus-src-alpha'
}
};
case constants.EXCLUSION:
return {
color: {
operation: 'add',
srcFactor: 'one-minus-dst-color',
dstFactor: 'one-minus-src-color'
},
alpha: {
operation: 'add',
srcFactor: 'one',
dstFactor: 'one'
}
};
case constants.REPLACE:
return {
color: {
operation: 'add',
srcFactor: 'one',
dstFactor: 'zero'
},
alpha: {
operation: 'add',
srcFactor: 'one',
dstFactor: 'zero'
}
};