@babylonjs/core 8.45.3 → 8.45.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/AudioV2/webAudio/components/webAudioParameterComponent.js +5 -1
  2. package/AudioV2/webAudio/components/webAudioParameterComponent.js.map +1 -1
  3. package/Cameras/touchCamera.js +1 -1
  4. package/Cameras/touchCamera.js.map +1 -1
  5. package/Engines/AbstractEngine/abstractEngine.loadFile.d.ts +11 -0
  6. package/Engines/AbstractEngine/abstractEngine.loadFile.js +12 -0
  7. package/Engines/AbstractEngine/abstractEngine.loadFile.js.map +1 -0
  8. package/Engines/AbstractEngine/abstractEngine.textureLoaders.d.ts +1 -0
  9. package/Engines/AbstractEngine/abstractEngine.textureLoaders.js +4 -0
  10. package/Engines/AbstractEngine/abstractEngine.textureLoaders.js.map +1 -0
  11. package/Engines/AbstractEngine/index.d.ts +2 -0
  12. package/Engines/AbstractEngine/index.js +2 -0
  13. package/Engines/AbstractEngine/index.js.map +1 -1
  14. package/Engines/Native/Extensions/index.d.ts +1 -0
  15. package/Engines/Native/Extensions/index.js +2 -0
  16. package/Engines/Native/Extensions/index.js.map +1 -0
  17. package/Engines/Native/Extensions/nativeEngine.cubeTexture.d.ts +27 -0
  18. package/Engines/Native/Extensions/nativeEngine.cubeTexture.js +96 -0
  19. package/Engines/Native/Extensions/nativeEngine.cubeTexture.js.map +1 -0
  20. package/Engines/Native/nativeHelpers.js +7 -0
  21. package/Engines/Native/nativeHelpers.js.map +1 -1
  22. package/Engines/Native/nativeInterfaces.d.ts +2 -0
  23. package/Engines/Native/nativeInterfaces.js.map +1 -1
  24. package/Engines/Native/nativePipelineContext.d.ts +2 -2
  25. package/Engines/Native/nativePipelineContext.js.map +1 -1
  26. package/Engines/Native/nativeRenderTargetWrapper.d.ts +3 -3
  27. package/Engines/Native/nativeRenderTargetWrapper.js.map +1 -1
  28. package/Engines/Native/validatedNativeDataStream.js +2 -2
  29. package/Engines/Native/validatedNativeDataStream.js.map +1 -1
  30. package/Engines/abstractEngine.d.ts +9 -0
  31. package/Engines/abstractEngine.js +13 -4
  32. package/Engines/abstractEngine.js.map +1 -1
  33. package/Engines/engine.d.ts +2 -6
  34. package/Engines/engine.js +2 -13
  35. package/Engines/engine.js.map +1 -1
  36. package/Engines/index.d.ts +1 -0
  37. package/Engines/index.js +1 -0
  38. package/Engines/index.js.map +1 -1
  39. package/Engines/nativeEngine.d.ts +19 -536
  40. package/Engines/nativeEngine.js +27 -2127
  41. package/Engines/nativeEngine.js.map +1 -1
  42. package/Engines/nullEngine.d.ts +2 -0
  43. package/Engines/nullEngine.js +2 -0
  44. package/Engines/nullEngine.js.map +1 -1
  45. package/Engines/thinNativeEngine.d.ts +537 -0
  46. package/Engines/thinNativeEngine.js +2033 -0
  47. package/Engines/thinNativeEngine.js.map +1 -0
  48. package/Engines/webgpuEngine.d.ts +2 -0
  49. package/Engines/webgpuEngine.js +2 -0
  50. package/Engines/webgpuEngine.js.map +1 -1
  51. package/FrameGraph/Node/nodeRenderGraph.d.ts +0 -5
  52. package/FrameGraph/Node/nodeRenderGraph.js +0 -7
  53. package/FrameGraph/Node/nodeRenderGraph.js.map +1 -1
  54. package/FrameGraph/frameGraph.d.ts +0 -6
  55. package/FrameGraph/frameGraph.js +0 -23
  56. package/FrameGraph/frameGraph.js.map +1 -1
  57. package/FrameGraph/frameGraphObjectList.d.ts +0 -1
  58. package/FrameGraph/frameGraphObjectList.js +0 -1
  59. package/FrameGraph/frameGraphObjectList.js.map +1 -1
  60. package/FrameGraph/frameGraphRenderContext.d.ts +0 -1
  61. package/FrameGraph/frameGraphRenderContext.js +0 -1
  62. package/FrameGraph/frameGraphRenderContext.js.map +1 -1
  63. package/FrameGraph/frameGraphRenderTarget.d.ts +0 -1
  64. package/FrameGraph/frameGraphRenderTarget.js +0 -1
  65. package/FrameGraph/frameGraphRenderTarget.js.map +1 -1
  66. package/FrameGraph/frameGraphTask.d.ts +0 -1
  67. package/FrameGraph/frameGraphTask.js +0 -1
  68. package/FrameGraph/frameGraphTask.js.map +1 -1
  69. package/FrameGraph/frameGraphTextureManager.d.ts +0 -1
  70. package/FrameGraph/frameGraphTextureManager.js +0 -1
  71. package/FrameGraph/frameGraphTextureManager.js.map +1 -1
  72. package/Meshes/GaussianSplatting/gaussianSplattingMesh.d.ts +6 -0
  73. package/Meshes/GaussianSplatting/gaussianSplattingMesh.js +100 -41
  74. package/Meshes/GaussianSplatting/gaussianSplattingMesh.js.map +1 -1
  75. package/Misc/tools.d.ts +3 -1
  76. package/Misc/tools.js +76 -59
  77. package/Misc/tools.js.map +1 -1
  78. package/Particles/Node/Blocks/Update/updateFlowMapBlock.d.ts +4 -14
  79. package/Particles/Node/Blocks/Update/updateFlowMapBlock.js +9 -27
  80. package/Particles/Node/Blocks/Update/updateFlowMapBlock.js.map +1 -1
  81. package/Particles/Node/Blocks/index.d.ts +2 -0
  82. package/Particles/Node/Blocks/index.js +2 -0
  83. package/Particles/Node/Blocks/index.js.map +1 -1
  84. package/Particles/Node/Blocks/particleClampBlock.d.ts +42 -0
  85. package/Particles/Node/Blocks/particleClampBlock.js +114 -0
  86. package/Particles/Node/Blocks/particleClampBlock.js.map +1 -0
  87. package/Particles/Node/Blocks/particleVectorMathBlock.d.ts +3 -7
  88. package/Particles/Node/Blocks/particleVectorMathBlock.js +15 -32
  89. package/Particles/Node/Blocks/particleVectorMathBlock.js.map +1 -1
  90. package/Particles/Node/Blocks/systemBlock.d.ts +4 -0
  91. package/Particles/Node/Blocks/systemBlock.js +9 -1
  92. package/Particles/Node/Blocks/systemBlock.js.map +1 -1
  93. package/Particles/Node/nodeParticleSystemSet.helper.js +62 -4
  94. package/Particles/Node/nodeParticleSystemSet.helper.js.map +1 -1
  95. package/Particles/baseParticleSystem.d.ts +7 -0
  96. package/Particles/baseParticleSystem.js +7 -0
  97. package/Particles/baseParticleSystem.js.map +1 -1
  98. package/Particles/particleSystem.d.ts +12 -0
  99. package/Particles/particleSystem.js +12 -0
  100. package/Particles/particleSystem.js.map +1 -1
  101. package/Particles/thinParticleSystem.d.ts +10 -0
  102. package/Particles/thinParticleSystem.js +10 -1
  103. package/Particles/thinParticleSystem.js.map +1 -1
  104. package/XR/native/nativeXRFrame.js +1 -1
  105. package/XR/native/nativeXRFrame.js.map +1 -1
  106. package/package.json +1 -1
@@ -1,2150 +1,50 @@
1
- import { Engine } from "../Engines/engine.js";
2
- import { InternalTexture } from "../Materials/Textures/internalTexture.js";
3
- import { Texture } from "../Materials/Textures/texture.js";
4
- import { DataBuffer } from "../Buffers/dataBuffer.js";
5
- import { Tools } from "../Misc/tools.js";
6
- import { Observable } from "../Misc/observable.js";
7
- import { CreateRadianceImageDataArrayBufferViews, GetEnvInfo, UploadEnvSpherical } from "../Misc/environmentTextureTools.js";
8
- import { Logger } from "../Misc/logger.js";
9
-
10
- import { ThinEngine } from "./thinEngine.js";
11
- import { EngineStore } from "./engineStore.js";
12
- import { ShaderCodeInliner } from "./Processors/shaderCodeInliner.js";
13
- import { NativeShaderProcessor } from "./Native/nativeShaderProcessors.js";
14
- import { NativeDataStream } from "./Native/nativeDataStream.js";
15
- import { NativePipelineContext } from "./Native/nativePipelineContext.js";
16
- import { NativeRenderTargetWrapper } from "./Native/nativeRenderTargetWrapper.js";
17
- import { NativeHardwareTexture } from "./Native/nativeHardwareTexture.js";
18
- import { getNativeAlphaMode, getNativeAttribType, getNativeSamplingMode, getNativeTextureFormat, getNativeStencilDepthFail, getNativeStencilDepthPass, getNativeStencilFunc, getNativeStencilOpFail, getNativeAddressMode, } from "./Native/nativeHelpers.js";
19
- import { checkNonFloatVertexBuffers } from "../Buffers/buffer.nonFloatVertexBuffers.js";
20
- import { NativeShaderProcessingContext } from "./Native/nativeShaderProcessingContext.js";
21
- import "../Buffers/buffer.align.js";
22
- import { _GetCompatibleTextureLoader } from "../Materials/Textures/Loaders/textureLoaderManager.js";
23
- import { _TimeToken } from "../Instrumentation/timeToken.js";
24
- const onNativeObjectInitialized = new Observable();
25
- if (typeof self !== "undefined" && !Object.prototype.hasOwnProperty.call(self, "_native")) {
26
- let __native;
27
- Object.defineProperty(self, "_native", {
28
- get: () => __native,
29
- set: (value) => {
30
- __native = value;
31
- if (__native) {
32
- onNativeObjectInitialized.notifyObservers(__native);
33
- }
34
- },
35
- });
36
- }
37
- /**
38
- * Returns _native only after it has been defined by BabylonNative.
39
- * @internal
40
- */
41
- export async function AcquireNativeObjectAsync() {
42
- return await new Promise((resolve) => {
43
- if (typeof _native === "undefined") {
44
- onNativeObjectInitialized.addOnce((nativeObject) => resolve(nativeObject));
45
- }
46
- else {
47
- resolve(_native);
48
- }
49
- });
50
- }
51
- /**
52
- * Registers a constructor on the _native object. See NativeXRFrame for an example.
53
- * @internal
54
- */
55
- export async function RegisterNativeTypeAsync(typeName, constructor) {
56
- (await AcquireNativeObjectAsync())[typeName] = constructor;
57
- }
58
- /**
59
- * Container for accessors for natively-stored mesh data buffers.
60
- */
61
- class NativeDataBuffer extends DataBuffer {
62
- }
63
- /** @internal */
64
- class CommandBufferEncoder {
65
- constructor(_engine) {
66
- this._engine = _engine;
67
- this._pending = new Array();
68
- this._isCommandBufferScopeActive = false;
69
- this._commandStream = NativeEngine._createNativeDataStream();
70
- this._engine.setCommandDataStream(this._commandStream);
71
- }
72
- beginCommandScope() {
73
- if (this._isCommandBufferScopeActive) {
74
- throw new Error("Command scope already active.");
75
- }
76
- this._isCommandBufferScopeActive = true;
77
- }
78
- endCommandScope() {
79
- if (!this._isCommandBufferScopeActive) {
80
- throw new Error("Command scope is not active.");
81
- }
82
- this._isCommandBufferScopeActive = false;
83
- this._submit();
84
- }
85
- startEncodingCommand(command) {
86
- this._commandStream.writeNativeData(command);
87
- }
88
- encodeCommandArgAsUInt32(commandArg) {
89
- this._commandStream.writeUint32(commandArg);
90
- }
91
- encodeCommandArgAsUInt32s(commandArg) {
92
- this._commandStream.writeUint32Array(commandArg);
93
- }
94
- encodeCommandArgAsInt32(commandArg) {
95
- this._commandStream.writeInt32(commandArg);
96
- }
97
- encodeCommandArgAsInt32s(commandArg) {
98
- this._commandStream.writeInt32Array(commandArg);
99
- }
100
- encodeCommandArgAsFloat32(commandArg) {
101
- this._commandStream.writeFloat32(commandArg);
102
- }
103
- encodeCommandArgAsFloat32s(commandArg) {
104
- this._commandStream.writeFloat32Array(commandArg);
105
- }
106
- encodeCommandArgAsNativeData(commandArg) {
107
- this._commandStream.writeNativeData(commandArg);
108
- this._pending.push(commandArg);
109
- }
110
- finishEncodingCommand() {
111
- if (!this._isCommandBufferScopeActive) {
112
- this._submit();
113
- }
114
- }
115
- _submit() {
116
- this._engine.submitCommands();
117
- this._pending.length = 0;
118
- }
119
- }
120
- const remappedAttributesNames = [];
1
+ /* eslint-disable @typescript-eslint/naming-convention */
2
+ import { Engine } from "./engine.js";
3
+ import { ThinNativeEngine } from "./thinNativeEngine.js";
4
+ import "./AbstractEngine/abstractEngine.loadFile.js";
5
+ import "./AbstractEngine/abstractEngine.textureLoaders.js";
6
+ import "./Native/Extensions/nativeEngine.cubeTexture.js";
121
7
  /** @internal */
122
8
  export class NativeEngine extends Engine {
123
- setHardwareScalingLevel(level) {
124
- super.setHardwareScalingLevel(level);
125
- this._engine.setHardwareScalingLevel(level);
126
- }
127
- constructor(options = {}) {
128
- super(null, false, undefined, options.adaptToDeviceRatio);
129
- this._engine = new _native.Engine({
130
- version: Engine.Version,
131
- nonFloatVertexBuffers: true,
132
- });
133
- this._camera = _native.Camera ? new _native.Camera() : null;
134
- this._commandBufferEncoder = new CommandBufferEncoder(this._engine);
135
- this._frameStats = { gpuTimeNs: Number.NaN };
136
- this._boundBuffersVertexArray = null;
137
- this._currentDepthTest = _native.Engine.DEPTH_TEST_LEQUAL;
138
- this._stencilTest = false;
139
- this._stencilMask = 255;
140
- this._stencilFunc = 519;
141
- this._stencilFuncRef = 0;
142
- this._stencilFuncMask = 255;
143
- this._stencilOpStencilFail = 7680;
144
- this._stencilOpDepthFail = 7680;
145
- this._stencilOpStencilDepthPass = 7681;
146
- this._zOffset = 0;
147
- this._zOffsetUnits = 0;
148
- this._depthWrite = true;
149
- // warning for non supported fill mode has already been displayed
150
- this._fillModeWarningDisplayed = false;
151
- if (_native.Engine.PROTOCOL_VERSION !== NativeEngine.PROTOCOL_VERSION) {
152
- throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${NativeEngine.PROTOCOL_VERSION} (JS)`);
153
- }
154
- if (this._engine.setDeviceLostCallback) {
155
- this._engine.setDeviceLostCallback(() => {
156
- this.onContextLostObservable.notifyObservers(this);
157
- this._contextWasLost = true;
158
- this._restoreEngineAfterContextLost();
159
- });
160
- }
161
- this._webGLVersion = 2;
162
- this.disableUniformBuffers = true;
163
- this._shaderPlatformName = "NATIVE";
164
- // TODO: Initialize this more correctly based on the hardware capabilities.
165
- // Init caps
166
- this._caps = {
167
- maxTexturesImageUnits: 16,
168
- maxVertexTextureImageUnits: 16,
169
- maxCombinedTexturesImageUnits: 32,
170
- maxTextureSize: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,
171
- maxCubemapTextureSize: 512,
172
- maxRenderTextureSize: 512,
173
- maxVertexAttribs: 16,
174
- maxVaryingVectors: 16,
175
- maxDrawBuffers: 8,
176
- maxFragmentUniformVectors: 16,
177
- maxVertexUniformVectors: 16,
178
- shaderFloatPrecision: 23, // TODO: is this correct?
179
- standardDerivatives: true,
180
- astc: null,
181
- pvrtc: null,
182
- etc1: null,
183
- etc2: null,
184
- bptc: null,
185
- maxAnisotropy: 16, // TODO: Retrieve this smartly. Currently set to D3D11 maximum allowable value.
186
- uintIndices: true,
187
- fragmentDepthSupported: false,
188
- highPrecisionShaderSupported: true,
189
- colorBufferFloat: false,
190
- blendFloat: false,
191
- supportFloatTexturesResolve: false,
192
- rg11b10ufColorRenderable: false,
193
- textureFloat: true,
194
- textureFloatLinearFiltering: true,
195
- textureFloatRender: true,
196
- textureHalfFloat: true,
197
- textureHalfFloatLinearFiltering: true,
198
- textureHalfFloatRender: true,
199
- textureLOD: true,
200
- texelFetch: false,
201
- drawBuffersExtension: false,
202
- depthTextureExtension: false,
203
- vertexArrayObject: true,
204
- instancedArrays: true,
205
- supportOcclusionQuery: false,
206
- canUseTimestampForTimerQuery: false,
207
- blendMinMax: false,
208
- maxMSAASamples: 16,
209
- canUseGLInstanceID: true,
210
- canUseGLVertexID: true,
211
- supportComputeShaders: false,
212
- supportSRGBBuffers: true,
213
- supportTransformFeedbacks: false,
214
- textureMaxLevel: false,
215
- texture2DArrayMaxLayerCount: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,
216
- disableMorphTargetTexture: false,
217
- parallelShaderCompile: { COMPLETION_STATUS_KHR: 0 },
218
- textureNorm16: false,
219
- blendParametersPerTarget: false,
220
- dualSourceBlending: false,
221
- };
222
- this._features = {
223
- forceBitmapOverHTMLImageElement: true,
224
- supportRenderAndCopyToLodForFloatTextures: false,
225
- supportDepthStencilTexture: false,
226
- supportShadowSamplers: false,
227
- uniformBufferHardCheckMatrix: false,
228
- allowTexturePrefiltering: false,
229
- trackUbosInFrame: false,
230
- checkUbosContentBeforeUpload: false,
231
- supportCSM: false,
232
- basisNeedsPOT: false,
233
- support3DTextures: false,
234
- needTypeSuffixInShaderConstants: false,
235
- supportMSAA: true,
236
- supportSSAO2: false,
237
- supportIBLShadows: false,
238
- supportExtendedTextureFormats: false,
239
- supportSwitchCaseInShader: false,
240
- supportSyncTextureRead: false,
241
- needsInvertingBitmap: true,
242
- useUBOBindingCache: true,
243
- needShaderCodeInlining: true,
244
- needToAlwaysBindUniformBuffers: false,
245
- supportRenderPasses: true,
246
- supportSpriteInstancing: false,
247
- forceVertexBufferStrideAndOffsetMultiple4Bytes: true,
248
- _checkNonFloatVertexBuffersDontRecreatePipelineContext: false,
249
- _collectUbosUpdatedInFrame: false,
250
- };
251
- Tools.Log("Babylon Native (v" + Engine.Version + ") launched");
252
- Tools.LoadScript = function (scriptUrl, onSuccess, onError, scriptId) {
253
- Tools.LoadFile(scriptUrl, (data) => {
254
- Function(data).apply(null);
255
- if (onSuccess) {
256
- onSuccess();
257
- }
258
- }, undefined, undefined, false, (request, exception) => {
259
- if (onError) {
260
- onError("LoadScript Error", exception);
261
- }
262
- });
263
- };
264
- // Wrappers
265
- if (typeof URL === "undefined") {
266
- window.URL = {
267
- createObjectURL: function () { },
268
- revokeObjectURL: function () { },
269
- };
270
- }
271
- // TODO: Remove in next protocol version update
272
- if (typeof Blob === "undefined") {
273
- window.Blob = function (v) {
274
- return v;
275
- };
276
- }
277
- // polyfill for Chakra
278
- if (!Array.prototype.flat) {
279
- Object.defineProperty(Array.prototype, "flat", {
280
- configurable: true,
281
- value: function flat() {
282
- const depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]);
283
- return depth
284
- ? Array.prototype.reduce.call(this, function (acc, cur) {
285
- if (Array.isArray(cur)) {
286
- // eslint-disable-next-line prefer-spread
287
- acc.push.apply(acc, flat.call(cur, depth - 1));
288
- }
289
- else {
290
- acc.push(cur);
291
- }
292
- return acc;
293
- }, [])
294
- : Array.prototype.slice.call(this);
295
- },
296
- writable: true,
297
- });
298
- }
299
- // Currently we do not fully configure the ThinEngine on construction of NativeEngine.
300
- // Setup resolution scaling based on display settings.
301
- const devicePixelRatio = window ? window.devicePixelRatio || 1.0 : 1.0;
302
- this._hardwareScalingLevel = options.adaptToDeviceRatio ? 1.0 / devicePixelRatio : 1.0;
303
- this._engine.setHardwareScalingLevel(this._hardwareScalingLevel);
304
- this._lastDevicePixelRatio = devicePixelRatio;
305
- this.resize();
306
- const currentDepthFunction = this.getDepthFunction();
307
- if (currentDepthFunction) {
308
- this.setDepthFunction(currentDepthFunction);
309
- }
310
- // Shader processor
311
- this._shaderProcessor = new NativeShaderProcessor();
312
- this.onNewSceneAddedObservable.add((scene) => {
313
- const originalRender = scene.render;
314
- scene.render = (...args) => {
315
- this._commandBufferEncoder.beginCommandScope();
316
- originalRender.apply(scene, args);
317
- this._commandBufferEncoder.endCommandScope();
318
- };
319
- });
320
- }
321
- dispose() {
322
- super.dispose();
323
- if (this._boundBuffersVertexArray) {
324
- this._deleteVertexArray(this._boundBuffersVertexArray);
325
- }
326
- this._engine.dispose();
327
- }
328
- /** @internal */
329
- static _createNativeDataStream() {
330
- return new NativeDataStream();
331
- }
332
- /**
333
- * Can be used to override the current requestAnimationFrame requester.
334
- * @internal
335
- */
336
- _queueNewFrame(bindedRenderFunction, requester) {
337
- // Use the provided requestAnimationFrame, unless the requester is the window. In that case, we will default to the Babylon Native version of requestAnimationFrame.
338
- if (requester.requestAnimationFrame && requester !== window) {
339
- requester.requestAnimationFrame(bindedRenderFunction);
340
- }
341
- else {
342
- this._engine.requestAnimationFrame(bindedRenderFunction);
343
- }
344
- return 0;
345
- }
346
- _restoreEngineAfterContextLost() {
347
- this._clearEmptyResources();
348
- const depthTest = this._depthCullingState.depthTest; // backup those values because the call to initEngine / wipeCaches will reset them
349
- const depthFunc = this._depthCullingState.depthFunc;
350
- const depthMask = this._depthCullingState.depthMask;
351
- const stencilTest = this._stencilState.stencilTest;
352
- this._rebuildGraphicsResources();
353
- this._depthCullingState.depthTest = depthTest;
354
- this._depthCullingState.depthFunc = depthFunc;
355
- this._depthCullingState.depthMask = depthMask;
356
- this._stencilState.stencilTest = stencilTest;
357
- this._flagContextRestored();
358
- }
359
- /**
360
- * Override default engine behavior.
361
- * @param framebuffer
362
- */
363
- _bindUnboundFramebuffer(framebuffer) {
364
- if (this._currentFramebuffer !== framebuffer) {
365
- if (this._currentFramebuffer) {
366
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER);
367
- this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer);
368
- this._commandBufferEncoder.finishEncodingCommand();
369
- }
370
- if (framebuffer) {
371
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER);
372
- this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer);
373
- this._commandBufferEncoder.finishEncodingCommand();
374
- }
375
- this._currentFramebuffer = framebuffer;
376
- }
377
- }
378
- /**
379
- * Gets host document
380
- * @returns the host document object
381
- */
382
- getHostDocument() {
383
- return null;
384
- }
385
- clear(color, backBuffer, depth, stencil = false, stencilClearValue = 0) {
386
- if (this.useReverseDepthBuffer) {
387
- throw new Error("reverse depth buffer is not currently implemented");
388
- }
389
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR);
390
- this._commandBufferEncoder.encodeCommandArgAsUInt32(backBuffer && color ? 1 : 0);
391
- this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.r : 0);
392
- this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.g : 0);
393
- this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.b : 0);
394
- this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.a : 1);
395
- this._commandBufferEncoder.encodeCommandArgAsUInt32(depth ? 1 : 0);
396
- this._commandBufferEncoder.encodeCommandArgAsFloat32(1);
397
- this._commandBufferEncoder.encodeCommandArgAsUInt32(stencil ? 1 : 0);
398
- this._commandBufferEncoder.encodeCommandArgAsUInt32(stencilClearValue);
399
- this._commandBufferEncoder.finishEncodingCommand();
400
- }
401
- createIndexBuffer(indices, updateable, _label) {
402
- const data = this._normalizeIndexData(indices);
403
- const buffer = new NativeDataBuffer();
404
- buffer.references = 1;
405
- buffer.is32Bits = data.BYTES_PER_ELEMENT === 4;
406
- if (data.byteLength) {
407
- buffer.nativeIndexBuffer = this._engine.createIndexBuffer(data.buffer, data.byteOffset, data.byteLength, buffer.is32Bits, updateable ?? false);
408
- }
409
- return buffer;
410
- }
411
- createVertexBuffer(vertices, updateable, _label) {
412
- const data = ArrayBuffer.isView(vertices) ? vertices : new Float32Array(vertices);
413
- const buffer = new NativeDataBuffer();
414
- buffer.references = 1;
415
- if (data.byteLength) {
416
- buffer.nativeVertexBuffer = this._engine.createVertexBuffer(data.buffer, data.byteOffset, data.byteLength, updateable ?? false);
417
- }
418
- return buffer;
419
- }
420
- _recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {
421
- if (!effect._checkedNonFloatVertexBuffers) {
422
- checkNonFloatVertexBuffers(vertexBuffers, effect);
423
- effect._checkedNonFloatVertexBuffers = true;
424
- }
425
- if (indexBuffer) {
426
- this._engine.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer);
427
- }
428
- const attributes = effect.getAttributesNames();
429
- for (let index = 0; index < attributes.length; index++) {
430
- const location = effect.getAttributeLocation(index);
431
- if (location >= 0) {
432
- const kind = attributes[index];
433
- let vertexBuffer = null;
434
- if (overrideVertexBuffers) {
435
- vertexBuffer = overrideVertexBuffers[kind];
436
- }
437
- if (!vertexBuffer) {
438
- vertexBuffer = vertexBuffers[kind];
439
- }
440
- if (vertexBuffer) {
441
- const buffer = vertexBuffer.effectiveBuffer;
442
- if (buffer && buffer.nativeVertexBuffer) {
443
- this._engine.recordVertexBuffer(vertexArray, buffer.nativeVertexBuffer, location, vertexBuffer.effectiveByteOffset, vertexBuffer.effectiveByteStride, vertexBuffer.getSize(), getNativeAttribType(vertexBuffer.type), vertexBuffer.normalized, vertexBuffer.getInstanceDivisor());
444
- }
445
- }
446
- }
447
- }
448
- }
449
- bindBuffers(vertexBuffers, indexBuffer, effect) {
450
- if (this._boundBuffersVertexArray) {
451
- this._deleteVertexArray(this._boundBuffersVertexArray);
452
- }
453
- this._boundBuffersVertexArray = this._engine.createVertexArray();
454
- this._recordVertexArrayObject(this._boundBuffersVertexArray, vertexBuffers, indexBuffer, effect);
455
- this.bindVertexArrayObject(this._boundBuffersVertexArray);
456
- }
457
- recordVertexArrayObject(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {
458
- const vertexArray = this._engine.createVertexArray();
459
- this._recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers);
460
- return vertexArray;
461
- }
462
- _deleteVertexArray(vertexArray) {
463
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY);
464
- this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray);
465
- this._commandBufferEncoder.finishEncodingCommand();
466
- }
467
- bindVertexArrayObject(vertexArray) {
468
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY);
469
- this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray);
470
- this._commandBufferEncoder.finishEncodingCommand();
471
- }
472
- releaseVertexArrayObject(vertexArray) {
473
- this._deleteVertexArray(vertexArray);
474
- }
475
- getAttributes(pipelineContext, attributesNames) {
476
- const nativePipelineContext = pipelineContext;
477
- const nativeShaderProcessingContext = nativePipelineContext.shaderProcessingContext;
478
- remappedAttributesNames.length = 0;
479
- for (let index = 0; index < attributesNames.length; index++) {
480
- const origAttributeName = attributesNames[index];
481
- const attributeName = nativeShaderProcessingContext.remappedAttributeNames[origAttributeName] ?? origAttributeName;
482
- remappedAttributesNames[index] = attributeName;
483
- }
484
- return this._engine.getAttributes(nativePipelineContext.program, remappedAttributesNames);
485
- }
486
9
  /**
487
- * Triangle Fan and Line Loop are not supported by modern rendering API
488
- * @param fillMode defines the primitive to use
489
- * @returns true if supported
490
- */
491
- _checkSupportedFillMode(fillMode) {
492
- if (fillMode == 5 || fillMode == 8) {
493
- if (!this._fillModeWarningDisplayed) {
494
- Logger.Warn("Line Loop and Triangle Fan are not supported fill modes with Babylon Native. Elements with these fill mode will not be visible.");
495
- this._fillModeWarningDisplayed = true;
496
- }
497
- return false;
498
- }
499
- return true;
500
- }
501
- /**
502
- * Draw a list of indexed primitives
503
- * @param fillMode defines the primitive to use
504
- * @param indexStart defines the starting index
505
- * @param indexCount defines the number of index to draw
506
- * @param instancesCount defines the number of instances to draw (if instantiation is enabled)
507
- */
508
- drawElementsType(fillMode, indexStart, indexCount, instancesCount) {
509
- if (!this._checkSupportedFillMode(fillMode)) {
510
- return;
511
- }
512
- // Apply states
513
- this._drawCalls.addCount(1, false);
514
- if (instancesCount) {
515
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED);
516
- this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);
517
- this._commandBufferEncoder.encodeCommandArgAsUInt32(indexStart);
518
- this._commandBufferEncoder.encodeCommandArgAsUInt32(indexCount);
519
- this._commandBufferEncoder.encodeCommandArgAsUInt32(instancesCount);
520
- }
521
- else {
522
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED);
523
- this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);
524
- this._commandBufferEncoder.encodeCommandArgAsUInt32(indexStart);
525
- this._commandBufferEncoder.encodeCommandArgAsUInt32(indexCount);
526
- }
527
- this._commandBufferEncoder.finishEncodingCommand();
528
- }
529
- /**
530
- * Draw a list of unindexed primitives
531
- * @param fillMode defines the primitive to use
532
- * @param verticesStart defines the index of first vertex to draw
533
- * @param verticesCount defines the count of vertices to draw
534
- * @param instancesCount defines the number of instances to draw (if instantiation is enabled)
535
- */
536
- drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) {
537
- if (!this._checkSupportedFillMode(fillMode)) {
538
- return;
539
- }
540
- // Apply states
541
- this._drawCalls.addCount(1, false);
542
- if (instancesCount) {
543
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED);
544
- this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);
545
- this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesStart);
546
- this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesCount);
547
- this._commandBufferEncoder.encodeCommandArgAsUInt32(instancesCount);
548
- }
549
- else {
550
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW);
551
- this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);
552
- this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesStart);
553
- this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesCount);
554
- }
555
- this._commandBufferEncoder.finishEncodingCommand();
556
- }
557
- createPipelineContext(shaderProcessingContext) {
558
- const isAsync = !!this._caps.parallelShaderCompile;
559
- return new NativePipelineContext(this, isAsync, shaderProcessingContext);
560
- }
561
- createMaterialContext() {
562
- return undefined;
563
- }
564
- createDrawContext() {
565
- return undefined;
566
- }
567
- /**
568
- * Function is not technically Async
569
10
  * @internal
11
+ * Will be overriden by the Thin Native engine implementation
12
+ * No code should be placed here
570
13
  */
571
- // eslint-disable-next-line no-restricted-syntax
572
- _preparePipelineContextAsync(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, _rawVertexSourceCode, _rawFragmentSourceCode, _rebuildRebind, defines, _transformFeedbackVaryings, _key, onReady) {
573
- if (createAsRaw) {
574
- this.createRawShaderProgram();
575
- }
576
- else {
577
- this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines);
578
- }
579
- onReady();
580
- }
14
+ _initializeNativeEngine(_adaptToDeviceRatio) { }
581
15
  /**
582
16
  * @internal
583
17
  */
584
- _getShaderProcessingContext(_shaderLanguage) {
585
- return new NativeShaderProcessingContext();
18
+ constructor(options = {}) {
19
+ super(null, false, undefined, options.adaptToDeviceRatio);
20
+ this._initializeNativeEngine(options.adaptToDeviceRatio ?? false);
586
21
  }
587
22
  /**
588
23
  * @internal
589
24
  */
590
- _executeWhenRenderingStateIsCompiled(pipelineContext, action) {
591
- const nativePipelineContext = pipelineContext;
592
- if (nativePipelineContext.isAsync) {
593
- if (nativePipelineContext.onCompiled) {
594
- const oldHandler = nativePipelineContext.onCompiled;
595
- nativePipelineContext.onCompiled = () => {
596
- oldHandler();
597
- action();
598
- };
599
- }
600
- else {
601
- nativePipelineContext.onCompiled = action;
602
- }
603
- }
604
- else {
605
- action();
606
- }
607
- }
608
- createRawShaderProgram() {
609
- throw new Error("Not Supported");
610
- }
611
- createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines) {
612
- const nativePipelineContext = pipelineContext;
613
- this.onBeforeShaderCompilationObservable.notifyObservers(this);
614
- const vertexInliner = new ShaderCodeInliner(vertexCode);
615
- vertexInliner.processCode();
616
- vertexCode = vertexInliner.code;
617
- const fragmentInliner = new ShaderCodeInliner(fragmentCode);
618
- fragmentInliner.processCode();
619
- fragmentCode = fragmentInliner.code;
620
- vertexCode = ThinEngine._ConcatenateShader(vertexCode, defines);
621
- fragmentCode = ThinEngine._ConcatenateShader(fragmentCode, defines);
622
- const onSuccess = () => {
623
- nativePipelineContext.isCompiled = true;
624
- nativePipelineContext.onCompiled?.();
625
- this.onAfterShaderCompilationObservable.notifyObservers(this);
626
- };
627
- if (pipelineContext.isAsync) {
628
- nativePipelineContext.program = this._engine.createProgramAsync(vertexCode, fragmentCode, onSuccess, (error) => {
629
- nativePipelineContext.compilationError = error;
630
- });
631
- }
632
- else {
633
- try {
634
- nativePipelineContext.program = this._engine.createProgram(vertexCode, fragmentCode);
635
- onSuccess();
636
- }
637
- catch (e) {
638
- const message = e?.message;
639
- throw new Error("SHADER ERROR" + (typeof message === "string" ? "\n" + message : ""));
640
- }
641
- }
642
- return nativePipelineContext.program;
643
- }
644
- /**
645
- * Inline functions in shader code that are marked to be inlined
646
- * @param code code to inline
647
- * @returns inlined code
648
- */
649
- inlineShaderCode(code) {
650
- const sci = new ShaderCodeInliner(code);
651
- sci.debug = false;
652
- sci.processCode();
653
- return sci.code;
654
- }
655
- _setProgram(program) {
656
- if (this._currentProgram !== program) {
657
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM);
658
- this._commandBufferEncoder.encodeCommandArgAsNativeData(program);
659
- this._commandBufferEncoder.finishEncodingCommand();
660
- this._currentProgram = program;
661
- }
662
- }
663
- _deletePipelineContext(pipelineContext) {
664
- const nativePipelineContext = pipelineContext;
665
- if (nativePipelineContext && nativePipelineContext.program) {
666
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM);
667
- this._commandBufferEncoder.encodeCommandArgAsNativeData(nativePipelineContext.program);
668
- this._commandBufferEncoder.finishEncodingCommand();
669
- }
670
- }
671
- getUniforms(pipelineContext, uniformsNames) {
672
- const nativePipelineContext = pipelineContext;
673
- return this._engine.getUniforms(nativePipelineContext.program, uniformsNames);
674
- }
675
- bindUniformBlock(pipelineContext, blockName, index) {
676
- // TODO
677
- throw new Error("Not Implemented");
678
- }
679
- bindSamplers(effect) {
680
- const nativePipelineContext = effect.getPipelineContext();
681
- this._setProgram(nativePipelineContext.program);
682
- // TODO: share this with engine?
683
- const samplers = effect.getSamplers();
684
- for (let index = 0; index < samplers.length; index++) {
685
- const uniform = effect.getUniform(samplers[index]);
686
- if (uniform) {
687
- this._boundUniforms[index] = uniform;
688
- }
689
- }
690
- this._currentEffect = null;
691
- }
692
- getRenderWidth(useScreen = false) {
693
- if (!useScreen && this._currentRenderTarget) {
694
- return this._currentRenderTarget.width;
695
- }
696
- return this._engine.getRenderWidth();
697
- }
698
- getRenderHeight(useScreen = false) {
699
- if (!useScreen && this._currentRenderTarget) {
700
- return this._currentRenderTarget.height;
701
- }
702
- return this._engine.getRenderHeight();
703
- }
704
- setViewport(viewport, requiredWidth, requiredHeight) {
705
- this._cachedViewport = viewport;
706
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT);
707
- this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.x);
708
- this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.y);
709
- this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.width);
710
- this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.height);
711
- this._commandBufferEncoder.finishEncodingCommand();
712
- }
713
- enableScissor(x, y, width, height) {
714
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR);
715
- this._commandBufferEncoder.encodeCommandArgAsFloat32(x);
716
- this._commandBufferEncoder.encodeCommandArgAsFloat32(y);
717
- this._commandBufferEncoder.encodeCommandArgAsFloat32(width);
718
- this._commandBufferEncoder.encodeCommandArgAsFloat32(height);
719
- this._commandBufferEncoder.finishEncodingCommand();
720
- }
721
- disableScissor() {
722
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR);
723
- this._commandBufferEncoder.encodeCommandArgAsFloat32(0);
724
- this._commandBufferEncoder.encodeCommandArgAsFloat32(0);
725
- this._commandBufferEncoder.encodeCommandArgAsFloat32(0);
726
- this._commandBufferEncoder.encodeCommandArgAsFloat32(0);
727
- this._commandBufferEncoder.finishEncodingCommand();
728
- }
729
- setStateCullFaceType(_cullBackFaces, _force) {
730
- throw new Error("setStateCullFaceType: Not Implemented");
731
- }
732
- setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) {
733
- this._zOffset = zOffset;
734
- this._zOffsetUnits = zOffsetUnits;
735
- if (this._zOffset !== 0) {
736
- Tools.Warn("zOffset is not supported in Native engine.");
737
- }
738
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE);
739
- this._commandBufferEncoder.encodeCommandArgAsUInt32(culling ? 1 : 0);
740
- this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffset);
741
- this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffsetUnits);
742
- this._commandBufferEncoder.encodeCommandArgAsUInt32((this.cullBackFaces ?? cullBackFaces ?? true) ? 1 : 0);
743
- this._commandBufferEncoder.encodeCommandArgAsUInt32(reverseSide ? 1 : 0);
744
- this._commandBufferEncoder.finishEncodingCommand();
745
- }
746
- /**
747
- * Gets the client rect of native canvas. Needed for InputManager.
748
- * @returns a client rectangle
749
- */
750
- getInputElementClientRect() {
751
- const rect = {
752
- bottom: this.getRenderHeight(),
753
- height: this.getRenderHeight(),
754
- left: 0,
755
- right: this.getRenderWidth(),
756
- top: 0,
757
- width: this.getRenderWidth(),
758
- x: 0,
759
- y: 0,
760
- toJSON: () => { },
761
- };
762
- return rect;
763
- }
764
- /**
765
- * Set the z offset Factor to apply to current rendering
766
- * @param value defines the offset to apply
767
- */
768
- setZOffset(value) {
769
- if (value !== this._zOffset) {
770
- this._zOffset = value;
771
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET);
772
- this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value);
773
- this._commandBufferEncoder.finishEncodingCommand();
774
- }
775
- }
776
- /**
777
- * Gets the current value of the zOffset Factor
778
- * @returns the current zOffset Factor state
779
- */
780
- getZOffset() {
781
- return this._zOffset;
782
- }
783
- /**
784
- * Set the z offset Units to apply to current rendering
785
- * @param value defines the offset to apply
786
- */
787
- setZOffsetUnits(value) {
788
- if (value !== this._zOffsetUnits) {
789
- this._zOffsetUnits = value;
790
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS);
791
- this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value);
792
- this._commandBufferEncoder.finishEncodingCommand();
793
- }
794
- }
795
- /**
796
- * Gets the current value of the zOffset Units
797
- * @returns the current zOffset Units state
798
- */
799
- getZOffsetUnits() {
800
- return this._zOffsetUnits;
801
- }
802
- /**
803
- * Enable or disable depth buffering
804
- * @param enable defines the state to set
805
- */
806
- setDepthBuffer(enable) {
807
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST);
808
- this._commandBufferEncoder.encodeCommandArgAsUInt32(enable ? this._currentDepthTest : _native.Engine.DEPTH_TEST_ALWAYS);
809
- this._commandBufferEncoder.finishEncodingCommand();
810
- }
811
- /**
812
- * Gets a boolean indicating if depth writing is enabled
813
- * @returns the current depth writing state
814
- */
815
- getDepthWrite() {
816
- return this._depthWrite;
817
- }
818
- getDepthFunction() {
819
- switch (this._currentDepthTest) {
820
- case _native.Engine.DEPTH_TEST_NEVER:
821
- return 512;
822
- case _native.Engine.DEPTH_TEST_ALWAYS:
823
- return 519;
824
- case _native.Engine.DEPTH_TEST_GREATER:
825
- return 516;
826
- case _native.Engine.DEPTH_TEST_GEQUAL:
827
- return 518;
828
- case _native.Engine.DEPTH_TEST_NOTEQUAL:
829
- return 517;
830
- case _native.Engine.DEPTH_TEST_EQUAL:
831
- return 514;
832
- case _native.Engine.DEPTH_TEST_LESS:
833
- return 513;
834
- case _native.Engine.DEPTH_TEST_LEQUAL:
835
- return 515;
836
- }
837
- return null;
838
- }
839
- setDepthFunction(depthFunc) {
840
- let nativeDepthFunc = 0;
841
- switch (depthFunc) {
842
- case 512:
843
- nativeDepthFunc = _native.Engine.DEPTH_TEST_NEVER;
844
- break;
845
- case 519:
846
- nativeDepthFunc = _native.Engine.DEPTH_TEST_ALWAYS;
847
- break;
848
- case 516:
849
- nativeDepthFunc = _native.Engine.DEPTH_TEST_GREATER;
850
- break;
851
- case 518:
852
- nativeDepthFunc = _native.Engine.DEPTH_TEST_GEQUAL;
853
- break;
854
- case 517:
855
- nativeDepthFunc = _native.Engine.DEPTH_TEST_NOTEQUAL;
856
- break;
857
- case 514:
858
- nativeDepthFunc = _native.Engine.DEPTH_TEST_EQUAL;
859
- break;
860
- case 513:
861
- nativeDepthFunc = _native.Engine.DEPTH_TEST_LESS;
862
- break;
863
- case 515:
864
- nativeDepthFunc = _native.Engine.DEPTH_TEST_LEQUAL;
865
- break;
866
- }
867
- this._currentDepthTest = nativeDepthFunc;
868
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST);
869
- this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest);
870
- this._commandBufferEncoder.finishEncodingCommand();
871
- }
872
- /**
873
- * Enable or disable depth writing
874
- * @param enable defines the state to set
875
- */
876
- setDepthWrite(enable) {
877
- this._depthWrite = enable;
878
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE);
879
- this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable));
880
- this._commandBufferEncoder.finishEncodingCommand();
881
- }
882
- /**
883
- * Enable or disable color writing
884
- * @param enable defines the state to set
885
- */
886
- setColorWrite(enable) {
887
- this._colorWrite = enable;
888
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE);
889
- this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable));
890
- this._commandBufferEncoder.finishEncodingCommand();
891
- }
892
- /**
893
- * Gets a boolean indicating if color writing is enabled
894
- * @returns the current color writing state
895
- */
896
- getColorWrite() {
897
- return this._colorWrite;
898
- }
899
- applyStencil() {
900
- this._setStencil(this._stencilMask, getNativeStencilOpFail(this._stencilOpStencilFail), getNativeStencilDepthFail(this._stencilOpDepthFail), getNativeStencilDepthPass(this._stencilOpStencilDepthPass), getNativeStencilFunc(this._stencilFunc), this._stencilFuncRef);
901
- }
902
- _setStencil(mask, stencilOpFail, depthOpFail, depthOpPass, func, ref) {
903
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL);
904
- this._commandBufferEncoder.encodeCommandArgAsUInt32(mask);
905
- this._commandBufferEncoder.encodeCommandArgAsUInt32(stencilOpFail);
906
- this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpFail);
907
- this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpPass);
908
- this._commandBufferEncoder.encodeCommandArgAsUInt32(func);
909
- this._commandBufferEncoder.encodeCommandArgAsUInt32(ref);
910
- this._commandBufferEncoder.finishEncodingCommand();
911
- }
912
- /**
913
- * Enable or disable the stencil buffer
914
- * @param enable defines if the stencil buffer must be enabled or disabled
915
- */
916
- setStencilBuffer(enable) {
917
- this._stencilTest = enable;
918
- if (enable) {
919
- this.applyStencil();
920
- }
921
- else {
922
- this._setStencil(255, _native.Engine.STENCIL_OP_FAIL_S_KEEP, _native.Engine.STENCIL_OP_FAIL_Z_KEEP, _native.Engine.STENCIL_OP_PASS_Z_KEEP, _native.Engine.STENCIL_TEST_ALWAYS, 0);
923
- }
924
- }
925
- /**
926
- * Gets a boolean indicating if stencil buffer is enabled
927
- * @returns the current stencil buffer state
928
- */
929
- getStencilBuffer() {
930
- return this._stencilTest;
931
- }
932
- /**
933
- * Gets the current stencil operation when stencil passes
934
- * @returns a number defining stencil operation to use when stencil passes
935
- */
936
- getStencilOperationPass() {
937
- return this._stencilOpStencilDepthPass;
938
- }
939
- /**
940
- * Sets the stencil operation to use when stencil passes
941
- * @param operation defines the stencil operation to use when stencil passes
942
- */
943
- setStencilOperationPass(operation) {
944
- this._stencilOpStencilDepthPass = operation;
945
- this.applyStencil();
946
- }
947
- /**
948
- * Sets the current stencil mask
949
- * @param mask defines the new stencil mask to use
950
- */
951
- setStencilMask(mask) {
952
- this._stencilMask = mask;
953
- this.applyStencil();
954
- }
955
- /**
956
- * Sets the current stencil function
957
- * @param stencilFunc defines the new stencil function to use
958
- */
959
- setStencilFunction(stencilFunc) {
960
- this._stencilFunc = stencilFunc;
961
- this.applyStencil();
962
- }
963
- /**
964
- * Sets the current stencil reference
965
- * @param reference defines the new stencil reference to use
966
- */
967
- setStencilFunctionReference(reference) {
968
- this._stencilFuncRef = reference;
969
- this.applyStencil();
970
- }
971
- /**
972
- * Sets the current stencil mask
973
- * @param mask defines the new stencil mask to use
974
- */
975
- setStencilFunctionMask(mask) {
976
- this._stencilFuncMask = mask;
977
- }
978
- /**
979
- * Sets the stencil operation to use when stencil fails
980
- * @param operation defines the stencil operation to use when stencil fails
981
- */
982
- setStencilOperationFail(operation) {
983
- this._stencilOpStencilFail = operation;
984
- this.applyStencil();
985
- }
986
- /**
987
- * Sets the stencil operation to use when depth fails
988
- * @param operation defines the stencil operation to use when depth fails
989
- */
990
- setStencilOperationDepthFail(operation) {
991
- this._stencilOpDepthFail = operation;
992
- this.applyStencil();
993
- }
994
- /**
995
- * Gets the current stencil mask
996
- * @returns a number defining the new stencil mask to use
997
- */
998
- getStencilMask() {
999
- return this._stencilMask;
1000
- }
1001
- /**
1002
- * Gets the current stencil function
1003
- * @returns a number defining the stencil function to use
1004
- */
1005
- getStencilFunction() {
1006
- return this._stencilFunc;
1007
- }
1008
- /**
1009
- * Gets the current stencil reference value
1010
- * @returns a number defining the stencil reference value to use
1011
- */
1012
- getStencilFunctionReference() {
1013
- return this._stencilFuncRef;
1014
- }
1015
- /**
1016
- * Gets the current stencil mask
1017
- * @returns a number defining the stencil mask to use
1018
- */
1019
- getStencilFunctionMask() {
1020
- return this._stencilFuncMask;
1021
- }
1022
- /**
1023
- * Gets the current stencil operation when stencil fails
1024
- * @returns a number defining stencil operation to use when stencil fails
1025
- */
1026
- getStencilOperationFail() {
1027
- return this._stencilOpStencilFail;
1028
- }
1029
- /**
1030
- * Gets the current stencil operation when depth fails
1031
- * @returns a number defining stencil operation to use when depth fails
1032
- */
1033
- getStencilOperationDepthFail() {
1034
- return this._stencilOpDepthFail;
1035
- }
1036
- /**
1037
- * Sets alpha constants used by some alpha blending modes
1038
- * @param r defines the red component
1039
- * @param g defines the green component
1040
- * @param b defines the blue component
1041
- * @param a defines the alpha component
1042
- */
1043
- setAlphaConstants(r, g, b, a) {
1044
- throw new Error("Setting alpha blend constant color not yet implemented.");
1045
- }
1046
- /**
1047
- * Sets the current alpha mode
1048
- * @param mode defines the mode to use (one of the BABYLON.undefined)
1049
- * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
1050
- * @param targetIndex defines the index of the target to set the alpha mode for (default is 0)
1051
- * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering
1052
- */
1053
- setAlphaMode(mode, noDepthWriteChange = false, targetIndex = 0) {
1054
- if (this._alphaMode[targetIndex] === mode) {
1055
- return;
1056
- }
1057
- const nativeMode = getNativeAlphaMode(mode);
1058
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE);
1059
- this._commandBufferEncoder.encodeCommandArgAsUInt32(nativeMode);
1060
- this._commandBufferEncoder.finishEncodingCommand();
1061
- if (!noDepthWriteChange) {
1062
- this.setDepthWrite(mode === 0);
1063
- }
1064
- this._alphaMode[targetIndex] = mode;
1065
- }
1066
- setInt(uniform, int) {
1067
- if (!uniform) {
1068
- return false;
1069
- }
1070
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT);
1071
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1072
- this._commandBufferEncoder.encodeCommandArgAsInt32(int);
1073
- this._commandBufferEncoder.finishEncodingCommand();
1074
- return true;
1075
- }
1076
- setIntArray(uniform, array) {
1077
- if (!uniform) {
1078
- return false;
1079
- }
1080
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY);
1081
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1082
- this._commandBufferEncoder.encodeCommandArgAsInt32s(array);
1083
- this._commandBufferEncoder.finishEncodingCommand();
1084
- return true;
1085
- }
1086
- setIntArray2(uniform, array) {
1087
- if (!uniform) {
1088
- return false;
1089
- }
1090
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2);
1091
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1092
- this._commandBufferEncoder.encodeCommandArgAsInt32s(array);
1093
- this._commandBufferEncoder.finishEncodingCommand();
1094
- return true;
1095
- }
1096
- setIntArray3(uniform, array) {
1097
- if (!uniform) {
1098
- return false;
1099
- }
1100
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3);
1101
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1102
- this._commandBufferEncoder.encodeCommandArgAsInt32s(array);
1103
- this._commandBufferEncoder.finishEncodingCommand();
1104
- return true;
1105
- }
1106
- setIntArray4(uniform, array) {
1107
- if (!uniform) {
1108
- return false;
1109
- }
1110
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4);
1111
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1112
- this._commandBufferEncoder.encodeCommandArgAsInt32s(array);
1113
- this._commandBufferEncoder.finishEncodingCommand();
1114
- return true;
1115
- }
1116
- setFloatArray(uniform, array) {
1117
- if (!uniform) {
1118
- return false;
1119
- }
1120
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY);
1121
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1122
- this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);
1123
- this._commandBufferEncoder.finishEncodingCommand();
1124
- return true;
1125
- }
1126
- setFloatArray2(uniform, array) {
1127
- if (!uniform) {
1128
- return false;
1129
- }
1130
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2);
1131
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1132
- this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);
1133
- this._commandBufferEncoder.finishEncodingCommand();
1134
- return true;
1135
- }
1136
- setFloatArray3(uniform, array) {
1137
- if (!uniform) {
1138
- return false;
1139
- }
1140
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3);
1141
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1142
- this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);
1143
- this._commandBufferEncoder.finishEncodingCommand();
1144
- return true;
1145
- }
1146
- setFloatArray4(uniform, array) {
1147
- if (!uniform) {
1148
- return false;
1149
- }
1150
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4);
1151
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1152
- this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);
1153
- this._commandBufferEncoder.finishEncodingCommand();
1154
- return true;
1155
- }
1156
- setArray(uniform, array) {
1157
- if (!uniform) {
1158
- return false;
1159
- }
1160
- return this.setFloatArray(uniform, new Float32Array(array));
1161
- }
1162
- setArray2(uniform, array) {
1163
- if (!uniform) {
1164
- return false;
1165
- }
1166
- return this.setFloatArray2(uniform, new Float32Array(array));
1167
- }
1168
- setArray3(uniform, array) {
1169
- if (!uniform) {
1170
- return false;
1171
- }
1172
- return this.setFloatArray3(uniform, new Float32Array(array));
1173
- }
1174
- setArray4(uniform, array) {
1175
- if (!uniform) {
1176
- return false;
1177
- }
1178
- return this.setFloatArray4(uniform, new Float32Array(array));
1179
- }
1180
- setMatrices(uniform, matrices) {
1181
- if (!uniform) {
1182
- return false;
1183
- }
1184
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES);
1185
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1186
- this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrices);
1187
- this._commandBufferEncoder.finishEncodingCommand();
1188
- return true;
1189
- }
1190
- setMatrix3x3(uniform, matrix) {
1191
- if (!uniform) {
1192
- return false;
1193
- }
1194
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3);
1195
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1196
- this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix);
1197
- this._commandBufferEncoder.finishEncodingCommand();
1198
- return true;
1199
- }
1200
- setMatrix2x2(uniform, matrix) {
1201
- if (!uniform) {
1202
- return false;
1203
- }
1204
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2);
1205
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1206
- this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix);
1207
- this._commandBufferEncoder.finishEncodingCommand();
1208
- return true;
1209
- }
1210
- setFloat(uniform, value) {
1211
- if (!uniform) {
1212
- return false;
1213
- }
1214
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT);
1215
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1216
- this._commandBufferEncoder.encodeCommandArgAsFloat32(value);
1217
- this._commandBufferEncoder.finishEncodingCommand();
1218
- return true;
1219
- }
1220
- setFloat2(uniform, x, y) {
1221
- if (!uniform) {
1222
- return false;
1223
- }
1224
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2);
1225
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1226
- this._commandBufferEncoder.encodeCommandArgAsFloat32(x);
1227
- this._commandBufferEncoder.encodeCommandArgAsFloat32(y);
1228
- this._commandBufferEncoder.finishEncodingCommand();
1229
- return true;
1230
- }
1231
- setFloat3(uniform, x, y, z) {
1232
- if (!uniform) {
1233
- return false;
1234
- }
1235
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3);
1236
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1237
- this._commandBufferEncoder.encodeCommandArgAsFloat32(x);
1238
- this._commandBufferEncoder.encodeCommandArgAsFloat32(y);
1239
- this._commandBufferEncoder.encodeCommandArgAsFloat32(z);
1240
- this._commandBufferEncoder.finishEncodingCommand();
1241
- return true;
1242
- }
1243
- setFloat4(uniform, x, y, z, w) {
1244
- if (!uniform) {
1245
- return false;
1246
- }
1247
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4);
1248
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1249
- this._commandBufferEncoder.encodeCommandArgAsFloat32(x);
1250
- this._commandBufferEncoder.encodeCommandArgAsFloat32(y);
1251
- this._commandBufferEncoder.encodeCommandArgAsFloat32(z);
1252
- this._commandBufferEncoder.encodeCommandArgAsFloat32(w);
1253
- this._commandBufferEncoder.finishEncodingCommand();
1254
- return true;
1255
- }
1256
- setColor3(uniform, color3) {
1257
- if (!uniform) {
1258
- return false;
1259
- }
1260
- this.setFloat3(uniform, color3.r, color3.g, color3.b);
1261
- return true;
1262
- }
1263
- setColor4(uniform, color3, alpha) {
1264
- if (!uniform) {
1265
- return false;
1266
- }
1267
- this.setFloat4(uniform, color3.r, color3.g, color3.b, alpha);
1268
- return true;
1269
- }
1270
- wipeCaches(bruteForce) {
1271
- if (this.preventCacheWipeBetweenFrames) {
1272
- return;
1273
- }
1274
- this.resetTextureCache();
1275
- this._currentEffect = null;
1276
- if (bruteForce) {
1277
- this._currentProgram = null;
1278
- this._stencilStateComposer.reset();
1279
- this._depthCullingState.reset();
1280
- this._alphaState.reset();
1281
- }
1282
- this._cachedVertexBuffers = null;
1283
- this._cachedIndexBuffer = null;
1284
- this._cachedEffectForVertexBuffers = null;
1285
- }
1286
- _createTexture() {
1287
- return this._engine.createTexture();
1288
- }
1289
- _deleteTexture(texture) {
1290
- if (texture) {
1291
- this._engine.deleteTexture(texture.underlyingResource);
1292
- }
1293
- }
1294
- /**
1295
- * Update the content of a dynamic texture
1296
- * @param texture defines the texture to update
1297
- * @param canvas defines the canvas containing the source
1298
- * @param invertY defines if data must be stored with Y axis inverted
1299
- * @param premulAlpha defines if alpha is stored as premultiplied
1300
- * @param format defines the format of the data
1301
- */
1302
- updateDynamicTexture(texture, canvas, invertY, premulAlpha = false, format) {
1303
- if (premulAlpha === void 0) {
1304
- premulAlpha = false;
1305
- }
1306
- if (!!texture && !!texture._hardwareTexture) {
1307
- const destination = texture._hardwareTexture.underlyingResource;
1308
- const context = canvas.getContext();
1309
- // flush need to happen before getCanvasTexture: flush will create the render target synchronously (if it's not been created before)
1310
- context.flush();
1311
- const source = canvas.getCanvasTexture();
1312
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_COPYTEXTURE);
1313
- this._commandBufferEncoder.encodeCommandArgAsNativeData(source);
1314
- this._commandBufferEncoder.encodeCommandArgAsNativeData(destination);
1315
- this._commandBufferEncoder.finishEncodingCommand();
1316
- texture.isReady = true;
1317
- }
1318
- }
1319
- createDynamicTexture(width, height, generateMipMaps, samplingMode) {
1320
- // it's not possible to create 0x0 texture sized. Many bgfx methods assume texture size is at least 1x1(best case).
1321
- // Worst case is getting a crash/assert.
1322
- width = Math.max(width, 1);
1323
- height = Math.max(height, 1);
1324
- return this.createRawTexture(new Uint8Array(width * height * 4), width, height, 5, false, false, samplingMode);
1325
- }
1326
- createVideoElement(constraints) {
1327
- // create native object depending on stream. Only NativeCamera is supported for now.
1328
- if (this._camera) {
1329
- return this._camera.createVideo(constraints);
1330
- }
1331
- return null;
1332
- }
1333
- updateVideoTexture(texture, video, invertY) {
1334
- if (texture && texture._hardwareTexture && this._camera) {
1335
- const webGLTexture = texture._hardwareTexture.underlyingResource;
1336
- this._camera.updateVideoTexture(webGLTexture, video, invertY);
1337
- }
1338
- }
1339
- createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) {
1340
- const texture = new InternalTexture(this, 3 /* InternalTextureSource.Raw */);
1341
- texture.format = format;
1342
- texture.generateMipMaps = generateMipMaps;
1343
- texture.samplingMode = samplingMode;
1344
- texture.invertY = invertY;
1345
- texture.baseWidth = width;
1346
- texture.baseHeight = height;
1347
- texture.width = texture.baseWidth;
1348
- texture.height = texture.baseHeight;
1349
- texture._compression = compression;
1350
- texture.type = type;
1351
- texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps);
1352
- this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer);
1353
- if (texture._hardwareTexture) {
1354
- const webGLTexture = texture._hardwareTexture.underlyingResource;
1355
- const filter = getNativeSamplingMode(samplingMode);
1356
- this._setTextureSampling(webGLTexture, filter);
1357
- }
1358
- this._internalTexturesCache.push(texture);
1359
- return texture;
1360
- }
1361
- createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) {
1362
- const texture = new InternalTexture(this, 11 /* InternalTextureSource.Raw2DArray */);
1363
- texture.baseWidth = width;
1364
- texture.baseHeight = height;
1365
- texture.baseDepth = depth;
1366
- texture.width = width;
1367
- texture.height = height;
1368
- texture.depth = depth;
1369
- texture.format = format;
1370
- texture.type = textureType;
1371
- texture.generateMipMaps = generateMipMaps;
1372
- texture.samplingMode = samplingMode;
1373
- texture.is2DArray = true;
1374
- if (texture._hardwareTexture) {
1375
- const nativeTexture = texture._hardwareTexture.underlyingResource;
1376
- this._engine.loadRawTexture2DArray(nativeTexture, data, width, height, depth, getNativeTextureFormat(format, textureType), generateMipMaps, invertY);
1377
- const filter = getNativeSamplingMode(samplingMode);
1378
- this._setTextureSampling(nativeTexture, filter);
1379
- }
1380
- texture.isReady = true;
1381
- this._internalTexturesCache.push(texture);
1382
- return texture;
1383
- }
1384
- updateRawTexture(texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {
1385
- if (!texture) {
1386
- return;
1387
- }
1388
- if (bufferView && texture._hardwareTexture) {
1389
- const underlyingResource = texture._hardwareTexture.underlyingResource;
1390
- this._engine.loadRawTexture(underlyingResource, bufferView, texture.width, texture.height, getNativeTextureFormat(format, type), texture.generateMipMaps, texture.invertY);
1391
- }
1392
- texture.isReady = true;
1393
- }
1394
- // TODO: Refactor to share more logic with babylon.engine.ts version.
1395
- /**
1396
- * Usually called from Texture.ts.
1397
- * Passed information to create a NativeTexture
1398
- * @param url defines a value which contains one of the following:
1399
- * * A conventional http URL, e.g. 'http://...' or 'file://...'
1400
- * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
1401
- * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
1402
- * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
1403
- * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
1404
- * @param scene needed for loading to the correct scene
1405
- * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
1406
- * @param onLoad optional callback to be called upon successful completion
1407
- * @param onError optional callback to be called upon failure
1408
- * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
1409
- * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
1410
- * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
1411
- * @param forcedExtension defines the extension to use to pick the right loader
1412
- * @param mimeType defines an optional mime type
1413
- * @param loaderOptions options to be passed to the loader
1414
- * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)
1415
- * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).
1416
- * @returns a InternalTexture for assignment back into BABYLON.Texture
1417
- */
1418
- createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer = false) {
1419
- url = url || "";
1420
- const fromData = url.substring(0, 5) === "data:";
1421
- //const fromBlob = url.substring(0, 5) === "blob:";
1422
- const isBase64 = fromData && url.indexOf(";base64,") !== -1;
1423
- const texture = fallback ? fallback : new InternalTexture(this, 1 /* InternalTextureSource.Url */);
1424
- const originalUrl = url;
1425
- if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {
1426
- url = this._transformTextureUrl(url);
1427
- }
1428
- // establish the file extension, if possible
1429
- const lastDot = url.lastIndexOf(".");
1430
- const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : "";
1431
- // some formats are already supported by bimg, no need to try to load them with JS
1432
- // leaving TextureLoader extension check for future use
1433
- let loaderPromise = null;
1434
- if (extension.endsWith(".basis") || extension.endsWith(".ktx") || extension.endsWith(".ktx2") || mimeType === "image/ktx" || mimeType === "image/ktx2") {
1435
- loaderPromise = _GetCompatibleTextureLoader(extension);
1436
- }
1437
- if (scene) {
1438
- scene.addPendingData(texture);
1439
- }
1440
- texture.url = url;
1441
- texture.generateMipMaps = !noMipmap;
1442
- texture.samplingMode = samplingMode;
1443
- texture.invertY = invertY;
1444
- texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, noMipmap);
1445
- if (!this.doNotHandleContextLost) {
1446
- // Keep a link to the buffer only if we plan to handle context lost
1447
- texture._buffer = buffer;
1448
- }
1449
- let onLoadObserver = null;
1450
- if (onLoad && !fallback) {
1451
- onLoadObserver = texture.onLoadedObservable.add(onLoad);
1452
- }
1453
- if (!fallback) {
1454
- this._internalTexturesCache.push(texture);
1455
- }
1456
- const onInternalError = (message, exception) => {
1457
- if (scene) {
1458
- scene.removePendingData(texture);
1459
- }
1460
- if (url === originalUrl) {
1461
- if (onLoadObserver) {
1462
- texture.onLoadedObservable.remove(onLoadObserver);
1463
- }
1464
- if (EngineStore.UseFallbackTexture) {
1465
- this.createTexture(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture);
1466
- }
1467
- if (onError) {
1468
- onError((message || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""), exception);
1469
- }
1470
- }
1471
- else {
1472
- // fall back to the original url if the transformed url fails to load
1473
- Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`);
1474
- this.createTexture(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, buffer, texture, format, forcedExtension, mimeType, loaderOptions);
1475
- }
1476
- };
1477
- // processing for non-image formats
1478
- if (loaderPromise) {
1479
- throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");
1480
- }
1481
- else {
1482
- const onload = (data) => {
1483
- if (!texture._hardwareTexture) {
1484
- if (scene) {
1485
- scene.removePendingData(texture);
1486
- }
1487
- return;
1488
- }
1489
- const underlyingResource = texture._hardwareTexture.underlyingResource;
1490
- this._engine.loadTexture(underlyingResource, data, !noMipmap, invertY, texture._useSRGBBuffer, () => {
1491
- texture.baseWidth = this._engine.getTextureWidth(underlyingResource);
1492
- texture.baseHeight = this._engine.getTextureHeight(underlyingResource);
1493
- texture.width = texture.baseWidth;
1494
- texture.height = texture.baseHeight;
1495
- texture.isReady = true;
1496
- const filter = getNativeSamplingMode(samplingMode);
1497
- this._setTextureSampling(underlyingResource, filter);
1498
- if (scene) {
1499
- scene.removePendingData(texture);
1500
- }
1501
- texture.onLoadedObservable.notifyObservers(texture);
1502
- texture.onLoadedObservable.clear();
1503
- }, () => {
1504
- throw new Error("Could not load a native texture.");
1505
- });
1506
- };
1507
- if (fromData && buffer) {
1508
- if (buffer instanceof ArrayBuffer) {
1509
- onload(new Uint8Array(buffer));
1510
- }
1511
- else if (ArrayBuffer.isView(buffer)) {
1512
- onload(buffer);
1513
- }
1514
- else if (typeof buffer === "string") {
1515
- onload(new Uint8Array(Tools.DecodeBase64(buffer)));
1516
- }
1517
- else {
1518
- throw new Error("Unsupported buffer type");
1519
- }
1520
- }
1521
- else {
1522
- if (isBase64) {
1523
- onload(new Uint8Array(Tools.DecodeBase64(url)));
1524
- }
1525
- else {
1526
- this._loadFile(url, (data) => onload(new Uint8Array(data)), undefined, undefined, true, (request, exception) => {
1527
- onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
1528
- });
1529
- }
1530
- }
1531
- }
1532
- return texture;
1533
- }
1534
- /**
1535
- * Wraps an external native texture in a Babylon texture.
1536
- * @param texture defines the external texture
1537
- * @param hasMipMaps defines whether the external texture has mip maps
1538
- * @param samplingMode defines the sampling mode for the external texture (default: 3)
1539
- * @returns the babylon internal texture
1540
- */
1541
- wrapNativeTexture(texture, hasMipMaps = false, samplingMode = 3) {
1542
- const hardwareTexture = new NativeHardwareTexture(texture, this._engine);
1543
- const internalTexture = new InternalTexture(this, 0 /* InternalTextureSource.Unknown */, true);
1544
- internalTexture._hardwareTexture = hardwareTexture;
1545
- internalTexture.baseWidth = this._engine.getTextureWidth(texture);
1546
- internalTexture.baseHeight = this._engine.getTextureHeight(texture);
1547
- internalTexture.width = internalTexture.baseWidth;
1548
- internalTexture.height = internalTexture.baseHeight;
1549
- internalTexture.isReady = true;
1550
- internalTexture.useMipMaps = hasMipMaps;
1551
- this.updateTextureSamplingMode(samplingMode, internalTexture);
1552
- return internalTexture;
1553
- }
1554
- // eslint-disable-next-line jsdoc/require-returns-check
1555
- /**
1556
- * Wraps an external web gl texture in a Babylon texture.
1557
- * @returns the babylon internal texture
1558
- */
1559
25
  wrapWebGLTexture() {
1560
26
  throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.");
1561
27
  }
1562
- _createDepthStencilTexture(size, options, rtWrapper) {
1563
- // TODO: handle other options?
1564
- const generateStencil = options.generateStencil || false;
1565
- const samples = options.samples || 1;
1566
- const nativeRTWrapper = rtWrapper;
1567
- const texture = new InternalTexture(this, 12 /* InternalTextureSource.DepthStencil */);
1568
- const width = size.width ?? size;
1569
- const height = size.height ?? size;
1570
- const framebuffer = this._engine.createFrameBuffer(texture._hardwareTexture.underlyingResource, width, height, generateStencil, true, samples);
1571
- nativeRTWrapper._framebufferDepthStencil = framebuffer;
1572
- return texture;
1573
- }
1574
- /**
1575
- * @internal
1576
- */
1577
- _releaseFramebufferObjects(framebuffer) {
1578
- if (framebuffer) {
1579
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER);
1580
- this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer);
1581
- this._commandBufferEncoder.finishEncodingCommand();
1582
- }
1583
- }
1584
- /**
1585
- * @internal Engine abstraction for loading and creating an image bitmap from a given source string.
1586
- * @param imageSource source to load the image from.
1587
- * @param _options An object that sets options for the image's extraction.
1588
- * @returns ImageBitmap
1589
- */
1590
- async _createImageBitmapFromSource(imageSource, _options) {
1591
- const promise = new Promise((resolve, reject) => {
1592
- const image = this.createCanvasImage();
1593
- image.onload = () => {
1594
- try {
1595
- const imageBitmap = this._engine.createImageBitmap(image);
1596
- resolve(imageBitmap);
1597
- }
1598
- catch (error) {
1599
- // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
1600
- reject(`Error loading image ${image.src} with exception: ${error}`);
1601
- }
1602
- };
1603
- image.onerror = (error) => {
1604
- // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
1605
- reject(`Error loading image ${image.src} with exception: ${error}`);
1606
- };
1607
- image.src = imageSource;
1608
- });
1609
- return await promise;
1610
- }
1611
- /**
1612
- * Engine abstraction for createImageBitmap
1613
- * @param image source for image
1614
- * @param options An object that sets options for the image's extraction.
1615
- * @returns ImageBitmap
1616
- */
1617
- async createImageBitmap(image, options) {
1618
- // Back-compat: Because of the previous Blob hack, this could be an array of BlobParts.
1619
- if (Array.isArray(image)) {
1620
- const arr = image;
1621
- if (arr.length) {
1622
- return this._engine.createImageBitmap(arr[0]);
1623
- }
1624
- }
1625
- if (image instanceof Blob) {
1626
- const data = await image.arrayBuffer();
1627
- return this._engine.createImageBitmap(data);
1628
- }
1629
- throw new Error("Unsupported data for createImageBitmap.");
1630
- }
1631
- /**
1632
- * Resize an image and returns the image data as an uint8array
1633
- * @param image image to resize
1634
- * @param bufferWidth destination buffer width
1635
- * @param bufferHeight destination buffer height
1636
- * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size
1637
- */
1638
- resizeImageBitmap(image, bufferWidth, bufferHeight) {
1639
- return this._engine.resizeImageBitmap(image, bufferWidth, bufferHeight);
1640
- }
1641
- /**
1642
- * Creates a cube texture
1643
- * @param rootUrl defines the url where the files to load is located
1644
- * @param scene defines the current scene
1645
- * @param files defines the list of files to load (1 per face)
1646
- * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
1647
- * @param onLoad defines an optional callback raised when the texture is loaded
1648
- * @param onError defines an optional callback raised if there is an issue to load the texture
1649
- * @param format defines the format of the data
1650
- * @param forcedExtension defines the extension to use to pick the right loader
1651
- * @param createPolynomials if a polynomial sphere should be created for the cube texture
1652
- * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
1653
- * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
1654
- * @param fallback defines texture to use while falling back when (compressed) texture file not found.
1655
- * @param loaderOptions options to be passed to the loader
1656
- * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).
1657
- * @param buffer defines the data buffer to load instead of loading the rootUrl
1658
- * @returns the cube texture as an InternalTexture
1659
- */
1660
- createCubeTexture(rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false, buffer = null) {
1661
- const texture = fallback ? fallback : new InternalTexture(this, 7 /* InternalTextureSource.Cube */);
1662
- texture.isCube = true;
1663
- texture.url = rootUrl;
1664
- texture.generateMipMaps = !noMipmap;
1665
- texture._lodGenerationScale = lodScale;
1666
- texture._lodGenerationOffset = lodOffset;
1667
- texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !!noMipmap);
1668
- if (!this._doNotHandleContextLost) {
1669
- texture._extension = forcedExtension;
1670
- texture._files = files;
1671
- texture._buffer = buffer;
1672
- }
1673
- const lastDot = rootUrl.lastIndexOf(".");
1674
- const extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "";
1675
- // TODO: use texture loader to load env files?
1676
- if (extension === ".env") {
1677
- const onloaddata = (data) => {
1678
- const info = GetEnvInfo(data);
1679
- texture.width = info.width;
1680
- texture.height = info.width;
1681
- UploadEnvSpherical(texture, info);
1682
- const specularInfo = info.specular;
1683
- if (!specularInfo) {
1684
- throw new Error(`Nothing else parsed so far`);
1685
- }
1686
- texture._lodGenerationScale = specularInfo.lodGenerationScale;
1687
- const imageData = CreateRadianceImageDataArrayBufferViews(data, info);
1688
- texture.format = 5;
1689
- texture.type = 0;
1690
- texture.generateMipMaps = true;
1691
- texture.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, texture);
1692
- texture._isRGBD = true;
1693
- texture.invertY = true;
1694
- this._engine.loadCubeTextureWithMips(texture._hardwareTexture.underlyingResource, imageData, false, texture._useSRGBBuffer, () => {
1695
- texture.isReady = true;
1696
- if (onLoad) {
1697
- onLoad();
1698
- }
1699
- }, () => {
1700
- throw new Error("Could not load a native cube texture.");
1701
- });
1702
- };
1703
- if (buffer) {
1704
- onloaddata(buffer);
1705
- }
1706
- else if (files && files.length === 6) {
1707
- throw new Error(`Multi-file loading not allowed on env files.`);
1708
- }
1709
- else {
1710
- const onInternalError = (request, exception) => {
1711
- if (onError && request) {
1712
- onError(request.status + " " + request.statusText, exception);
1713
- }
1714
- };
1715
- this._loadFile(rootUrl, (data) => {
1716
- onloaddata(new Uint8Array(data, 0, data.byteLength));
1717
- }, undefined, undefined, true, onInternalError);
1718
- }
1719
- }
1720
- else {
1721
- if (!files || files.length !== 6) {
1722
- throw new Error("Cannot load cubemap because 6 files were not defined");
1723
- }
1724
- // Reorder from [+X, +Y, +Z, -X, -Y, -Z] to [+X, -X, +Y, -Y, +Z, -Z].
1725
- const reorderedFiles = [files[0], files[3], files[1], files[4], files[2], files[5]];
1726
- // eslint-disable-next-line github/no-then
1727
- Promise.all(reorderedFiles.map(async (file) => await this._loadFileAsync(file, undefined, true).then((data) => new Uint8Array(data, 0, data.byteLength))))
1728
- // eslint-disable-next-line github/no-then
1729
- .then(async (data) => {
1730
- return await new Promise((resolve, reject) => {
1731
- this._engine.loadCubeTexture(texture._hardwareTexture.underlyingResource, data, !noMipmap, true, texture._useSRGBBuffer, resolve, reject);
1732
- });
1733
- })
1734
- // eslint-disable-next-line github/no-then
1735
- .then(() => {
1736
- texture.isReady = true;
1737
- if (onLoad) {
1738
- onLoad();
1739
- }
1740
- }, (error) => {
1741
- if (onError) {
1742
- onError(`Failed to load cubemap: ${error.message}`, error);
1743
- }
1744
- });
1745
- }
1746
- this._internalTexturesCache.push(texture);
1747
- return texture;
1748
- }
1749
- /** @internal */
1750
- _createHardwareTexture() {
1751
- return new NativeHardwareTexture(this._createTexture(), this._engine);
1752
- }
1753
- /** @internal */
1754
- _createHardwareRenderTargetWrapper(isMulti, isCube, size) {
1755
- const rtWrapper = new NativeRenderTargetWrapper(isMulti, isCube, size, this);
1756
- this._renderTargetWrapperCache.push(rtWrapper);
1757
- return rtWrapper;
1758
- }
1759
- /** @internal */
1760
- _createInternalTexture(size, options, _delayGPUTextureCreation = true, source = 0 /* InternalTextureSource.Unknown */) {
1761
- let generateMipMaps = false;
1762
- let type = 0;
1763
- let samplingMode = 3;
1764
- let format = 5;
1765
- let useSRGBBuffer = false;
1766
- let samples = 1;
1767
- let label;
1768
- if (options !== undefined && typeof options === "object") {
1769
- generateMipMaps = !!options.generateMipMaps;
1770
- type = options.type === undefined ? 0 : options.type;
1771
- samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;
1772
- format = options.format === undefined ? 5 : options.format;
1773
- useSRGBBuffer = options.useSRGBBuffer === undefined ? false : options.useSRGBBuffer;
1774
- samples = options.samples ?? 1;
1775
- label = options.label;
1776
- }
1777
- else {
1778
- generateMipMaps = !!options;
1779
- }
1780
- useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps);
1781
- if (type === 1 && !this._caps.textureFloatLinearFiltering) {
1782
- // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
1783
- samplingMode = 1;
1784
- }
1785
- else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {
1786
- // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
1787
- samplingMode = 1;
1788
- }
1789
- if (type === 1 && !this._caps.textureFloat) {
1790
- type = 0;
1791
- Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE");
1792
- }
1793
- const texture = new InternalTexture(this, source);
1794
- const width = size.width ?? size;
1795
- const height = size.height ?? size;
1796
- const layers = size.layers || 0;
1797
- if (layers !== 0) {
1798
- throw new Error("Texture layers are not supported in Babylon Native");
1799
- }
1800
- const nativeTexture = texture._hardwareTexture.underlyingResource;
1801
- const nativeTextureFormat = getNativeTextureFormat(format, type);
1802
- // REVIEW: We are always setting the renderTarget flag as we don't know whether the texture will be used as a render target.
1803
- this._engine.initializeTexture(nativeTexture, width, height, generateMipMaps, nativeTextureFormat, true, useSRGBBuffer, samples);
1804
- this._setTextureSampling(nativeTexture, getNativeSamplingMode(samplingMode));
1805
- texture._useSRGBBuffer = useSRGBBuffer;
1806
- texture.baseWidth = width;
1807
- texture.baseHeight = height;
1808
- texture.width = width;
1809
- texture.height = height;
1810
- texture.depth = layers;
1811
- texture.isReady = true;
1812
- texture.samples = samples;
1813
- texture.generateMipMaps = generateMipMaps;
1814
- texture.samplingMode = samplingMode;
1815
- texture.type = type;
1816
- texture.format = format;
1817
- texture.label = label;
1818
- this._internalTexturesCache.push(texture);
1819
- return texture;
1820
- }
1821
- createRenderTargetTexture(size, options) {
1822
- const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);
1823
- let generateDepthBuffer = true;
1824
- let generateStencilBuffer = false;
1825
- let noColorAttachment = false;
1826
- let colorAttachment = undefined;
1827
- let samples = 1;
1828
- if (options !== undefined && typeof options === "object") {
1829
- generateDepthBuffer = options.generateDepthBuffer ?? true;
1830
- generateStencilBuffer = !!options.generateStencilBuffer;
1831
- noColorAttachment = !!options.noColorAttachment;
1832
- colorAttachment = options.colorAttachment;
1833
- samples = options.samples ?? 1;
1834
- }
1835
- const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, 5 /* InternalTextureSource.RenderTarget */));
1836
- const width = size.width ?? size;
1837
- const height = size.height ?? size;
1838
- const framebuffer = this._engine.createFrameBuffer(texture ? texture._hardwareTexture.underlyingResource : null, width, height, generateStencilBuffer, generateDepthBuffer, samples);
1839
- rtWrapper._framebuffer = framebuffer;
1840
- rtWrapper._generateDepthBuffer = generateDepthBuffer;
1841
- rtWrapper._generateStencilBuffer = generateStencilBuffer;
1842
- rtWrapper._samples = samples;
1843
- rtWrapper.setTextures(texture);
1844
- return rtWrapper;
1845
- }
1846
- updateRenderTargetTextureSampleCount(rtWrapper, samples) {
1847
- Logger.Warn("Updating render target sample count is not currently supported");
1848
- return rtWrapper.samples;
1849
- }
1850
- updateTextureSamplingMode(samplingMode, texture) {
1851
- if (texture._hardwareTexture) {
1852
- const filter = getNativeSamplingMode(samplingMode);
1853
- this._setTextureSampling(texture._hardwareTexture.underlyingResource, filter);
1854
- }
1855
- texture.samplingMode = samplingMode;
1856
- }
1857
- bindFramebuffer(texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
1858
- const nativeRTWrapper = texture;
1859
- if (this._currentRenderTarget) {
1860
- this.unBindFramebuffer(this._currentRenderTarget);
1861
- }
1862
- this._currentRenderTarget = texture;
1863
- if (faceIndex) {
1864
- throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");
1865
- }
1866
- if (requiredWidth || requiredHeight) {
1867
- throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");
1868
- }
1869
- if (nativeRTWrapper._framebufferDepthStencil) {
1870
- this._bindUnboundFramebuffer(nativeRTWrapper._framebufferDepthStencil);
1871
- }
1872
- else {
1873
- this._bindUnboundFramebuffer(nativeRTWrapper._framebuffer);
1874
- }
1875
- }
1876
- unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) {
1877
- // NOTE: Disabling mipmap generation is not yet supported in NativeEngine.
1878
- this._currentRenderTarget = null;
1879
- if (onBeforeUnbind) {
1880
- onBeforeUnbind();
1881
- }
1882
- this._bindUnboundFramebuffer(null);
1883
- }
1884
- createDynamicVertexBuffer(data) {
1885
- return this.createVertexBuffer(data, true);
1886
- }
1887
- updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) {
1888
- const buffer = indexBuffer;
1889
- const data = this._normalizeIndexData(indices);
1890
- buffer.is32Bits = data.BYTES_PER_ELEMENT === 4;
1891
- this._engine.updateDynamicIndexBuffer(buffer.nativeIndexBuffer, data.buffer, data.byteOffset, data.byteLength, offset);
1892
- }
1893
- updateDynamicVertexBuffer(vertexBuffer, data, byteOffset = 0, byteLength) {
1894
- const buffer = vertexBuffer;
1895
- const dataView = data instanceof Array ? new Float32Array(data) : data instanceof ArrayBuffer ? new Uint8Array(data) : data;
1896
- const byteView = new Uint8Array(dataView.buffer, dataView.byteOffset, byteLength ?? dataView.byteLength);
1897
- this._engine.updateDynamicVertexBuffer(buffer.nativeVertexBuffer, byteView.buffer, byteView.byteOffset, byteView.byteLength, byteOffset);
1898
- }
1899
- // TODO: Refactor to share more logic with base Engine implementation.
1900
- /**
1901
- * @internal
1902
- */
1903
- _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false) {
1904
- const uniform = this._boundUniforms[channel];
1905
- if (!uniform) {
1906
- return false;
1907
- }
1908
- // Not ready?
1909
- if (!texture) {
1910
- if (this._boundTexturesCache[channel] != null) {
1911
- this._activeChannel = channel;
1912
- this._boundTexturesCache[channel] = null;
1913
- this._unsetNativeTexture(uniform);
1914
- }
1915
- return false;
1916
- }
1917
- // Video
1918
- if (texture.video) {
1919
- this._activeChannel = channel;
1920
- texture.update();
1921
- }
1922
- else if (texture.delayLoadState === 4) {
1923
- // Delay loading
1924
- texture.delayLoad();
1925
- return false;
1926
- }
1927
- let internalTexture;
1928
- if (depthStencilTexture) {
1929
- internalTexture = texture.depthStencilTexture;
1930
- }
1931
- else if (texture.isReady()) {
1932
- internalTexture = texture.getInternalTexture();
1933
- }
1934
- else if (texture.isCube) {
1935
- internalTexture = this.emptyCubeTexture;
1936
- }
1937
- else if (texture.is3D) {
1938
- internalTexture = this.emptyTexture3D;
1939
- }
1940
- else if (texture.is2DArray) {
1941
- internalTexture = this.emptyTexture2DArray;
1942
- }
1943
- else {
1944
- internalTexture = this.emptyTexture;
1945
- }
1946
- this._activeChannel = channel;
1947
- if (!internalTexture || !internalTexture._hardwareTexture) {
1948
- return false;
1949
- }
1950
- this._setTextureWrapMode(internalTexture._hardwareTexture.underlyingResource, getNativeAddressMode(texture.wrapU), getNativeAddressMode(texture.wrapV), getNativeAddressMode(texture.wrapR));
1951
- this._updateAnisotropicLevel(texture);
1952
- this._setNativeTexture(uniform, internalTexture._hardwareTexture.underlyingResource);
1953
- return true;
1954
- }
1955
- // filter is a NativeFilter.XXXX value.
1956
- _setTextureSampling(texture, filter) {
1957
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING);
1958
- this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);
1959
- this._commandBufferEncoder.encodeCommandArgAsUInt32(filter);
1960
- this._commandBufferEncoder.finishEncodingCommand();
1961
- }
1962
- // addressModes are NativeAddressMode.XXXX values.
1963
- _setTextureWrapMode(texture, addressModeU, addressModeV, addressModeW) {
1964
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE);
1965
- this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);
1966
- this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeU);
1967
- this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeV);
1968
- this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeW);
1969
- this._commandBufferEncoder.finishEncodingCommand();
1970
- }
1971
- _setNativeTexture(uniform, texture) {
1972
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE);
1973
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1974
- this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);
1975
- this._commandBufferEncoder.finishEncodingCommand();
1976
- }
1977
- _unsetNativeTexture(uniform) {
1978
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNSETTEXTURE);
1979
- this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);
1980
- this._commandBufferEncoder.finishEncodingCommand();
1981
- }
1982
- // TODO: Share more of this logic with the base implementation.
1983
- // TODO: Rename to match naming in base implementation once refactoring allows different parameters.
1984
- _updateAnisotropicLevel(texture) {
1985
- const internalTexture = texture.getInternalTexture();
1986
- const value = texture.anisotropicFilteringLevel;
1987
- if (!internalTexture || !internalTexture._hardwareTexture) {
1988
- return;
1989
- }
1990
- if (internalTexture._cachedAnisotropicFilteringLevel !== value) {
1991
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL);
1992
- this._commandBufferEncoder.encodeCommandArgAsNativeData(internalTexture._hardwareTexture.underlyingResource);
1993
- this._commandBufferEncoder.encodeCommandArgAsUInt32(value);
1994
- this._commandBufferEncoder.finishEncodingCommand();
1995
- internalTexture._cachedAnisotropicFilteringLevel = value;
1996
- }
1997
- }
1998
28
  /**
1999
29
  * @internal
2000
30
  */
2001
- _bindTexture(channel, texture) {
2002
- const uniform = this._boundUniforms[channel];
2003
- if (!uniform) {
2004
- return;
2005
- }
2006
- if (texture && texture._hardwareTexture) {
2007
- const underlyingResource = texture._hardwareTexture.underlyingResource;
2008
- this._setNativeTexture(uniform, underlyingResource);
2009
- }
2010
- else {
2011
- this._unsetNativeTexture(uniform);
2012
- }
2013
- }
2014
- /**
2015
- * Unbind all textures
2016
- */
2017
- unbindAllTextures() {
2018
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DISCARDALLTEXTURES);
2019
- this._commandBufferEncoder.finishEncodingCommand();
2020
- }
2021
- _deleteBuffer(buffer) {
2022
- if (buffer.nativeIndexBuffer) {
2023
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER);
2024
- this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer.nativeIndexBuffer);
2025
- this._commandBufferEncoder.finishEncodingCommand();
2026
- delete buffer.nativeIndexBuffer;
2027
- }
2028
- if (buffer.nativeVertexBuffer) {
2029
- this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER);
2030
- this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer.nativeVertexBuffer);
2031
- this._commandBufferEncoder.finishEncodingCommand();
2032
- delete buffer.nativeVertexBuffer;
2033
- }
2034
- }
2035
- /**
2036
- * Create a canvas
2037
- * @param width width
2038
- * @param height height
2039
- * @returns ICanvas interface
2040
- */
2041
- createCanvas(width, height) {
2042
- if (!_native.Canvas) {
2043
- throw new Error("Native Canvas plugin not available.");
2044
- }
2045
- const canvas = new _native.Canvas();
2046
- canvas.width = width;
2047
- canvas.height = height;
2048
- return canvas;
2049
- }
2050
- /**
2051
- * Create an image to use with canvas
2052
- * @returns IImage interface
2053
- */
2054
- createCanvasImage() {
2055
- if (!_native.Image) {
2056
- throw new Error("Native Canvas plugin not available.");
2057
- }
2058
- const image = new _native.Image();
2059
- return image;
2060
- }
2061
- /**
2062
- * Create a 2D path to use with canvas
2063
- * @returns IPath2D interface
2064
- * @param d SVG path string
2065
- */
2066
- createCanvasPath2D(d) {
2067
- if (!_native.Path2D) {
2068
- throw new Error("Native Canvas plugin not available.");
2069
- }
2070
- const path2d = new _native.Path2D(d);
2071
- return path2d;
2072
- }
2073
- /**
2074
- * Update a portion of an internal texture
2075
- * @param texture defines the texture to update
2076
- * @param imageData defines the data to store into the texture
2077
- * @param xOffset defines the x coordinates of the update rectangle
2078
- * @param yOffset defines the y coordinates of the update rectangle
2079
- * @param width defines the width of the update rectangle
2080
- * @param height defines the height of the update rectangle
2081
- * @param faceIndex defines the face index if texture is a cube (0 by default)
2082
- * @param lod defines the lod level to update (0 by default)
2083
- * @param generateMipMaps defines whether to generate mipmaps or not
2084
- */
2085
- updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) {
2086
- throw new Error("updateTextureData not implemented.");
2087
- }
2088
- /**
2089
- * @internal
2090
- */
2091
- _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) {
2092
- throw new Error("_uploadCompressedDataToTextureDirectly not implemented.");
2093
- }
2094
- /**
2095
- * @internal
2096
- */
2097
- _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0) {
2098
- throw new Error("_uploadDataToTextureDirectly not implemented.");
2099
- }
2100
- /**
2101
- * @internal
2102
- */
2103
- _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) {
2104
- throw new Error("_uploadArrayBufferViewToTexture not implemented.");
2105
- }
2106
- /**
2107
- * @internal
2108
- */
2109
- _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) {
31
+ _uploadImageToTexture(texture, image, _faceIndex = 0, _lod = 0) {
2110
32
  throw new Error("_uploadArrayBufferViewToTexture not implemented.");
2111
33
  }
2112
- getFontOffset(font) {
2113
- // TODO
2114
- const result = { ascent: 0, height: 0, descent: 0 };
2115
- return result;
2116
- }
2117
- /**
2118
- * No equivalent for native. Do nothing.
2119
- */
2120
- flushFramebuffer() { }
2121
- // eslint-disable-next-line @typescript-eslint/promise-function-async
2122
- _readTexturePixels(texture, width, height, faceIndex, level, buffer, _flushRenderer, _noDataConversion, x, y) {
2123
- if (faceIndex !== undefined && faceIndex !== -1) {
2124
- throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${faceIndex}.`);
2125
- }
2126
- return (this._engine
2127
- .readTexture(texture._hardwareTexture?.underlyingResource, level ?? 0, x ?? 0, y ?? 0, width, height, buffer?.buffer ?? null, buffer?.byteOffset ?? 0, buffer?.byteLength ?? 0)
2128
- // eslint-disable-next-line github/no-then
2129
- .then((rawBuffer) => {
2130
- if (!buffer) {
2131
- buffer = new Uint8Array(rawBuffer);
34
+ }
35
+ /**
36
+ * @internal
37
+ * Applies the functionality of one or more base constructors to a derived constructor.
38
+ */
39
+ function applyMixins(derivedCtor, constructors) {
40
+ constructors.forEach((baseCtor) => {
41
+ Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
42
+ if (name !== "constructor") {
43
+ derivedCtor.prototype[name] = baseCtor.prototype[name];
2132
44
  }
2133
- return buffer;
2134
- }));
2135
- }
2136
- startTimeQuery() {
2137
- if (!this._gpuFrameTimeToken) {
2138
- this._gpuFrameTimeToken = new _TimeToken();
2139
- }
2140
- // Always return the same time token. For native, we don't need a start marker, we just query for native frame stats.
2141
- return this._gpuFrameTimeToken;
2142
- }
2143
- endTimeQuery(token) {
2144
- this._engine.populateFrameStats(this._frameStats);
2145
- return this._frameStats.gpuTimeNs;
2146
- }
45
+ });
46
+ });
2147
47
  }
2148
- // This must match the protocol version in NativeEngine.cpp
2149
- NativeEngine.PROTOCOL_VERSION = 9;
48
+ // Apply the ThinNativeEngine mixins to the NativeEngine.
49
+ applyMixins(NativeEngine, [ThinNativeEngine]);
2150
50
  //# sourceMappingURL=nativeEngine.js.map