-
Notifications
You must be signed in to change notification settings - Fork 26
/
lib_webgpu.js
2713 lines (2375 loc) · 135 KB
/
lib_webgpu.js
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
#if parseInt(EMSCRIPTEN_VERSION.split('.')[0]) < 3 || (parseInt(EMSCRIPTEN_VERSION.split('.')[0]) == 3 && parseInt(EMSCRIPTEN_VERSION.split('.')[1]) < 1) || (parseInt(EMSCRIPTEN_VERSION.split('.')[0]) == 3 && parseInt(EMSCRIPTEN_VERSION.split('.')[1]) == 1 && parseInt(EMSCRIPTEN_VERSION.split('.')[2]) < 35)
// Emscripten 3.1.35 or newer is needed because of https://github.com/emscripten-core/emscripten/issues/19469
#error "wasm_webgpu requires building with Emscripten 3.1.35 or newer. Please update"
#endif
{{{
globalThis.wassert = function(condition) {
if (ASSERTIONS || parseInt(globalThis.WEBGPU_DEBUG)) return `assert(${condition}, "assert(${condition.replace(/"/g, "'")}) failed!");`;
else return '';
};
globalThis.wdebuglog = function(condition) {
return parseInt(globalThis.WEBGPU_DEBUG) ? `console.log(${condition});` : '';
}
globalThis.wdebugwarn = function(condition) {
return parseInt(globalThis.WEBGPU_DEBUG) ? `console.warn(${condition});` : '';
}
globalThis.wdebugerror = function(condition) {
return parseInt(globalThis.WEBGPU_DEBUG) ? `console.error(${condition});` : '';
}
globalThis.wdebugdir = function(condition, desc) {
return parseInt(globalThis.WEBGPU_DEBUG) ? (typeof desc === 'undefined' ? `console.dir(${condition});` : `console.log(${desc}); console.dir(${condition});`) : '';
}
globalThis.werror = function(condition) {
return parseInt(globalThis.WEBGPU_DEBUG) ? `console.error(${condition});` : '';
}
// Given a ptr, shift it to become an index to appropriate HEAPxxx type.
globalThis.replacePtrToIdx = function(ptr, shift) {
var shr = (MEMORY64 || MAXIMUM_MEMORY <= 2*1024*1024*1024) ? '>>' : '>>>';
shift = MEMORY64 ? `${shift}n` : `${shift}`;
var s = '';
if (ASSERTIONS || parseInt(globalThis.WEBGPU_DEBUG)) {
s += `assert((${ptr} ${shr} ${shift}) << ${shift} == ${ptr});\n`;
}
if (MEMORY64) s += `${ptr} = Number(${ptr} ${shr} ${shift});`;
else if (shift == 0 && MEMORY64) s += `${ptr} = Number(${ptr});`;
else if (shift > 0 || MAXIMUM_MEMORY > 2*1024*1024*1024) s += `${ptr} ${shr}= ${shift};`;
return s;
}
// Returns given ptr converted to an index to appropriate HEAPxxx type.
globalThis.shiftPtr = function(ptr, shift) {
var shr = (MEMORY64 || MAXIMUM_MEMORY <= 2*1024*1024*1024) ? '>>' : '>>>';
if (ASSERTIONS || parseInt(globalThis.WEBGPU_DEBUG)) return `wgpu_checked_shift(${ptr}, ${shift})`;
if (MEMORY64) return `Number(${ptr} ${shr} ${shift}n)`;
else if (shift == 0 && MEMORY64) return `Number(${ptr})`;
else if (shift > 0 || MAXIMUM_MEMORY > 2*1024*1024*1024) return `(${ptr} ${shr} ${shift})`;
else return `(${ptr})`;
}
globalThis.shiftIndex = function(index, shift) {
if (MAXIMUM_MEMORY <= 2*1024*1024*1024) return `${index} >> ${shift}`;
else return `${index} >>> ${shift}`;
}
// Given ptr, read ptr
globalThis.readPtr = function(ptr, offset) {
var shr = (MEMORY64 || MAXIMUM_MEMORY <= 2*1024*1024*1024) ? '>>' : '>>>';
var ofs = offset ? ` + ${offset}${MEMORY64?"n":""}` : '';
if (MEMORY64) return `HEAPU64[${ptr} ${ofs} ${shr} 3n]`;
else return `HEAPU32[${ptr} ${ofs} ${shr} 2]`;
}
// Given i32 index to ptr location, read it back as an i32 index
globalThis.readIdx32 = function(heap32Idx) {
var shr = (MEMORY64 || MAXIMUM_MEMORY <= 2*1024*1024*1024) ? '>>' : '>>>';
if (ASSERTIONS || parseInt(globalThis.WEBGPU_DEBUG)) {
if (MEMORY64) return `wgpu_checked_shift(HEAPU64[${heap32Idx} ${shr} 1], 2)`;
else return `wgpu_checked_shift(HEAPU32[${heap32Idx}], 2)`;
}
if (MEMORY64) return `Number(HEAPU64[${heap32Idx} ${shr} 1] ${shr} 2n)`;
else return `(HEAPU32[${heap32Idx}] ${shr} 2)`;
}
// Given i32 index to ptr location, read ptr
globalThis.readPtrFromIdx32 = function(heap32Idx, offset) {
var shr = (MEMORY64 || MAXIMUM_MEMORY <= 2*1024*1024*1024) ? '>>' : '>>>';
var ofs = offset ? ` + ${offset}` : '';
if (MEMORY64) return `HEAPU64[${heap32Idx} ${ofs} ${shr} 1]`;
else return `HEAPU32[${heap32Idx} ${ofs}]`;
}
null;
}}}
let api = {
$wgpu__deps: ['$utf8'
#if (ASSERTIONS || parseInt(globalThis.WEBGPU_DEBUG))
, '$wgpu_checked_shift'
#endif
],
#if (ASSERTIONS || parseInt(globalThis.WEBGPU_DEBUG))
$wgpuOffscreenCanvases__deps: ['$wgpu_checked_shift'],
#endif
// Stores a ID->WebGPU object mapping registry of global top-level WebGPU objects.
$wgpu: {},
// Stores ID->OffscreenCanvas objects that are owned by the current thread.
$wgpuOffscreenCanvases: {},
// Free ID counter generation number
// 0: reserved for invalid object (i.e. undefined) for e.g. wgpu_encoder_set_bind_group() purposes,
// 1: reserved for a special GPUTexture that GPUCanvasContext.getCurrentTexture() returns.
// [2, 2147483647]: valid WebGPU IDs
$wgpuIdCounter: 2,
// Stores the given WebGPU object under a new free WebGPU object ID.
// Returns the new ID. Can be called with a null/undefined, in which
// case no object/ID is persisted.
$wgpuStore__deps: ['$wgpu', '$wgpuIdCounter'],
$wgpuStore: function(object) {
if (object) {
// WebGPU renderer usage can burn through a lot of object IDs each rendered frame
// (a number of GPUCommandEncoder, GPUTexture, GPUTextureView, GPURenderPassEncoder,
// GPUCommandBuffer objects are created each application frame)
// If we assume an upper bound of 1000 object IDs created per rendered frame, and a
// new mobile device with 120hz display, a signed int32 state space is exhausted in
// 2147483646 / 1000 / 120 / 60 / 60 = 4.97 hours, which is realistic for a page to
// stay open for that long. Therefore handle wraparound of the ID counter generation,
// and find free gaps in the object IDs for new objects.
while(wgpu[wgpuIdCounter]) wgpuIdCounter = wgpuIdCounter < 2147483647 ? wgpuIdCounter + 1 : 2;
wgpu[wgpuIdCounter] = object;
// Each persisted objects gets a custom 'wid' field (wasm ID) which stores the ID that
// this object is known by on Wasm side.
object.wid = wgpuIdCounter;
{{{ wdebugdir('object', '`Stored WebGPU object of type \'${object.constructor.name}\' with ID ${wgpuIdCounter}:`') }}};
return wgpuIdCounter++;
}
// Implicit return undefined to marshal ID 0 over to Wasm.
},
$wgpuLinkParentAndChild: function(parent, childId, child) {
child.parentObject = parent; // Link child->parent
// WebGPU objects form an object hierarchy, and deleting an object (adapter, device, texture, etc.) will
// destroy all child objects in the hierarchy)
if (!parent.derivedObjects) parent.derivedObjects = {};
parent.derivedObjects[childId] = child; // Link parent->child
},
// Marks the given 'object' to be a child/derived object of 'parent',
// and stores a reference to the object in the WebGPU table,
// returning the ID.
$wgpuStoreAndSetParent__deps: ['$wgpuStore', '$wgpuLinkParentAndChild'],
$wgpuStoreAndSetParent: function(object, parent) {
if (object) {
var objectId = wgpuStore(object);
wgpuLinkParentAndChild(parent, objectId, object);
return objectId;
}
},
$wgpuReadArrayOfWgpuObjects: function(ptr, numObjects) {
{{{ wassert('numObjects >= 0'); }}}
{{{ wassert('ptr != 0 || numObjects == 0'); }}} // Must be non-null pointer
{{{ replacePtrToIdx('ptr', 2); }}}
var arrayOfObjects = new Array(numObjects);
for(var i = 0; i < numObjects;) {
{{{ wassert('HEAPU32[ptr]'); }}} // Must reference a nonzero WebGPU object handle
{{{ wassert('wgpu[HEAPU32[ptr]]'); }}} // Must reference a valid WebGPU object
arrayOfObjects[i++] = wgpu[HEAPU32[ptr++]];
}
return arrayOfObjects;
},
$wgpuReadI53FromU64HeapIdx: function(heap32Idx) {
{{{ wassert('heap32Idx != 0'); }}}
#if WASM_BIGINT
{{{ wassert('heap32Idx % 2 == 0'); }}}
return Number(HEAPU64[heap32Idx >>> 1]);
#else
return HEAPU32[heap32Idx] + HEAPU32[heap32Idx+1] * 4294967296;
#endif
},
$wgpuWriteI53ToU64HeapIdx: function(heap32Idx, number) {
{{{ wassert('heap32Idx != 0'); }}}
#if WASM_BIGINT
{{{ wassert('heap32Idx % 2 == 0'); }}}
HEAPU64[heap32Idx >>> 1] = BigInt(number);
#else
HEAPU32[heap32Idx] = number;
HEAPU32[heap32Idx+1] = number / 4294967296;
#endif
},
wgpu_get_num_live_objects__deps: ['$wgpu'],
wgpu_get_num_live_objects: function() {
var numObjects = 0;
for(var o in wgpu) if (Object.hasOwn(wgpu, o)) ++numObjects;
return numObjects;
},
// Calls .destroy() on the given WebGPU object, and releases the reference to it.
wgpu_object_destroy__deps: ['$wgpu'],
wgpu_object_destroy: function(object) {
let o = wgpu[object];
{{{ wassert(`o || !wgpu.hasOwnProperty(object), 'wgpu dictionary should never be storing key-values with null/undefined value in it'`); }}}
if (o) {
// Make sure if there might exist any other references to this JS object, that they will no longer see the .wid
// field, since this object no longer exists in the wgpu table.
o.wid = 0;
// WebGPU objects of type GPUDevice, GPUBuffer, GPUTexture and GPUQuerySet have an explicit .destroy() function. Call that if applicable.
if (o['destroy']) o['destroy']();
// If the given object has derived objects (GPUTexture -> GPUTextureViews), delete those in a hierarchy as well.
if (o.derivedObjects) for(var d in o.derivedObjects) if (Object.hasOwn(o.derivedObjects, d)) _wgpu_object_destroy(d);
// If this object has a parent, unlink this object from its parent.
if (o.parentObject) delete o.parentObject.derivedObjects[object];
// Finally erase reference to this object.
delete wgpu[object];
}
{{{ wassert(`!wgpu.hasOwnProperty(object), 'object should have gotten deleted'`); }}}
},
wgpu_destroy_all_objects__deps: ['$wgpu'],
wgpu_destroy_all_objects: function() {
Object.values(wgpu).forEach(o => {
o.wid = 0;
if (o['destroy']) o['destroy']();
});
wgpu = {};
},
wgpu_is_valid_object: function(o) { return !!wgpu[o]; }, // Tests if this ID references anything (not just a GPUObjectBase)
wgpu_is_adapter: function(o) { return wgpu[o] instanceof GPUAdapter; },
wgpu_is_device: function(o) { return wgpu[o] instanceof GPUDevice; },
wgpu_is_buffer: function(o) { return wgpu[o] instanceof GPUBuffer; },
wgpu_is_texture: function(o) { return wgpu[o] instanceof GPUTexture; },
wgpu_is_texture_view: function(o) { return wgpu[o] instanceof GPUTextureView; },
wgpu_is_external_texture: function(o) { return wgpu[o] instanceof GPUExternalTexture; },
wgpu_is_sampler: function(o) { return wgpu[o] instanceof GPUSampler; },
wgpu_is_bind_group_layout: function(o) { return wgpu[o] instanceof GPUBindGroupLayout; },
wgpu_is_bind_group: function(o) { return wgpu[o] instanceof GPUBindGroup; },
wgpu_is_pipeline_layout: function(o) { return wgpu[o] instanceof GPUPipelineLayout; },
wgpu_is_shader_module: function(o) { return wgpu[o] instanceof GPUShaderModule; },
wgpu_is_compute_pipeline: function(o) { return wgpu[o] instanceof GPUComputePipeline; },
wgpu_is_render_pipeline: function(o) { return wgpu[o] instanceof GPURenderPipeline; },
wgpu_is_command_buffer: function(o) { return wgpu[o] instanceof GPUCommandBuffer; },
wgpu_is_command_encoder: function(o) { return wgpu[o] instanceof GPUCommandEncoder; },
wgpu_is_binding_commands_mixin: function(o) { return wgpu[o] instanceof GPUComputePassEncoder || wgpu[o] instanceof GPURenderPassEncoder || wgpu[o] instanceof GPURenderBundleEncoder; },
wgpu_is_render_commands_mixin: function(o) { return wgpu[o] instanceof GPURenderPassEncoder || wgpu[o] instanceof GPURenderBundleEncoder; },
wgpu_is_render_pass_encoder: function(o) { return wgpu[o] instanceof GPURenderPassEncoder; },
wgpu_is_render_bundle: function(o) { return wgpu[o] instanceof GPURenderBundle; },
wgpu_is_render_bundle_encoder: function(o) { return wgpu[o] instanceof GPURenderBundleEncoder; },
wgpu_is_queue: function(o) { return wgpu[o] instanceof GPUQueue; },
wgpu_is_query_set: function(o) { return wgpu[o] instanceof GPUQuerySet; },
wgpu_is_canvas_context: function(o) { return wgpu[o] instanceof GPUCanvasContext; },
wgpu_is_device_lost_info: function(o) { return wgpu[o] instanceof GPUDeviceLostInfo; },
wgpu_is_error: function(o) { return wgpu[o] instanceof GPUError; },
wgpu_object_set_label__deps: ['$utf8'],
wgpu_object_set_label: function(o, label) {
{{{ wassert('wgpu[o]'); }}}
wgpu[o]['label'] = utf8(label);
},
wgpu_object_get_label__deps: ['$stringToUTF8'],
wgpu_object_get_label: function(o, dstLabel, dstLabelSize) {
{{{ wassert('wgpu[o]'); }}}
#if MEMORY64
stringToUTF8(wgpu[o]['label'], Number(dstLabel), dstLabelSize);
#else
stringToUTF8(wgpu[o]['label'], dstLabel, dstLabelSize);
#endif
},
$wgpu_checked_shift: function(ptr, shift) {
#if MEMORY64
assert(BigInt(Number(ptr >> BigInt(shift))) << BigInt(shift) == ptr);
return Number(ptr >> BigInt(shift));
#else
assert(((ptr >>> shift) << shift) >>> 0 == (ptr >>> 0));
return ptr >>> shift;
#endif
},
// UTF8ToString(ptr) does not work with Wasm64 pointers (cannot take in a BigInt), so use a custom
// Wasm string -> JS string marshalling wrapper that is Wasm64 aware.
$utf8: function(ptr) {
#if MEMORY64
return UTF8ToString(Number(ptr));
#else
return UTF8ToString(ptr);
#endif
},
wgpu_canvas_get_webgpu_context__deps: ['$wgpuStore'
#if PROXY_TO_PTHREAD
, '$GL'
#endif
],
wgpu_canvas_get_webgpu_context: function(canvasSelector) {
{{{ wdebuglog('`wgpu_canvas_get_webgpu_context(canvasSelector="${utf8(canvasSelector)}")`'); }}}
{{{ wassert('canvasSelector'); }}}
#if PROXY_TO_PTHREAD
// Search transferred OffscreenCanvases
{{{ wdebugdir('GL.offscreenCanvases', '`Calling thread owns ${Object.keys(GL.offscreenCanvases).length} OffscreenCanvases in its object table:`') }}};
let canvas = GL.offscreenCanvases[utf8(canvasSelector)].offscreenCanvas;
#else
// Search Canvas elements in DOM.
let canvas = document.querySelector(utf8(canvasSelector));
#endif
{{{ wdebugdir('canvas', '`querySelector returned:`') }}};
let ctx = canvas.getContext('webgpu');
{{{ wdebugdir('ctx', '`canvas.getContext("webgpu") returned:`') }}};
if (ctx.wid) return ctx.wid;
return wgpuStore(ctx);
},
wgpu_offscreen_canvas_get_webgpu_context__deps: ['$wgpuOffscreenCanvases'],
wgpu_offscreen_canvas_get_webgpu_context: function(offscreenCanvasId) {
{{{ wdebuglog('`wgpu_offscreen_canvas_get_webgpu_context(offscreenCanvasId=${offscreenCanvasId})`'); }}}
{{{ wassert('offscreenCanvasId'); }}}
{{{ wassert('wgpuOffscreenCanvases[offscreenCanvasId]'); }}}
{{{ wassert('wgpuOffscreenCanvases[offscreenCanvasId] instanceof OffscreenCanvas'); }}}
let ctx = wgpuOffscreenCanvases[offscreenCanvasId].getContext('webgpu');
{{{ wdebugdir('ctx', '`offscreenCanvas.getContext("webgpu") returned:`') }}};
return wgpuStore(ctx);
},
#if ASYNCIFY
wgpu_request_animation_frame_loop__deps: ['_wgpuNumAsyncifiedOperationsPending'],
#endif
wgpu_request_animation_frame_loop: (cb, userData) => {
#if ASYNCIFY == 2
cb = WebAssembly.promising(getWasmTableEntry(cb));
#else
cb = getWasmTableEntry(cb);
#endif
function tick(timeStamp) {
if (
#if ASYNCIFY
__wgpuNumAsyncifiedOperationsPending ||
#endif
cb(timeStamp, userData)) requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
},
////////////////////////////////////////////////////////////
// Automatically generated with scripts/compress_strings.js:
$wgpuDecodeStrings__docs: '/** @param {number=} ch */',
$wgpuDecodeStrings: function(s, c, ch) {
ch = ch || 65;
for(c = c.split('|'); c[0];) s = s['replaceAll'](String.fromCharCode(ch++), c.pop());
return [,].concat(s.split(' '));
},
$GPUTextureAndVertexFormats__deps: ['$wgpuDecodeStrings'],
//$GPUTextureAndVertexFormats: [undefined (0), 'r8unorm' (1), 'r8snorm' (2), 'r8uint' (3), 'r8sint' (4), 'r16uint' (5), 'r16sint' (6), 'r16float' (7), 'rg8unorm' (8), 'rg8snorm' (9), 'rg8uint' (10), 'rg8sint' (11), 'r32uint' (12), 'r32sint' (13), 'r32float' (14), 'rg16uint' (15), 'rg16sint' (16), 'rg16float' (17), 'rgba8unorm' (18), 'rgba8unorm-srgb' (19), 'rgba8snorm' (20), 'rgba8uint' (21), 'rgba8sint' (22), 'bgra8unorm' (23), 'bgra8unorm-srgb' (24), 'rgb9e5ufloat' (25), 'rgb10a2uint' (26), 'rgb10a2unorm' (27), 'rg11b10ufloat' (28), 'rg32uint' (29), 'rg32sint' (30), 'rg32float' (31), 'rgba16uint' (32), 'rgba16sint' (33), 'rgba16float' (34), 'rgba32uint' (35), 'rgba32sint' (36), 'rgba32float' (37), 'stencil8' (38), 'depth16unorm' (39), 'depth24plus' (40), 'depth24plus-stencil8' (41), 'depth32float' (42), 'depth32float-stencil8' (43), 'bc1-rgba-unorm' (44), 'bc1-rgba-unorm-srgb' (45), 'bc2-rgba-unorm' (46), 'bc2-rgba-unorm-srgb' (47), 'bc3-rgba-unorm' (48), 'bc3-rgba-unorm-srgb' (49), 'bc4-r-unorm' (50), 'bc4-r-snorm' (51), 'bc5-rg-unorm' (52), 'bc5-rg-snorm' (53), 'bc6h-rgb-ufloat' (54), 'bc6h-rgb-float' (55), 'bc7-rgba-unorm' (56), 'bc7-rgba-unorm-srgb' (57), 'etc2-rgb8unorm' (58), 'etc2-rgb8unorm-srgb' (59), 'etc2-rgb8a1unorm' (60), 'etc2-rgb8a1unorm-srgb' (61), 'etc2-rgba8unorm' (62), 'etc2-rgba8unorm-srgb' (63), 'eac-r11unorm' (64), 'eac-r11snorm' (65), 'eac-rg11unorm' (66), 'eac-rg11snorm' (67), 'astc-4x4-unorm' (68), 'astc-4x4-unorm-srgb' (69), 'astc-5x4-unorm' (70), 'astc-5x4-unorm-srgb' (71), 'astc-5x5-unorm' (72), 'astc-5x5-unorm-srgb' (73), 'astc-6x5-unorm' (74), 'astc-6x5-unorm-srgb' (75), 'astc-6x6-unorm' (76), 'astc-6x6-unorm-srgb' (77), 'astc-8x5-unorm' (78), 'astc-8x5-unorm-srgb' (79), 'astc-8x6-unorm' (80), 'astc-8x6-unorm-srgb' (81), 'astc-8x8-unorm' (82), 'astc-8x8-unorm-srgb' (83), 'astc-10x5-unorm' (84), 'astc-10x5-unorm-srgb' (85), 'astc-10x6-unorm' (86), 'astc-10x6-unorm-srgb' (87), 'astc-10x8-unorm' (88), 'astc-10x8-unorm-srgb' (89), 'astc-10x10-unorm' (90), 'astc-10x10-unorm-srgb' (91), 'astc-12x10-unorm' (92), 'astc-12x10-unorm-srgb' (93), 'astc-12x12-unorm' (94), 'astc-12x12-unorm-srgb' (95), 'uint8x2' (96), 'uint8x4' (97), 'sint8x2' (98), 'sint8x4' (99), 'unorm8x2' (100), 'unorm8x4' (101), 'snorm8x2' (102), 'snorm8x4' (103), 'uint16x2' (104), 'uint16x4' (105), 'sint16x2' (106), 'sint16x4' (107), 'unorm16x2' (108), 'unorm16x4' (109), 'snorm16x2' (110), 'snorm16x4' (111), 'float16x2' (112), 'float16x4' (113), 'float32' (114), 'float32x2' (115), 'float32x3' (116), 'float32x4' (117), 'uint32' (118), 'uint32x2' (119), 'uint32x3' (120), 'uint32x4' (121), 'sint32' (122), 'sint32x2' (123), 'sint32x3' (124), 'sint32x4' (125), 'unorm10-10-10-2' (126)],
$GPUTextureAndVertexFormats: "wgpuDecodeStrings('r8YA8TA8SA8UALSALUALWR8YR8TR8SR8UANSANUANWRLSRLURLW V8Y V8Z V8T V8S V8U bgra8Y bgra8ZRb9e5uWRbJa2SRbJa2YR11bJuWRNSRNURNW VLS VLU VLW VNS VNU VNWB8ILYI24plusI24plus-E8INWINW-E8Q1-V-YQ1-V-ZQ2-V-YQ2-V-ZQ3-V-YQ3-V-ZQ4-r-YQ4-r-TQ5-rg-YQ5-rg-TQ6h-rgb-uWQ6h-rgb-WQ7-V-YQ7-V-ZPYPZPa1YPa1Z etc2-V8Y etc2-V8ZFr11YFr11TFrg11YFrg11TX4x4-YX4x4-ZX5x4-YX5x4-ZX5x5-YX5x5-ZX6x5-YX6x5-ZX6x6-YX6x6-ZX8x5-YX8x5-ZX8x6-YX8x6-ZX8x8-YX8x8-ZXJx5-YXJx5-ZXJx6-YXJx6-ZXJx8-YXJx8-ZXJxJ-YXJxJ-ZX12xJ-YX12xJ-ZX12x12-YX12x12-Z S8MS8KU8MU8KY8MY8KT8MT8KSLMSLKULMULKYLMYLKTLMTLKWLMWLKWN WNMWNx3 WNKSN SNMSNx3 SNKUN UNMUNx3 UNKYJ-J-J-2', 'unorm-srgb|unorm| astc-|float|rgba|sint|snorm|uint| rg| bc| etc2-rgb8|-AC|32|x2 |16|x4 |10| depth|-B|SC| eac-|stencil|-ESJ|-E-A| E| r')",
wgpu32BitLimitNames__deps: ['$wgpuDecodeStrings'],
//wgpu32BitLimitNames: ['maxTextureDimension1D' (0), 'maxTextureDimension2D' (1), 'maxTextureDimension3D' (2), 'maxTextureArrayLayers' (3), 'maxBindGroups' (4), 'maxBindGroupsPlusVertexBuffers' (5), 'maxBindingsPerBindGroup' (6), 'maxDynamicUniformBuffersPerPipelineLayout' (7), 'maxDynamicStorageBuffersPerPipelineLayout' (8), 'maxSampledTexturesPerShaderStage' (9), 'maxSamplersPerShaderStage' (10), 'maxStorageBuffersPerShaderStage' (11), 'maxStorageTexturesPerShaderStage' (12), 'maxUniformBuffersPerShaderStage' (13), 'minUniformBufferOffsetAlignment' (14), 'minStorageBufferOffsetAlignment' (15), 'maxVertexBuffers' (16), 'maxVertexAttributes' (17), 'maxVertexBufferArrayStride' (18), 'maxInterStageShaderVariables' (19), 'maxColorAttachments' (20), 'maxColorAttachmentBytesPerSample' (21), 'maxComputeWorkgroupStorageSize' (22), 'maxComputeInvocationsPerWorkgroup' (23), 'maxComputeWorkgroupSizeX' (24), 'maxComputeWorkgroupSizeY' (25), 'maxComputeWorkgroupSizeZ' (26)],
wgpu32BitLimitNames: "wgpuDecodeStrings('max<1D=<2D=<3D=T4ArrayLayers=9s=9sPlus5>s=BindingsPer9=DynamicUniform>:=Dynamic;e>:=SampledT4s@axSamplers@ax;e>s@ax;eT4s@axUniform>s@inUniform>6t min;e>6t=5>s=5Attributes=5>ArrayStride=InterStageShaderVariables=ColorAttachments=ColorAttachmentBytesPerSample?;eSize=ComputeInvocationsPerWorkgroup?SizeX?SizeY?SizeZ', 'PerShaderStage m| maxComputeWorkgroup|Buffer| max|TextureDimension|Storag|sPerPipelineLayout|BindGroup|s7ColorAttachment|Uniform6|OffsetAlignmen|Vertex|exture', 52).slice(1)",
wgpu64BitLimitNames__deps: ['$wgpuDecodeStrings'],
//wgpu64BitLimitNames: ['maxUniformBufferBindingSize' (0), 'maxStorageBufferBindingSize' (1), 'maxBufferSize' (2)],
wgpu64BitLimitNames: "wgpuDecodeStrings('maxUniform4Storage4BufferSize', 'BufferBindingSize max', 52).slice(1)",
wgpuFeatures__deps: ['$wgpuDecodeStrings'],
//wgpuFeatures: ['depth-clip-control' (0), 'depth32float-stencil8' (1), 'texture-compression-bc' (2), 'texture-compression-bc-sliced-3d' (3), 'texture-compression-etc2' (4), 'texture-compression-astc' (5), 'timestamp-query' (6), 'indirect-first-instance' (7), 'shader-f16' (8), 'rg11b10ufloat-renderable' (9), 'bgra8unorm-storage' (10), 'float32-filterable' (11), 'clip-distances' (12), 'dual-source-blending' (13)],
wgpuFeatures: "wgpuDecodeStrings('A-Ccontrol A32F-Dencil8GbcGbc-sliced-3dGetc2GaDc timeDamp-query indirect-firD-inB shader-f16 rg11b10uF-rendEbgra8unorm-Dorage F32-filtECdiBs dual-source-blending', ' texture-compression-|float|erable |st|clip-|Dance|depth').slice(1)",
$GPUBlendFactors__deps: ['$wgpuDecodeStrings'],
//$GPUBlendFactors: [undefined (0), 'zero' (1), 'one' (2), 'src' (3), 'one-minus-src' (4), 'src-alpha' (5), 'one-minus-src-alpha' (6), 'dst' (7), 'one-minus-dst' (8), 'dst-alpha' (9), 'one-minus-dst-alpha' (10), 'src-alpha-saturated' (11), 'constant' (12), 'one-minus-constant' (13), 'src1' (14), 'one-minus-src1' (15), 'src1-alpha' (16), 'one-minus-src1-alpha' (17)],
$GPUBlendFactors: "wgpuDecodeStrings('zero one CFC CEFCE AFA AEFAE CE-saturated BFB DFD DEFDE', ' one-minus-|-alpha|src1|src|constant|dst')",
$GPUStencilOperations__deps: ['$wgpuDecodeStrings'],
//$GPUStencilOperations: [undefined (0), 'keep' (1), 'zero' (2), 'replace' (3), 'invert' (4), 'increment-clamp' (5), 'decrement-clamp' (6), 'increment-wrap' (7), 'decrement-wrap' (8)],
$GPUStencilOperations: "wgpuDecodeStrings('keep zero replace invert inCBdeCBinCA deCA', 'crement-|clamp |wrap')",
$GPUCompareFunctions__deps: ['$wgpuDecodeStrings'],
//$GPUCompareFunctions: [undefined (0), 'never' (1), 'less' (2), 'equal' (3), 'less-equal' (4), 'greater' (5), 'not-equal' (6), 'greater-equal' (7), 'always' (8)],
$GPUCompareFunctions: "wgpuDecodeStrings('neverA equalACB notCBCalways', '-equal |greater| less')",
$GPUBlendOperations__deps: ['$wgpuDecodeStrings'],
//$GPUBlendOperations: [undefined (0), 'add' (1), 'subtract' (2), 'reverse-subtract' (3), 'min' (4), 'max' (5)],
$GPUBlendOperations: "wgpuDecodeStrings('add Areverse-Amin max', 'subtract ')",
$GPUIndexFormats__deps: ['$wgpuDecodeStrings'],
//$GPUIndexFormats: [undefined (0), 'uint16' (1), 'uint32' (2)],
$GPUIndexFormats: "wgpuDecodeStrings('A16 A32', 'uint')",
$GPUBufferMapStates__deps: ['$wgpuDecodeStrings'],
//$GPUBufferMapStates: [undefined (0), 'unmapped' (1), 'pending' (2), 'mapped' (3)],
$GPUBufferMapStates: "wgpuDecodeStrings('unA pending A', 'mapped')",
$GPUTextureDimensions: [, '1d', '2d', '3d'],
$GPUTextureViewDimensions__deps: ['$wgpuDecodeStrings'],
//$GPUTextureViewDimensions: [undefined (0), '1d' (1), '2d' (2), '2d-array' (3), 'cube' (4), 'cube-array' (5), '3d' (6)],
$GPUTextureViewDimensions: "wgpuDecodeStrings('1B 2dCA AC3d', '-array |d 2d|cube')",
$GPUStorageTextureSampleTypes__deps: ['$wgpuDecodeStrings'],
//$GPUStorageTextureSampleTypes: [undefined (0), 'write-only' (1), 'read-only' (2), 'read-write' (3)],
$GPUStorageTextureSampleTypes: "wgpuDecodeStrings('A-BBA', 'only read-|write')",
$GPUAddressModes__deps: ['$wgpuDecodeStrings'],
//$GPUAddressModes: [undefined (0), 'clamp-to-edge' (1), 'repeat' (2), 'mirror-repeat' (3)],
$GPUAddressModes: "wgpuDecodeStrings('clamp-to-edge A mirror-A', 'repeat')",
$GPUTextureAspects__deps: ['$wgpuDecodeStrings'],
//$GPUTextureAspects: [undefined (0), 'all' (1), 'stencil-only' (2), 'depth-only' (3)],
$GPUTextureAspects: "wgpuDecodeStrings('all stencilA depthA', '-only')",
$GPUPipelineStatisticNames: [, 'timestamp'],
$GPUPrimitiveTopologys__deps: ['$wgpuDecodeStrings'],
//$GPUPrimitiveTopologys: [undefined (0), 'point-list' (1), 'line-list' (2), 'line-strip' (3), 'triangle-list' (4), 'triangle-strip' (5)],
$GPUPrimitiveTopologys: "wgpuDecodeStrings('pointDADAB CDCB', '-list |triangle|-strip|line')",
$GPUBufferBindingTypes__deps: ['$wgpuDecodeStrings'],
//$GPUBufferBindingTypes: [undefined (0), 'uniform' (1), 'storage' (2), 'read-only-storage' (3)],
$GPUBufferBindingTypes: "wgpuDecodeStrings('uniform A read-only-A', 'storage')",
$GPUSamplerBindingTypes__deps: ['$wgpuDecodeStrings'],
//$GPUSamplerBindingTypes: [undefined (0), 'filtering' (1), 'non-filtering' (2), 'comparison' (3)],
$GPUSamplerBindingTypes: "wgpuDecodeStrings('Anon-Acomparison', 'filtering ')",
$GPUTextureSampleTypes__deps: ['$wgpuDecodeStrings'],
//$GPUTextureSampleTypes: [undefined (0), 'float' (1), 'unfilterable-float' (2), 'depth' (3), 'sint' (4), 'uint' (5)],
$GPUTextureSampleTypes: "wgpuDecodeStrings('Aunfilterable-Adepth sint uint', 'float ')",
$GPUQueryTypes: [, 'occlusion', 'timestamp'],
$HTMLPredefinedColorSpaces: [, 'srgb', 'display-p3'],
$GPUFilterModes__deps: ['$wgpuDecodeStrings'],
//$GPUFilterModes: [undefined (0), 'nearest' (1), 'linear' (2)],
$GPUFilterModes: "wgpuDecodeStrings('Aest liA', 'near')",
$GPUMipmapFilterModes__deps: ['$wgpuDecodeStrings'],
//$GPUMipmapFilterModes: [undefined (0), 'nearest' (1), 'linear' (2)],
$GPUMipmapFilterModes: "wgpuDecodeStrings('Aest liA', 'near')",
$GPULoadOps: [, 'load', 'clear'],
$GPUStoreOps: [, 'store', 'discard'],
$GPUAutoLayoutMode: '="auto"',
// End of automatically generated with scripts/compress_strings.js
//////////////////////////////////////////////////////////////////
wgpu_canvas_context_configure__deps: ['$GPUTextureAndVertexFormats', '$HTMLPredefinedColorSpaces', '$wgpuReadArrayOfWgpuObjects'],
wgpu_canvas_context_configure: function(canvasContext, config) {
{{{ wdebuglog('`wgpu_canvas_context_configure(canvasContext=${canvasContext}, config=${config})`'); }}}
{{{ wassert('canvasContext != 0'); }}}
{{{ wassert('wgpu[canvasContext]'); }}}
{{{ wassert('wgpu[canvasContext] instanceof GPUCanvasContext'); }}}
{{{ wassert('config != 0'); }}} // Must be non-null
{{{ replacePtrToIdx('config', 2); }}}
let desc = {
'device': wgpu[HEAPU32[config]],
'format': GPUTextureAndVertexFormats[HEAPU32[config+1]],
'usage': HEAPU32[config+2],
'viewFormats': wgpuReadArrayOfWgpuObjects({{{ readPtrFromIdx32('config', 4) }}}, HEAPU32[config+3]),
'colorSpace': HTMLPredefinedColorSpaces[HEAPU32[config+6]],
'toneMapping': {
'mode': [, 'standard', 'extended'][HEAPU32[config+7]]
},
'alphaMode': [, 'opaque', 'premultiplied'][HEAPU32[config+8]]
};
{{{ wdebugdir('desc', '`canvasContext.configure() with descriptor:`') }}};
wgpu[canvasContext]['configure'](desc);
},
wgpu_canvas_context_unconfigure: function(canvasContext) {
{{{ wdebuglog('`wgpu_canvas_context_get_current_texture(canvasContext=${canvasContext})`'); }}}
{{{ wassert('canvasContext != 0'); }}}
{{{ wassert('wgpu[canvasContext]'); }}}
{{{ wassert('wgpu[canvasContext] instanceof GPUCanvasContext'); }}}
wgpu[canvasContext]['unconfigure']();
},
wgpu_canvas_context_get_current_texture__deps: ['wgpu_object_destroy', '$wgpuLinkParentAndChild'],
wgpu_canvas_context_get_current_texture: function(canvasContext) {
{{{ wdebuglog('`wgpu_canvas_context_get_current_texture(canvasContext=${canvasContext})`'); }}}
{{{ wassert('canvasContext != 0'); }}}
{{{ wassert('wgpu[canvasContext]'); }}}
{{{ wassert('wgpu[canvasContext] instanceof GPUCanvasContext'); }}}
canvasContext = wgpu[canvasContext];
// The canvas context texture is a special texture that automatically invalidates itself after the current rAF()
// callback if over. Therefore when a new swap chain texture is produced, we need to delete the old one to avoid
// accumulating references to stale textures from each frame.
// Acquire the new canvas context texture..
var canvasTexture = canvasContext['getCurrentTexture']();
{{{ wassert('canvasTexture'); }}}
if (canvasTexture != wgpu[1]) {
// ... and destroy previous special canvas context texture, if it was an old one.
_wgpu_object_destroy(1);
wgpu[1] = canvasTexture;
canvasTexture.wid = 1;
wgpuLinkParentAndChild(canvasContext, 1, canvasTexture);
}
// The canvas context texture is hardcoded the special ID 1. Return that ID to caller.
return 1;
},
wgpuReportErrorCodeAndMessage__deps: ['$lengthBytesUTF8', '$stringToUTF8'
#if parseInt(EMSCRIPTEN_VERSION.split('.')[0]) > 3 || (parseInt(EMSCRIPTEN_VERSION.split('.')[0]) == 3 && parseInt(EMSCRIPTEN_VERSION.split('.')[1]) > 1) || (parseInt(EMSCRIPTEN_VERSION.split('.')[0]) == 3 && parseInt(EMSCRIPTEN_VERSION.split('.')[1]) == 1 && parseInt(EMSCRIPTEN_VERSION.split('.')[2]) >= 57)
, '$stackSave', '$stackAlloc', '$stackRestore'
#endif
],
wgpuReportErrorCodeAndMessage: function(device, callback, errorCode, stringMessage, userData) {
if (stringMessage) {
// n.b. these variables deliberately rely on 'var' scope.
var stackTop = stackSave(),
len = lengthBytesUTF8(stringMessage)+1,
errorMessage = stackAlloc(len);
stringToUTF8(stringMessage, errorMessage, len);
}
#if MEMORY64
{{{ makeDynCall('viipp', 'callback') }}}(device, errorCode, errorMessage||0n, userData);
#else
{{{ makeDynCall('viipp', 'callback') }}}(device, errorCode, errorMessage, userData);
#endif
if (stackTop) stackRestore(stackTop);
},
wgpu_device_set_lost_callback__deps: ['wgpuReportErrorCodeAndMessage'],
wgpu_device_set_lost_callback: function(device, callback, userData) {
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
wgpu[device]['lost'].then((deviceLostInfo) => {
_wgpuReportErrorCodeAndMessage(device, callback,
deviceLostInfo['reason'] == 'destroyed' ? 1/*WGPU_DEVICE_LOST_REASON_DESTROYED*/ : 0/*WGPU_DEVICE_LOST_REASON_UNKNOWN*/,
deviceLostInfo['message'], userData);
});
},
wgpu_device_push_error_scope: function(device, filter) {
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
wgpu[device]['pushErrorScope']([, 'out-of-memory', 'validation', 'internal'][filter]);
},
wgpuErrorObjectToErrorType: function(error) {
return error
? (error instanceof GPUInternalError ? 3/*WGPU_ERROR_TYPE_INTERNAL*/
: (error instanceof GPUValidationError ? 2/*WGPU_ERROR_TYPE_VALIDATION*/
: (error instanceof GPUOutOfMemoryError ? 1/*WGPU_ERROR_TYPE_OUT_OF_MEMORY*/
: 3/*WGPU_ERROR_TYPE_UNKNOWN_ERROR*/)))
: 0/*WGPU_ERROR_TYPE_NO_ERROR*/;
},
wgpuDispatchWebGpuErrorEvent__deps: ['wgpuReportErrorCodeAndMessage', 'wgpuErrorObjectToErrorType'],
wgpuDispatchWebGpuErrorEvent: function(device, callback, error, userData) {
// Awkward WebGPU spec: errors do not contain a data-driven error code that
// could be used to identify the error type in a general forward compatible
// fashion, but must do an 'instanceof' check to look at the types of the
// errors. If new error types are introduced in the future, their types won't
// be recognized! (and code size creeps by having to do an 'instanceof' on every
// error type)
_wgpuReportErrorCodeAndMessage(device,
callback,
_wgpuErrorObjectToErrorType(error),
error && error['message'],
userData);
},
// wgpuMuteJsExceptions(fn) returns a new function that can be called to invoke
// the passed function in a way that all exceptions coming out from that function
// are guarded inside a try-catch.
wgpuMuteJsExceptions: function(fn) {
return (p) => { // only support one argument to function fn (we could do ...params, but we only ever need one arg so that's fine)
try {
return fn(p);
} catch(e) {
{{{ werror('`Exception thrown when handling a WebGPU callback: ${e}`'); }}}
}
}
},
wgpu_device_pop_error_scope_async__deps: ['wgpuDispatchWebGpuErrorEvent', 'wgpuMuteJsExceptions'],
wgpu_device_pop_error_scope_async: function(device, callback, userData) {
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
{{{ wassert('callback'); }}}
function dispatchErrorCallback(error) {
_wgpuDispatchWebGpuErrorEvent(device, callback, error, userData);
}
wgpu[device]['popErrorScope']()
.then(_wgpuMuteJsExceptions(dispatchErrorCallback))
.catch(dispatchErrorCallback);
},
wgpu_device_pop_error_scope_sync__deps: ['_wgpuNumAsyncifiedOperationsPending', '$wgpu_async', 'wgpuMuteJsExceptions', '$stringToUTF8', 'wgpuErrorObjectToErrorType'],
// wgpu_device_pop_error_scope_sync__sig: 'iipi', // Iirc this would be needed for -sASYNCIFY=1 build mode, but this breaks -sMEMORY64=1 due to the detrimental automatic wrappers
wgpu_device_pop_error_scope_sync__async: true,
wgpu_device_pop_error_scope_sync: function(device, msg, msgLen) {
return wgpu_async(() => {
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
{{{ wassert('msgLen >= 0'); }}}
{{{ wassert('msg || msgLen == 0'); }}}
function dispatchErrorCallback(error) {
--__wgpuNumAsyncifiedOperationsPending;
var err = (error && error['message']) || '';
console.dir(err);
stringToUTF8(err, msg, msgLen);
return _wgpuErrorObjectToErrorType(error);
}
++__wgpuNumAsyncifiedOperationsPending;
return wgpu[device]['popErrorScope']()
.then(_wgpuMuteJsExceptions(dispatchErrorCallback))
.catch(dispatchErrorCallback);
});
},
wgpu_device_set_uncapturederror_callback__deps: ['wgpuDispatchWebGpuErrorEvent'],
wgpu_device_set_uncapturederror_callback: function(device, callback, userData) {
{{{ wassert('device != 0'); }}}
{{{ wassert('wgpu[device]'); }}}
{{{ wassert('wgpu[device] instanceof GPUDevice'); }}}
wgpu[device]['onuncapturederror'] = callback ? function(uncapturedError) {
{{{ wdebugdir('uncapturedError'); }}}
_wgpuDispatchWebGpuErrorEvent(device, callback, uncapturedError['error'], userData);
} : null;
},
navigator_gpu_available: function() {
return !!navigator['gpu'];
},
navigator_delete_webgpu_api_access: function() {
// N.b. removing access to WebGPU is done via the prototype chain of Navigator,
// and not the instance object navigator.
delete Navigator.prototype.gpu;
},
navigator_gpu_request_adapter_async__deps: ['$wgpuStore', 'wgpuMuteJsExceptions'],
navigator_gpu_request_adapter_async__docs: '/** @suppress{checkTypes} */', // This function intentionally calls cb() without args.
navigator_gpu_request_adapter_async: function(options, adapterCallback, userData) {
{{{ wdebuglog('`navigator_gpu_request_adapter_async: options: ${options}, adapterCallback: ${adapterCallback}, userData: ${userData}`'); }}}
{{{ wassert('adapterCallback, "must pass a callback function to navigator_gpu_request_adapter_async!"'); }}}
{{{ wassert('navigator["gpu"], "Your browser does not support WebGPU!"'); }}}
{{{ wassert('options != 0'); }}}
{{{ replacePtrToIdx('options', 2); }}}
let gpu = navigator['gpu'],
powerPreference = [, 'low-power', 'high-performance'][HEAPU32[options]],
opts = {};
if (gpu) {
if (options) {
opts['forceFallbackAdapter'] = !!HEAPU32[options+1];
if (powerPreference) opts['powerPreference'] = powerPreference;
}
{{{ wdebuglog('`navigator.gpu.requestAdapter(options=${JSON.stringify(opts)})`'); }}}
function cb(adapter) {
{{{ wdebugdir('adapter', '`navigator.gpu.requestAdapter resolved with following adapter:`'); }}}
{{{ makeDynCall('vip', 'adapterCallback') }}}(wgpuStore(adapter), userData);
}
gpu['requestAdapter'](opts)
.then(_wgpuMuteJsExceptions(cb))
.catch(
#if ASSERTIONS || globalThis.WEBGPU_DEBUG
(e)=>{console.error(`navigator.gpu.requestAdapter() Promise failed: ${e}`); cb(/*intentionally omit arg to pass undefined*/)}
#else
()=>{cb(/*intentionally omit arg to pass undefined*/)}
#endif
);
return 1/*WGPU_TRUE*/;
}
{{{ werror('`WebGPU is not supported by the current browser!`'); }}}
// Implicit return WGPU_FALSE, WebGPU is not supported.
},
#if ASYNCIFY
_wgpuNumAsyncifiedOperationsPending: 0,
$wgpuStoreAsyncifiedOp__deps: ['_wgpuNumAsyncifiedOperationsPending', '$wgpuStoreAndSetParent', '$wgpuStore'],
$wgpuStoreAsyncifiedOp: function(object, parent) {
{{{ wassert('__wgpuNumAsyncifiedOperationsPending > 0'); }}}
--__wgpuNumAsyncifiedOperationsPending;
return parent ? wgpuStoreAndSetParent(object, parent) : wgpuStore(object);
},
wgpu_sync_operations_pending: function() {
return __wgpuNumAsyncifiedOperationsPending;
},
$wgpu_async: async function(func) {
return await func();
},
navigator_gpu_request_adapter_sync__deps: ['$wgpuStoreAsyncifiedOp', '_wgpuNumAsyncifiedOperationsPending', '$wgpu_async'],
// navigator_gpu_request_adapter_sync__sig: 'ip', // Iirc this would be needed for -sASYNCIFY=1 build mode, but this breaks -sMEMORY64=1 due to the detrimental automatic wrappers
navigator_gpu_request_adapter_sync__async: true,
navigator_gpu_request_adapter_sync: function(options) {
return wgpu_async(() => {
{{{ wdebuglog('`navigator_gpu_request_adapter_sync: options: ${options}`'); }}}
{{{ wassert('navigator["gpu"], "Your browser does not support WebGPU!"'); }}}
{{{ wassert('options != 0'); }}}
{{{ replacePtrToIdx('options', 2); }}}
let gpu = navigator['gpu'],
powerPreference = [, 'low-power', 'high-performance'][HEAPU32[options]],
opts = {};
if (gpu) {
if (options) {
opts['forceFallbackAdapter'] = !!HEAPU32[options+1];
if (powerPreference) opts['powerPreference'] = powerPreference;
}
{{{ wdebuglog('`navigator.gpu.requestAdapter(options=${JSON.stringify(opts)})`'); }}}
++__wgpuNumAsyncifiedOperationsPending;
return gpu['requestAdapter'](opts).then(wgpuStoreAsyncifiedOp);
}
{{{ werror('`WebGPU is not supported by the current browser!`'); }}}
// Implicit return WGPU_FALSE, WebGPU is not supported.
});
},
#else
wgpu_sync_operations_pending: function() {
return 0;
},
#endif
// A "_simple" variant of navigator_gpu_request_adapter_async() that does
// not take in any descriptor params, for building tiny code with default
// args and creating readable test cases etc.
navigator_gpu_request_adapter_async_simple__deps: ['$wgpuStore'],
navigator_gpu_request_adapter_async_simple: function(adapterCallback) {
{{{ wdebuglog('`navigator_gpu_request_adapter_async_simple(adapterCallback=${adapterCallback})`'); }}}
{{{ wassert('navigator["gpu"], "Your browser does not support WebGPU!"'); }}}
navigator['gpu']['requestAdapter']().then(adapter => {
// N.b. this function deliberately invokes a callback with signature 'vii',
// the second integer parameter is intentionally passed as undefined and coerced to zero to save code bytes.
#if MEMORY64
getWasmTableEntry(adapterCallback)(wgpuStore(adapter), 0n);
#else
getWasmTableEntry(adapterCallback)(wgpuStore(adapter));
#endif
});
},
#if ASYNCIFY
navigator_gpu_request_adapter_sync_simple__deps: ['$wgpuStoreAsyncifiedOp', '_wgpuNumAsyncifiedOperationsPending', '$wgpu_async'],
navigator_gpu_request_adapter_sync_simple__sig: 'i',
navigator_gpu_request_adapter_sync_simple__async: true,
navigator_gpu_request_adapter_sync_simple: function() {
return wgpu_async(() => {
{{{ wdebuglog('`navigator_gpu_request_adapter_sync_simple()`'); }}}
{{{ wassert('navigator["gpu"], "Your browser does not support WebGPU!"'); }}}
++__wgpuNumAsyncifiedOperationsPending;
return navigator['gpu']['requestAdapter']().then(wgpuStoreAsyncifiedOp);
});
},
#endif
navigator_gpu_get_preferred_canvas_format__deps: ['$GPUTextureAndVertexFormats'],
navigator_gpu_get_preferred_canvas_format: function() {
{{{ wdebuglog('`navigator_gpu_get_preferred_canvas_format()`'); }}}
{{{ wassert('navigator["gpu"], "Your browser does not support WebGPU!"'); }}}
{{{ wassert('GPUTextureAndVertexFormats.includes(navigator["gpu"]["getPreferredCanvasFormat"]())'); }}}
return GPUTextureAndVertexFormats.indexOf(navigator['gpu']['getPreferredCanvasFormat']());
},
$wgpuSupportedWgslLanguageFeatures: 0,
navigator_gpu_get_wgsl_language_features__deps: ['$wgpuSupportedWgslLanguageFeatures', 'malloc', '$stringToNewUTF8'],
navigator_gpu_get_wgsl_language_features: function() {
if (!wgpuSupportedWgslLanguageFeatures) {
// This function allocates an un-freeable constant memory block for an immutable array of strings representing the WGSL
// language features. The intention is that this allocation is done only once, and behaves like global static data.
let f = navigator['gpu']['wgslLanguageFeatures'];
#if MEMORY64 // TODO: use a macro to clean up these #ifs
let i = 0n;
#else
let i = 0;
#endif
wgpuSupportedWgslLanguageFeatures = _malloc((f.size+1) * 8); // 8 == sizeof(char*) in Wasm64 mode
for(var feat of f.keys()) {
#if MEMORY64
HEAPU64[BigInt(wgpuSupportedWgslLanguageFeatures) + i >> 3n] = BigInt(stringToNewUTF8(feat));
i += 8n;
#else
HEAPU32[wgpuSupportedWgslLanguageFeatures + i >> 2] = stringToNewUTF8(feat);
i += 4;
#endif
}
}
#if MEMORY64
return BigInt(wgpuSupportedWgslLanguageFeatures);
#else
return wgpuSupportedWgslLanguageFeatures;
#endif
},
navigator_gpu_is_wgsl_language_feature_supported__deps: ['$utf8'],
navigator_gpu_is_wgsl_language_feature_supported: function(feature) {
return navigator['gpu']['wgslLanguageFeatures']['has'](utf8(feature));
},
wgpu_adapter_or_device_get_features__deps: ['wgpuFeatures'],
wgpu_adapter_or_device_get_features: function(adapterOrDevice) {
{{{ wdebuglog('`wgpu_adapter_or_device_get_features(adapterOrDevice: ${adapterOrDevice})`'); }}}
{{{ wassert('adapterOrDevice != 0'); }}}
{{{ wassert('wgpu[adapterOrDevice]'); }}}
{{{ wassert('wgpu[adapterOrDevice] instanceof GPUAdapter || wgpu[adapterOrDevice] instanceof GPUDevice'); }}}
let id = 1,
featuresBitMask = 0;
{{{ wdebuglog('`The following adapter features are supported:`'); }}}
for(let feature of _wgpuFeatures) {
if (wgpu[adapterOrDevice]['features'].has(feature)) {
{{{ wdebuglog('` - "${feature}", feature bit 0x${id.toString(16)}`'); }}}
featuresBitMask |= id;
}
id *= 2;
}
return featuresBitMask;
},
wgpu_adapter_or_device_supports_feature__deps: ['wgpuFeatures'],
wgpu_adapter_or_device_supports_feature: function(adapterOrDevice, feature) {
{{{ wdebuglog('`wgpu_adapter_or_device_supports_feature(adapterOrDevice: ${adapterOrDevice}, feature: ${feature} == ${_wgpuFeatures[31 - Math.clz32(feature)]})`'); }}}
{{{ wassert('adapterOrDevice != 0'); }}}
{{{ wassert('(adapterOrDevice & (adapterOrDevice-1)) == 0'); }}} // Only call on a single feature at a time, not a bit combination of multiple features!
{{{ wassert('wgpu[adapterOrDevice]'); }}}
{{{ wassert('wgpu[adapterOrDevice] instanceof GPUAdapter || wgpu[adapterOrDevice] instanceof GPUDevice'); }}}
return wgpu[adapterOrDevice]['features'].has(_wgpuFeatures[31 - Math.clz32(feature)])
},
wgpu_adapter_or_device_get_limits__deps: ['wgpu32BitLimitNames', 'wgpu64BitLimitNames', '$wgpuWriteI53ToU64HeapIdx'],
wgpu_adapter_or_device_get_limits: function(adapterOrDevice, limits) {
{{{ wdebuglog('`wgpu_adapter_or_device_get_limits(adapterOrDevice: ${adapterOrDevice}, limits: ${limits})`'); }}}
{{{ wassert('limits != 0, "passed a null limits struct pointer"'); }}}
{{{ wassert('adapterOrDevice != 0'); }}}
{{{ wassert('wgpu[adapterOrDevice]'); }}}
{{{ wassert('wgpu[adapterOrDevice] instanceof GPUAdapter || wgpu[adapterOrDevice] instanceof GPUDevice'); }}}
let l = wgpu[adapterOrDevice]['limits'];
{{{ replacePtrToIdx('limits', 2); }}}
for(let limitName of _wgpu64BitLimitNames) {
{{{ wassert('l[limitName] !== undefined, `Browser WebGPU implementation incorrect: it should advertise limit ${limitName}`'); }}}
wgpuWriteI53ToU64HeapIdx(limits, l[limitName]);
limits += 2;
}
for(let limitName of _wgpu32BitLimitNames) {
HEAPU32[limits++] = l[limitName];
}
},
wgpu_adapter_is_fallback_adapter: function(adapter) {
{{{ wdebuglog('`wgpu_adapter_is_fallback_adapter(adapter: ${adapter}`'); }}}
{{{ wassert('adapter != 0'); }}}
{{{ wassert('wgpu[adapter]'); }}}
{{{ wassert('wgpu[adapter] instanceof GPUAdapter'); }}}
return wgpu[adapter]['isFallbackAdapter'];
},
$wgpuReadSupportedLimits__deps: ['wgpu32BitLimitNames', 'wgpu64BitLimitNames', '$wgpuReadI53FromU64HeapIdx'],
$wgpuReadSupportedLimits: function(heap32Idx) {
let requiredLimits = {}, v;
// Marshal all the complex 64-bit quantities first ..
for(let limitName of _wgpu64BitLimitNames) {
if ((v = wgpuReadI53FromU64HeapIdx(heap32Idx))) requiredLimits[limitName] = v;
heap32Idx += 2;
}
// .. followed by the 32-bit quantities.
for(let limitName of _wgpu32BitLimitNames) {
if ((v = HEAPU32[heap32Idx++])) requiredLimits[limitName] = v;
}
return requiredLimits;
},
$wgpuReadQueueDescriptor: function(heap32Idx) {
return HEAPU32[heap32Idx] ? { 'label': utf8(HEAPU32[heap32Idx]) } : void 0;
},
$wgpuReadFeaturesBitfield__deps: ['wgpuFeatures'],
$wgpuReadFeaturesBitfield: function(heap32Idx) {
let requiredFeatures = [], v = HEAPU32[heap32Idx];
{{{ wassert('_wgpuFeatures.length == 14'); }}}
{{{ wassert('_wgpuFeatures.length <= 30'); }}} // We can only do up to 30 distinct feature bits here with the current code.
for(let i = 0; i < 14/*_wgpuFeatures.length*/; ++i) {
if (v & (1 << i)) requiredFeatures.push(_wgpuFeatures[i]);
}
return requiredFeatures;
},
$wgpuReadDeviceDescriptor__deps: ['$wgpuReadSupportedLimits', '$wgpuReadQueueDescriptor', '$wgpuReadFeaturesBitfield'],
$wgpuReadDeviceDescriptor: function(descriptor) {
{{{ wassert('descriptor != 0'); }}}
{{{ replacePtrToIdx('descriptor', 2); }}}
return {
'requiredLimits': wgpuReadSupportedLimits(descriptor),
'defaultQueue': wgpuReadQueueDescriptor(descriptor+34/*sizeof(WGpuSupportedLimits)*/),
'requiredFeatures': wgpuReadFeaturesBitfield(descriptor+36/*sizeof(WGpuSupportedLimits)+sizeof(WGpuQueueDescriptor)*/)
};
},
wgpu_adapter_request_device_async__deps: ['$wgpuStore', 'wgpuMuteJsExceptions', '$wgpuReadDeviceDescriptor'],
wgpu_adapter_request_device_async__docs: '/** @suppress{checkTypes} */', // This function intentionally calls cb() without args.
wgpu_adapter_request_device_async: function(adapter, descriptor, deviceCallback, userData) {
{{{ wdebuglog('`wgpu_adapter_request_device_async(adapter: ${adapter}, deviceCallback: ${deviceCallback}, userData: ${userData})`'); }}}
{{{ wassert('adapter != 0'); }}}
{{{ wassert('wgpu[adapter]'); }}}
{{{ wassert('wgpu[adapter] instanceof GPUAdapter'); }}}
function cb(device) {
// If device is non-null, initialization succeeded.
{{{ wdebugdir('device', '`wgpu[adapter].requestDevice resolved with following device:`'); }}}
if (device) {
// Register an ID for the queue of this newly created device
wgpuStore(device['queue']);
}
{{{ makeDynCall('vii', 'deviceCallback') }}}(wgpuStore(device), userData);
}
let desc = wgpuReadDeviceDescriptor(descriptor);
{{{ wdebugdir('desc', '`GPUAdapter.requestDevice() with descriptor:`') }}};
wgpu[adapter]['requestDevice'](desc)
.then(_wgpuMuteJsExceptions(cb))
.catch(
#if ASSERTIONS || globalThis.WEBGPU_DEBUG
(e)=>{console.error(`GPUAdapter.requestDevice() Promise failed: ${e}`); cb(/*intentionally omit arg to pass undefined*/)}
#else
()=>{cb(/*intentionally omit arg to pass undefined*/)}
#endif
);
},
#if ASYNCIFY
wgpu_adapter_request_device_sync__deps: ['$wgpuStoreAndSetParent', '$wgpuStoreAsyncifiedOp', '$wgpuReadDeviceDescriptor', '_wgpuNumAsyncifiedOperationsPending', '$wgpu_async'],
//wgpu_adapter_request_device_sync__sig: 'iip', // Iirc this would be needed for -sASYNCIFY=1 build mode, but this breaks -sMEMORY64=1 due to the detrimental automatic wrappers
wgpu_adapter_request_device_sync__async: true,
wgpu_adapter_request_device_sync: function(adapter, descriptor) {
return wgpu_async(() => {
{{{ wdebuglog('`wgpu_adapter_request_device_sync(adapter: ${adapter})`'); }}}
{{{ wassert('adapter != 0'); }}}
{{{ wassert('wgpu[adapter]'); }}}
{{{ wassert('wgpu[adapter] instanceof GPUAdapter'); }}}
function cb(device) {
// If device is non-null, initialization succeeded.
{{{ wdebugdir('device', '`wgpu[adapter].requestDevice resolved with following device:`'); }}}
if (device) {
// Register an ID for the queue of this newly created device
wgpuStoreAndSetParent(device['queue'], device);
}
return wgpuStoreAsyncifiedOp(device, wgpu[adapter]);
}
++__wgpuNumAsyncifiedOperationsPending;
let desc = wgpuReadDeviceDescriptor(descriptor);
{{{ wdebugdir('desc', '`GPUAdapter.requestDevice() with descriptor:`') }}};
return wgpu[adapter]['requestDevice'](desc).then(cb);
});
},
#endif
// A "_simple" variant of wgpu_adapter_request_device_async() that does
// not take in any descriptor params, for building tiny code with default
// args and creating readable test cases etc.
wgpu_adapter_request_device_async_simple__deps: ['$wgpuStoreAndSetParent'],
wgpu_adapter_request_device_async_simple: function(adapter, deviceCallback) {
{{{ wdebuglog('`wgpu_adapter_request_device_async_simple(adapter: ${adapter}, deviceCallback=${deviceCallback})`'); }}}