-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathwebgpuEngine.pure.ts
More file actions
4277 lines (3710 loc) · 188 KB
/
Copy pathwebgpuEngine.pure.ts
File metadata and controls
4277 lines (3710 loc) · 188 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
/** This file must only contain pure code and pure imports */
/* eslint-disable babylonjs/available */
import { Logger } from "../Misc/logger";
import { ThinWebGPUEngine } from "./thinWebGPUEngine";
import { type Nullable, type DataArray, type IndicesArray, type Immutable, type FloatArray } from "../types";
import { Color4 } from "../Maths/math";
import { InternalTexture, InternalTextureSource } from "../Materials/Textures/internalTexture";
import { type IEffectCreationOptions, type IShaderPath, Effect } from "../Materials/effect.pure";
import { type EffectFallbacks } from "../Materials/effectFallbacks";
import { Constants } from "./constants";
// eslint-disable-next-line @typescript-eslint/naming-convention
import * as WebGPUConstants from "./WebGPU/webgpuConstants";
import { VertexBuffer } from "../Buffers/buffer.pure";
import { type IWebGPURenderPipelineStageDescriptor, WebGPUPipelineContext } from "./WebGPU/webgpuPipelineContext";
import { type IPipelineContext } from "./IPipelineContext";
import { type DataBuffer } from "../Buffers/dataBuffer";
import { type BaseTexture } from "../Materials/Textures/baseTexture.pure";
import { type IShaderProcessor } from "./Processors/iShaderProcessor";
import { WebGPUShaderProcessorGLSL } from "./WebGPU/webgpuShaderProcessorsGLSL";
import { WebGPUShaderProcessorWGSL } from "./WebGPU/webgpuShaderProcessorsWGSL.pure";
import { type _IShaderProcessingContext } from "./Processors/shaderProcessingOptions";
import { WebGPUShaderProcessingContext } from "./WebGPU/webgpuShaderProcessingContext";
import { Tools } from "../Misc/tools.pure";
import { WebGPUTextureHelper } from "./WebGPU/webgpuTextureHelper";
import { WebGPUTextureManager } from "./WebGPU/webgpuTextureManager";
import { AbstractEngine, type ISceneLike, type AbstractEngineOptions } from "./abstractEngine.pure";
import { WebGPUBufferManager } from "./WebGPU/webgpuBufferManager";
import { type IHardwareTextureWrapper } from "../Materials/Textures/hardwareTextureWrapper";
import { WebGPUHardwareTexture } from "./WebGPU/webgpuHardwareTexture";
import { type IColor4Like } from "../Maths/math.like";
import { type UniformBuffer } from "../Materials/uniformBuffer";
import { WebGPUCacheSampler } from "./WebGPU/webgpuCacheSampler";
import { WebGPUCacheRenderPipelineTree } from "./WebGPU/webgpuCacheRenderPipelineTree";
import { WebGPUStencilStateComposer } from "./WebGPU/webgpuStencilStateComposer";
import { WebGPUDepthCullingState } from "./WebGPU/webgpuDepthCullingState";
import { type DrawWrapper } from "../Materials/drawWrapper";
import { WebGPUMaterialContext } from "./WebGPU/webgpuMaterialContext";
import { WebGPUDrawContext } from "./WebGPU/webgpuDrawContext";
import { WebGPUCacheBindGroups } from "./WebGPU/webgpuCacheBindGroups";
import { WebGPUClearQuad } from "./WebGPU/webgpuClearQuad.pure";
import { type IStencilState } from "../States/IStencilState";
import { WebGPURenderItemBlendColor, WebGPURenderItemScissor, WebGPURenderItemStencilRef, WebGPURenderItemViewport, WebGPUBundleList } from "./WebGPU/webgpuBundleList";
import { WebGPUTimestampQuery } from "./WebGPU/webgpuTimestampQuery";
import { type ComputeEffect } from "../Compute/computeEffect";
import { WebGPUOcclusionQuery } from "./WebGPU/webgpuOcclusionQuery";
import { ShaderCodeInliner } from "./Processors/shaderCodeInliner";
import { type TwgslOptions, WebGPUTintWASM } from "./WebGPU/webgpuTintWASM";
import { type ExternalTexture } from "../Materials/Textures/externalTexture";
import { WebGPUShaderProcessor } from "./WebGPU/webgpuShaderProcessor";
import { ShaderLanguage } from "../Materials/shaderLanguage";
import { type InternalTextureCreationOptions, type TextureSize } from "../Materials/Textures/textureCreationOptions";
import { WebGPUSnapshotRendering } from "./WebGPU/webgpuSnapshotRendering";
import { type WebGPUDataBuffer } from "../Meshes/WebGPU/webgpuDataBuffer";
import { type WebGPURenderTargetWrapper } from "./WebGPU/webgpuRenderTargetWrapper";
import { AlphaState } from "../States/alphaCullingState";
import { type VideoTexture } from "../Materials/Textures/videoTexture.pure";
import { type RenderTargetTexture } from "../Materials/Textures/renderTargetTexture.pure";
import { type RenderTargetWrapper } from "./renderTargetWrapper";
import { type Scene } from "../scene.pure";
import { type AbstractMesh } from "../Meshes/abstractMesh.pure";
import { SphericalPolynomial } from "../Maths/sphericalPolynomial.pure";
import { PerformanceMonitor } from "../Misc/performanceMonitor";
import {
CreateImageBitmapFromSource,
ExitFullscreen,
ExitPointerlock,
GetFontOffset,
RequestFullscreen,
RequestPointerlock,
ResizeImageBitmap,
_CommonDispose,
_CommonInit,
} from "./engine.common";
import { IsWrapper } from "../Materials/drawWrapper.functions";
import { PerfCounter } from "../Misc/perfCounter";
import { resetCachedPipeline } from "../Materials/effect.functions";
import { RegisterAbstractEngineDom } from "./AbstractEngine/abstractEngine.dom.pure";
import { RegisterAbstractEngineRenderPass } from "./AbstractEngine/abstractEngine.renderPass.pure";
import { WebGPUExternalTexture } from "./WebGPU/webgpuExternalTexture";
import { type TextureSampler } from "../Materials/Textures/textureSampler";
import { type StorageBuffer } from "../Buffers/storageBuffer";
const ViewDescriptorSwapChainAntialiasing: GPUTextureViewDescriptor = {
label: `TextureView_SwapChain_ResolveTarget`,
dimension: WebGPUConstants.TextureDimension.E2d,
format: undefined as any, // will be updated with the right value
mipLevelCount: 1,
arrayLayerCount: 1,
};
const ViewDescriptorSwapChain: GPUTextureViewDescriptor = {
label: `TextureView_SwapChain`,
dimension: WebGPUConstants.TextureDimension.E2d,
format: undefined as any, // will be updated with the right value
mipLevelCount: 1,
arrayLayerCount: 1,
};
const TempColor4 = /*#__PURE__*/ new Color4();
/** @internal */
interface IWebGPURenderPassWrapper {
renderPassDescriptor: Nullable<GPURenderPassDescriptor>;
colorAttachmentViewDescriptor: Nullable<GPUTextureViewDescriptor>;
depthAttachmentViewDescriptor: Nullable<GPUTextureViewDescriptor>;
colorAttachmentGPUTextures: (WebGPUHardwareTexture | null)[];
depthTextureFormat: GPUTextureFormat | undefined;
}
/**
* Options to load the associated Glslang library
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export interface GlslangOptions {
/**
* Defines an existing instance of Glslang (useful in modules who do not access the global instance).
*/
glslang?: any;
/**
* Defines the URL of the glslang JS File.
*/
jsPath?: string;
/**
* Defines the URL of the glslang WASM File.
*/
wasmPath?: string;
}
/**
* Options to create the WebGPU engine
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export interface WebGPUEngineOptions extends AbstractEngineOptions, GPURequestAdapterOptions {
/**
* The featureLevel property of the GPURequestAdapterOptions interface
*/
featureLevel?: string;
/**
* Defines the category of adapter to use.
* Is it the discrete or integrated device.
*/
powerPreference?: GPUPowerPreference;
/**
* When set to true, indicates that only a fallback adapter may be returned when requesting an adapter.
* If the user agent does not support a fallback adapter, will cause requestAdapter() to resolve to null.
* Default: false
*/
forceFallbackAdapter?: boolean;
/**
* When set to true, requests a GPU adapter that is compatible with the user agent's XR device,
* as required to create a WebGPU-compatible WebXR session (see the WebXR/WebGPU binding spec).
* This mirrors the WebGL `xrCompatible` context attribute and must be set when the engine is
* created (adapter-request time): WebGPU has no post-hoc "make XR compatible" step, so it cannot
* be toggled on later. Leave unset/false for the default non-XR path.
* Default: false
*/
xrCompatible?: boolean;
/**
* Defines the device descriptor used to create a device once we have retrieved an appropriate adapter
*/
deviceDescriptor?: GPUDeviceDescriptor;
/**
* When requesting the device, enable all the features supported by the adapter. Default: false
* Note that this setting is ignored if you explicitely set deviceDescriptor.requiredFeatures
*/
enableAllFeatures?: boolean;
/**
* When requesting the device, set the required limits to the maximum possible values (the ones from adapter.limits). Default: false
* Note that this setting is ignored if you explicitely set deviceDescriptor.requiredLimits
*/
setMaximumLimits?: boolean;
/**
* Defines the requested Swap Chain Format.
*/
swapChainFormat?: GPUTextureFormat;
/**
* Defines whether we should generate debug markers in the gpu command lists (can be seen with PIX for eg). Default: false
*/
enableGPUDebugMarkers?: boolean;
/**
* Options to load the associated Glslang library
*/
glslangOptions?: GlslangOptions;
/**
* Options to load the associated Twgsl library
*/
twgslOptions?: TwgslOptions;
}
/**
* Options for pre-warming a render pipeline asynchronously.
* All render state properties are optional and default to the most common opaque rendering state.
*/
export interface IWebGPURenderPipelineAsyncCreationOptions {
/**
* The compiled effect (shader stages) for the pipeline.
*/
effect: Effect;
/**
* The mesh whose vertex buffer layout to use.
*/
mesh: AbstractMesh;
/**
* The fill mode / primitive topology. Defaults to Constants.MATERIAL_TriangleFillMode.
*/
fillMode?: number;
/**
* The MSAA sample count. Defaults to the engine's current sample count.
*/
sampleCount?: number;
/**
* The color render target format. Defaults to the engine's current canvas color format.
*/
colorFormat?: GPUTextureFormat;
/**
* The depth-stencil render target format. Defaults to the engine's current depth format.
*/
depthStencilFormat?: GPUTextureFormat;
/**
* The alpha blending mode (e.g. Constants.ALPHA_DISABLE, Constants.ALPHA_COMBINE).
* Defaults to Constants.ALPHA_DISABLE.
*/
alphaMode?: number;
/**
* Whether depth writing is enabled. Defaults to true.
*/
depthWrite?: boolean;
/**
* Whether depth testing is enabled. Defaults to true.
*/
depthTest?: boolean;
/**
* The depth comparison function (e.g. Constants.LEQUAL). Defaults to Constants.LEQUAL.
*/
depthCompare?: number;
/**
* Whether back-face culling is enabled. Defaults to true.
*/
cullEnabled?: boolean;
/**
* Which face to cull (1 = back, 2 = front). Defaults to 1 (back).
*/
cullFace?: number;
/**
* Front face winding order (1 = CCW, 2 = CW). Defaults to 2 (CW).
*/
frontFace?: number;
/**
* Color channel write mask (bitmask of RGBA channels). Defaults to 0xF (all channels).
*/
writeMask?: number;
/**
* Whether stencil testing is enabled. Defaults to false.
*/
stencilEnabled?: boolean;
}
/**
* The web GPU engine class provides support for WebGPU version of babylon.js.
* @since 5.0.0
*/
export class WebGPUEngine extends ThinWebGPUEngine {
// Default glslang options.
private static readonly _GlslangDefaultOptions: GlslangOptions = {
jsPath: `${Tools._DefaultCdnUrl}/glslang/glslang.js`,
wasmPath: `${Tools._DefaultCdnUrl}/glslang/glslang.wasm`,
};
private static _InstanceId = 0;
/** A unique id to identify this instance */
public readonly uniqueId = -1;
// Page Life cycle and constants
private readonly _uploadEncoderDescriptor = { label: "upload" };
private readonly _renderEncoderDescriptor = { label: "render" };
/** @internal */
public readonly _clearDepthValue = 1;
/** @internal */
public readonly _clearReverseDepthValue = 0;
/** @internal */
public _clearStencilValue = 0;
private readonly _defaultSampleCount = 4; // Only supported value for now.
// Engine Life Cycle
/** @internal */
public _options: WebGPUEngineOptions;
private _glslang: any = null;
private _tintWASM: Nullable<WebGPUTintWASM> = null;
private _glslangAndTintAreFullyLoaded = false;
private _adapter: GPUAdapter;
private _adapterSupportedExtensions: GPUFeatureName[];
private _adapterInfo: GPUAdapterInfo = {
vendor: "",
architecture: "",
device: "",
description: "",
subgroupMinSize: 0,
subgroupMaxSize: 0,
isFallbackAdapter: false,
};
private _adapterSupportedLimits: GPUSupportedLimits;
/** @internal */
public _device: GPUDevice;
private _deviceEnabledExtensions: GPUFeatureName[];
private _deviceLimits: GPUSupportedLimits;
private _context: GPUCanvasContext;
private _mainPassSampleCount: number;
private _glslangOptions?: GlslangOptions;
private _twgslOptions?: TwgslOptions;
/** @internal */
public _bufferManager: WebGPUBufferManager;
private _clearQuad: WebGPUClearQuad;
/** @internal */
public _cacheSampler: WebGPUCacheSampler;
private _cacheBindGroups: WebGPUCacheBindGroups;
private _emptyVertexBuffer: VertexBuffer;
/** @internal */
public _mrtAttachments: number[];
/** @internal */
public _compiledComputeEffects: { [key: string]: ComputeEffect } = {};
/** @internal */
public _counters: {
numEnableEffects: number;
numEnableDrawWrapper: number;
numBundleCreationNonCompatMode: number;
numBundleReuseNonCompatMode: number;
} = {
numEnableEffects: 0,
numEnableDrawWrapper: 0,
numBundleCreationNonCompatMode: 0,
numBundleReuseNonCompatMode: 0,
};
/**
* Counters from last frame
*/
public readonly countersLastFrame: {
numEnableEffects: number;
numEnableDrawWrapper: number;
numBundleCreationNonCompatMode: number;
numBundleReuseNonCompatMode: number;
} = {
numEnableEffects: 0,
numEnableDrawWrapper: 0,
numBundleCreationNonCompatMode: 0,
numBundleReuseNonCompatMode: 0,
};
/**
* Max number of uncaptured error messages to log
*/
public numMaxUncapturedErrors = 20;
/**
* Gets the list of created scenes
*/
public override scenes: Scene[] = [];
/** @internal */
public override _virtualScenes = new Array<Scene>();
// Some of the internal state might change during the render pass.
// This happens mainly during clear for the state
// And when the frame starts to swap the target texture from the swap chain
private _mainTexture: GPUTexture;
private _depthTexture: GPUTexture;
private _mainTextureExtends: GPUExtent3D;
private _depthTextureFormat: GPUTextureFormat | undefined;
private _colorFormat: GPUTextureFormat | null;
/** @internal */
public _ubInvertY: WebGPUDataBuffer;
/** @internal */
public _ubDontInvertY: WebGPUDataBuffer;
private _commandBuffers: GPUCommandBuffer[] = [null as any, null as any];
// Frame Buffer Life Cycle (recreated for each render target pass)
private _mainRenderPassWrapper: IWebGPURenderPassWrapper = {
renderPassDescriptor: null,
colorAttachmentViewDescriptor: null,
depthAttachmentViewDescriptor: null,
colorAttachmentGPUTextures: [],
depthTextureFormat: undefined,
};
private _rttRenderPassWrapper: IWebGPURenderPassWrapper = {
renderPassDescriptor: null,
colorAttachmentViewDescriptor: null,
depthAttachmentViewDescriptor: null,
colorAttachmentGPUTextures: [],
depthTextureFormat: undefined,
};
// DrawCall Life Cycle
// Effect is on the parent class
// protected _currentEffect: Nullable<Effect> = null;
private _defaultDrawContext: WebGPUDrawContext;
private _defaultMaterialContext: WebGPUMaterialContext;
/** @internal */
public override _currentDrawContext: WebGPUDrawContext;
/** @internal */
public override _currentMaterialContext: WebGPUMaterialContext;
private _currentVertexBuffers: { [key: string]: Nullable<VertexBuffer> } = {};
private _currentOverrideVertexBuffers: Nullable<{ [key: string]: Nullable<VertexBuffer> }> = null;
private _currentIndexBuffer: Nullable<DataBuffer> = null;
private _dummyIndexBuffer: WebGPUDataBuffer;
private _colorWriteLocal = true;
private _forceEnableEffect = false;
private _internalFrameCounter = 0;
/**
* Gets or sets the snapshot rendering mode
*/
public override get snapshotRenderingMode(): number {
return this._snapshotRendering.mode;
}
public override set snapshotRenderingMode(mode: number) {
this._snapshotRendering.mode = mode;
}
/**
* Creates a new snapshot at the next frame using the current snapshotRenderingMode
*/
public snapshotRenderingReset(): void {
this._snapshotRendering.reset();
}
/**
* Enables or disables the snapshot rendering mode
* Note that the WebGL engine does not support snapshot rendering so setting the value won't have any effect for this engine
*/
public override get snapshotRendering(): boolean {
return this._snapshotRendering.enabled;
}
public override set snapshotRendering(activate) {
this._snapshotRendering.enabled = activate;
}
/**
* Sets this to true to disable the cache for the samplers. You should do it only for testing purpose!
*/
public get disableCacheSamplers(): boolean {
return this._cacheSampler ? this._cacheSampler.disabled : false;
}
public set disableCacheSamplers(disable: boolean) {
if (this._cacheSampler) {
this._cacheSampler.disabled = disable;
}
}
/**
* Sets this to true to disable the cache for the render pipelines. You should do it only for testing purpose!
*/
public get disableCacheRenderPipelines(): boolean {
return this._cacheRenderPipeline ? this._cacheRenderPipeline.disabled : false;
}
public set disableCacheRenderPipelines(disable: boolean) {
if (this._cacheRenderPipeline) {
this._cacheRenderPipeline.disabled = disable;
}
}
/**
* Sets this to true to disable the cache for the bind groups. You should do it only for testing purpose!
*/
public get disableCacheBindGroups(): boolean {
return this._cacheBindGroups ? this._cacheBindGroups.disabled : false;
}
public set disableCacheBindGroups(disable: boolean) {
if (this._cacheBindGroups) {
this._cacheBindGroups.disabled = disable;
}
}
/**
* Gets a boolean indicating if all created effects are ready
* @returns true if all effects are ready
*/
public areAllEffectsReady(): boolean {
return true;
}
/**
* Get Font size information
* @param font font name
* @returns an object containing ascent, height and descent
*/
public override getFontOffset(font: string): { ascent: number; height: number; descent: number } {
return GetFontOffset(font);
}
/**
* Gets a Promise<boolean> indicating if the engine can be instantiated (ie. if a WebGPU context can be found)
*/
// eslint-disable-next-line no-restricted-syntax
public static get IsSupportedAsync(): Promise<boolean> {
return !navigator.gpu
? Promise.resolve(false)
: navigator.gpu
.requestAdapter()
// eslint-disable-next-line github/no-then
.then(
(adapter: GPUAdapter | null | undefined) => !!adapter,
() => false
)
// eslint-disable-next-line github/no-then
.catch(() => false);
}
/**
* Not supported by WebGPU, you should call IsSupportedAsync instead!
*/
public static get IsSupported(): boolean {
Logger.Warn("You must call IsSupportedAsync for WebGPU!");
return false;
}
/**
* Gets a boolean indicating that the engine supports uniform buffers
*/
public get supportsUniformBuffers(): boolean {
return true;
}
/** Gets the supported extensions by the WebGPU adapter */
public get supportedExtensions(): Immutable<GPUFeatureName[]> {
return this._adapterSupportedExtensions;
}
/** Gets the currently enabled extensions on the WebGPU device */
public get enabledExtensions(): Immutable<GPUFeatureName[]> {
return this._deviceEnabledExtensions;
}
/** Gets the supported limits by the WebGPU adapter */
public get supportedLimits(): GPUSupportedLimits {
return this._adapterSupportedLimits;
}
/** Gets the current limits of the WebGPU device */
public get currentLimits() {
return this._deviceLimits;
}
/**
* Returns a string describing the current engine
*/
public override get description(): string {
const description = this.name + this.version;
return description;
}
/**
* Returns the version of the engine
*/
public get version(): number {
return 1;
}
/**
* Gets an object containing information about the current engine context
* @returns an object containing the vendor, the renderer and the version of the current engine context
*/
public getInfo() {
return {
vendor: this._adapterInfo.vendor || "unknown vendor",
renderer: this._adapterInfo.architecture || "unknown renderer",
version: this._adapterInfo.description || "unknown version",
};
}
/**
* (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL).
* Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken.
* See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details
*/
public override get compatibilityMode() {
return this._compatibilityMode;
}
public override set compatibilityMode(mode: boolean) {
this._compatibilityMode = mode;
}
/** @internal */
public get currentSampleCount(): number {
return this._currentRenderTarget ? this._currentRenderTarget.samples : this._mainPassSampleCount;
}
/**
* Create a new instance of the gpu engine asynchronously
* @param canvas Defines the canvas to use to display the result
* @param options Defines the options passed to the engine to create the GPU context dependencies
* @returns a promise that resolves with the created engine
*/
// eslint-disable-next-line @typescript-eslint/promise-function-async, no-restricted-syntax
public static CreateAsync(canvas: HTMLCanvasElement, options: WebGPUEngineOptions = {}): Promise<WebGPUEngine> {
const engine = new WebGPUEngine(canvas, options);
return new Promise((resolve) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises, github/no-then
engine.initAsync(options.glslangOptions, options.twgslOptions).then(() => resolve(engine));
});
}
/**
* Indicates if the z range in NDC space is 0..1 (value: true) or -1..1 (value: false)
*/
public override readonly isNDCHalfZRange: boolean = true;
/**
* Indicates that the origin of the texture/framebuffer space is the bottom left corner. If false, the origin is top left
*/
public override readonly hasOriginBottomLeft: boolean = false;
/**
* Create a new instance of the gpu engine.
* @param canvas Defines the canvas to use to display the result
* @param options Defines the options passed to the engine to create the GPU context dependencies
*/
public constructor(canvas: HTMLCanvasElement | OffscreenCanvas, options: WebGPUEngineOptions = {}) {
RegisterAbstractEngineDom();
RegisterAbstractEngineRenderPass();
super(options.antialias ?? true, options);
this._name = "WebGPU";
this._drawCalls = new PerfCounter();
options.deviceDescriptor = options.deviceDescriptor || {};
options.enableGPUDebugMarkers = options.enableGPUDebugMarkers ?? false;
this._enableGPUDebugMarkers = options.enableGPUDebugMarkers;
Logger.Log(`Babylon.js v${AbstractEngine.Version} - ${this.description} engine`);
if (!navigator.gpu) {
Logger.Error("WebGPU is not supported by your browser.");
return;
}
options.swapChainFormat = options.swapChainFormat || navigator.gpu.getPreferredCanvasFormat();
this._isWebGPU = true;
this._shaderPlatformName = "WEBGPU";
this._renderingCanvas = canvas as HTMLCanvasElement;
this._options = options;
this._mainPassSampleCount = options.antialias ? this._defaultSampleCount : 1;
if (navigator && navigator.userAgent) {
this._setupMobileChecks();
}
this._sharedInit(this._renderingCanvas);
this._shaderProcessor = new WebGPUShaderProcessorGLSL();
this._shaderProcessorWGSL = new WebGPUShaderProcessorWGSL();
}
//------------------------------------------------------------------------------
// Initialization
//------------------------------------------------------------------------------
private _workingGlslangAndTintPromise: Nullable<Promise<void>> = null;
/**
* Load the glslang and tintWASM libraries and prepare them for use.
* @returns a promise that resolves when the engine is ready to use the glslang and tintWASM
*/
// eslint-disable-next-line @typescript-eslint/promise-function-async, no-restricted-syntax
public prepareGlslangAndTintAsync(): Promise<void> {
if (!this._workingGlslangAndTintPromise) {
this._workingGlslangAndTintPromise = new Promise<void>((resolve) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises, github/no-then
this._initGlslangAsync(this._glslangOptions ?? this._options?.glslangOptions).then((glslang: any) => {
this._glslang = glslang;
this._tintWASM = new WebGPUTintWASM();
// eslint-disable-next-line @typescript-eslint/no-floating-promises, github/no-then
this._tintWASM.initTwgsl(this._twgslOptions ?? this._options?.twgslOptions).then(() => {
this._glslangAndTintAreFullyLoaded = true;
resolve();
});
});
});
}
return this._workingGlslangAndTintPromise;
}
/**
* Initializes the WebGPU context and dependencies.
* @param glslangOptions Defines the GLSLang compiler options if necessary
* @param twgslOptions Defines the Twgsl compiler options if necessary
* @returns a promise notifying the readiness of the engine.
*/
// eslint-disable-next-line @typescript-eslint/promise-function-async, no-restricted-syntax
public initAsync(glslangOptions?: GlslangOptions, twgslOptions?: TwgslOptions): Promise<void> {
(this.uniqueId as number) = WebGPUEngine._InstanceId++;
this._glslangOptions = glslangOptions;
this._twgslOptions = twgslOptions;
return (
navigator
.gpu!.requestAdapter(this._options)
// eslint-disable-next-line github/no-then
.then(async (adapter: GPUAdapter | null | undefined) => {
if (!adapter) {
// eslint-disable-next-line no-throw-literal
throw "Could not retrieve a WebGPU adapter (adapter is null or undefined).";
} else {
this._adapter = adapter!;
this._adapterSupportedExtensions = [];
this._adapter.features?.forEach((feature) => {
this._adapterSupportedExtensions.push(feature as GPUFeatureName);
});
this._adapterSupportedLimits = this._adapter.limits;
this._adapterInfo = this._adapter.info;
const deviceDescriptor = this._options.deviceDescriptor ?? {};
const requiredFeatures = deviceDescriptor?.requiredFeatures ?? (this._options.enableAllFeatures ? this._adapterSupportedExtensions : undefined);
if (requiredFeatures) {
const requestedExtensions = requiredFeatures;
const validExtensions: GPUFeatureName[] = [];
for (const extension of requestedExtensions) {
if (this._adapterSupportedExtensions.indexOf(extension) !== -1) {
validExtensions.push(extension);
}
}
deviceDescriptor.requiredFeatures = validExtensions;
}
if (this._options.setMaximumLimits && !deviceDescriptor.requiredLimits) {
deviceDescriptor.requiredLimits = {};
for (const name in this._adapterSupportedLimits) {
if (name === "minSubgroupSize" || name === "maxSubgroupSize") {
// Chrome exposes these limits in "webgpu developer" mode, but these can't be set on the device.
continue;
}
deviceDescriptor.requiredLimits[name] = this._adapterSupportedLimits[name];
}
}
deviceDescriptor.label = `BabylonWebGPUDevice${this.uniqueId}`;
return await this._adapter.requestDevice(deviceDescriptor);
}
})
// eslint-disable-next-line github/no-then
.then((device: GPUDevice) => {
this._device = device;
this._deviceEnabledExtensions = [];
this._device.features?.forEach((feature) => {
this._deviceEnabledExtensions.push(feature as GPUFeatureName);
});
this._deviceLimits = device.limits;
let numUncapturedErrors = -1;
this._device.addEventListener("uncapturederror", (event) => {
if (++numUncapturedErrors < this.numMaxUncapturedErrors) {
Logger.Warn(
`[Frame ${this._frameId}] WebGPU uncaptured error (${numUncapturedErrors + 1}): ${(<GPUUncapturedErrorEvent>event).error} - ${(<any>event).error.message}`
);
} else if (numUncapturedErrors++ === this.numMaxUncapturedErrors) {
Logger.Warn(
`[Frame ${this._frameId}] WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`
);
}
});
if (!this._doNotHandleContextLost) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises, github/no-then
this._device.lost?.then((info) => {
if (this._isDisposed) {
return;
}
this._contextWasLost = true;
Logger.Warn("WebGPU context lost. " + info);
this.onContextLostObservable.notifyObservers(this);
// eslint-disable-next-line @typescript-eslint/no-misused-promises
this._restoreEngineAfterContextLost(async () => {
const snapshotRenderingMode = this.snapshotRenderingMode;
const snapshotRendering = this.snapshotRendering;
const disableCacheSamplers = this.disableCacheSamplers;
const disableCacheRenderPipelines = this.disableCacheRenderPipelines;
const disableCacheBindGroups = this.disableCacheBindGroups;
const enableGPUTimingMeasurements = this.enableGPUTimingMeasurements;
await this.initAsync(this._glslangOptions ?? this._options?.glslangOptions, this._twgslOptions ?? this._options?.twgslOptions);
this.snapshotRenderingMode = snapshotRenderingMode;
this.snapshotRendering = snapshotRendering;
this.disableCacheSamplers = disableCacheSamplers;
this.disableCacheRenderPipelines = disableCacheRenderPipelines;
this.disableCacheBindGroups = disableCacheBindGroups;
this.enableGPUTimingMeasurements = enableGPUTimingMeasurements;
this._currentRenderPass = null;
});
});
}
})
// eslint-disable-next-line github/no-then
.then(() => {
this._initializeLimits();
this._bufferManager = new WebGPUBufferManager(this, this._device);
this._textureHelper = new WebGPUTextureManager(this, this._device, this._bufferManager, this._deviceEnabledExtensions);
this._cacheSampler = new WebGPUCacheSampler(this._device);
this._cacheBindGroups = new WebGPUCacheBindGroups(this._device, this._cacheSampler, this);
this._timestampQuery = new WebGPUTimestampQuery(this, this._device, this._bufferManager);
this._occlusionQuery = (this._device as any).createQuerySet ? new WebGPUOcclusionQuery(this, this._device, this._bufferManager) : (undefined as any);
this._bundleList = new WebGPUBundleList(this._device);
this._snapshotRendering = new WebGPUSnapshotRendering(this, this._snapshotRenderingMode, this._bundleList);
this._ubInvertY = this._bufferManager.createBuffer(
new Float32Array([-1, 0]),
WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst,
"UBInvertY"
);
this._ubDontInvertY = this._bufferManager.createBuffer(
new Float32Array([1, 0]),
WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst,
"UBDontInvertY"
);
const frameCounter = this._internalFrameCounter++;
this._uploadEncoderDescriptor.label = `[${this.frameId}|${frameCounter}] - UploadEncoder`;
this._renderEncoderDescriptor.label = `[${this.frameId}|${frameCounter}] - RenderEncoder`;
this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
this._emptyVertexBuffer = new VertexBuffer(this, [0], "", {
stride: 1,
offset: 0,
size: 1,
label: "EmptyVertexBuffer",
});
this._dummyIndexBuffer = this._bufferManager.createBuffer(
new Uint16Array([0, 0, 0, 0]),
WebGPUConstants.BufferUsage.Storage | WebGPUConstants.BufferUsage.CopyDst,
"DummyIndices"
);
this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, this._emptyVertexBuffer);
this._depthCullingState = new WebGPUDepthCullingState(this._cacheRenderPipeline);
this._stencilStateComposer = new WebGPUStencilStateComposer(this._cacheRenderPipeline);
this._stencilStateComposer.stencilGlobal = this._stencilState;
this._depthCullingState.depthTest = true;
this._depthCullingState.depthFunc = Constants.LEQUAL;
this._depthCullingState.depthMask = true;
this._textureHelper.setCommandEncoder(this._uploadEncoder);
this._clearQuad = new WebGPUClearQuad(this._device, this, this._emptyVertexBuffer);
this._defaultDrawContext = this.createDrawContext()!;
this._currentDrawContext = this._defaultDrawContext;
this._defaultMaterialContext = this.createMaterialContext()!;
this._currentMaterialContext = this._defaultMaterialContext;
this._initializeContextAndSwapChain();
this._initializeMainAttachments();
this.resize();
})
// eslint-disable-next-line github/no-then
.catch((e: any) => {
Logger.Error("A fatal error occurred during WebGPU creation/initialization.");
throw e;
})
);
}
// eslint-disable-next-line @typescript-eslint/promise-function-async, no-restricted-syntax
private _initGlslangAsync(glslangOptions?: GlslangOptions): Promise<any> {
glslangOptions = glslangOptions || {};
glslangOptions = {
...WebGPUEngine._GlslangDefaultOptions,
...glslangOptions,
};
if (glslangOptions.glslang) {
return glslangOptions.glslang;
}
if ((self as any).glslang) {
return (self as any).glslang(glslangOptions.wasmPath);
}
if (glslangOptions.jsPath && glslangOptions.wasmPath) {
// eslint-disable-next-line github/no-then
return Tools.LoadBabylonScriptAsync(glslangOptions.jsPath).then(() => {
return (self as any).glslang(Tools.GetBabylonScriptURL(glslangOptions.wasmPath!));
});
}
throw new Error("glslang is not available");
}
private _initializeLimits(): void {
// Init caps
const textureFormatsTier1 = this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureFormatsTier1) >= 0;
this._caps = {
maxTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage,
maxVertexTextureImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage,
maxCombinedTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage * 2,
maxTextureSize: this._deviceLimits.maxTextureDimension2D,
maxCubemapTextureSize: this._deviceLimits.maxTextureDimension2D,
maxRenderTextureSize: this._deviceLimits.maxTextureDimension2D,
maxVertexAttribs: this._deviceLimits.maxVertexAttributes,
maxDrawBuffers: 8,
maxVaryingVectors: this._deviceLimits.maxInterStageShaderVariables,
maxFragmentUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4),
maxVertexUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4),
shaderFloatPrecision: 23, // WGSL always uses IEEE-754 binary32 floats (which have 23 bits of significand)
standardDerivatives: true,
astc: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionASTC) >= 0 ? true : undefined) as any,
s3tc: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionBC) >= 0 ? true : undefined) as any,
pvrtc: null,
etc1: null,
etc2: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionETC2) >= 0 ? true : undefined) as any,
bptc: this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionBC) >= 0 ? true : undefined,
maxAnisotropy: 16, // Most implementations support maxAnisotropy values in range between 1 and 16, inclusive. The used value of maxAnisotropy will be clamped to the maximum value that the platform supports.
uintIndices: true,
fragmentDepthSupported: true,
highPrecisionShaderSupported: true,
colorBufferFloat: true,
blendFloat: this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.Float32Blendable) >= 0,
supportFloatTexturesResolve: false, // See https://github.com/gpuweb/gpuweb/issues/3844
rg11b10ufColorRenderable: this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.RG11B10UFloatRenderable) >= 0,
textureFloat: true,
textureFloatLinearFiltering: this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.Float32Filterable) >= 0,
textureFloatRender: true,
textureHalfFloat: true,
textureHalfFloatLinearFiltering: true,
textureHalfFloatRender: true,
textureLOD: true,
texelFetch: true,
drawBuffersExtension: true,
depthTextureExtension: true,
vertexArrayObject: false,
instancedArrays: true,
timerQuery:
typeof BigUint64Array !== "undefined" && this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TimestampQuery) !== -1 ? (true as any) : undefined,
supportOcclusionQuery: typeof BigUint64Array !== "undefined",
canUseTimestampForTimerQuery: true,
multiview: false,
oculusMultiview: false,
parallelShaderCompile: undefined,
blendMinMax: true,
maxMSAASamples: 4, // the spec only supports values of 1 and 4
canUseGLInstanceID: true,
canUseGLVertexID: true,
supportComputeShaders: true,
supportSRGBBuffers: true,
supportTransformFeedbacks: false,
textureMaxLevel: true,
texture2DArrayMaxLayerCount: this._deviceLimits.maxTextureArrayLayers,
disableMorphTargetTexture: false,
textureNorm16: textureFormatsTier1,
blendParametersPerTarget: true,
dualSourceBlending: this._deviceEnabledExtensions.includes(WebGPUConstants.FeatureName.DualSourceBlending),
supportReadWriteStorageTextures: typeof navigator !== "undefined" && navigator.gpu?.wgslLanguageFeatures?.has("readonly_and_readwrite_storage_textures") === true,
};
this._features = {
forceBitmapOverHTMLImageElement: true,
supportRenderAndCopyToLodForFloatTextures: true,
supportDepthStencilTexture: true,
supportShadowSamplers: true,
uniformBufferHardCheckMatrix: false,
allowTexturePrefiltering: true,
trackUbosInFrame: true,
checkUbosContentBeforeUpload: true,
supportCSM: true,
basisNeedsPOT: false,
support3DTextures: true,