-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy paththinEngine.ts
4578 lines (3992 loc) · 188 KB
/
thinEngine.ts
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
/* eslint-disable @typescript-eslint/no-unused-vars */
import type { IEffectCreationOptions, IShaderPath } from "../Materials/effect";
import type { ShaderProcessingContext } from "./Processors/shaderProcessingOptions";
import type { Nullable, DataArray, IndicesArray, FloatArray, DeepImmutable } from "../types";
import type { IColor4Like } from "../Maths/math.like";
import type { DataBuffer } from "../Buffers/dataBuffer";
import type { IPipelineContext } from "./IPipelineContext";
import type { WebGLPipelineContext } from "./WebGL/webGLPipelineContext";
import type { VertexBuffer } from "../Buffers/buffer";
import type { InstancingAttributeInfo } from "./instancingAttributeInfo";
import type { ThinTexture } from "../Materials/Textures/thinTexture";
import type { IEffectFallbacks } from "../Materials/iEffectFallbacks";
import type { HardwareTextureWrapper } from "../Materials/Textures/hardwareTextureWrapper";
import type { DrawWrapper } from "../Materials/drawWrapper";
import type { IMaterialContext } from "./IMaterialContext";
import type { IDrawContext } from "./IDrawContext";
import type { ICanvas, ICanvasRenderingContext } from "./ICanvas";
import type { IStencilState } from "../States/IStencilState";
import type { InternalTextureCreationOptions, TextureSize } from "../Materials/Textures/textureCreationOptions";
import type { RenderTargetWrapper } from "./renderTargetWrapper";
import type { WebGLRenderTargetWrapper } from "./WebGL/webGLRenderTargetWrapper";
import type { VideoTexture } from "../Materials/Textures/videoTexture";
import type { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
import {
createPipelineContext,
createRawShaderProgram,
createShaderProgram,
_finalizePipelineContext,
_preparePipelineContext,
_setProgram,
_executeWhenRenderingStateIsCompiled,
getStateObject,
_createShaderProgram,
deleteStateObject,
_isRenderingStateCompiled,
} from "./thinEngine.functions";
import type { AbstractEngineOptions, ISceneLike, PrepareTextureFunction, PrepareTextureProcessFunction } from "./abstractEngine";
import type { PerformanceMonitor } from "../Misc/performanceMonitor";
import { IsWrapper } from "../Materials/drawWrapper.functions";
import { Logger } from "../Misc/logger";
import { IsWindowObjectExist } from "../Misc/domManagement";
import { WebGLShaderProcessor } from "./WebGL/webGLShaderProcessors";
import { WebGL2ShaderProcessor } from "./WebGL/webGL2ShaderProcessors";
import { WebGLDataBuffer } from "../Meshes/WebGL/webGLDataBuffer";
import { GetExponentOfTwo } from "../Misc/tools.functions";
import { AbstractEngine } from "./abstractEngine";
import { Constants } from "./constants";
import { WebGLHardwareTexture } from "./WebGL/webGLHardwareTexture";
import { ShaderLanguage } from "../Materials/shaderLanguage";
import { InternalTexture, InternalTextureSource } from "../Materials/Textures/internalTexture";
import { Effect } from "../Materials/effect";
import { _ConcatenateShader, _getGlobalDefines } from "./abstractEngine.functions";
import { resetCachedPipeline } from "core/Materials/effect.functions";
import { HasStencilAspect, IsDepthTexture } from "core/Materials/Textures/textureHelper.functions";
/**
* Keeps track of all the buffer info used in engine.
*/
class BufferPointer {
public active: boolean;
public index: number;
public size: number;
public type: number;
public normalized: boolean;
public stride: number;
public offset: number;
public buffer: WebGLBuffer;
}
/** Interface defining initialization parameters for Engine class */
export interface EngineOptions extends AbstractEngineOptions, WebGLContextAttributes {
/**
* Defines if webgl2 should be turned off even if supported
* @see https://doc.babylonjs.com/setup/support/webGL2
*/
disableWebGL2Support?: boolean;
/**
* Defines that engine should compile shaders with high precision floats (if supported). True by default
*/
useHighPrecisionFloats?: boolean;
/**
* Make the canvas XR Compatible for XR sessions
*/
xrCompatible?: boolean;
/**
* Will prevent the system from falling back to software implementation if a hardware device cannot be created
*/
failIfMajorPerformanceCaveat?: boolean;
/**
* If sRGB Buffer support is not set during construction, use this value to force a specific state
* This is added due to an issue when processing textures in chrome/edge/firefox
* This will not influence NativeEngine and WebGPUEngine which set the behavior to true during construction.
*/
forceSRGBBufferSupportState?: boolean;
/**
* Defines if the gl context should be released.
* It's false by default for backward compatibility, but you should probably pass true (see https://registry.khronos.org/webgl/extensions/WEBGL_lose_context/)
*/
loseContextOnDispose?: boolean;
}
/**
* The base engine class (root of all engines)
*/
export class ThinEngine extends AbstractEngine {
private static _TempClearColorUint32 = new Uint32Array(4);
private static _TempClearColorInt32 = new Int32Array(4);
/** Use this array to turn off some WebGL2 features on known buggy browsers version */
public static ExceptionList = [
{ key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
{ key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
{ key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
{ key: "Chrome/72.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
{ key: "Chrome/73.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
{ key: "Chrome/74.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
{ key: "Mac OS.+Chrome/71", capture: null, captureConstraint: null, targets: ["vao"] },
{ key: "Mac OS.+Chrome/72", capture: null, captureConstraint: null, targets: ["vao"] },
{ key: "Mac OS.+Chrome", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
{ key: "Chrome/12\\d\\..+?Mobile", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
// desktop osx safari 15.4
{ key: ".*AppleWebKit.*(15.4).*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] },
// mobile browsers using safari 15.4 on ios
{ key: ".*(15.4).*AppleWebKit.*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] },
];
/** @internal */
protected override _name = "WebGL";
/**
* Gets or sets the name of the engine
*/
public override get name(): string {
return this._name;
}
public override set name(value: string) {
this._name = value;
}
/**
* Returns the version of the engine
*/
public get version(): number {
return this._webGLVersion;
}
/**
* Gets or sets the relative url used to load shaders if using the engine in non-minified mode
*/
public static get ShadersRepository(): string {
return Effect.ShadersRepository;
}
public static set ShadersRepository(value: string) {
Effect.ShadersRepository = value;
}
/**
* Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
*/
public forcePOTTextures = false;
/** Gets or sets a boolean indicating if the engine should validate programs after compilation */
public validateShaderPrograms = false;
/**
* Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
*/
public disableUniformBuffers = false;
/**
* Gets a boolean indicating that the engine supports uniform buffers
* @see https://doc.babylonjs.com/setup/support/webGL2#uniform-buffer-objets
*/
public get supportsUniformBuffers(): boolean {
return this.webGLVersion > 1 && !this.disableUniformBuffers;
}
// Private Members
/** @internal */
public _gl: WebGL2RenderingContext;
/** @internal */
public _webGLVersion = 1.0;
/** @internal */
public _glSRGBExtensionValues: {
SRGB: typeof WebGL2RenderingContext.SRGB;
SRGB8: typeof WebGL2RenderingContext.SRGB8 | EXT_sRGB["SRGB_ALPHA_EXT"];
SRGB8_ALPHA8: typeof WebGL2RenderingContext.SRGB8_ALPHA8 | EXT_sRGB["SRGB_ALPHA_EXT"];
};
/**
* Gets a boolean indicating that only power of 2 textures are supported
* Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
*/
public get needPOTTextures(): boolean {
return this._webGLVersion < 2 || this.forcePOTTextures;
}
private _glVersion: string;
private _glRenderer: string;
private _glVendor: string;
// Cache
/** @internal */
public _currentMaterialContext: IMaterialContext;
/** @internal */
protected _currentProgram: Nullable<WebGLProgram>;
private _vertexAttribArraysEnabled: boolean[] = [];
private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
private _uintIndicesCurrentlySet = false;
protected _currentBoundBuffer = new Array<Nullable<DataBuffer>>();
/** @internal */
public _currentFramebuffer: Nullable<WebGLFramebuffer> = null;
/** @internal */
public _dummyFramebuffer: Nullable<WebGLFramebuffer> = null;
private _currentBufferPointers = new Array<BufferPointer>();
private _currentInstanceLocations = new Array<number>();
private _currentInstanceBuffers = new Array<DataBuffer>();
private _textureUnits: Int32Array;
/** @internal */
public _workingCanvas: Nullable<ICanvas>;
/** @internal */
public _workingContext: Nullable<ICanvasRenderingContext>;
private _vaoRecordInProgress = false;
private _mustWipeVertexAttributes = false;
private _nextFreeTextureSlots = new Array<number>();
private _maxSimultaneousTextures = 0;
private _maxMSAASamplesOverride: Nullable<number> = null;
protected get _supportsHardwareTextureRescaling() {
return false;
}
protected _framebufferDimensionsObject: Nullable<{ framebufferWidth: number; framebufferHeight: number }>;
/**
* sets the object from which width and height will be taken from when getting render width and height
* Will fallback to the gl object
* @param dimensions the framebuffer width and height that will be used.
*/
public set framebufferDimensionsObject(dimensions: Nullable<{ framebufferWidth: number; framebufferHeight: number }>) {
this._framebufferDimensionsObject = dimensions;
}
/**
* Creates a new snapshot at the next frame using the current snapshotRenderingMode
*/
public snapshotRenderingReset(): void {
this.snapshotRendering = false;
}
/**
* Creates a new engine
* @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which already used the WebGL context
* @param antialias defines whether anti-aliasing should be enabled (default value is "undefined", meaning that the browser may or may not enable it)
* @param options defines further options to be sent to the getContext() function
* @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
*/
constructor(
canvasOrContext: Nullable<HTMLCanvasElement | OffscreenCanvas | WebGLRenderingContext | WebGL2RenderingContext>,
antialias?: boolean,
options?: EngineOptions,
adaptToDeviceRatio?: boolean
) {
options = options || {};
super(antialias ?? options.antialias, options, adaptToDeviceRatio);
if (!canvasOrContext) {
return;
}
let canvas: Nullable<HTMLCanvasElement> = null;
if ((canvasOrContext as any).getContext) {
canvas = <HTMLCanvasElement>canvasOrContext;
if (options.preserveDrawingBuffer === undefined) {
options.preserveDrawingBuffer = false;
}
if (options.xrCompatible === undefined) {
options.xrCompatible = false;
}
// Exceptions
if (navigator && navigator.userAgent) {
this._setupMobileChecks();
const ua = navigator.userAgent;
for (const exception of ThinEngine.ExceptionList) {
const key = exception.key;
const targets = exception.targets;
const check = new RegExp(key);
if (check.test(ua)) {
if (exception.capture && exception.captureConstraint) {
const capture = exception.capture;
const constraint = exception.captureConstraint;
const regex = new RegExp(capture);
const matches = regex.exec(ua);
if (matches && matches.length > 0) {
const capturedValue = parseInt(matches[matches.length - 1]);
if (capturedValue >= constraint) {
continue;
}
}
}
for (const target of targets) {
switch (target) {
case "uniformBuffer":
this.disableUniformBuffers = true;
break;
case "vao":
this.disableVertexArrayObjects = true;
break;
case "antialias":
options.antialias = false;
break;
case "maxMSAASamples":
this._maxMSAASamplesOverride = 1;
break;
}
}
}
}
}
// Context lost
if (!this._doNotHandleContextLost) {
this._onContextLost = (evt: Event) => {
evt.preventDefault();
this._contextWasLost = true;
deleteStateObject(this._gl);
Logger.Warn("WebGL context lost.");
this.onContextLostObservable.notifyObservers(this);
};
this._onContextRestored = () => {
this._restoreEngineAfterContextLost(() => this._initGLContext());
};
canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
options.powerPreference = options.powerPreference || "high-performance";
} else {
this._onContextLost = () => {
deleteStateObject(this._gl);
};
}
canvas.addEventListener("webglcontextlost", this._onContextLost, false);
if (this._badDesktopOS) {
options.xrCompatible = false;
}
// GL
if (!options.disableWebGL2Support) {
try {
this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
if (this._gl) {
this._webGLVersion = 2.0;
this._shaderPlatformName = "WEBGL2";
// Prevent weird browsers to lie (yeah that happens!)
if (!this._gl.deleteQuery) {
this._webGLVersion = 1.0;
this._shaderPlatformName = "WEBGL1";
}
}
} catch (e) {
// Do nothing
}
}
if (!this._gl) {
if (!canvas) {
throw new Error("The provided canvas is null or undefined.");
}
try {
this._gl = <WebGL2RenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
} catch (e) {
throw new Error("WebGL not supported");
}
}
if (!this._gl) {
throw new Error("WebGL not supported");
}
} else {
this._gl = <WebGL2RenderingContext>canvasOrContext;
canvas = this._gl.canvas as HTMLCanvasElement;
if ((this._gl as any).renderbufferStorageMultisample) {
this._webGLVersion = 2.0;
this._shaderPlatformName = "WEBGL2";
} else {
this._shaderPlatformName = "WEBGL1";
}
const attributes = this._gl.getContextAttributes();
if (attributes) {
options.stencil = attributes.stencil;
}
}
this._sharedInit(canvas);
// Ensures a consistent color space unpacking of textures cross browser.
this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
if (options.useHighPrecisionFloats !== undefined) {
this._highPrecisionShadersAllowed = options.useHighPrecisionFloats;
}
this.resize();
this._initGLContext();
this._initFeatures();
// Prepare buffer pointers
for (let i = 0; i < this._caps.maxVertexAttribs; i++) {
this._currentBufferPointers[i] = new BufferPointer();
}
// Shader processor
this._shaderProcessor = this.webGLVersion > 1 ? new WebGL2ShaderProcessor() : new WebGLShaderProcessor();
// Starting with iOS 14, we can trust the browser
// let matches = navigator.userAgent.match(/Version\/(\d+)/);
// if (matches && matches.length === 2) {
// if (parseInt(matches[1]) >= 14) {
// this._badOS = false;
// }
// }
const versionToLog = `Babylon.js v${ThinEngine.Version}`;
Logger.Log(versionToLog + ` - ${this.description}`);
// Check setAttribute in case of workers
if (this._renderingCanvas && this._renderingCanvas.setAttribute) {
this._renderingCanvas.setAttribute("data-engine", versionToLog);
}
const stateObject = getStateObject(this._gl);
// update state object with the current engine state
stateObject.validateShaderPrograms = this.validateShaderPrograms;
stateObject.parallelShaderCompile = this._caps.parallelShaderCompile;
}
protected override _clearEmptyResources(): void {
this._dummyFramebuffer = null;
super._clearEmptyResources();
}
/**
* @internal
*/
public _getShaderProcessingContext(shaderLanguage: ShaderLanguage): Nullable<ShaderProcessingContext> {
return null;
}
/**
* Gets a boolean indicating if all created effects are ready
* @returns true if all effects are ready
*/
public areAllEffectsReady(): boolean {
for (const key in this._compiledEffects) {
const effect = <Effect>this._compiledEffects[key];
if (!effect.isReady()) {
return false;
}
}
return true;
}
protected _initGLContext(): void {
// Caps
this._caps = {
maxTexturesImageUnits: this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),
maxCombinedTexturesImageUnits: this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),
maxVertexTextureImageUnits: this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
maxTextureSize: this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),
maxSamples: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_SAMPLES) : 1,
maxCubemapTextureSize: this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),
maxRenderTextureSize: this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),
maxVertexAttribs: this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),
maxVaryingVectors: this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),
maxFragmentUniformVectors: this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),
maxVertexUniformVectors: this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),
parallelShaderCompile: this._gl.getExtension("KHR_parallel_shader_compile") || undefined,
standardDerivatives: this._webGLVersion > 1 || this._gl.getExtension("OES_standard_derivatives") !== null,
maxAnisotropy: 1,
astc: this._gl.getExtension("WEBGL_compressed_texture_astc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),
bptc: this._gl.getExtension("EXT_texture_compression_bptc") || this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),
s3tc: this._gl.getExtension("WEBGL_compressed_texture_s3tc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),
// eslint-disable-next-line @typescript-eslint/naming-convention
s3tc_srgb: this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),
pvrtc: this._gl.getExtension("WEBGL_compressed_texture_pvrtc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),
etc1: this._gl.getExtension("WEBGL_compressed_texture_etc1") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),
etc2:
this._gl.getExtension("WEBGL_compressed_texture_etc") ||
this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc") ||
this._gl.getExtension("WEBGL_compressed_texture_es3_0"), // also a requirement of OpenGL ES 3
textureAnisotropicFilterExtension:
this._gl.getExtension("EXT_texture_filter_anisotropic") ||
this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic") ||
this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),
uintIndices: this._webGLVersion > 1 || this._gl.getExtension("OES_element_index_uint") !== null,
fragmentDepthSupported: this._webGLVersion > 1 || this._gl.getExtension("EXT_frag_depth") !== null,
highPrecisionShaderSupported: false,
timerQuery: this._gl.getExtension("EXT_disjoint_timer_query_webgl2") || this._gl.getExtension("EXT_disjoint_timer_query"),
supportOcclusionQuery: this._webGLVersion > 1,
canUseTimestampForTimerQuery: false,
drawBuffersExtension: false,
maxMSAASamples: 1,
colorBufferFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_float")),
supportFloatTexturesResolve: false,
rg11b10ufColorRenderable: false,
colorBufferHalfFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_half_float")),
textureFloat: this._webGLVersion > 1 || this._gl.getExtension("OES_texture_float") ? true : false,
textureHalfFloat: this._webGLVersion > 1 || this._gl.getExtension("OES_texture_half_float") ? true : false,
textureHalfFloatRender: false,
textureFloatLinearFiltering: false,
textureFloatRender: false,
textureHalfFloatLinearFiltering: false,
vertexArrayObject: false,
instancedArrays: false,
textureLOD: this._webGLVersion > 1 || this._gl.getExtension("EXT_shader_texture_lod") ? true : false,
texelFetch: this._webGLVersion !== 1,
blendMinMax: false,
multiview: this._gl.getExtension("OVR_multiview2"),
oculusMultiview: this._gl.getExtension("OCULUS_multiview"),
depthTextureExtension: false,
canUseGLInstanceID: this._webGLVersion > 1,
canUseGLVertexID: this._webGLVersion > 1,
supportComputeShaders: false,
supportSRGBBuffers: false,
supportTransformFeedbacks: this._webGLVersion > 1,
textureMaxLevel: this._webGLVersion > 1,
texture2DArrayMaxLayerCount: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS) : 128,
disableMorphTargetTexture: false,
textureNorm16: this._gl.getExtension("EXT_texture_norm16") ? true : false,
};
this._caps.supportFloatTexturesResolve = this._caps.colorBufferFloat;
this._caps.rg11b10ufColorRenderable = this._caps.colorBufferFloat;
// Infos
this._glVersion = this._gl.getParameter(this._gl.VERSION);
const rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
if (rendererInfo != null) {
this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
}
if (!this._glVendor) {
this._glVendor = this._gl.getParameter(this._gl.VENDOR) || "Unknown vendor";
}
if (!this._glRenderer) {
this._glRenderer = this._gl.getParameter(this._gl.RENDERER) || "Unknown renderer";
}
// Constants
if (this._gl.HALF_FLOAT_OES !== 0x8d61) {
this._gl.HALF_FLOAT_OES = 0x8d61; // Half floating-point type (16-bit).
}
if (this._gl.RGBA16F !== 0x881a) {
this._gl.RGBA16F = 0x881a; // RGBA 16-bit floating-point color-renderable internal sized format.
}
if (this._gl.RGBA32F !== 0x8814) {
this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
}
if (this._gl.DEPTH24_STENCIL8 !== 35056) {
this._gl.DEPTH24_STENCIL8 = 35056;
}
// Extensions
if (this._caps.timerQuery) {
if (this._webGLVersion === 1) {
this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
}
// WebGLQuery casted to number to avoid TS error
this._caps.canUseTimestampForTimerQuery = ((this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) as number) ?? 0) > 0;
}
this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension
? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT)
: 0;
this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension("OES_texture_float_linear") ? true : false;
this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
this._caps.textureHalfFloatLinearFiltering =
this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension("OES_texture_half_float_linear")) ? true : false;
if (this._caps.textureNorm16) {
this._gl.R16_EXT = 0x822a;
this._gl.RG16_EXT = 0x822c;
this._gl.RGB16_EXT = 0x8054;
this._gl.RGBA16_EXT = 0x805b;
this._gl.R16_SNORM_EXT = 0x8f98;
this._gl.RG16_SNORM_EXT = 0x8f99;
this._gl.RGB16_SNORM_EXT = 0x8f9a;
this._gl.RGBA16_SNORM_EXT = 0x8f9b;
}
// Compressed formats
if (this._caps.astc) {
this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
}
if (this._caps.bptc) {
this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;
}
if (this._caps.s3tc_srgb) {
this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT;
this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
}
if (this._caps.etc2) {
this._gl.COMPRESSED_SRGB8_ETC2 = this._caps.etc2.COMPRESSED_SRGB8_ETC2;
this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
}
// Checks if some of the format renders first to allow the use of webgl inspector.
if (this._webGLVersion > 1) {
if (this._gl.HALF_FLOAT_OES !== 0x140b) {
this._gl.HALF_FLOAT_OES = 0x140b;
}
}
this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
// Draw buffers
if (this._webGLVersion > 1) {
this._caps.drawBuffersExtension = true;
this._caps.maxMSAASamples = this._maxMSAASamplesOverride !== null ? this._maxMSAASamplesOverride : this._gl.getParameter(this._gl.MAX_SAMPLES);
this._caps.maxDrawBuffers = this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS);
} else {
const drawBuffersExtension = this._gl.getExtension("WEBGL_draw_buffers");
if (drawBuffersExtension !== null) {
this._caps.drawBuffersExtension = true;
this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
this._caps.maxDrawBuffers = this._gl.getParameter(drawBuffersExtension.MAX_DRAW_BUFFERS_WEBGL);
(this._gl.DRAW_FRAMEBUFFER as any) = this._gl.FRAMEBUFFER;
for (let i = 0; i < 16; i++) {
(<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
}
}
}
// Depth Texture
if (this._webGLVersion > 1) {
this._caps.depthTextureExtension = true;
} else {
const depthTextureExtension = this._gl.getExtension("WEBGL_depth_texture");
if (depthTextureExtension != null) {
this._caps.depthTextureExtension = true;
this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
}
}
// Vertex array object
if (this.disableVertexArrayObjects) {
this._caps.vertexArrayObject = false;
} else if (this._webGLVersion > 1) {
this._caps.vertexArrayObject = true;
} else {
const vertexArrayObjectExtension = this._gl.getExtension("OES_vertex_array_object");
if (vertexArrayObjectExtension != null) {
this._caps.vertexArrayObject = true;
this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
}
}
// Instances count
if (this._webGLVersion > 1) {
this._caps.instancedArrays = true;
} else {
const instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension("ANGLE_instanced_arrays");
if (instanceExtension != null) {
this._caps.instancedArrays = true;
this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
} else {
this._caps.instancedArrays = false;
}
}
if (this._gl.getShaderPrecisionFormat) {
const vertexhighp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
const fragmenthighp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
if (vertexhighp && fragmenthighp) {
this._caps.highPrecisionShaderSupported = vertexhighp.precision !== 0 && fragmenthighp.precision !== 0;
}
}
if (this._webGLVersion > 1) {
this._caps.blendMinMax = true;
} else {
const blendMinMaxExtension = this._gl.getExtension("EXT_blend_minmax");
if (blendMinMaxExtension != null) {
this._caps.blendMinMax = true;
this._gl.MAX = blendMinMaxExtension.MAX_EXT as typeof WebGL2RenderingContext.MAX;
this._gl.MIN = blendMinMaxExtension.MIN_EXT as typeof WebGL2RenderingContext.MIN;
}
}
// sRGB buffers
// only run this if not already set to true (in the constructor, for example)
if (!this._caps.supportSRGBBuffers) {
if (this._webGLVersion > 1) {
this._caps.supportSRGBBuffers = true;
this._glSRGBExtensionValues = {
SRGB: WebGL2RenderingContext.SRGB,
SRGB8: WebGL2RenderingContext.SRGB8,
SRGB8_ALPHA8: WebGL2RenderingContext.SRGB8_ALPHA8,
};
} else {
const sRGBExtension = this._gl.getExtension("EXT_sRGB");
if (sRGBExtension != null) {
this._caps.supportSRGBBuffers = true;
this._glSRGBExtensionValues = {
SRGB: sRGBExtension.SRGB_EXT as typeof WebGL2RenderingContext.SRGB | EXT_sRGB["SRGB_EXT"],
SRGB8: sRGBExtension.SRGB_ALPHA_EXT as typeof WebGL2RenderingContext.SRGB8 | EXT_sRGB["SRGB_ALPHA_EXT"],
SRGB8_ALPHA8: sRGBExtension.SRGB_ALPHA_EXT as typeof WebGL2RenderingContext.SRGB8_ALPHA8 | EXT_sRGB["SRGB8_ALPHA8_EXT"],
};
}
}
// take into account the forced state that was provided in options
if (this._creationOptions) {
const forceSRGBBufferSupportState = (this._creationOptions as EngineOptions).forceSRGBBufferSupportState;
if (forceSRGBBufferSupportState !== undefined) {
this._caps.supportSRGBBuffers = this._caps.supportSRGBBuffers && forceSRGBBufferSupportState;
}
}
}
// Depth buffer
this._depthCullingState.depthTest = true;
this._depthCullingState.depthFunc = this._gl.LEQUAL;
this._depthCullingState.depthMask = true;
// Texture maps
this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
this._nextFreeTextureSlots.push(slot);
}
if (this._glRenderer === "Mali-G72") {
// Overcome a bug when using a texture to store morph targets on Mali-G72
this._caps.disableMorphTargetTexture = true;
}
}
protected _initFeatures(): void {
this._features = {
forceBitmapOverHTMLImageElement: typeof HTMLImageElement === "undefined",
supportRenderAndCopyToLodForFloatTextures: this._webGLVersion !== 1,
supportDepthStencilTexture: this._webGLVersion !== 1,
supportShadowSamplers: this._webGLVersion !== 1,
uniformBufferHardCheckMatrix: false,
allowTexturePrefiltering: this._webGLVersion !== 1,
trackUbosInFrame: false,
checkUbosContentBeforeUpload: false,
supportCSM: this._webGLVersion !== 1,
basisNeedsPOT: this._webGLVersion === 1,
support3DTextures: this._webGLVersion !== 1,
needTypeSuffixInShaderConstants: this._webGLVersion !== 1,
supportMSAA: this._webGLVersion !== 1,
supportSSAO2: this._webGLVersion !== 1,
supportIBLShadows: this._webGLVersion !== 1,
supportExtendedTextureFormats: this._webGLVersion !== 1,
supportSwitchCaseInShader: this._webGLVersion !== 1,
supportSyncTextureRead: true,
needsInvertingBitmap: true,
useUBOBindingCache: true,
needShaderCodeInlining: false,
needToAlwaysBindUniformBuffers: false,
supportRenderPasses: false,
supportSpriteInstancing: true,
forceVertexBufferStrideAndOffsetMultiple4Bytes: false,
_checkNonFloatVertexBuffersDontRecreatePipelineContext: false,
_collectUbosUpdatedInFrame: false,
};
}
/**
* Gets version of the current webGL context
* Keep it for back compat - use version instead
*/
public get webGLVersion(): number {
return this._webGLVersion;
}
/**
* Gets a string identifying the name of the class
* @returns "Engine" string
*/
public override getClassName(): string {
return "ThinEngine";
}
/** @internal */
public _prepareWorkingCanvas(): void {
if (this._workingCanvas) {
return;
}
this._workingCanvas = this.createCanvas(1, 1);
const context = this._workingCanvas.getContext("2d");
if (context) {
this._workingContext = context;
}
}
/**
* 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 this.getGlInfo();
}
/**
* Gets an object containing information about the current webGL context
* @returns an object containing the vendor, the renderer and the version of the current webGL context
*/
public getGlInfo() {
return {
vendor: this._glVendor,
renderer: this._glRenderer,
version: this._glVersion,
};
}
/**Gets driver info if available */
public extractDriverInfo() {
const glInfo = this.getGlInfo();
if (glInfo && glInfo.renderer) {
return glInfo.renderer;
}
return "";
}
/**
* Gets the current render width
* @param useScreen defines if screen size must be used (or the current render target if any)
* @returns a number defining the current render width
*/
public getRenderWidth(useScreen = false): number {
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.width;
}
return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferWidth : this._gl.drawingBufferWidth;
}
/**
* Gets the current render height
* @param useScreen defines if screen size must be used (or the current render target if any)
* @returns a number defining the current render height
*/
public getRenderHeight(useScreen = false): number {
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.height;
}
return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight;
}
/**
* Clear the current render buffer or the current render target (if any is set up)
* @param color defines the color to use
* @param backBuffer defines if the back buffer must be cleared
* @param depth defines if the depth buffer must be cleared
* @param stencil defines if the stencil buffer must be cleared
*/
public clear(color: Nullable<IColor4Like>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
const useStencilGlobalOnly = this.stencilStateComposer.useStencilGlobalOnly;
this.stencilStateComposer.useStencilGlobalOnly = true; // make sure the stencil mask is coming from the global stencil and not from a material (effect) which would currently be in effect
this.applyStates();
this.stencilStateComposer.useStencilGlobalOnly = useStencilGlobalOnly;
let mode = 0;
if (backBuffer && color) {
let setBackBufferColor = true;
if (this._currentRenderTarget) {
const textureFormat = this._currentRenderTarget.texture?.format;
if (
textureFormat === Constants.TEXTUREFORMAT_RED_INTEGER ||
textureFormat === Constants.TEXTUREFORMAT_RG_INTEGER ||
textureFormat === Constants.TEXTUREFORMAT_RGB_INTEGER ||
textureFormat === Constants.TEXTUREFORMAT_RGBA_INTEGER
) {
const textureType = this._currentRenderTarget.texture?.type;
if (textureType === Constants.TEXTURETYPE_UNSIGNED_INTEGER || textureType === Constants.TEXTURETYPE_UNSIGNED_SHORT) {
ThinEngine._TempClearColorUint32[0] = color.r * 255;
ThinEngine._TempClearColorUint32[1] = color.g * 255;
ThinEngine._TempClearColorUint32[2] = color.b * 255;
ThinEngine._TempClearColorUint32[3] = color.a * 255;
this._gl.clearBufferuiv(this._gl.COLOR, 0, ThinEngine._TempClearColorUint32);
setBackBufferColor = false;
} else {
ThinEngine._TempClearColorInt32[0] = color.r * 255;
ThinEngine._TempClearColorInt32[1] = color.g * 255;
ThinEngine._TempClearColorInt32[2] = color.b * 255;
ThinEngine._TempClearColorInt32[3] = color.a * 255;
this._gl.clearBufferiv(this._gl.COLOR, 0, ThinEngine._TempClearColorInt32);
setBackBufferColor = false;
}
}
}
if (setBackBufferColor) {
this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
mode |= this._gl.COLOR_BUFFER_BIT;
}
}
if (depth) {
if (this.useReverseDepthBuffer) {
this._depthCullingState.depthFunc = this._gl.GEQUAL;
this._gl.clearDepth(0.0);
} else {
this._gl.clearDepth(1.0);
}
mode |= this._gl.DEPTH_BUFFER_BIT;
}
if (stencil) {
this._gl.clearStencil(0);
mode |= this._gl.STENCIL_BUFFER_BIT;
}
this._gl.clear(mode);
}
/**
* @internal
*/
public _viewport(x: number, y: number, width: number, height: number): void {
if (x !== this._viewportCached.x || y !== this._viewportCached.y || width !== this._viewportCached.z || height !== this._viewportCached.w) {
this._viewportCached.x = x;
this._viewportCached.y = y;
this._viewportCached.z = width;
this._viewportCached.w = height;
this._gl.viewport(x, y, width, height);
}
}
/**
* End the current frame
*/
public override endFrame(): void {
super.endFrame();
// Force a flush in case we are using a bad OS.
if (this._badOS) {
this.flushFramebuffer();
}
}
/**
* Gets the performance monitor attached to this engine
* @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation
*/
public get performanceMonitor(): PerformanceMonitor {
throw new Error("Not Supported by ThinEngine");
}
/**
* Binds the frame buffer to the specified texture.