nativeEngine.ts 88 KB

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