nativeEngine.ts 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170
  1. import { Nullable, IndicesArray, DataArray } from "../types";
  2. import { Engine } from "../Engines/engine";
  3. import { VertexBuffer } from "../Meshes/buffer";
  4. import { InternalTexture, InternalTextureSource } from "../Materials/Textures/internalTexture";
  5. import { IInternalTextureLoader } from "../Materials/Textures/internalTextureLoader";
  6. import { Texture } from "../Materials/Textures/texture";
  7. import { BaseTexture } from "../Materials/Textures/baseTexture";
  8. import { VideoTexture } from "../Materials/Textures/videoTexture";
  9. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  10. import { Effect } from "../Materials/effect";
  11. import { DataBuffer } from '../Meshes/dataBuffer';
  12. import { Tools } from "../Misc/tools";
  13. import { Observer } from "../Misc/observable";
  14. import { EnvironmentTextureTools, EnvironmentTextureSpecularInfoV1 } from "../Misc/environmentTextureTools";
  15. import { Scene } from "../scene";
  16. import { RenderTargetCreationOptions } from "../Materials/Textures/renderTargetCreationOptions";
  17. import { IPipelineContext } from './IPipelineContext';
  18. import { IMatrixLike, IVector2Like, IVector3Like, IVector4Like, IColor3Like, IColor4Like, IViewportLike } from '../Maths/math.like';
  19. import { Logger } from "../Misc/logger";
  20. import { Constants } from './constants';
  21. import { ThinEngine, ISceneLike } from './thinEngine';
  22. import { IWebRequest } from '../Misc/interfaces/iWebRequest';
  23. import { EngineStore } from './engineStore';
  24. import { ShaderCodeInliner } from "./Processors/shaderCodeInliner";
  25. import { WebGL2ShaderProcessor } from '../Engines/WebGL/webGL2ShaderProcessors';
  26. import { RenderTargetTextureSize } from '../Engines/Extensions/engine.renderTarget';
  27. import { DepthTextureCreationOptions } from '../Engines/depthTextureCreationOptions';
  28. interface INativeEngine {
  29. readonly TEXTURE_NEAREST_NEAREST: number;
  30. readonly TEXTURE_LINEAR_LINEAR: number;
  31. readonly TEXTURE_LINEAR_LINEAR_MIPLINEAR: number;
  32. readonly TEXTURE_NEAREST_NEAREST_MIPNEAREST: number;
  33. readonly TEXTURE_NEAREST_LINEAR_MIPNEAREST: number;
  34. readonly TEXTURE_NEAREST_LINEAR_MIPLINEAR: number;
  35. readonly TEXTURE_NEAREST_LINEAR: number;
  36. readonly TEXTURE_NEAREST_NEAREST_MIPLINEAR: number;
  37. readonly TEXTURE_LINEAR_NEAREST_MIPNEAREST: number;
  38. readonly TEXTURE_LINEAR_NEAREST_MIPLINEAR: number;
  39. readonly TEXTURE_LINEAR_LINEAR_MIPNEAREST: number;
  40. readonly TEXTURE_LINEAR_NEAREST: number;
  41. readonly DEPTH_TEST_LESS: number;
  42. readonly DEPTH_TEST_LEQUAL: number;
  43. readonly DEPTH_TEST_EQUAL: number;
  44. readonly DEPTH_TEST_GEQUAL: number;
  45. readonly DEPTH_TEST_GREATER: number;
  46. readonly DEPTH_TEST_NOTEQUAL: number;
  47. readonly DEPTH_TEST_NEVER: number;
  48. readonly DEPTH_TEST_ALWAYS: number;
  49. readonly CLEAR_FLAG_COLOR: number;
  50. readonly CLEAR_FLAG_DEPTH: number;
  51. readonly CLEAR_FLAG_STENCIL: number;
  52. readonly ADDRESS_MODE_WRAP: number;
  53. readonly ADDRESS_MODE_MIRROR: number;
  54. readonly ADDRESS_MODE_CLAMP: number;
  55. readonly ADDRESS_MODE_BORDER: number;
  56. readonly ADDRESS_MODE_MIRROR_ONCE: number;
  57. readonly TEXTURE_FORMAT_RGBA8: number;
  58. readonly TEXTURE_FORMAT_RGBA32F: number;
  59. readonly ATTRIB_TYPE_UINT8: number;
  60. readonly ATTRIB_TYPE_INT16: number;
  61. readonly ATTRIB_TYPE_FLOAT: number;
  62. readonly ALPHA_DISABLE: number;
  63. readonly ALPHA_ADD: number;
  64. readonly ALPHA_COMBINE: number;
  65. readonly ALPHA_SUBTRACT: number;
  66. readonly ALPHA_MULTIPLY: number;
  67. readonly ALPHA_MAXIMIZED: number;
  68. readonly ALPHA_ONEONE: number;
  69. readonly ALPHA_PREMULTIPLIED: number;
  70. readonly ALPHA_PREMULTIPLIED_PORTERDUFF: number;
  71. readonly ALPHA_INTERPOLATE: number;
  72. readonly ALPHA_SCREENMODE: number;
  73. dispose(): void;
  74. requestAnimationFrame(callback: () => void): void;
  75. createVertexArray(): any;
  76. deleteVertexArray(vertexArray: any): void;
  77. bindVertexArray(vertexArray: any): void;
  78. createIndexBuffer(data: ArrayBufferView, dynamic: boolean): any;
  79. deleteIndexBuffer(buffer: any): void;
  80. recordIndexBuffer(vertexArray: any, buffer: any): void;
  81. updateDynamicIndexBuffer(buffer: any, data: ArrayBufferView, startingIndex: number): void;
  82. createVertexBuffer(data: ArrayBufferView, dynamic: boolean): any;
  83. deleteVertexBuffer(buffer: any): void;
  84. recordVertexBuffer(vertexArray: any, buffer: any, location: number, byteOffset: number, byteStride: number, numElements: number, type: number, normalized: boolean): void;
  85. updateDynamicVertexBuffer(buffer: any, data: ArrayBufferView, byteOffset: number, byteLength: number): void;
  86. createProgram(vertexShader: string, fragmentShader: string): any;
  87. getUniforms(shaderProgram: any, uniformsNames: string[]): WebGLUniformLocation[];
  88. getAttributes(shaderProgram: any, attributeNames: string[]): number[];
  89. setProgram(program: any): void;
  90. setState(culling: boolean, zOffset: number, reverseSide: boolean): void;
  91. setZOffset(zOffset: number): void;
  92. getZOffset(): number;
  93. setDepthTest(enable: number): void;
  94. getDepthWrite(): boolean;
  95. setDepthWrite(enable: boolean): void;
  96. setColorWrite(enable: boolean): void;
  97. setBlendMode(blendMode: number): void;
  98. setMatrix(uniform: WebGLUniformLocation, matrix: Float32Array): void;
  99. setInt(uniform: WebGLUniformLocation, int: number): void;
  100. setInt2(uniform: WebGLUniformLocation, int1: number, int2: number): void;
  101. setInt3(uniform: WebGLUniformLocation, int1: number, int2: number, int3: number): void;
  102. setInt4(uniform: WebGLUniformLocation, int1: number, int2: number, int3: number, int4: number): void;
  103. setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void;
  104. setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void;
  105. setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void;
  106. setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void;
  107. setFloatArray(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  108. setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  109. setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  110. setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array | number[]): void;
  111. setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void;
  112. setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void;
  113. setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void;
  114. setFloat(uniform: WebGLUniformLocation, value: number): void;
  115. setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void;
  116. setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void;
  117. setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void;
  118. createTexture(): WebGLTexture;
  119. createDepthTexture(texture: WebGLTexture, width: number, height: number): WebGLTexture;
  120. loadTexture(texture: WebGLTexture, data: ArrayBufferView, generateMips: boolean, invertY: boolean, onSuccess: () => void, onError: () => void): void;
  121. loadCubeTexture(texture: WebGLTexture, data: Array<ArrayBufferView>, generateMips: boolean, onSuccess: () => void, onError: () => void): void;
  122. loadCubeTextureWithMips(texture: WebGLTexture, data: Array<Array<ArrayBufferView>>, onSuccess: () => void, onError: () => void): void;
  123. getTextureWidth(texture: WebGLTexture): number;
  124. getTextureHeight(texture: WebGLTexture): number;
  125. setTextureSampling(texture: WebGLTexture, filter: number): void; // filter is a NativeFilter.XXXX value.
  126. setTextureWrapMode(texture: WebGLTexture, addressModeU: number, addressModeV: number, addressModeW: number): void; // addressModes are NativeAddressMode.XXXX values.
  127. setTextureAnisotropicLevel(texture: WebGLTexture, value: number): void;
  128. setTexture(uniform: WebGLUniformLocation, texture: Nullable<WebGLTexture>): void;
  129. deleteTexture(texture: Nullable<WebGLTexture>): void;
  130. createFramebuffer(texture: WebGLTexture, width: number, height: number, format: number, samplingMode: number, generateStencilBuffer: boolean, generateDepthBuffer: boolean, generateMips: boolean): WebGLFramebuffer;
  131. deleteFramebuffer(framebuffer: WebGLFramebuffer): void;
  132. bindFramebuffer(framebuffer: WebGLFramebuffer): void;
  133. unbindFramebuffer(framebuffer: WebGLFramebuffer): void;
  134. drawIndexed(fillMode: number, indexStart: number, indexCount: number): void;
  135. draw(fillMode: number, vertexStart: number, vertexCount: number): void;
  136. clear(flags: number): void;
  137. clearColor(r: number, g: number, b: number, a: number): void;
  138. clearDepth(depth: number): void;
  139. clearStencil(stencil: number): void;
  140. getRenderWidth(): number;
  141. getRenderHeight(): number;
  142. setViewPort(x: number, y: number, width: number, height: number): void;
  143. }
  144. class NativePipelineContext implements IPipelineContext {
  145. // TODO: async should be true?
  146. public isAsync = false;
  147. public isReady = false;
  148. public _getVertexShaderCode(): string | null {
  149. return null;
  150. }
  151. public _getFragmentShaderCode(): string | null {
  152. return null;
  153. }
  154. // TODO: what should this do?
  155. public _handlesSpectorRebuildCallback(onCompiled: (compiledObject: any) => void): void {
  156. throw new Error("Not implemented");
  157. }
  158. public nativeProgram: any;
  159. private _valueCache: { [key: string]: any } = {};
  160. private _uniforms: { [key: string]: Nullable<WebGLUniformLocation> };
  161. public engine: NativeEngine;
  162. public context?: WebGLRenderingContext;
  163. public vertexShader?: WebGLShader;
  164. public fragmentShader?: WebGLShader;
  165. public isParallelCompiled: boolean;
  166. public onCompiled?: () => void;
  167. public transformFeedback?: WebGLTransformFeedback | null;
  168. public _fillEffectInformation(effect: Effect, uniformBuffersNames: { [key: string]: number }, uniformsNames: string[], uniforms: { [key: string]: Nullable<WebGLUniformLocation> }, samplerList: string[], samplers: { [key: string]: number }, attributesNames: string[], attributes: number[]) {
  169. const engine = this.engine;
  170. if (engine.supportsUniformBuffers) {
  171. for (var name in uniformBuffersNames) {
  172. effect.bindUniformBlock(name, uniformBuffersNames[name]);
  173. }
  174. }
  175. const effectAvailableUniforms = this.engine.getUniforms(this, uniformsNames);
  176. effectAvailableUniforms.forEach((uniform, index) => {
  177. uniforms[uniformsNames[index]] = uniform;
  178. });
  179. this._uniforms = uniforms;
  180. let index: number;
  181. for (index = 0; index < samplerList.length; index++) {
  182. const sampler = effect.getUniform(samplerList[index]);
  183. if (sampler == null) {
  184. samplerList.splice(index, 1);
  185. index--;
  186. }
  187. }
  188. samplerList.forEach((name, index) => {
  189. samplers[name] = index;
  190. });
  191. attributes.push(...engine.getAttributes(this, attributesNames));
  192. }
  193. /**
  194. * Release all associated resources.
  195. **/
  196. public dispose() {
  197. this._uniforms = { };
  198. }
  199. /** @hidden */
  200. public _cacheMatrix(uniformName: string, matrix: IMatrixLike): boolean {
  201. var cache = this._valueCache[uniformName];
  202. var flag = matrix.updateFlag;
  203. if (cache !== undefined && cache === flag) {
  204. return false;
  205. }
  206. this._valueCache[uniformName] = flag;
  207. return true;
  208. }
  209. /** @hidden */
  210. public _cacheFloat2(uniformName: string, x: number, y: number): boolean {
  211. var cache = this._valueCache[uniformName];
  212. if (!cache) {
  213. cache = [x, y];
  214. this._valueCache[uniformName] = cache;
  215. return true;
  216. }
  217. var changed = false;
  218. if (cache[0] !== x) {
  219. cache[0] = x;
  220. changed = true;
  221. }
  222. if (cache[1] !== y) {
  223. cache[1] = y;
  224. changed = true;
  225. }
  226. return changed;
  227. }
  228. /** @hidden */
  229. public _cacheFloat3(uniformName: string, x: number, y: number, z: number): boolean {
  230. var cache = this._valueCache[uniformName];
  231. if (!cache) {
  232. cache = [x, y, z];
  233. this._valueCache[uniformName] = cache;
  234. return true;
  235. }
  236. var changed = false;
  237. if (cache[0] !== x) {
  238. cache[0] = x;
  239. changed = true;
  240. }
  241. if (cache[1] !== y) {
  242. cache[1] = y;
  243. changed = true;
  244. }
  245. if (cache[2] !== z) {
  246. cache[2] = z;
  247. changed = true;
  248. }
  249. return changed;
  250. }
  251. /** @hidden */
  252. public _cacheFloat4(uniformName: string, x: number, y: number, z: number, w: number): boolean {
  253. var cache = this._valueCache[uniformName];
  254. if (!cache) {
  255. cache = [x, y, z, w];
  256. this._valueCache[uniformName] = cache;
  257. return true;
  258. }
  259. var changed = false;
  260. if (cache[0] !== x) {
  261. cache[0] = x;
  262. changed = true;
  263. }
  264. if (cache[1] !== y) {
  265. cache[1] = y;
  266. changed = true;
  267. }
  268. if (cache[2] !== z) {
  269. cache[2] = z;
  270. changed = true;
  271. }
  272. if (cache[3] !== w) {
  273. cache[3] = w;
  274. changed = true;
  275. }
  276. return changed;
  277. }
  278. /**
  279. * Sets an interger value on a uniform variable.
  280. * @param uniformName Name of the variable.
  281. * @param value Value to be set.
  282. */
  283. public setInt(uniformName: string, value: number): void {
  284. var cache = this._valueCache[uniformName];
  285. if (cache !== undefined && cache === value) {
  286. return;
  287. }
  288. if (this.engine.setInt(this._uniforms[uniformName]!, value)) {
  289. this._valueCache[uniformName] = value;
  290. }
  291. }
  292. /**
  293. * Sets a int2 on a uniform variable.
  294. * @param uniformName Name of the variable.
  295. * @param x First int in int2.
  296. * @param y Second int in int2.
  297. */
  298. public setInt2(uniformName: string, x: number, y: number): void {
  299. if (this._cacheFloat2(uniformName, x, y)) {
  300. if (!this.engine.setInt2(this._uniforms[uniformName], x, y)) {
  301. this._valueCache[uniformName] = null;
  302. }
  303. }
  304. }
  305. /**
  306. * Sets a int3 on a uniform variable.
  307. * @param uniformName Name of the variable.
  308. * @param x First int in int3.
  309. * @param y Second int in int3.
  310. * @param y Third int in int3.
  311. */
  312. public setInt3(uniformName: string, x: number, y: number, z: number): void {
  313. if (this._cacheFloat3(uniformName, x, y, z)) {
  314. if (!this.engine.setInt3(this._uniforms[uniformName], x, y, z)) {
  315. this._valueCache[uniformName] = null;
  316. }
  317. }
  318. }
  319. /**
  320. * Sets a int4 on a uniform variable.
  321. * @param uniformName Name of the variable.
  322. * @param x First int in int4.
  323. * @param y Second int in int4.
  324. * @param y Third int in int4.
  325. * @param w Fourth int in int4.
  326. */
  327. public setInt4(uniformName: string, x: number, y: number, z: number, w: number): void {
  328. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  329. if (!this.engine.setInt4(this._uniforms[uniformName], x, y, z, w)) {
  330. this._valueCache[uniformName] = null;
  331. }
  332. }
  333. }
  334. /**
  335. * Sets an int array on a uniform variable.
  336. * @param uniformName Name of the variable.
  337. * @param array array to be set.
  338. */
  339. public setIntArray(uniformName: string, array: Int32Array): void {
  340. this._valueCache[uniformName] = null;
  341. this.engine.setIntArray(this._uniforms[uniformName]!, array);
  342. }
  343. /**
  344. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  345. * @param uniformName Name of the variable.
  346. * @param array array to be set.
  347. */
  348. public setIntArray2(uniformName: string, array: Int32Array): void {
  349. this._valueCache[uniformName] = null;
  350. this.engine.setIntArray2(this._uniforms[uniformName]!, array);
  351. }
  352. /**
  353. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  354. * @param uniformName Name of the variable.
  355. * @param array array to be set.
  356. */
  357. public setIntArray3(uniformName: string, array: Int32Array): void {
  358. this._valueCache[uniformName] = null;
  359. this.engine.setIntArray3(this._uniforms[uniformName]!, array);
  360. }
  361. /**
  362. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  363. * @param uniformName Name of the variable.
  364. * @param array array to be set.
  365. */
  366. public setIntArray4(uniformName: string, array: Int32Array): void {
  367. this._valueCache[uniformName] = null;
  368. this.engine.setIntArray4(this._uniforms[uniformName]!, array);
  369. }
  370. /**
  371. * Sets an float array on a uniform variable.
  372. * @param uniformName Name of the variable.
  373. * @param array array to be set.
  374. */
  375. public setFloatArray(uniformName: string, array: Float32Array): void {
  376. this._valueCache[uniformName] = null;
  377. this.engine.setFloatArray(this._uniforms[uniformName]!, array);
  378. }
  379. /**
  380. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  381. * @param uniformName Name of the variable.
  382. * @param array array to be set.
  383. */
  384. public setFloatArray2(uniformName: string, array: Float32Array): void {
  385. this._valueCache[uniformName] = null;
  386. this.engine.setFloatArray2(this._uniforms[uniformName]!, array);
  387. }
  388. /**
  389. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  390. * @param uniformName Name of the variable.
  391. * @param array array to be set.
  392. */
  393. public setFloatArray3(uniformName: string, array: Float32Array): void {
  394. this._valueCache[uniformName] = null;
  395. this.engine.setFloatArray3(this._uniforms[uniformName]!, array);
  396. }
  397. /**
  398. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  399. * @param uniformName Name of the variable.
  400. * @param array array to be set.
  401. */
  402. public setFloatArray4(uniformName: string, array: Float32Array): void {
  403. this._valueCache[uniformName] = null;
  404. this.engine.setFloatArray4(this._uniforms[uniformName]!, array);
  405. }
  406. /**
  407. * Sets an array on a uniform variable.
  408. * @param uniformName Name of the variable.
  409. * @param array array to be set.
  410. */
  411. public setArray(uniformName: string, array: number[]): void {
  412. this._valueCache[uniformName] = null;
  413. this.engine.setArray(this._uniforms[uniformName]!, array);
  414. }
  415. /**
  416. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  417. * @param uniformName Name of the variable.
  418. * @param array array to be set.
  419. */
  420. public setArray2(uniformName: string, array: number[]): void {
  421. this._valueCache[uniformName] = null;
  422. this.engine.setArray2(this._uniforms[uniformName]!, array);
  423. }
  424. /**
  425. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  426. * @param uniformName Name of the variable.
  427. * @param array array to be set.
  428. * @returns this effect.
  429. */
  430. public setArray3(uniformName: string, array: number[]): void {
  431. this._valueCache[uniformName] = null;
  432. this.engine.setArray3(this._uniforms[uniformName]!, array);
  433. }
  434. /**
  435. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  436. * @param uniformName Name of the variable.
  437. * @param array array to be set.
  438. */
  439. public setArray4(uniformName: string, array: number[]): void {
  440. this._valueCache[uniformName] = null;
  441. this.engine.setArray4(this._uniforms[uniformName]!, array);
  442. }
  443. /**
  444. * Sets matrices on a uniform variable.
  445. * @param uniformName Name of the variable.
  446. * @param matrices matrices to be set.
  447. */
  448. public setMatrices(uniformName: string, matrices: Float32Array): void {
  449. if (!matrices) {
  450. return;
  451. }
  452. this._valueCache[uniformName] = null;
  453. this.engine.setMatrices(this._uniforms[uniformName]!, matrices);
  454. }
  455. /**
  456. * Sets matrix on a uniform variable.
  457. * @param uniformName Name of the variable.
  458. * @param matrix matrix to be set.
  459. */
  460. public setMatrix(uniformName: string, matrix: IMatrixLike): void {
  461. if (this._cacheMatrix(uniformName, matrix)) {
  462. if (!this.engine.setMatrices(this._uniforms[uniformName]!, matrix.toArray() as Float32Array)) {
  463. this._valueCache[uniformName] = null;
  464. }
  465. }
  466. }
  467. /**
  468. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  469. * @param uniformName Name of the variable.
  470. * @param matrix matrix to be set.
  471. */
  472. public setMatrix3x3(uniformName: string, matrix: Float32Array): void {
  473. this._valueCache[uniformName] = null;
  474. this.engine.setMatrix3x3(this._uniforms[uniformName]!, matrix);
  475. }
  476. /**
  477. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  478. * @param uniformName Name of the variable.
  479. * @param matrix matrix to be set.
  480. */
  481. public setMatrix2x2(uniformName: string, matrix: Float32Array): void {
  482. this._valueCache[uniformName] = null;
  483. this.engine.setMatrix2x2(this._uniforms[uniformName]!, matrix);
  484. }
  485. /**
  486. * Sets a float on a uniform variable.
  487. * @param uniformName Name of the variable.
  488. * @param value value to be set.
  489. * @returns this effect.
  490. */
  491. public setFloat(uniformName: string, value: number): void {
  492. var cache = this._valueCache[uniformName];
  493. if (cache !== undefined && cache === value) {
  494. return;
  495. }
  496. if (this.engine.setFloat(this._uniforms[uniformName]!, value)) {
  497. this._valueCache[uniformName] = value;
  498. }
  499. }
  500. /**
  501. * Sets a boolean on a uniform variable.
  502. * @param uniformName Name of the variable.
  503. * @param bool value to be set.
  504. */
  505. public setBool(uniformName: string, bool: boolean): void {
  506. var cache = this._valueCache[uniformName];
  507. if (cache !== undefined && cache === bool) {
  508. return;
  509. }
  510. if (this.engine.setInt(this._uniforms[uniformName]!, bool ? 1 : 0)) {
  511. this._valueCache[uniformName] = bool ? 1 : 0;
  512. }
  513. }
  514. /**
  515. * Sets a Vector2 on a uniform variable.
  516. * @param uniformName Name of the variable.
  517. * @param vector2 vector2 to be set.
  518. */
  519. public setVector2(uniformName: string, vector2: IVector2Like): void {
  520. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  521. if (!this.engine.setFloat2(this._uniforms[uniformName]!, vector2.x, vector2.y)) {
  522. this._valueCache[uniformName] = null;
  523. }
  524. }
  525. }
  526. /**
  527. * Sets a float2 on a uniform variable.
  528. * @param uniformName Name of the variable.
  529. * @param x First float in float2.
  530. * @param y Second float in float2.
  531. */
  532. public setFloat2(uniformName: string, x: number, y: number): void {
  533. if (this._cacheFloat2(uniformName, x, y)) {
  534. if (!this.engine.setFloat2(this._uniforms[uniformName]!, x, y)) {
  535. this._valueCache[uniformName] = null;
  536. }
  537. }
  538. }
  539. /**
  540. * Sets a Vector3 on a uniform variable.
  541. * @param uniformName Name of the variable.
  542. * @param vector3 Value to be set.
  543. */
  544. public setVector3(uniformName: string, vector3: IVector3Like): void {
  545. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  546. if (!this.engine.setFloat3(this._uniforms[uniformName]!, vector3.x, vector3.y, vector3.z)) {
  547. this._valueCache[uniformName] = null;
  548. }
  549. }
  550. }
  551. /**
  552. * Sets a float3 on a uniform variable.
  553. * @param uniformName Name of the variable.
  554. * @param x First float in float3.
  555. * @param y Second float in float3.
  556. * @param z Third float in float3.
  557. */
  558. public setFloat3(uniformName: string, x: number, y: number, z: number): void {
  559. if (this._cacheFloat3(uniformName, x, y, z)) {
  560. if (!this.engine.setFloat3(this._uniforms[uniformName]!, x, y, z)) {
  561. this._valueCache[uniformName] = null;
  562. }
  563. }
  564. }
  565. /**
  566. * Sets a Vector4 on a uniform variable.
  567. * @param uniformName Name of the variable.
  568. * @param vector4 Value to be set.
  569. */
  570. public setVector4(uniformName: string, vector4: IVector4Like): void {
  571. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  572. if (!this.engine.setFloat4(this._uniforms[uniformName]!, vector4.x, vector4.y, vector4.z, vector4.w)) {
  573. this._valueCache[uniformName] = null;
  574. }
  575. }
  576. }
  577. /**
  578. * Sets a float4 on a uniform variable.
  579. * @param uniformName Name of the variable.
  580. * @param x First float in float4.
  581. * @param y Second float in float4.
  582. * @param z Third float in float4.
  583. * @param w Fourth float in float4.
  584. * @returns this effect.
  585. */
  586. public setFloat4(uniformName: string, x: number, y: number, z: number, w: number): void {
  587. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  588. if (!this.engine.setFloat4(this._uniforms[uniformName]!, x, y, z, w)) {
  589. this._valueCache[uniformName] = null;
  590. }
  591. }
  592. }
  593. /**
  594. * Sets a Color3 on a uniform variable.
  595. * @param uniformName Name of the variable.
  596. * @param color3 Value to be set.
  597. */
  598. public setColor3(uniformName: string, color3: IColor3Like): void {
  599. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  600. if (!this.engine.setFloat3(this._uniforms[uniformName]!, color3.r, color3.g, color3.b)) {
  601. this._valueCache[uniformName] = null;
  602. }
  603. }
  604. }
  605. /**
  606. * Sets a Color4 on a uniform variable.
  607. * @param uniformName Name of the variable.
  608. * @param color3 Value to be set.
  609. * @param alpha Alpha value to be set.
  610. */
  611. public setColor4(uniformName: string, color3: IColor3Like, alpha: number): void {
  612. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  613. if (!this.engine.setFloat4(this._uniforms[uniformName]!, color3.r, color3.g, color3.b, alpha)) {
  614. this._valueCache[uniformName] = null;
  615. }
  616. }
  617. }
  618. /**
  619. * Sets a Color4 on a uniform variable
  620. * @param uniformName defines the name of the variable
  621. * @param color4 defines the value to be set
  622. */
  623. public setDirectColor4(uniformName: string, color4: IColor4Like): void {
  624. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  625. if (!this.engine.setFloat4(this._uniforms[uniformName]!, color4.r, color4.g, color4.b, color4.a)) {
  626. this._valueCache[uniformName] = null;
  627. }
  628. }
  629. }
  630. }
  631. /**
  632. * Container for accessors for natively-stored mesh data buffers.
  633. */
  634. class NativeDataBuffer extends DataBuffer {
  635. /**
  636. * Accessor value used to identify/retrieve a natively-stored index buffer.
  637. */
  638. public nativeIndexBuffer?: any;
  639. /**
  640. * Accessor value used to identify/retrieve a natively-stored vertex buffer.
  641. */
  642. public nativeVertexBuffer?: any;
  643. }
  644. /** @hidden */
  645. class NativeTexture extends InternalTexture {
  646. public getInternalTexture(): InternalTexture {
  647. return this;
  648. }
  649. public getViewCount(): number {
  650. return 1;
  651. }
  652. }
  653. /** @hidden */
  654. declare var _native: any;
  655. /** @hidden */
  656. export class NativeEngine extends Engine {
  657. private readonly _native: INativeEngine = new _native.Engine();
  658. /** Defines the invalid handle returned by bgfx when resource creation goes wrong */
  659. private readonly INVALID_HANDLE = 65535;
  660. private _boundBuffersVertexArray: any = null;
  661. private _currentDepthTest: number = this._native.DEPTH_TEST_LEQUAL;
  662. public getHardwareScalingLevel(): number {
  663. return 1.0;
  664. }
  665. public constructor() {
  666. super(null);
  667. this._webGLVersion = 2;
  668. this.disableUniformBuffers = true;
  669. // TODO: Initialize this more correctly based on the hardware capabilities.
  670. // Init caps
  671. this._caps = {
  672. maxTexturesImageUnits: 16,
  673. maxVertexTextureImageUnits: 16,
  674. maxCombinedTexturesImageUnits: 32,
  675. maxTextureSize: 512,
  676. maxCubemapTextureSize: 512,
  677. maxRenderTextureSize: 512,
  678. maxVertexAttribs: 16,
  679. maxVaryingVectors: 16,
  680. maxFragmentUniformVectors: 16,
  681. maxVertexUniformVectors: 16,
  682. standardDerivatives: true,
  683. astc: null,
  684. pvrtc: null,
  685. etc1: null,
  686. etc2: null,
  687. bptc: null,
  688. maxAnisotropy: 16, // TODO: Retrieve this smartly. Currently set to D3D11 maximum allowable value.
  689. uintIndices: true,
  690. fragmentDepthSupported: false,
  691. highPrecisionShaderSupported: true,
  692. colorBufferFloat: false,
  693. textureFloat: false,
  694. textureFloatLinearFiltering: false,
  695. textureFloatRender: false,
  696. textureHalfFloat: false,
  697. textureHalfFloatLinearFiltering: false,
  698. textureHalfFloatRender: false,
  699. textureLOD: true,
  700. drawBuffersExtension: false,
  701. depthTextureExtension: false,
  702. vertexArrayObject: true,
  703. instancedArrays: false,
  704. canUseTimestampForTimerQuery: false,
  705. blendMinMax: false,
  706. maxMSAASamples: 1
  707. };
  708. Tools.Log("Babylon Native (v" + Engine.Version + ") launched");
  709. Tools.LoadScript = function (scriptUrl, onSuccess, onError, scriptId) {
  710. Tools.LoadFile(scriptUrl, (data) => {
  711. Function(data as string).apply(null);
  712. if (onSuccess) {
  713. onSuccess();
  714. }
  715. }, undefined, undefined, false,
  716. (request, exception) => {
  717. if (onError) {
  718. onError("LoadScript Error", exception);
  719. }
  720. });
  721. };
  722. // Wrappers
  723. if (typeof URL === "undefined") {
  724. (window.URL as any) = {
  725. createObjectURL: function() { },
  726. revokeObjectURL: function() { }
  727. };
  728. }
  729. if (typeof Blob === "undefined") {
  730. (window.Blob as any) = function() { };
  731. }
  732. // Shader processor
  733. this._shaderProcessor = new WebGL2ShaderProcessor();
  734. }
  735. public dispose(): void {
  736. super.dispose();
  737. if (this._boundBuffersVertexArray) {
  738. this._native.deleteVertexArray(this._boundBuffersVertexArray);
  739. }
  740. this._native.dispose();
  741. }
  742. /**
  743. * Can be used to override the current requestAnimationFrame requester.
  744. * @hidden
  745. */
  746. protected _queueNewFrame(bindedRenderFunction: any, requester?: any): number {
  747. // Use the provided requestAnimationFrame, unless the requester is the window. In that case, we will default to the Babylon Native version of requestAnimationFrame.
  748. if (requester.requestAnimationFrame && requester !== window) {
  749. requester.requestAnimationFrame(bindedRenderFunction);
  750. } else {
  751. this._native.requestAnimationFrame(bindedRenderFunction);
  752. }
  753. return 0;
  754. }
  755. /**
  756. * Override default engine behavior.
  757. * @param color
  758. * @param backBuffer
  759. * @param depth
  760. * @param stencil
  761. */
  762. public _bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  763. if (this._currentFramebuffer !== framebuffer) {
  764. if (this._currentFramebuffer) {
  765. this._native.unbindFramebuffer(this._currentFramebuffer!);
  766. }
  767. if (framebuffer) {
  768. this._native.bindFramebuffer(framebuffer);
  769. }
  770. this._currentFramebuffer = framebuffer;
  771. }
  772. }
  773. /**
  774. * Gets host document
  775. * @returns the host document object
  776. */
  777. public getHostDocument(): Nullable<Document> {
  778. return null;
  779. }
  780. public clear(color: Nullable<IColor4Like>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  781. var mode = 0;
  782. if (backBuffer && color) {
  783. this._native.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  784. mode |= this._native.CLEAR_FLAG_COLOR;
  785. }
  786. if (depth) {
  787. this._native.clearDepth(1.0);
  788. mode |= this._native.CLEAR_FLAG_DEPTH;
  789. }
  790. if (stencil) {
  791. this._native.clearStencil(0);
  792. mode |= this._native.CLEAR_FLAG_STENCIL;
  793. }
  794. this._native.clear(mode);
  795. }
  796. public createIndexBuffer(indices: IndicesArray, updateable?: boolean): NativeDataBuffer {
  797. const data = this._normalizeIndexData(indices);
  798. const buffer = new NativeDataBuffer();
  799. buffer.references = 1;
  800. buffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
  801. if (data.length) {
  802. buffer.nativeIndexBuffer = this._native.createIndexBuffer(data, updateable ?? false);
  803. if (buffer.nativeVertexBuffer === this.INVALID_HANDLE) {
  804. throw new Error("Could not create a native index buffer.");
  805. }
  806. } else {
  807. buffer.nativeVertexBuffer = this.INVALID_HANDLE;
  808. }
  809. return buffer;
  810. }
  811. public createVertexBuffer(data: DataArray, updateable?: boolean): NativeDataBuffer {
  812. const buffer = new NativeDataBuffer();
  813. buffer.references = 1;
  814. buffer.nativeVertexBuffer = this._native.createVertexBuffer(ArrayBuffer.isView(data) ? data : new Float32Array(data), updateable ?? false);
  815. if (buffer.nativeVertexBuffer === this.INVALID_HANDLE) {
  816. throw new Error("Could not create a native vertex buffer.");
  817. }
  818. return buffer;
  819. }
  820. protected _recordVertexArrayObject(vertexArray: any, vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<NativeDataBuffer>, effect: Effect): void {
  821. if (indexBuffer) {
  822. this._native.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer);
  823. }
  824. const attributes = effect.getAttributesNames();
  825. for (let index = 0; index < attributes.length; index++) {
  826. const location = effect.getAttributeLocation(index);
  827. if (location >= 0) {
  828. const kind = attributes[index];
  829. const vertexBuffer = vertexBuffers[kind];
  830. if (vertexBuffer) {
  831. const buffer = vertexBuffer.getBuffer() as Nullable<NativeDataBuffer>;
  832. if (buffer) {
  833. this._native.recordVertexBuffer(
  834. vertexArray,
  835. buffer.nativeVertexBuffer,
  836. location,
  837. vertexBuffer.byteOffset,
  838. vertexBuffer.byteStride,
  839. vertexBuffer.getSize(),
  840. this._getNativeAttribType(vertexBuffer.type),
  841. vertexBuffer.normalized);
  842. }
  843. }
  844. }
  845. }
  846. }
  847. public bindBuffers(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<NativeDataBuffer>, effect: Effect): void {
  848. if (this._boundBuffersVertexArray) {
  849. this._native.deleteVertexArray(this._boundBuffersVertexArray);
  850. }
  851. this._boundBuffersVertexArray = this._native.createVertexArray();
  852. this._recordVertexArrayObject(this._boundBuffersVertexArray, vertexBuffers, indexBuffer, effect);
  853. this._native.bindVertexArray(this._boundBuffersVertexArray);
  854. }
  855. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<NativeDataBuffer>, effect: Effect): WebGLVertexArrayObject {
  856. const vertexArray = this._native.createVertexArray();
  857. this._recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect);
  858. return vertexArray;
  859. }
  860. public bindVertexArrayObject(vertexArray: WebGLVertexArrayObject): void {
  861. this._native.bindVertexArray(vertexArray);
  862. }
  863. public releaseVertexArrayObject(vertexArray: WebGLVertexArrayObject) {
  864. this._native.deleteVertexArray(vertexArray);
  865. }
  866. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  867. const nativePipelineContext = pipelineContext as NativePipelineContext;
  868. return this._native.getAttributes(nativePipelineContext.nativeProgram, attributesNames);
  869. }
  870. /**
  871. * Draw a list of indexed primitives
  872. * @param fillMode defines the primitive to use
  873. * @param indexStart defines the starting index
  874. * @param indexCount defines the number of index to draw
  875. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  876. */
  877. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  878. // Apply states
  879. this._drawCalls.addCount(1, false);
  880. // TODO: Make this implementation more robust like core Engine version.
  881. // Render
  882. //var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  883. //var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  884. // if (instancesCount) {
  885. // this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  886. // } else {
  887. this._native.drawIndexed(fillMode, indexStart, indexCount);
  888. // }
  889. }
  890. /**
  891. * Draw a list of unindexed primitives
  892. * @param fillMode defines the primitive to use
  893. * @param verticesStart defines the index of first vertex to draw
  894. * @param verticesCount defines the count of vertices to draw
  895. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  896. */
  897. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  898. // Apply states
  899. this._drawCalls.addCount(1, false);
  900. // TODO: Make this implementation more robust like core Engine version.
  901. // if (instancesCount) {
  902. // this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  903. // } else {
  904. this._native.draw(fillMode, verticesStart, verticesCount);
  905. // }
  906. }
  907. public createPipelineContext(): IPipelineContext {
  908. return new NativePipelineContext();
  909. }
  910. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean, rawVertexSourceCode: string, rawFragmentSourceCode: string, rebuildRebind: any, defines: Nullable<string>, transformFeedbackVaryings: Nullable<string[]>) {
  911. const nativePipelineContext = pipelineContext as NativePipelineContext;
  912. if (createAsRaw) {
  913. nativePipelineContext.nativeProgram = this.createRawShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings);
  914. }
  915. else {
  916. nativePipelineContext.nativeProgram = this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings);
  917. }
  918. }
  919. /** @hidden */
  920. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  921. // TODO: support async shader compilcation
  922. return true;
  923. }
  924. /** @hidden */
  925. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  926. // TODO: support async shader compilcation
  927. action();
  928. }
  929. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): any {
  930. throw new Error("Not Supported");
  931. }
  932. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): any {
  933. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  934. const vertexInliner = new ShaderCodeInliner(vertexCode);
  935. vertexInliner.processCode();
  936. vertexCode = vertexInliner.code;
  937. const fragmentInliner = new ShaderCodeInliner(fragmentCode);
  938. fragmentInliner.processCode();
  939. fragmentCode = fragmentInliner.code;
  940. vertexCode = ThinEngine._ConcatenateShader(vertexCode, defines);
  941. fragmentCode = ThinEngine._ConcatenateShader(fragmentCode, defines);
  942. const program = this._native.createProgram(vertexCode, fragmentCode);
  943. this.onAfterShaderCompilationObservable.notifyObservers(this);
  944. return program;
  945. }
  946. protected _setProgram(program: WebGLProgram): void {
  947. if (this._currentProgram !== program) {
  948. this._native.setProgram(program);
  949. this._currentProgram = program;
  950. }
  951. }
  952. public _releaseEffect(effect: Effect): void {
  953. // TODO
  954. }
  955. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  956. // TODO
  957. }
  958. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): WebGLUniformLocation[] {
  959. const nativePipelineContext = pipelineContext as NativePipelineContext;
  960. return this._native.getUniforms(nativePipelineContext.nativeProgram, uniformsNames);
  961. }
  962. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  963. // TODO
  964. throw new Error("Not Implemented");
  965. }
  966. public bindSamplers(effect: Effect): void {
  967. const nativePipelineContext = effect.getPipelineContext() as NativePipelineContext;
  968. this._setProgram(nativePipelineContext.nativeProgram);
  969. // TODO: share this with engine?
  970. var samplers = effect.getSamplers();
  971. for (var index = 0; index < samplers.length; index++) {
  972. var uniform = effect.getUniform(samplers[index]);
  973. if (uniform) {
  974. this._boundUniforms[index] = uniform;
  975. }
  976. }
  977. this._currentEffect = null;
  978. }
  979. public setMatrix(uniform: WebGLUniformLocation, matrix: IMatrixLike): void {
  980. if (!uniform) {
  981. return;
  982. }
  983. this._native.setMatrix(uniform, matrix.toArray() as Float32Array);
  984. }
  985. public getRenderWidth(useScreen = false): number {
  986. if (!useScreen && this._currentRenderTarget) {
  987. return this._currentRenderTarget.width;
  988. }
  989. return this._native.getRenderWidth();
  990. }
  991. public getRenderHeight(useScreen = false): number {
  992. if (!useScreen && this._currentRenderTarget) {
  993. return this._currentRenderTarget.height;
  994. }
  995. return this._native.getRenderHeight();
  996. }
  997. public setViewport(viewport: IViewportLike, requiredWidth?: number, requiredHeight?: number): void {
  998. this._cachedViewport = viewport;
  999. this._native.setViewPort(viewport.x, viewport.y, viewport.width, viewport.height);
  1000. }
  1001. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1002. this._native.setState(culling, zOffset, reverseSide);
  1003. }
  1004. /**
  1005. * Set the z offset to apply to current rendering
  1006. * @param value defines the offset to apply
  1007. */
  1008. public setZOffset(value: number): void {
  1009. this._native.setZOffset(value);
  1010. }
  1011. /**
  1012. * Gets the current value of the zOffset
  1013. * @returns the current zOffset state
  1014. */
  1015. public getZOffset(): number {
  1016. return this._native.getZOffset();
  1017. }
  1018. /**
  1019. * Enable or disable depth buffering
  1020. * @param enable defines the state to set
  1021. */
  1022. public setDepthBuffer(enable: boolean): void {
  1023. this._native.setDepthTest(enable ? this._currentDepthTest : this._native.DEPTH_TEST_ALWAYS);
  1024. }
  1025. /**
  1026. * Gets a boolean indicating if depth writing is enabled
  1027. * @returns the current depth writing state
  1028. */
  1029. public getDepthWrite(): boolean {
  1030. return this._native.getDepthWrite();
  1031. }
  1032. public setDepthFunctionToGreater(): void {
  1033. this._currentDepthTest = this._native.DEPTH_TEST_GREATER;
  1034. this._native.setDepthTest(this._currentDepthTest);
  1035. }
  1036. public setDepthFunctionToGreaterOrEqual(): void {
  1037. this._currentDepthTest = this._native.DEPTH_TEST_GEQUAL;
  1038. this._native.setDepthTest(this._currentDepthTest);
  1039. }
  1040. public setDepthFunctionToLess(): void {
  1041. this._currentDepthTest = this._native.DEPTH_TEST_LESS;
  1042. this._native.setDepthTest(this._currentDepthTest);
  1043. }
  1044. public setDepthFunctionToLessOrEqual(): void {
  1045. this._currentDepthTest = this._native.DEPTH_TEST_LEQUAL;
  1046. this._native.setDepthTest(this._currentDepthTest);
  1047. }
  1048. /**
  1049. * Enable or disable depth writing
  1050. * @param enable defines the state to set
  1051. */
  1052. public setDepthWrite(enable: boolean): void {
  1053. this._native.setDepthWrite(enable);
  1054. }
  1055. /**
  1056. * Enable or disable color writing
  1057. * @param enable defines the state to set
  1058. */
  1059. public setColorWrite(enable: boolean): void {
  1060. this._native.setColorWrite(enable);
  1061. this._colorWrite = enable;
  1062. }
  1063. /**
  1064. * Gets a boolean indicating if color writing is enabled
  1065. * @returns the current color writing state
  1066. */
  1067. public getColorWrite(): boolean {
  1068. return this._colorWrite;
  1069. }
  1070. /**
  1071. * Sets alpha constants used by some alpha blending modes
  1072. * @param r defines the red component
  1073. * @param g defines the green component
  1074. * @param b defines the blue component
  1075. * @param a defines the alpha component
  1076. */
  1077. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  1078. throw new Error("Setting alpha blend constant color not yet implemented.");
  1079. }
  1080. /**
  1081. * Sets the current alpha mode
  1082. * @param mode defines the mode to use (one of the BABYLON.Constants.ALPHA_XXX)
  1083. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  1084. * @see https://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  1085. */
  1086. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  1087. if (this._alphaMode === mode) {
  1088. return;
  1089. }
  1090. mode = this._getNativeAlphaMode(mode);
  1091. this._native.setBlendMode(mode);
  1092. if (!noDepthWriteChange) {
  1093. this.setDepthWrite(mode === Constants.ALPHA_DISABLE);
  1094. }
  1095. this._alphaMode = mode;
  1096. }
  1097. /**
  1098. * Gets the current alpha mode
  1099. * @see https://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  1100. * @returns the current alpha mode
  1101. */
  1102. public getAlphaMode(): number {
  1103. return this._alphaMode;
  1104. }
  1105. public setInt(uniform: WebGLUniformLocation, int: number): boolean {
  1106. if (!uniform) {
  1107. return false;
  1108. }
  1109. this._native.setInt(uniform, int);
  1110. return true;
  1111. }
  1112. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  1113. if (!uniform) {
  1114. return false;
  1115. }
  1116. this._native.setIntArray(uniform, array);
  1117. return true;
  1118. }
  1119. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  1120. if (!uniform) {
  1121. return false;
  1122. }
  1123. this._native.setIntArray2(uniform, array);
  1124. return true;
  1125. }
  1126. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  1127. if (!uniform) {
  1128. return false;
  1129. }
  1130. this._native.setIntArray3(uniform, array);
  1131. return true;
  1132. }
  1133. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  1134. if (!uniform) {
  1135. return false;
  1136. }
  1137. this._native.setIntArray4(uniform, array);
  1138. return true;
  1139. }
  1140. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): boolean {
  1141. if (!uniform) {
  1142. return false;
  1143. }
  1144. this._native.setFloatArray(uniform, array);
  1145. return true;
  1146. }
  1147. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): boolean {
  1148. if (!uniform) {
  1149. return false;
  1150. }
  1151. this._native.setFloatArray2(uniform, array);
  1152. return true;
  1153. }
  1154. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): boolean {
  1155. if (!uniform) {
  1156. return false;
  1157. }
  1158. this._native.setFloatArray3(uniform, array);
  1159. return true;
  1160. }
  1161. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): boolean {
  1162. if (!uniform) {
  1163. return false;
  1164. }
  1165. this._native.setFloatArray4(uniform, array);
  1166. return true;
  1167. }
  1168. public setArray(uniform: WebGLUniformLocation, array: number[]): boolean {
  1169. if (!uniform) {
  1170. return false;
  1171. }
  1172. this._native.setFloatArray(uniform, array);
  1173. return true;
  1174. }
  1175. public setArray2(uniform: WebGLUniformLocation, array: number[]): boolean {
  1176. if (!uniform) {
  1177. return false;
  1178. }
  1179. this._native.setFloatArray2(uniform, array);
  1180. return true;
  1181. }
  1182. public setArray3(uniform: WebGLUniformLocation, array: number[]): boolean {
  1183. if (!uniform) {
  1184. return false;
  1185. }
  1186. this._native.setFloatArray3(uniform, array);
  1187. return true;
  1188. }
  1189. public setArray4(uniform: WebGLUniformLocation, array: number[]): boolean {
  1190. if (!uniform) {
  1191. return false;
  1192. }
  1193. this._native.setFloatArray4(uniform, array);
  1194. return true;
  1195. }
  1196. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): boolean {
  1197. if (!uniform) {
  1198. return false;
  1199. }
  1200. this._native.setMatrices(uniform, matrices);
  1201. return true;
  1202. }
  1203. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): boolean {
  1204. if (!uniform) {
  1205. return false;
  1206. }
  1207. this._native.setMatrix3x3(uniform, matrix);
  1208. return true;
  1209. }
  1210. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): boolean {
  1211. if (!uniform) {
  1212. return false;
  1213. }
  1214. this._native.setMatrix2x2(uniform, matrix);
  1215. return true;
  1216. }
  1217. public setFloat(uniform: WebGLUniformLocation, value: number): boolean {
  1218. if (!uniform) {
  1219. return false;
  1220. }
  1221. this._native.setFloat(uniform, value);
  1222. return true;
  1223. }
  1224. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): boolean {
  1225. if (!uniform) {
  1226. return false;
  1227. }
  1228. this._native.setFloat2(uniform, x, y);
  1229. return true;
  1230. }
  1231. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): boolean {
  1232. if (!uniform) {
  1233. return false;
  1234. }
  1235. this._native.setFloat3(uniform, x, y, z);
  1236. return true;
  1237. }
  1238. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): boolean {
  1239. if (!uniform) {
  1240. return false;
  1241. }
  1242. this._native.setFloat4(uniform, x, y, z, w);
  1243. return true;
  1244. }
  1245. public setColor3(uniform: WebGLUniformLocation, color3: IColor3Like): boolean {
  1246. if (!uniform) {
  1247. return false;
  1248. }
  1249. this._native.setFloat3(uniform, color3.r, color3.g, color3.b);
  1250. return true;
  1251. }
  1252. public setColor4(uniform: WebGLUniformLocation, color3: IColor3Like, alpha: number): boolean {
  1253. if (!uniform) {
  1254. return false;
  1255. }
  1256. this._native.setFloat4(uniform, color3.r, color3.g, color3.b, alpha);
  1257. return true;
  1258. }
  1259. public wipeCaches(bruteForce?: boolean): void {
  1260. if (this.preventCacheWipeBetweenFrames) {
  1261. return;
  1262. }
  1263. this.resetTextureCache();
  1264. this._currentEffect = null;
  1265. if (bruteForce) {
  1266. this._currentProgram = null;
  1267. this._stencilState.reset();
  1268. this._depthCullingState.reset();
  1269. this._alphaState.reset();
  1270. }
  1271. this._cachedVertexBuffers = null;
  1272. this._cachedIndexBuffer = null;
  1273. this._cachedEffectForVertexBuffers = null;
  1274. }
  1275. protected _createTexture(): WebGLTexture {
  1276. return this._native.createTexture();
  1277. }
  1278. protected _deleteTexture(texture: Nullable<WebGLTexture>): void {
  1279. this._native.deleteTexture(texture);
  1280. }
  1281. /**
  1282. * Update the content of a dynamic texture
  1283. * @param texture defines the texture to update
  1284. * @param canvas defines the canvas containing the source
  1285. * @param invertY defines if data must be stored with Y axis inverted
  1286. * @param premulAlpha defines if alpha is stored as premultiplied
  1287. * @param format defines the format of the data
  1288. * @param forceBindTexture if the texture should be forced to be bound eg. after a graphics context loss (Default: false)
  1289. */
  1290. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  1291. // TODO: Stub! This function is needed for some GLTF validation tests.
  1292. // Loads a dummy 8x8 transparent png
  1293. var imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYSURBVChTY/z//z8DPsAEpXGC4aCAgQEAGGMDDWwwgqsAAAAASUVORK5CYII=';
  1294. this.createTexture('data:my_image_name', true, invertY, null, Texture.BILINEAR_SAMPLINGMODE, undefined, undefined, imageData, texture, NativeEngine.TEXTUREFORMAT_RGBA, null, undefined);
  1295. }
  1296. // TODO: Refactor to share more logic with babylon.engine.ts version.
  1297. /**
  1298. * Usually called from Texture.ts.
  1299. * Passed information to create a WebGLTexture
  1300. * @param url defines a value which contains one of the following:
  1301. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  1302. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  1303. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  1304. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  1305. * @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)
  1306. * @param scene needed for loading to the correct scene
  1307. * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
  1308. * @param onLoad optional callback to be called upon successful completion
  1309. * @param onError optional callback to be called upon failure
  1310. * @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
  1311. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  1312. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  1313. * @param forcedExtension defines the extension to use to pick the right loader
  1314. * @param mimeType defines an optional mime type
  1315. * @param loaderOptions options to be passed to the loader
  1316. * @returns a InternalTexture for assignment back into BABYLON.Texture
  1317. */
  1318. public createTexture(url: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<ISceneLike>, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  1319. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  1320. buffer: Nullable<string | ArrayBuffer | ArrayBufferView | HTMLImageElement | Blob | ImageBitmap> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  1321. forcedExtension: Nullable<string> = null, mimeType?: string, loaderOptions?: any): InternalTexture {
  1322. url = url || "";
  1323. const fromData = url.substr(0, 5) === "data:";
  1324. //const fromBlob = url.substr(0, 5) === "blob:";
  1325. const isBase64 = fromData && url.indexOf(";base64,") !== -1;
  1326. let texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Url);
  1327. const originalUrl = url;
  1328. if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {
  1329. url = this._transformTextureUrl(url);
  1330. }
  1331. // establish the file extension, if possible
  1332. var lastDot = url.lastIndexOf('.');
  1333. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  1334. let loader: Nullable<IInternalTextureLoader> = null;
  1335. for (let availableLoader of Engine._TextureLoaders) {
  1336. if (availableLoader.canLoad(extension)) {
  1337. loader = availableLoader;
  1338. break;
  1339. }
  1340. }
  1341. if (scene) {
  1342. scene._addPendingData(texture);
  1343. }
  1344. texture.url = url;
  1345. texture.generateMipMaps = !noMipmap;
  1346. texture.samplingMode = samplingMode;
  1347. texture.invertY = invertY;
  1348. if (!this.doNotHandleContextLost) {
  1349. // Keep a link to the buffer only if we plan to handle context lost
  1350. texture._buffer = buffer;
  1351. }
  1352. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  1353. if (onLoad && !fallback) {
  1354. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  1355. }
  1356. if (!fallback) { this._internalTexturesCache.push(texture); }
  1357. let onInternalError = (message?: string, exception?: any) => {
  1358. if (scene) {
  1359. scene._removePendingData(texture);
  1360. }
  1361. if (url === originalUrl) {
  1362. if (onLoadObserver) {
  1363. texture.onLoadedObservable.remove(onLoadObserver);
  1364. }
  1365. if (EngineStore.UseFallbackTexture) {
  1366. this.createTexture(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture);
  1367. }
  1368. if (onError) {
  1369. onError((message || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""), exception);
  1370. }
  1371. }
  1372. else {
  1373. // fall back to the original url if the transformed url fails to load
  1374. Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`);
  1375. this.createTexture(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, buffer, texture, format, forcedExtension, mimeType, loaderOptions);
  1376. }
  1377. };
  1378. // processing for non-image formats
  1379. if (loader) {
  1380. throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");
  1381. } else {
  1382. const onload = (data: ArrayBufferView) => {
  1383. const webGLTexture = texture._hardwareTexture?.underlyingResource;
  1384. if (!webGLTexture) {
  1385. if (scene) {
  1386. scene._removePendingData(texture);
  1387. }
  1388. return;
  1389. }
  1390. this._native.loadTexture(webGLTexture, data, !noMipmap, invertY, () => {
  1391. texture.baseWidth = this._native.getTextureWidth(webGLTexture);
  1392. texture.baseHeight = this._native.getTextureHeight(webGLTexture);
  1393. texture.width = texture.baseWidth;
  1394. texture.height = texture.baseHeight;
  1395. texture.isReady = true;
  1396. var filter = this._getNativeSamplingMode(samplingMode);
  1397. this._native.setTextureSampling(webGLTexture, filter);
  1398. if (scene) {
  1399. scene._removePendingData(texture);
  1400. }
  1401. texture.onLoadedObservable.notifyObservers(texture);
  1402. texture.onLoadedObservable.clear();
  1403. }, () => {
  1404. throw new Error("Could not load a native texture.");
  1405. });
  1406. };
  1407. if (fromData) {
  1408. if (buffer instanceof ArrayBuffer) {
  1409. onload(new Uint8Array(buffer));
  1410. } else if (ArrayBuffer.isView(buffer)) {
  1411. onload(buffer);
  1412. } else if (typeof buffer === "string") {
  1413. onload(new Uint8Array(Tools.DecodeBase64(buffer)));
  1414. } else {
  1415. throw new Error("Unsupported buffer type");
  1416. }
  1417. }
  1418. else {
  1419. if (isBase64) {
  1420. onload(new Uint8Array(Tools.DecodeBase64(url)));
  1421. }
  1422. else {
  1423. this._loadFile(url, (data) => onload(new Uint8Array(data as ArrayBuffer)), undefined, undefined, true, (request?: IWebRequest, exception?: any) => {
  1424. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  1425. });
  1426. }
  1427. }
  1428. }
  1429. return texture;
  1430. }
  1431. _createDepthStencilTexture(size: RenderTargetTextureSize, options: DepthTextureCreationOptions): NativeTexture {
  1432. var texture = new NativeTexture(this, InternalTextureSource.Depth);
  1433. const width = (<{ width: number, height: number, layers?: number }>size).width || <number>size;
  1434. const height = (<{ width: number, height: number, layers?: number }>size).height || <number>size;
  1435. var framebuffer = this._native.createDepthTexture(
  1436. texture._hardwareTexture!.underlyingResource,
  1437. width,
  1438. height);
  1439. texture._framebuffer = framebuffer;
  1440. return texture;
  1441. }
  1442. public _releaseFramebufferObjects(texture: InternalTexture): void {
  1443. if (texture._framebuffer) {
  1444. this._native.deleteFramebuffer(texture._framebuffer);
  1445. texture._framebuffer = null;
  1446. }
  1447. }
  1448. /**
  1449. * Creates a cube texture
  1450. * @param rootUrl defines the url where the files to load is located
  1451. * @param scene defines the current scene
  1452. * @param files defines the list of files to load (1 per face)
  1453. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  1454. * @param onLoad defines an optional callback raised when the texture is loaded
  1455. * @param onError defines an optional callback raised if there is an issue to load the texture
  1456. * @param format defines the format of the data
  1457. * @param forcedExtension defines the extension to use to pick the right loader
  1458. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  1459. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  1460. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  1461. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  1462. * @returns the cube texture as an InternalTexture
  1463. */
  1464. public createCubeTexture(
  1465. rootUrl: string,
  1466. scene: Nullable<Scene>,
  1467. files: Nullable<string[]>,
  1468. noMipmap?: boolean,
  1469. onLoad: Nullable<(data?: any) => void> = null,
  1470. onError: Nullable<(message?: string, exception?: any) => void> = null,
  1471. format?: number,
  1472. forcedExtension: any = null,
  1473. createPolynomials = false,
  1474. lodScale: number = 0,
  1475. lodOffset: number = 0,
  1476. fallback: Nullable<InternalTexture> = null): InternalTexture
  1477. {
  1478. var texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Cube);
  1479. texture.isCube = true;
  1480. texture.url = rootUrl;
  1481. texture.generateMipMaps = !noMipmap;
  1482. texture._lodGenerationScale = lodScale;
  1483. texture._lodGenerationOffset = lodOffset;
  1484. if (!this._doNotHandleContextLost) {
  1485. texture._extension = forcedExtension;
  1486. texture._files = files;
  1487. }
  1488. var lastDot = rootUrl.lastIndexOf('.');
  1489. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  1490. // TODO: use texture loader to load env files?
  1491. if (extension === ".env") {
  1492. const onloaddata = (data: ArrayBufferView) => {
  1493. var info = EnvironmentTextureTools.GetEnvInfo(data)!;
  1494. texture.width = info.width;
  1495. texture.height = info.width;
  1496. EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  1497. if (info.version !== 1) {
  1498. throw new Error(`Unsupported babylon environment map version "${info.version}"`);
  1499. }
  1500. let specularInfo = info.specular as EnvironmentTextureSpecularInfoV1;
  1501. if (!specularInfo) {
  1502. throw new Error(`Nothing else parsed so far`);
  1503. }
  1504. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  1505. const imageData = EnvironmentTextureTools.CreateImageDataArrayBufferViews(data, info);
  1506. texture.format = Constants.TEXTUREFORMAT_RGBA;
  1507. texture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  1508. texture.generateMipMaps = true;
  1509. texture.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, texture);
  1510. texture._isRGBD = true;
  1511. texture.invertY = true;
  1512. this._native.loadCubeTextureWithMips(texture._hardwareTexture!.underlyingResource, imageData, () => {
  1513. texture.isReady = true;
  1514. if (onLoad) {
  1515. onLoad();
  1516. }
  1517. }, () => {
  1518. throw new Error("Could not load a native cube texture.");
  1519. });
  1520. };
  1521. if (files && files.length === 6) {
  1522. throw new Error(`Multi-file loading not allowed on env files.`);
  1523. }
  1524. else {
  1525. let onInternalError = (request?: IWebRequest, exception?: any) => {
  1526. if (onError && request) {
  1527. onError(request.status + " " + request.statusText, exception);
  1528. }
  1529. };
  1530. this._loadFile(rootUrl, (data) => onloaddata(new Uint8Array(data as ArrayBuffer)), undefined, undefined, true, onInternalError);
  1531. }
  1532. }
  1533. else {
  1534. if (!files || files.length !== 6) {
  1535. throw new Error("Cannot load cubemap because 6 files were not defined");
  1536. }
  1537. // Reorder from [+X, +Y, +Z, -X, -Y, -Z] to [+X, -X, +Y, -Y, +Z, -Z].
  1538. const reorderedFiles = [files[0], files[3], files[1], files[4], files[2], files[5]];
  1539. Promise.all(reorderedFiles.map((file) => Tools.LoadFileAsync(file).then((data) => new Uint8Array(data as ArrayBuffer)))).then((data) => {
  1540. return new Promise((resolve: (_: void) => void, reject) => {
  1541. this._native.loadCubeTexture(texture._hardwareTexture!.underlyingResource, data, !noMipmap, resolve, reject);
  1542. });
  1543. }).then(() => {
  1544. texture.isReady = true;
  1545. if (onLoad) {
  1546. onLoad();
  1547. }
  1548. }, (error) => {
  1549. if (onError) {
  1550. onError(`Failed to load cubemap: ${error.message}`, error);
  1551. }
  1552. });
  1553. }
  1554. this._internalTexturesCache.push(texture);
  1555. return texture;
  1556. }
  1557. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): NativeTexture {
  1558. let fullOptions = new RenderTargetCreationOptions();
  1559. if (options !== undefined && typeof options === "object") {
  1560. fullOptions.generateMipMaps = options.generateMipMaps;
  1561. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1562. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  1563. fullOptions.type = options.type === undefined ? Constants.TEXTURETYPE_UNSIGNED_INT : options.type;
  1564. fullOptions.samplingMode = options.samplingMode === undefined ? Constants.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  1565. fullOptions.format = options.format === undefined ? Constants.TEXTUREFORMAT_RGBA : options.format;
  1566. } else {
  1567. fullOptions.generateMipMaps = <boolean>options;
  1568. fullOptions.generateDepthBuffer = true;
  1569. fullOptions.generateStencilBuffer = false;
  1570. fullOptions.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  1571. fullOptions.samplingMode = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  1572. fullOptions.format = Constants.TEXTUREFORMAT_RGBA;
  1573. }
  1574. if (fullOptions.type === Constants.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  1575. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1576. fullOptions.samplingMode = Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  1577. }
  1578. else if (fullOptions.type === Constants.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  1579. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  1580. fullOptions.samplingMode = Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  1581. }
  1582. var texture = new NativeTexture(this, InternalTextureSource.RenderTarget);
  1583. var width = (<{ width: number, height: number }>size).width || <number>size;
  1584. var height = (<{ width: number, height: number }>size).height || <number>size;
  1585. if (fullOptions.type === Constants.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1586. fullOptions.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  1587. Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1588. }
  1589. var framebuffer = this._native.createFramebuffer(
  1590. texture._hardwareTexture!.underlyingResource,
  1591. width,
  1592. height,
  1593. this._getNativeTextureFormat(fullOptions.format, fullOptions.type),
  1594. fullOptions.samplingMode!,
  1595. fullOptions.generateStencilBuffer ? true : false,
  1596. fullOptions.generateDepthBuffer,
  1597. fullOptions.generateMipMaps ? true : false);
  1598. texture._framebuffer = framebuffer;
  1599. texture.baseWidth = width;
  1600. texture.baseHeight = height;
  1601. texture.width = width;
  1602. texture.height = height;
  1603. texture.isReady = true;
  1604. texture.samples = 1;
  1605. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  1606. texture.samplingMode = fullOptions.samplingMode;
  1607. texture.type = fullOptions.type;
  1608. texture.format = fullOptions.format;
  1609. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  1610. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  1611. this._internalTexturesCache.push(texture);
  1612. return texture;
  1613. }
  1614. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  1615. if (texture._hardwareTexture?.underlyingResource ?? false) {
  1616. var filter = this._getNativeSamplingMode(samplingMode);
  1617. this._native.setTextureSampling(texture._hardwareTexture?.underlyingResource, filter);
  1618. }
  1619. texture.samplingMode = samplingMode;
  1620. }
  1621. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1622. if (faceIndex) {
  1623. throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");
  1624. }
  1625. if (requiredWidth || requiredHeight) {
  1626. throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");
  1627. }
  1628. if (forceFullscreenViewport) {
  1629. //Not supported yet but don't stop rendering
  1630. }
  1631. if (texture._depthStencilTexture) {
  1632. this._bindUnboundFramebuffer(texture._depthStencilTexture._framebuffer);
  1633. } else {
  1634. this._bindUnboundFramebuffer(texture._framebuffer);
  1635. }
  1636. }
  1637. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1638. if (disableGenerateMipMaps) {
  1639. Logger.Warn("Disabling mipmap generation not yet supported in NativeEngine. Ignoring.");
  1640. }
  1641. if (onBeforeUnbind) {
  1642. onBeforeUnbind();
  1643. }
  1644. this._bindUnboundFramebuffer(null);
  1645. }
  1646. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  1647. return this.createVertexBuffer(data, true);
  1648. }
  1649. public updateDynamicIndexBuffer(indexBuffer: DataBuffer, indices: IndicesArray, offset: number = 0): void {
  1650. const buffer = indexBuffer as NativeDataBuffer;
  1651. const data = this._normalizeIndexData(indices);
  1652. buffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
  1653. this._native.updateDynamicIndexBuffer(buffer.nativeIndexBuffer, data, offset);
  1654. }
  1655. /**
  1656. * Updates a dynamic vertex buffer.
  1657. * @param vertexBuffer the vertex buffer to update
  1658. * @param data the data used to update the vertex buffer
  1659. * @param byteOffset the byte offset of the data (optional)
  1660. * @param byteLength the byte length of the data (optional)
  1661. */
  1662. public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  1663. const buffer = vertexBuffer as NativeDataBuffer;
  1664. const dataView = ArrayBuffer.isView(data) ? data : new Float32Array(data);
  1665. this._native.updateDynamicVertexBuffer(
  1666. buffer.nativeVertexBuffer,
  1667. dataView,
  1668. byteOffset ?? 0,
  1669. byteLength ?? dataView.byteLength);
  1670. }
  1671. // TODO: Refactor to share more logic with base Engine implementation.
  1672. protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  1673. let uniform = this._boundUniforms[channel];
  1674. if (!uniform) {
  1675. return false;
  1676. }
  1677. // Not ready?
  1678. if (!texture) {
  1679. if (this._boundTexturesCache[channel] != null) {
  1680. this._activeChannel = channel;
  1681. this._native.setTexture(uniform, null);
  1682. }
  1683. return false;
  1684. }
  1685. // Video
  1686. if ((<VideoTexture>texture).video) {
  1687. this._activeChannel = channel;
  1688. (<VideoTexture>texture).update();
  1689. } else if (texture.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1690. texture.delayLoad();
  1691. return false;
  1692. }
  1693. let internalTexture: InternalTexture;
  1694. if (depthStencilTexture) {
  1695. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  1696. } else if (texture.isReady()) {
  1697. internalTexture = <InternalTexture>texture.getInternalTexture();
  1698. } else if (texture.isCube) {
  1699. internalTexture = this.emptyCubeTexture;
  1700. } else if (texture.is3D) {
  1701. internalTexture = this.emptyTexture3D;
  1702. } else if (texture.is2DArray) {
  1703. internalTexture = this.emptyTexture2DArray;
  1704. } else {
  1705. internalTexture = this.emptyTexture;
  1706. }
  1707. this._activeChannel = channel;
  1708. if (!internalTexture ||
  1709. !internalTexture._hardwareTexture?.underlyingResource) {
  1710. return false;
  1711. }
  1712. this._native.setTextureWrapMode(
  1713. internalTexture._hardwareTexture?.underlyingResource,
  1714. this._getAddressMode(texture.wrapU),
  1715. this._getAddressMode(texture.wrapV),
  1716. this._getAddressMode(texture.wrapR));
  1717. this._updateAnisotropicLevel(texture);
  1718. this._native.setTexture(uniform, internalTexture._hardwareTexture?.underlyingResource);
  1719. return true;
  1720. }
  1721. // TODO: Share more of this logic with the base implementation.
  1722. // TODO: Rename to match naming in base implementation once refactoring allows different parameters.
  1723. private _updateAnisotropicLevel(texture: BaseTexture) {
  1724. var internalTexture = texture.getInternalTexture();
  1725. var value = texture.anisotropicFilteringLevel;
  1726. if (!internalTexture || !internalTexture._hardwareTexture?.underlyingResource) {
  1727. return;
  1728. }
  1729. if (internalTexture._cachedAnisotropicFilteringLevel !== value) {
  1730. this._native.setTextureAnisotropicLevel(internalTexture._hardwareTexture?.underlyingResource, value);
  1731. internalTexture._cachedAnisotropicFilteringLevel = value;
  1732. }
  1733. }
  1734. // Returns a NativeAddressMode.XXX value.
  1735. private _getAddressMode(wrapMode: number): number {
  1736. switch (wrapMode) {
  1737. case Constants.TEXTURE_WRAP_ADDRESSMODE:
  1738. return this._native.ADDRESS_MODE_WRAP;
  1739. case Constants.TEXTURE_CLAMP_ADDRESSMODE:
  1740. return this._native.ADDRESS_MODE_CLAMP;
  1741. case Constants.TEXTURE_MIRROR_ADDRESSMODE:
  1742. return this._native.ADDRESS_MODE_MIRROR;
  1743. default:
  1744. throw new Error("Unexpected wrap mode: " + wrapMode + ".");
  1745. }
  1746. }
  1747. /** @hidden */
  1748. public _bindTexture(channel: number, texture: InternalTexture): void {
  1749. let uniform = this._boundUniforms[channel];
  1750. if (!uniform) {
  1751. return ;
  1752. }
  1753. this._native.setTexture(uniform, texture._hardwareTexture?.underlyingResource);
  1754. }
  1755. protected _deleteBuffer(buffer: NativeDataBuffer): void {
  1756. if (buffer.nativeIndexBuffer) {
  1757. this._native.deleteIndexBuffer(buffer.nativeIndexBuffer);
  1758. delete buffer.nativeIndexBuffer;
  1759. }
  1760. if (buffer.nativeVertexBuffer) {
  1761. this._native.deleteVertexBuffer(buffer.nativeVertexBuffer);
  1762. delete buffer.nativeVertexBuffer;
  1763. }
  1764. }
  1765. public releaseEffects() {
  1766. // TODO
  1767. }
  1768. /** @hidden */
  1769. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  1770. throw new Error("_uploadCompressedDataToTextureDirectly not implemented.");
  1771. }
  1772. /** @hidden */
  1773. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1774. throw new Error("_uploadDataToTextureDirectly not implemented.");
  1775. }
  1776. /** @hidden */
  1777. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1778. throw new Error("_uploadArrayBufferViewToTexture not implemented.");
  1779. }
  1780. /** @hidden */
  1781. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  1782. throw new Error("_uploadArrayBufferViewToTexture not implemented.");
  1783. }
  1784. // JavaScript-to-Native conversion helper functions.
  1785. private _getNativeSamplingMode(samplingMode: number): number {
  1786. switch (samplingMode) {
  1787. case Constants.TEXTURE_NEAREST_NEAREST:
  1788. return this._native.TEXTURE_NEAREST_NEAREST;
  1789. case Constants.TEXTURE_LINEAR_LINEAR:
  1790. return this._native.TEXTURE_LINEAR_LINEAR;
  1791. case Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR:
  1792. return this._native.TEXTURE_LINEAR_LINEAR_MIPLINEAR;
  1793. case Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  1794. return this._native.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  1795. case Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  1796. return this._native.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  1797. case Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  1798. return this._native.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  1799. case Constants.TEXTURE_NEAREST_LINEAR:
  1800. return this._native.TEXTURE_NEAREST_LINEAR;
  1801. case Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR:
  1802. return this._native.TEXTURE_NEAREST_NEAREST_MIPLINEAR;
  1803. case Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  1804. return this._native.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  1805. case Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  1806. return this._native.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  1807. case Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST:
  1808. return this._native.TEXTURE_LINEAR_LINEAR_MIPNEAREST;
  1809. case Constants.TEXTURE_LINEAR_NEAREST:
  1810. return this._native.TEXTURE_LINEAR_NEAREST;
  1811. default:
  1812. throw new Error(`Unsupported sampling mode: ${samplingMode}.`);
  1813. }
  1814. }
  1815. private _getNativeTextureFormat(format: number, type: number): number {
  1816. if (format == Constants.TEXTUREFORMAT_RGBA && type == Constants.TEXTURETYPE_UNSIGNED_INT) {
  1817. return this._native.TEXTURE_FORMAT_RGBA8;
  1818. }
  1819. else if (format == Constants.TEXTUREFORMAT_RGBA && type == Constants.TEXTURETYPE_FLOAT) {
  1820. return this._native.TEXTURE_FORMAT_RGBA32F;
  1821. }
  1822. else {
  1823. throw new Error(`Unsupported texture format or type: format ${format}, type ${type}.`);
  1824. }
  1825. }
  1826. private _getNativeAlphaMode(mode: number): number {
  1827. switch (mode) {
  1828. case Constants.ALPHA_DISABLE:
  1829. return this._native.ALPHA_DISABLE;
  1830. case Constants.ALPHA_ADD:
  1831. return this._native.ALPHA_ADD;
  1832. case Constants.ALPHA_COMBINE:
  1833. return this._native.ALPHA_COMBINE;
  1834. case Constants.ALPHA_SUBTRACT:
  1835. return this._native.ALPHA_SUBTRACT;
  1836. case Constants.ALPHA_MULTIPLY:
  1837. return this._native.ALPHA_MULTIPLY;
  1838. case Constants.ALPHA_MAXIMIZED:
  1839. return this._native.ALPHA_MAXIMIZED;
  1840. case Constants.ALPHA_ONEONE:
  1841. return this._native.ALPHA_ONEONE;
  1842. case Constants.ALPHA_PREMULTIPLIED:
  1843. return this._native.ALPHA_PREMULTIPLIED;
  1844. case Constants.ALPHA_PREMULTIPLIED_PORTERDUFF:
  1845. return this._native.ALPHA_PREMULTIPLIED_PORTERDUFF;
  1846. case Constants.ALPHA_INTERPOLATE:
  1847. return this._native.ALPHA_INTERPOLATE;
  1848. case Constants.ALPHA_SCREENMODE:
  1849. return this._native.ALPHA_SCREENMODE;
  1850. default:
  1851. throw new Error(`Unsupported alpha mode: ${mode}.`);
  1852. }
  1853. }
  1854. private _getNativeAttribType(type: number): number {
  1855. switch (type) {
  1856. case VertexBuffer.UNSIGNED_BYTE:
  1857. return this._native.ATTRIB_TYPE_UINT8;
  1858. case VertexBuffer.SHORT:
  1859. return this._native.ATTRIB_TYPE_INT16;
  1860. case VertexBuffer.FLOAT:
  1861. return this._native.ATTRIB_TYPE_FLOAT;
  1862. default:
  1863. throw new Error(`Unsupported attribute type: ${type}.`);
  1864. }
  1865. }
  1866. }