babylon.engine.js 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var compileShader = function (gl, source, type, defines) {
  4. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6. gl.compileShader(shader);
  7. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8. throw new Error(gl.getShaderInfoLog(shader));
  9. }
  10. return shader;
  11. };
  12. var HALF_FLOAT_OES = 0x8D61;
  13. var getWebGLTextureType = function (gl, type) {
  14. if (type === Engine.TEXTURETYPE_FLOAT) {
  15. return gl.FLOAT;
  16. }
  17. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18. // Add Half Float Constant.
  19. return HALF_FLOAT_OES;
  20. }
  21. return gl.UNSIGNED_BYTE;
  22. };
  23. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  24. var magFilter = gl.NEAREST;
  25. var minFilter = gl.NEAREST;
  26. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  27. magFilter = gl.LINEAR;
  28. if (generateMipMaps) {
  29. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  30. }
  31. else {
  32. minFilter = gl.LINEAR;
  33. }
  34. }
  35. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  36. magFilter = gl.LINEAR;
  37. if (generateMipMaps) {
  38. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  39. }
  40. else {
  41. minFilter = gl.LINEAR;
  42. }
  43. }
  44. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  45. magFilter = gl.NEAREST;
  46. if (generateMipMaps) {
  47. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  48. }
  49. else {
  50. minFilter = gl.NEAREST;
  51. }
  52. }
  53. return {
  54. min: minFilter,
  55. mag: magFilter
  56. };
  57. };
  58. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  59. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60. var engine = scene.getEngine();
  61. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  62. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  63. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  64. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  65. texture._baseWidth = width;
  66. texture._baseHeight = height;
  67. texture._width = potWidth;
  68. texture._height = potHeight;
  69. texture.isReady = true;
  70. processFunction(potWidth, potHeight);
  71. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  72. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  73. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  74. if (!noMipmap && !isCompressed) {
  75. gl.generateMipmap(gl.TEXTURE_2D);
  76. }
  77. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  78. engine.resetTextureCache();
  79. scene._removePendingData(texture);
  80. if (onLoad) {
  81. onLoad();
  82. }
  83. };
  84. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  85. var img;
  86. var onload = function () {
  87. loadedImages[index] = img;
  88. loadedImages._internalCount++;
  89. scene._removePendingData(img);
  90. if (loadedImages._internalCount === 6) {
  91. onfinish(loadedImages);
  92. }
  93. };
  94. var onerror = function () {
  95. scene._removePendingData(img);
  96. };
  97. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  98. scene._addPendingData(img);
  99. };
  100. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  101. var loadedImages = [];
  102. loadedImages._internalCount = 0;
  103. for (var index = 0; index < 6; index++) {
  104. partialLoad(files[index], index, loadedImages, scene, onfinish);
  105. }
  106. };
  107. var InstancingAttributeInfo = (function () {
  108. function InstancingAttributeInfo() {
  109. }
  110. return InstancingAttributeInfo;
  111. })();
  112. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  113. var EngineCapabilities = (function () {
  114. function EngineCapabilities() {
  115. }
  116. return EngineCapabilities;
  117. })();
  118. BABYLON.EngineCapabilities = EngineCapabilities;
  119. /**
  120. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  121. */
  122. var Engine = (function () {
  123. /**
  124. * @constructor
  125. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  126. * @param {boolean} [antialias] - enable antialias
  127. * @param options - further options to be sent to the getContext function
  128. */
  129. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  130. var _this = this;
  131. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  132. // Public members
  133. this.isFullscreen = false;
  134. this.isPointerLock = false;
  135. this.cullBackFaces = true;
  136. this.renderEvenInBackground = true;
  137. // To enable/disable IDB support and avoid XHR on .manifest
  138. this.enableOfflineSupport = true;
  139. this.scenes = new Array();
  140. this._windowIsBackground = false;
  141. this._webGLVersion = "1.0";
  142. this._drawCalls = new BABYLON.PerfCounter();
  143. this._renderingQueueLaunched = false;
  144. this._activeRenderLoops = [];
  145. // FPS
  146. this.fpsRange = 60;
  147. this.previousFramesDuration = [];
  148. this.fps = 60;
  149. this.deltaTime = 0;
  150. // States
  151. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  152. this._stencilState = new BABYLON.Internals._StencilState();
  153. this._alphaState = new BABYLON.Internals._AlphaState();
  154. this._alphaMode = Engine.ALPHA_DISABLE;
  155. // Cache
  156. this._loadedTexturesCache = new Array();
  157. this._maxTextureChannels = 16;
  158. this._activeTexturesCache = new Array(this._maxTextureChannels);
  159. this._compiledEffects = {};
  160. this._vertexAttribArraysEnabled = [];
  161. this._uintIndicesCurrentlySet = false;
  162. this._currentBoundBuffer = new Array();
  163. this._currentBufferPointers = [];
  164. this._currentInstanceLocations = new Array();
  165. this._currentInstanceBuffers = new Array();
  166. this._renderingCanvas = canvas;
  167. this._externalData = new BABYLON.StringDictionary();
  168. options = options || {};
  169. if (antialias != null) {
  170. options.antialias = antialias;
  171. }
  172. if (options.preserveDrawingBuffer === undefined) {
  173. options.preserveDrawingBuffer = false;
  174. }
  175. // Checks if some of the format renders first to allow the use of webgl inspector.
  176. var renderToFullFloat = this._canRenderToFloatTexture();
  177. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  178. // GL
  179. //try {
  180. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  181. // if (this._gl) {
  182. // this._webGLVersion = "2.0";
  183. // }
  184. //} catch (e) {
  185. // // Do nothing
  186. //}
  187. if (!this._gl) {
  188. try {
  189. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  190. }
  191. catch (e) {
  192. throw new Error("WebGL not supported");
  193. }
  194. }
  195. if (!this._gl) {
  196. throw new Error("WebGL not supported");
  197. }
  198. this._onBlur = function () {
  199. _this._windowIsBackground = true;
  200. };
  201. this._onFocus = function () {
  202. _this._windowIsBackground = false;
  203. };
  204. window.addEventListener("blur", this._onBlur);
  205. window.addEventListener("focus", this._onFocus);
  206. // Viewport
  207. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  208. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  209. this.resize();
  210. // Caps
  211. this._isStencilEnable = options.stencil;
  212. this._caps = new EngineCapabilities();
  213. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  214. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  215. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  216. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  217. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  218. // Infos
  219. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  220. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  221. if (rendererInfo != null) {
  222. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  223. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  224. }
  225. if (!this._glVendor) {
  226. this._glVendor = "Unknown vendor";
  227. }
  228. if (!this._glRenderer) {
  229. this._glRenderer = "Unknown renderer";
  230. }
  231. // Extensions
  232. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  233. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  234. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  235. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  236. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  237. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  238. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  239. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  240. this._caps.highPrecisionShaderSupported = true;
  241. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  242. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  243. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  244. this._caps.textureFloatRender = renderToFullFloat;
  245. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  246. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  247. this._caps.textureHalfFloatRender = renderToHalfFloat;
  248. if (this._gl.getShaderPrecisionFormat) {
  249. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  250. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  251. }
  252. // Depth buffer
  253. this.setDepthBuffer(true);
  254. this.setDepthFunctionToLessOrEqual();
  255. this.setDepthWrite(true);
  256. // Fullscreen
  257. this._onFullscreenChange = function () {
  258. if (document.fullscreen !== undefined) {
  259. _this.isFullscreen = document.fullscreen;
  260. }
  261. else if (document.mozFullScreen !== undefined) {
  262. _this.isFullscreen = document.mozFullScreen;
  263. }
  264. else if (document.webkitIsFullScreen !== undefined) {
  265. _this.isFullscreen = document.webkitIsFullScreen;
  266. }
  267. else if (document.msIsFullScreen !== undefined) {
  268. _this.isFullscreen = document.msIsFullScreen;
  269. }
  270. // Pointer lock
  271. if (_this.isFullscreen && _this._pointerLockRequested) {
  272. canvas.requestPointerLock = canvas.requestPointerLock ||
  273. canvas.msRequestPointerLock ||
  274. canvas.mozRequestPointerLock ||
  275. canvas.webkitRequestPointerLock;
  276. if (canvas.requestPointerLock) {
  277. canvas.requestPointerLock();
  278. }
  279. }
  280. };
  281. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  282. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  283. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  284. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  285. // Pointer lock
  286. this._onPointerLockChange = function () {
  287. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  288. document.webkitPointerLockElement === canvas ||
  289. document.msPointerLockElement === canvas ||
  290. document.pointerLockElement === canvas);
  291. };
  292. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  293. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  294. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  295. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  296. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  297. Engine.audioEngine = new BABYLON.AudioEngine();
  298. }
  299. //default loading screen
  300. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  301. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  302. }
  303. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  304. get: function () {
  305. return Engine._ALPHA_DISABLE;
  306. },
  307. enumerable: true,
  308. configurable: true
  309. });
  310. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  311. get: function () {
  312. return Engine._ALPHA_ONEONE;
  313. },
  314. enumerable: true,
  315. configurable: true
  316. });
  317. Object.defineProperty(Engine, "ALPHA_ADD", {
  318. get: function () {
  319. return Engine._ALPHA_ADD;
  320. },
  321. enumerable: true,
  322. configurable: true
  323. });
  324. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  325. get: function () {
  326. return Engine._ALPHA_COMBINE;
  327. },
  328. enumerable: true,
  329. configurable: true
  330. });
  331. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  332. get: function () {
  333. return Engine._ALPHA_SUBTRACT;
  334. },
  335. enumerable: true,
  336. configurable: true
  337. });
  338. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  339. get: function () {
  340. return Engine._ALPHA_MULTIPLY;
  341. },
  342. enumerable: true,
  343. configurable: true
  344. });
  345. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  346. get: function () {
  347. return Engine._ALPHA_MAXIMIZED;
  348. },
  349. enumerable: true,
  350. configurable: true
  351. });
  352. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  353. get: function () {
  354. return Engine._DELAYLOADSTATE_NONE;
  355. },
  356. enumerable: true,
  357. configurable: true
  358. });
  359. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  360. get: function () {
  361. return Engine._DELAYLOADSTATE_LOADED;
  362. },
  363. enumerable: true,
  364. configurable: true
  365. });
  366. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  367. get: function () {
  368. return Engine._DELAYLOADSTATE_LOADING;
  369. },
  370. enumerable: true,
  371. configurable: true
  372. });
  373. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  374. get: function () {
  375. return Engine._DELAYLOADSTATE_NOTLOADED;
  376. },
  377. enumerable: true,
  378. configurable: true
  379. });
  380. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  381. get: function () {
  382. return Engine._TEXTUREFORMAT_ALPHA;
  383. },
  384. enumerable: true,
  385. configurable: true
  386. });
  387. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  388. get: function () {
  389. return Engine._TEXTUREFORMAT_LUMINANCE;
  390. },
  391. enumerable: true,
  392. configurable: true
  393. });
  394. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  395. get: function () {
  396. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  397. },
  398. enumerable: true,
  399. configurable: true
  400. });
  401. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  402. get: function () {
  403. return Engine._TEXTUREFORMAT_RGB;
  404. },
  405. enumerable: true,
  406. configurable: true
  407. });
  408. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  409. get: function () {
  410. return Engine._TEXTUREFORMAT_RGBA;
  411. },
  412. enumerable: true,
  413. configurable: true
  414. });
  415. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  416. get: function () {
  417. return Engine._TEXTURETYPE_UNSIGNED_INT;
  418. },
  419. enumerable: true,
  420. configurable: true
  421. });
  422. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  423. get: function () {
  424. return Engine._TEXTURETYPE_FLOAT;
  425. },
  426. enumerable: true,
  427. configurable: true
  428. });
  429. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  430. get: function () {
  431. return Engine._TEXTURETYPE_HALF_FLOAT;
  432. },
  433. enumerable: true,
  434. configurable: true
  435. });
  436. Object.defineProperty(Engine, "Version", {
  437. get: function () {
  438. return "2.5-alpha";
  439. },
  440. enumerable: true,
  441. configurable: true
  442. });
  443. Object.defineProperty(Engine.prototype, "webGLVersion", {
  444. get: function () {
  445. return this._webGLVersion;
  446. },
  447. enumerable: true,
  448. configurable: true
  449. });
  450. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  451. /**
  452. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  453. */
  454. get: function () {
  455. return this._isStencilEnable;
  456. },
  457. enumerable: true,
  458. configurable: true
  459. });
  460. Engine.prototype._prepareWorkingCanvas = function () {
  461. if (this._workingCanvas) {
  462. return;
  463. }
  464. this._workingCanvas = document.createElement("canvas");
  465. this._workingContext = this._workingCanvas.getContext("2d");
  466. };
  467. Engine.prototype.resetTextureCache = function () {
  468. for (var index = 0; index < this._maxTextureChannels; index++) {
  469. this._activeTexturesCache[index] = null;
  470. }
  471. };
  472. Engine.prototype.getGlInfo = function () {
  473. return {
  474. vendor: this._glVendor,
  475. renderer: this._glRenderer,
  476. version: this._glVersion
  477. };
  478. };
  479. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  480. if (useScreen === void 0) { useScreen = false; }
  481. var viewport = camera.viewport;
  482. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  483. };
  484. Engine.prototype.getRenderWidth = function (useScreen) {
  485. if (useScreen === void 0) { useScreen = false; }
  486. if (!useScreen && this._currentRenderTarget) {
  487. return this._currentRenderTarget._width;
  488. }
  489. return this._renderingCanvas.width;
  490. };
  491. Engine.prototype.getRenderHeight = function (useScreen) {
  492. if (useScreen === void 0) { useScreen = false; }
  493. if (!useScreen && this._currentRenderTarget) {
  494. return this._currentRenderTarget._height;
  495. }
  496. return this._renderingCanvas.height;
  497. };
  498. Engine.prototype.getRenderingCanvas = function () {
  499. return this._renderingCanvas;
  500. };
  501. Engine.prototype.getRenderingCanvasClientRect = function () {
  502. return this._renderingCanvas.getBoundingClientRect();
  503. };
  504. Engine.prototype.setHardwareScalingLevel = function (level) {
  505. this._hardwareScalingLevel = level;
  506. this.resize();
  507. };
  508. Engine.prototype.getHardwareScalingLevel = function () {
  509. return this._hardwareScalingLevel;
  510. };
  511. Engine.prototype.getLoadedTexturesCache = function () {
  512. return this._loadedTexturesCache;
  513. };
  514. Engine.prototype.getCaps = function () {
  515. return this._caps;
  516. };
  517. Object.defineProperty(Engine.prototype, "drawCalls", {
  518. get: function () {
  519. return this._drawCalls.current;
  520. },
  521. enumerable: true,
  522. configurable: true
  523. });
  524. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  525. get: function () {
  526. return this._drawCalls;
  527. },
  528. enumerable: true,
  529. configurable: true
  530. });
  531. Engine.prototype.getDepthFunction = function () {
  532. return this._depthCullingState.depthFunc;
  533. };
  534. Engine.prototype.setDepthFunction = function (depthFunc) {
  535. this._depthCullingState.depthFunc = depthFunc;
  536. };
  537. Engine.prototype.setDepthFunctionToGreater = function () {
  538. this._depthCullingState.depthFunc = this._gl.GREATER;
  539. };
  540. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  541. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  542. };
  543. Engine.prototype.setDepthFunctionToLess = function () {
  544. this._depthCullingState.depthFunc = this._gl.LESS;
  545. };
  546. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  547. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  548. };
  549. Engine.prototype.getStencilBuffer = function () {
  550. return this._stencilState.stencilTest;
  551. };
  552. Engine.prototype.setStencilBuffer = function (enable) {
  553. this._stencilState.stencilTest = enable;
  554. };
  555. Engine.prototype.getStencilMask = function () {
  556. return this._stencilState.stencilMask;
  557. };
  558. Engine.prototype.setStencilMask = function (mask) {
  559. this._stencilState.stencilMask = mask;
  560. };
  561. Engine.prototype.getStencilFunction = function () {
  562. return this._stencilState.stencilFunc;
  563. };
  564. Engine.prototype.getStencilFunctionReference = function () {
  565. return this._stencilState.stencilFuncRef;
  566. };
  567. Engine.prototype.getStencilFunctionMask = function () {
  568. return this._stencilState.stencilFuncMask;
  569. };
  570. Engine.prototype.setStencilFunction = function (stencilFunc) {
  571. this._stencilState.stencilFunc = stencilFunc;
  572. };
  573. Engine.prototype.setStencilFunctionReference = function (reference) {
  574. this._stencilState.stencilFuncRef = reference;
  575. };
  576. Engine.prototype.setStencilFunctionMask = function (mask) {
  577. this._stencilState.stencilFuncMask = mask;
  578. };
  579. Engine.prototype.getStencilOperationFail = function () {
  580. return this._stencilState.stencilOpStencilFail;
  581. };
  582. Engine.prototype.getStencilOperationDepthFail = function () {
  583. return this._stencilState.stencilOpDepthFail;
  584. };
  585. Engine.prototype.getStencilOperationPass = function () {
  586. return this._stencilState.stencilOpStencilDepthPass;
  587. };
  588. Engine.prototype.setStencilOperationFail = function (operation) {
  589. this._stencilState.stencilOpStencilFail = operation;
  590. };
  591. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  592. this._stencilState.stencilOpDepthFail = operation;
  593. };
  594. Engine.prototype.setStencilOperationPass = function (operation) {
  595. this._stencilState.stencilOpStencilDepthPass = operation;
  596. };
  597. /**
  598. * stop executing a render loop function and remove it from the execution array
  599. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  600. */
  601. Engine.prototype.stopRenderLoop = function (renderFunction) {
  602. if (!renderFunction) {
  603. this._activeRenderLoops = [];
  604. return;
  605. }
  606. var index = this._activeRenderLoops.indexOf(renderFunction);
  607. if (index >= 0) {
  608. this._activeRenderLoops.splice(index, 1);
  609. }
  610. };
  611. Engine.prototype._renderLoop = function () {
  612. var shouldRender = true;
  613. if (!this.renderEvenInBackground && this._windowIsBackground) {
  614. shouldRender = false;
  615. }
  616. if (shouldRender) {
  617. // Start new frame
  618. this.beginFrame();
  619. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  620. var renderFunction = this._activeRenderLoops[index];
  621. renderFunction();
  622. }
  623. // Present
  624. this.endFrame();
  625. }
  626. if (this._activeRenderLoops.length > 0) {
  627. // Register new frame
  628. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  629. }
  630. else {
  631. this._renderingQueueLaunched = false;
  632. }
  633. };
  634. /**
  635. * Register and execute a render loop. The engine can have more than one render function.
  636. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  637. * @example
  638. * engine.runRenderLoop(function () {
  639. * scene.render()
  640. * })
  641. */
  642. Engine.prototype.runRenderLoop = function (renderFunction) {
  643. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  644. return;
  645. }
  646. this._activeRenderLoops.push(renderFunction);
  647. if (!this._renderingQueueLaunched) {
  648. this._renderingQueueLaunched = true;
  649. this._bindedRenderFunction = this._renderLoop.bind(this);
  650. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  651. }
  652. };
  653. /**
  654. * Toggle full screen mode.
  655. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  656. * @param {any} options - an options object to be sent to the requestFullscreen function
  657. */
  658. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  659. if (this.isFullscreen) {
  660. BABYLON.Tools.ExitFullscreen();
  661. }
  662. else {
  663. this._pointerLockRequested = requestPointerLock;
  664. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  665. }
  666. };
  667. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  668. if (stencil === void 0) { stencil = false; }
  669. this.applyStates();
  670. var mode = 0;
  671. if (backBuffer) {
  672. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  673. mode |= this._gl.COLOR_BUFFER_BIT;
  674. }
  675. if (depth) {
  676. this._gl.clearDepth(1.0);
  677. mode |= this._gl.DEPTH_BUFFER_BIT;
  678. }
  679. if (stencil) {
  680. this._gl.clearStencil(0);
  681. mode |= this._gl.STENCIL_BUFFER_BIT;
  682. }
  683. this._gl.clear(mode);
  684. };
  685. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  686. var gl = this._gl;
  687. // Save state
  688. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  689. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  690. // Change state
  691. gl.enable(gl.SCISSOR_TEST);
  692. gl.scissor(x, y, width, height);
  693. // Clear
  694. this.clear(clearColor, true, true, true);
  695. // Restore state
  696. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  697. if (curScissor === true) {
  698. gl.enable(gl.SCISSOR_TEST);
  699. }
  700. else {
  701. gl.disable(gl.SCISSOR_TEST);
  702. }
  703. };
  704. /**
  705. * Set the WebGL's viewport
  706. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  707. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  708. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  709. */
  710. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  711. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  712. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  713. var x = viewport.x || 0;
  714. var y = viewport.y || 0;
  715. this._cachedViewport = viewport;
  716. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  717. };
  718. /**
  719. * Directly set the WebGL Viewport
  720. * The x, y, width & height are directly passed to the WebGL call
  721. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  722. */
  723. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  724. var currentViewport = this._cachedViewport;
  725. this._cachedViewport = null;
  726. this._gl.viewport(x, y, width, height);
  727. return currentViewport;
  728. };
  729. Engine.prototype.beginFrame = function () {
  730. this._measureFps();
  731. };
  732. Engine.prototype.endFrame = function () {
  733. //this.flushFramebuffer();
  734. };
  735. /**
  736. * resize the view according to the canvas' size.
  737. * @example
  738. * window.addEventListener("resize", function () {
  739. * engine.resize();
  740. * });
  741. */
  742. Engine.prototype.resize = function () {
  743. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  744. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  745. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  746. for (var index = 0; index < this.scenes.length; index++) {
  747. var scene = this.scenes[index];
  748. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  749. scene.debugLayer._syncPositions();
  750. }
  751. }
  752. };
  753. /**
  754. * force a specific size of the canvas
  755. * @param {number} width - the new canvas' width
  756. * @param {number} height - the new canvas' height
  757. */
  758. Engine.prototype.setSize = function (width, height) {
  759. this._renderingCanvas.width = width;
  760. this._renderingCanvas.height = height;
  761. for (var index = 0; index < this.scenes.length; index++) {
  762. var scene = this.scenes[index];
  763. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  764. var cam = scene.cameras[camIndex];
  765. cam._currentRenderId = 0;
  766. }
  767. }
  768. };
  769. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  770. this._currentRenderTarget = texture;
  771. this.bindUnboundFramebuffer(texture._framebuffer);
  772. var gl = this._gl;
  773. if (texture.isCube) {
  774. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  775. }
  776. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  777. this.wipeCaches();
  778. };
  779. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  780. if (this._currentFramebuffer !== framebuffer) {
  781. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  782. this._currentFramebuffer = framebuffer;
  783. }
  784. };
  785. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  786. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  787. this._currentRenderTarget = null;
  788. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  789. var gl = this._gl;
  790. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  791. gl.generateMipmap(gl.TEXTURE_2D);
  792. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  793. }
  794. this.bindUnboundFramebuffer(null);
  795. };
  796. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  797. if (texture.generateMipMaps) {
  798. var gl = this._gl;
  799. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  800. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  801. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  802. }
  803. };
  804. Engine.prototype.flushFramebuffer = function () {
  805. this._gl.flush();
  806. };
  807. Engine.prototype.restoreDefaultFramebuffer = function () {
  808. this._currentRenderTarget = null;
  809. this.bindUnboundFramebuffer(null);
  810. this.setViewport(this._cachedViewport);
  811. this.wipeCaches();
  812. };
  813. // VBOs
  814. Engine.prototype._resetVertexBufferBinding = function () {
  815. this.bindArrayBuffer(null);
  816. this._cachedVertexBuffers = null;
  817. };
  818. Engine.prototype.createVertexBuffer = function (vertices) {
  819. var vbo = this._gl.createBuffer();
  820. this.bindArrayBuffer(vbo);
  821. if (vertices instanceof Float32Array) {
  822. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  823. }
  824. else {
  825. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  826. }
  827. this._resetVertexBufferBinding();
  828. vbo.references = 1;
  829. return vbo;
  830. };
  831. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  832. var vbo = this._gl.createBuffer();
  833. this.bindArrayBuffer(vbo);
  834. if (vertices instanceof Float32Array) {
  835. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  836. }
  837. else {
  838. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  839. }
  840. this._resetVertexBufferBinding();
  841. vbo.references = 1;
  842. return vbo;
  843. };
  844. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  845. this.bindArrayBuffer(vertexBuffer);
  846. if (offset === undefined) {
  847. offset = 0;
  848. }
  849. if (count === undefined) {
  850. if (vertices instanceof Float32Array) {
  851. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  852. }
  853. else {
  854. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  855. }
  856. }
  857. else {
  858. if (vertices instanceof Float32Array) {
  859. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  860. }
  861. else {
  862. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  863. }
  864. }
  865. this._resetVertexBufferBinding();
  866. };
  867. Engine.prototype._resetIndexBufferBinding = function () {
  868. this.bindIndexBuffer(null);
  869. this._cachedIndexBuffer = null;
  870. };
  871. Engine.prototype.createIndexBuffer = function (indices) {
  872. var vbo = this._gl.createBuffer();
  873. this.bindIndexBuffer(vbo);
  874. // Check for 32 bits indices
  875. var arrayBuffer;
  876. var need32Bits = false;
  877. if (this._caps.uintIndices) {
  878. for (var index = 0; index < indices.length; index++) {
  879. if (indices[index] > 65535) {
  880. need32Bits = true;
  881. break;
  882. }
  883. }
  884. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  885. }
  886. else {
  887. arrayBuffer = new Uint16Array(indices);
  888. }
  889. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  890. this._resetIndexBufferBinding();
  891. vbo.references = 1;
  892. vbo.is32Bits = need32Bits;
  893. return vbo;
  894. };
  895. Engine.prototype.bindArrayBuffer = function (buffer) {
  896. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  897. };
  898. Engine.prototype.bindIndexBuffer = function (buffer) {
  899. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  900. };
  901. Engine.prototype.bindBuffer = function (buffer, target) {
  902. if (this._currentBoundBuffer[target] !== buffer) {
  903. this._gl.bindBuffer(target, buffer);
  904. this._currentBoundBuffer[target] = buffer;
  905. }
  906. };
  907. Engine.prototype.updateArrayBuffer = function (data) {
  908. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  909. };
  910. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  911. var pointer = this._currentBufferPointers[indx];
  912. var changed = false;
  913. if (!pointer) {
  914. changed = true;
  915. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  916. }
  917. else {
  918. if (pointer.buffer !== buffer) {
  919. pointer.buffer = buffer;
  920. changed = true;
  921. }
  922. if (pointer.size !== size) {
  923. pointer.size = size;
  924. changed = true;
  925. }
  926. if (pointer.type !== type) {
  927. pointer.type = type;
  928. changed = true;
  929. }
  930. if (pointer.normalized !== normalized) {
  931. pointer.normalized = normalized;
  932. changed = true;
  933. }
  934. if (pointer.stride !== stride) {
  935. pointer.stride = stride;
  936. changed = true;
  937. }
  938. if (pointer.offset !== offset) {
  939. pointer.offset = offset;
  940. changed = true;
  941. }
  942. }
  943. if (changed) {
  944. this.bindArrayBuffer(buffer);
  945. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  946. }
  947. };
  948. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  949. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  950. this._cachedVertexBuffers = vertexBuffer;
  951. this._cachedEffectForVertexBuffers = effect;
  952. var attributesCount = effect.getAttributesCount();
  953. var offset = 0;
  954. for (var index = 0; index < attributesCount; index++) {
  955. if (index < vertexDeclaration.length) {
  956. var order = effect.getAttributeLocation(index);
  957. if (order >= 0) {
  958. if (!this._vertexAttribArraysEnabled[order]) {
  959. this._gl.enableVertexAttribArray(order);
  960. this._vertexAttribArraysEnabled[order] = true;
  961. }
  962. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  963. }
  964. offset += vertexDeclaration[index] * 4;
  965. }
  966. else {
  967. //disable effect attributes that have no data
  968. var order = effect.getAttributeLocation(index);
  969. if (this._vertexAttribArraysEnabled[order]) {
  970. this._gl.disableVertexAttribArray(order);
  971. this._vertexAttribArraysEnabled[order] = false;
  972. }
  973. }
  974. }
  975. }
  976. if (this._cachedIndexBuffer !== indexBuffer) {
  977. this._cachedIndexBuffer = indexBuffer;
  978. this.bindIndexBuffer(indexBuffer);
  979. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  980. }
  981. };
  982. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  983. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  984. this._cachedVertexBuffers = vertexBuffers;
  985. this._cachedEffectForVertexBuffers = effect;
  986. var attributes = effect.getAttributesNames();
  987. for (var index = 0; index < attributes.length; index++) {
  988. var order = effect.getAttributeLocation(index);
  989. if (order >= 0) {
  990. var vertexBuffer = vertexBuffers[attributes[index]];
  991. if (!vertexBuffer) {
  992. if (this._vertexAttribArraysEnabled[order]) {
  993. this._gl.disableVertexAttribArray(order);
  994. this._vertexAttribArraysEnabled[order] = false;
  995. }
  996. continue;
  997. }
  998. if (!this._vertexAttribArraysEnabled[order]) {
  999. this._gl.enableVertexAttribArray(order);
  1000. this._vertexAttribArraysEnabled[order] = true;
  1001. }
  1002. var buffer = vertexBuffer.getBuffer();
  1003. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1004. if (vertexBuffer.getIsInstanced()) {
  1005. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  1006. this._currentInstanceLocations.push(order);
  1007. this._currentInstanceBuffers.push(buffer);
  1008. }
  1009. }
  1010. }
  1011. }
  1012. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  1013. this._cachedIndexBuffer = indexBuffer;
  1014. this.bindIndexBuffer(indexBuffer);
  1015. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1016. }
  1017. };
  1018. Engine.prototype.unbindInstanceAttributes = function () {
  1019. var boundBuffer;
  1020. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1021. var instancesBuffer = this._currentInstanceBuffers[i];
  1022. if (boundBuffer != instancesBuffer) {
  1023. boundBuffer = instancesBuffer;
  1024. this.bindArrayBuffer(instancesBuffer);
  1025. }
  1026. var offsetLocation = this._currentInstanceLocations[i];
  1027. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  1028. }
  1029. this._currentInstanceBuffers.length = 0;
  1030. this._currentInstanceLocations.length = 0;
  1031. };
  1032. Engine.prototype._releaseBuffer = function (buffer) {
  1033. buffer.references--;
  1034. if (buffer.references === 0) {
  1035. this._gl.deleteBuffer(buffer);
  1036. return true;
  1037. }
  1038. return false;
  1039. };
  1040. Engine.prototype.createInstancesBuffer = function (capacity) {
  1041. var buffer = this._gl.createBuffer();
  1042. buffer.capacity = capacity;
  1043. this.bindArrayBuffer(buffer);
  1044. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1045. return buffer;
  1046. };
  1047. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  1048. this._gl.deleteBuffer(buffer);
  1049. };
  1050. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  1051. this.bindArrayBuffer(instancesBuffer);
  1052. if (data) {
  1053. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1054. }
  1055. if (offsetLocations[0].index !== undefined) {
  1056. var stride = 0;
  1057. for (var i = 0; i < offsetLocations.length; i++) {
  1058. var ai = offsetLocations[i];
  1059. stride += ai.attributeSize * 4;
  1060. }
  1061. for (var i = 0; i < offsetLocations.length; i++) {
  1062. var ai = offsetLocations[i];
  1063. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1064. this._gl.enableVertexAttribArray(ai.index);
  1065. this._vertexAttribArraysEnabled[ai.index] = true;
  1066. }
  1067. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1068. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  1069. this._currentInstanceLocations.push(ai.index);
  1070. this._currentInstanceBuffers.push(instancesBuffer);
  1071. }
  1072. }
  1073. else {
  1074. for (var index = 0; index < 4; index++) {
  1075. var offsetLocation = offsetLocations[index];
  1076. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1077. this._gl.enableVertexAttribArray(offsetLocation);
  1078. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1079. }
  1080. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1081. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  1082. this._currentInstanceLocations.push(offsetLocation);
  1083. this._currentInstanceBuffers.push(instancesBuffer);
  1084. }
  1085. }
  1086. };
  1087. Engine.prototype.applyStates = function () {
  1088. this._depthCullingState.apply(this._gl);
  1089. this._stencilState.apply(this._gl);
  1090. this._alphaState.apply(this._gl);
  1091. };
  1092. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  1093. // Apply states
  1094. this.applyStates();
  1095. this._drawCalls.addCount(1, false);
  1096. // Render
  1097. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1098. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1099. if (instancesCount) {
  1100. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1101. return;
  1102. }
  1103. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1104. };
  1105. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  1106. // Apply states
  1107. this.applyStates();
  1108. this._drawCalls.addCount(1, false);
  1109. if (instancesCount) {
  1110. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1111. return;
  1112. }
  1113. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1114. };
  1115. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  1116. // Apply states
  1117. this.applyStates();
  1118. this._drawCalls.addCount(1, false);
  1119. if (instancesCount) {
  1120. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  1121. return;
  1122. }
  1123. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  1124. };
  1125. // Shaders
  1126. Engine.prototype._releaseEffect = function (effect) {
  1127. if (this._compiledEffects[effect._key]) {
  1128. delete this._compiledEffects[effect._key];
  1129. if (effect.getProgram()) {
  1130. this._gl.deleteProgram(effect.getProgram());
  1131. }
  1132. }
  1133. };
  1134. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  1135. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1136. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1137. var name = vertex + "+" + fragment + "@" + defines;
  1138. if (this._compiledEffects[name]) {
  1139. return this._compiledEffects[name];
  1140. }
  1141. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1142. effect._key = name;
  1143. this._compiledEffects[name] = effect;
  1144. return effect;
  1145. };
  1146. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  1147. if (uniformsNames === void 0) { uniformsNames = []; }
  1148. if (samplers === void 0) { samplers = []; }
  1149. if (defines === void 0) { defines = ""; }
  1150. return this.createEffect({
  1151. vertex: "particles",
  1152. fragmentElement: fragmentName
  1153. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1154. };
  1155. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  1156. context = context || this._gl;
  1157. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  1158. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  1159. var shaderProgram = context.createProgram();
  1160. context.attachShader(shaderProgram, vertexShader);
  1161. context.attachShader(shaderProgram, fragmentShader);
  1162. context.linkProgram(shaderProgram);
  1163. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  1164. if (!linked) {
  1165. var error = context.getProgramInfoLog(shaderProgram);
  1166. if (error) {
  1167. throw new Error(error);
  1168. }
  1169. }
  1170. context.deleteShader(vertexShader);
  1171. context.deleteShader(fragmentShader);
  1172. return shaderProgram;
  1173. };
  1174. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  1175. var results = [];
  1176. for (var index = 0; index < uniformsNames.length; index++) {
  1177. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1178. }
  1179. return results;
  1180. };
  1181. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  1182. var results = [];
  1183. for (var index = 0; index < attributesNames.length; index++) {
  1184. try {
  1185. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1186. }
  1187. catch (e) {
  1188. results.push(-1);
  1189. }
  1190. }
  1191. return results;
  1192. };
  1193. Engine.prototype.enableEffect = function (effect) {
  1194. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  1195. if (effect && effect.onBind) {
  1196. effect.onBind(effect);
  1197. }
  1198. return;
  1199. }
  1200. // Use program
  1201. this.setProgram(effect.getProgram());
  1202. this._currentEffect = effect;
  1203. if (effect.onBind) {
  1204. effect.onBind(effect);
  1205. }
  1206. };
  1207. Engine.prototype.setIntArray = function (uniform, array) {
  1208. if (!uniform)
  1209. return;
  1210. this._gl.uniform1iv(uniform, array);
  1211. };
  1212. Engine.prototype.setIntArray2 = function (uniform, array) {
  1213. if (!uniform || array.length % 2 !== 0)
  1214. return;
  1215. this._gl.uniform2iv(uniform, array);
  1216. };
  1217. Engine.prototype.setIntArray3 = function (uniform, array) {
  1218. if (!uniform || array.length % 3 !== 0)
  1219. return;
  1220. this._gl.uniform3iv(uniform, array);
  1221. };
  1222. Engine.prototype.setIntArray4 = function (uniform, array) {
  1223. if (!uniform || array.length % 4 !== 0)
  1224. return;
  1225. this._gl.uniform4iv(uniform, array);
  1226. };
  1227. Engine.prototype.setFloatArray = function (uniform, array) {
  1228. if (!uniform)
  1229. return;
  1230. this._gl.uniform1fv(uniform, array);
  1231. };
  1232. Engine.prototype.setFloatArray2 = function (uniform, array) {
  1233. if (!uniform || array.length % 2 !== 0)
  1234. return;
  1235. this._gl.uniform2fv(uniform, array);
  1236. };
  1237. Engine.prototype.setFloatArray3 = function (uniform, array) {
  1238. if (!uniform || array.length % 3 !== 0)
  1239. return;
  1240. this._gl.uniform3fv(uniform, array);
  1241. };
  1242. Engine.prototype.setFloatArray4 = function (uniform, array) {
  1243. if (!uniform || array.length % 4 !== 0)
  1244. return;
  1245. this._gl.uniform4fv(uniform, array);
  1246. };
  1247. Engine.prototype.setArray = function (uniform, array) {
  1248. if (!uniform)
  1249. return;
  1250. this._gl.uniform1fv(uniform, array);
  1251. };
  1252. Engine.prototype.setArray2 = function (uniform, array) {
  1253. if (!uniform || array.length % 2 !== 0)
  1254. return;
  1255. this._gl.uniform2fv(uniform, array);
  1256. };
  1257. Engine.prototype.setArray3 = function (uniform, array) {
  1258. if (!uniform || array.length % 3 !== 0)
  1259. return;
  1260. this._gl.uniform3fv(uniform, array);
  1261. };
  1262. Engine.prototype.setArray4 = function (uniform, array) {
  1263. if (!uniform || array.length % 4 !== 0)
  1264. return;
  1265. this._gl.uniform4fv(uniform, array);
  1266. };
  1267. Engine.prototype.setMatrices = function (uniform, matrices) {
  1268. if (!uniform)
  1269. return;
  1270. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1271. };
  1272. Engine.prototype.setMatrix = function (uniform, matrix) {
  1273. if (!uniform)
  1274. return;
  1275. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1276. };
  1277. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  1278. if (!uniform)
  1279. return;
  1280. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1281. };
  1282. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  1283. if (!uniform)
  1284. return;
  1285. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1286. };
  1287. Engine.prototype.setFloat = function (uniform, value) {
  1288. if (!uniform)
  1289. return;
  1290. this._gl.uniform1f(uniform, value);
  1291. };
  1292. Engine.prototype.setFloat2 = function (uniform, x, y) {
  1293. if (!uniform)
  1294. return;
  1295. this._gl.uniform2f(uniform, x, y);
  1296. };
  1297. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  1298. if (!uniform)
  1299. return;
  1300. this._gl.uniform3f(uniform, x, y, z);
  1301. };
  1302. Engine.prototype.setBool = function (uniform, bool) {
  1303. if (!uniform)
  1304. return;
  1305. this._gl.uniform1i(uniform, bool);
  1306. };
  1307. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  1308. if (!uniform)
  1309. return;
  1310. this._gl.uniform4f(uniform, x, y, z, w);
  1311. };
  1312. Engine.prototype.setColor3 = function (uniform, color3) {
  1313. if (!uniform)
  1314. return;
  1315. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1316. };
  1317. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  1318. if (!uniform)
  1319. return;
  1320. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1321. };
  1322. // States
  1323. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  1324. if (zOffset === void 0) { zOffset = 0; }
  1325. if (reverseSide === void 0) { reverseSide = false; }
  1326. // Culling
  1327. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1328. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1329. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1330. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1331. if (culling) {
  1332. this._depthCullingState.cullFace = cullFace;
  1333. this._depthCullingState.cull = true;
  1334. }
  1335. else {
  1336. this._depthCullingState.cull = false;
  1337. }
  1338. }
  1339. // Z offset
  1340. this._depthCullingState.zOffset = zOffset;
  1341. };
  1342. Engine.prototype.setDepthBuffer = function (enable) {
  1343. this._depthCullingState.depthTest = enable;
  1344. };
  1345. Engine.prototype.getDepthWrite = function () {
  1346. return this._depthCullingState.depthMask;
  1347. };
  1348. Engine.prototype.setDepthWrite = function (enable) {
  1349. this._depthCullingState.depthMask = enable;
  1350. };
  1351. Engine.prototype.setColorWrite = function (enable) {
  1352. this._gl.colorMask(enable, enable, enable, enable);
  1353. };
  1354. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  1355. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  1356. if (this._alphaMode === mode) {
  1357. return;
  1358. }
  1359. switch (mode) {
  1360. case Engine.ALPHA_DISABLE:
  1361. this._alphaState.alphaBlend = false;
  1362. break;
  1363. case Engine.ALPHA_COMBINE:
  1364. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1365. this._alphaState.alphaBlend = true;
  1366. break;
  1367. case Engine.ALPHA_ONEONE:
  1368. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1369. this._alphaState.alphaBlend = true;
  1370. break;
  1371. case Engine.ALPHA_ADD:
  1372. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1373. this._alphaState.alphaBlend = true;
  1374. break;
  1375. case Engine.ALPHA_SUBTRACT:
  1376. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1377. this._alphaState.alphaBlend = true;
  1378. break;
  1379. case Engine.ALPHA_MULTIPLY:
  1380. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1381. this._alphaState.alphaBlend = true;
  1382. break;
  1383. case Engine.ALPHA_MAXIMIZED:
  1384. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1385. this._alphaState.alphaBlend = true;
  1386. break;
  1387. }
  1388. if (!noDepthWriteChange) {
  1389. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  1390. }
  1391. this._alphaMode = mode;
  1392. };
  1393. Engine.prototype.getAlphaMode = function () {
  1394. return this._alphaMode;
  1395. };
  1396. Engine.prototype.setAlphaTesting = function (enable) {
  1397. this._alphaTest = enable;
  1398. };
  1399. Engine.prototype.getAlphaTesting = function () {
  1400. return this._alphaTest;
  1401. };
  1402. // Textures
  1403. Engine.prototype.wipeCaches = function () {
  1404. this.resetTextureCache();
  1405. this._currentEffect = null;
  1406. this._stencilState.reset();
  1407. this._depthCullingState.reset();
  1408. this.setDepthFunctionToLessOrEqual();
  1409. this._alphaState.reset();
  1410. this._cachedVertexBuffers = null;
  1411. this._cachedIndexBuffer = null;
  1412. this._cachedEffectForVertexBuffers = null;
  1413. };
  1414. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  1415. var gl = this._gl;
  1416. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1417. var magFilter = gl.NEAREST;
  1418. var minFilter = gl.NEAREST;
  1419. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  1420. magFilter = gl.LINEAR;
  1421. minFilter = gl.LINEAR;
  1422. }
  1423. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  1424. magFilter = gl.LINEAR;
  1425. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1426. }
  1427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1429. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1430. texture.samplingMode = samplingMode;
  1431. };
  1432. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  1433. var _this = this;
  1434. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1435. if (onLoad === void 0) { onLoad = null; }
  1436. if (onError === void 0) { onError = null; }
  1437. if (buffer === void 0) { buffer = null; }
  1438. var texture = this._gl.createTexture();
  1439. var extension;
  1440. var fromData = false;
  1441. if (url.substr(0, 5) === "data:") {
  1442. fromData = true;
  1443. }
  1444. if (!fromData)
  1445. extension = url.substr(url.length - 4, 4).toLowerCase();
  1446. else {
  1447. var oldUrl = url;
  1448. fromData = oldUrl.split(':');
  1449. url = oldUrl;
  1450. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1451. }
  1452. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1453. var isTGA = (extension === ".tga");
  1454. scene._addPendingData(texture);
  1455. texture.url = url;
  1456. texture.noMipmap = noMipmap;
  1457. texture.references = 1;
  1458. texture.samplingMode = samplingMode;
  1459. this._loadedTexturesCache.push(texture);
  1460. var onerror = function () {
  1461. scene._removePendingData(texture);
  1462. if (onError) {
  1463. onError();
  1464. }
  1465. };
  1466. var callback;
  1467. if (isTGA) {
  1468. callback = function (arrayBuffer) {
  1469. var data = new Uint8Array(arrayBuffer);
  1470. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  1471. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  1472. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  1473. }, onLoad, samplingMode);
  1474. };
  1475. if (!(fromData instanceof Array))
  1476. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  1477. callback(arrayBuffer);
  1478. }, onerror, scene.database, true);
  1479. else
  1480. callback(buffer);
  1481. }
  1482. else if (isDDS) {
  1483. callback = function (data) {
  1484. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1485. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1486. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  1487. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  1488. }, onLoad, samplingMode);
  1489. };
  1490. if (!(fromData instanceof Array))
  1491. BABYLON.Tools.LoadFile(url, function (data) {
  1492. callback(data);
  1493. }, onerror, scene.database, true);
  1494. else
  1495. callback(buffer);
  1496. }
  1497. else {
  1498. var onload = function (img) {
  1499. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  1500. var isPot = (img.width === potWidth && img.height === potHeight);
  1501. if (!isPot) {
  1502. _this._prepareWorkingCanvas();
  1503. _this._workingCanvas.width = potWidth;
  1504. _this._workingCanvas.height = potHeight;
  1505. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  1506. _this._workingContext.imageSmoothingEnabled = false;
  1507. _this._workingContext.mozImageSmoothingEnabled = false;
  1508. _this._workingContext.oImageSmoothingEnabled = false;
  1509. _this._workingContext.webkitImageSmoothingEnabled = false;
  1510. _this._workingContext.msImageSmoothingEnabled = false;
  1511. }
  1512. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1513. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  1514. _this._workingContext.imageSmoothingEnabled = true;
  1515. _this._workingContext.mozImageSmoothingEnabled = true;
  1516. _this._workingContext.oImageSmoothingEnabled = true;
  1517. _this._workingContext.webkitImageSmoothingEnabled = true;
  1518. _this._workingContext.msImageSmoothingEnabled = true;
  1519. }
  1520. }
  1521. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  1522. }, onLoad, samplingMode);
  1523. };
  1524. if (!(fromData instanceof Array))
  1525. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  1526. else
  1527. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  1528. }
  1529. return texture;
  1530. };
  1531. Engine.prototype._getInternalFormat = function (format) {
  1532. var internalFormat = this._gl.RGBA;
  1533. switch (format) {
  1534. case Engine.TEXTUREFORMAT_ALPHA:
  1535. internalFormat = this._gl.ALPHA;
  1536. break;
  1537. case Engine.TEXTUREFORMAT_LUMINANCE:
  1538. internalFormat = this._gl.LUMINANCE;
  1539. break;
  1540. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1541. internalFormat = this._gl.LUMINANCE_ALPHA;
  1542. break;
  1543. case Engine.TEXTUREFORMAT_RGB:
  1544. internalFormat = this._gl.RGB;
  1545. break;
  1546. case Engine.TEXTUREFORMAT_RGBA:
  1547. internalFormat = this._gl.RGBA;
  1548. break;
  1549. }
  1550. return internalFormat;
  1551. };
  1552. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  1553. if (compression === void 0) { compression = null; }
  1554. var internalFormat = this._getInternalFormat(format);
  1555. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1556. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1557. if (texture._width % 4 !== 0) {
  1558. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  1559. }
  1560. if (compression) {
  1561. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  1562. }
  1563. else {
  1564. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1565. }
  1566. if (texture.generateMipMaps) {
  1567. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1568. }
  1569. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1570. this.resetTextureCache();
  1571. texture.isReady = true;
  1572. };
  1573. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  1574. if (compression === void 0) { compression = null; }
  1575. var texture = this._gl.createTexture();
  1576. texture._baseWidth = width;
  1577. texture._baseHeight = height;
  1578. texture._width = width;
  1579. texture._height = height;
  1580. texture.references = 1;
  1581. this.updateRawTexture(texture, data, format, invertY, compression);
  1582. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1583. // Filters
  1584. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1585. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1586. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1587. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1588. texture.samplingMode = samplingMode;
  1589. this._loadedTexturesCache.push(texture);
  1590. return texture;
  1591. };
  1592. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  1593. var texture = this._gl.createTexture();
  1594. texture._baseWidth = width;
  1595. texture._baseHeight = height;
  1596. if (generateMipMaps) {
  1597. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  1598. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  1599. }
  1600. this.resetTextureCache();
  1601. texture._width = width;
  1602. texture._height = height;
  1603. texture.isReady = false;
  1604. texture.generateMipMaps = generateMipMaps;
  1605. texture.references = 1;
  1606. texture.samplingMode = samplingMode;
  1607. this.updateTextureSamplingMode(samplingMode, texture);
  1608. this._loadedTexturesCache.push(texture);
  1609. return texture;
  1610. };
  1611. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  1612. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1613. if (texture.isCube) {
  1614. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  1615. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1616. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1617. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  1618. }
  1619. else {
  1620. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1622. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1623. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1624. }
  1625. };
  1626. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  1627. if (premulAlpha === void 0) { premulAlpha = false; }
  1628. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1629. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1630. if (premulAlpha) {
  1631. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  1632. }
  1633. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1634. if (texture.generateMipMaps) {
  1635. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1636. }
  1637. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1638. this.resetTextureCache();
  1639. texture.isReady = true;
  1640. };
  1641. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  1642. if (texture._isDisabled) {
  1643. return;
  1644. }
  1645. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  1646. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1647. try {
  1648. // Testing video texture support
  1649. if (this._videoTextureSupported === undefined) {
  1650. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1651. if (this._gl.getError() !== 0) {
  1652. this._videoTextureSupported = false;
  1653. }
  1654. else {
  1655. this._videoTextureSupported = true;
  1656. }
  1657. }
  1658. // Copy video through the current working canvas if video texture is not supported
  1659. if (!this._videoTextureSupported) {
  1660. if (!texture._workingCanvas) {
  1661. texture._workingCanvas = document.createElement("canvas");
  1662. texture._workingContext = texture._workingCanvas.getContext("2d");
  1663. texture._workingCanvas.width = texture._width;
  1664. texture._workingCanvas.height = texture._height;
  1665. }
  1666. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1667. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1668. }
  1669. else {
  1670. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1671. }
  1672. if (texture.generateMipMaps) {
  1673. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1674. }
  1675. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  1676. this.resetTextureCache();
  1677. texture.isReady = true;
  1678. }
  1679. catch (ex) {
  1680. // Something unexpected
  1681. // Let's disable the texture
  1682. texture._isDisabled = true;
  1683. }
  1684. };
  1685. Engine.prototype.createRenderTargetTexture = function (size, options) {
  1686. // old version had a "generateMipMaps" arg instead of options.
  1687. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1688. // in the same way, generateDepthBuffer is defaulted to true
  1689. var generateMipMaps = false;
  1690. var generateDepthBuffer = true;
  1691. var generateStencilBuffer = false;
  1692. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1693. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1694. if (options !== undefined) {
  1695. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1696. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1697. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  1698. type = options.type === undefined ? type : options.type;
  1699. if (options.samplingMode !== undefined) {
  1700. samplingMode = options.samplingMode;
  1701. }
  1702. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  1703. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1704. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1705. }
  1706. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  1707. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  1708. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1709. }
  1710. }
  1711. var gl = this._gl;
  1712. var texture = gl.createTexture();
  1713. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1714. var width = size.width || size;
  1715. var height = size.height || size;
  1716. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1717. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1718. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1719. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1720. }
  1721. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1722. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1723. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1725. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1726. var depthStencilBuffer;
  1727. // Create the depth/stencil buffer
  1728. if (generateStencilBuffer) {
  1729. depthStencilBuffer = gl.createRenderbuffer();
  1730. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1731. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  1732. }
  1733. else if (generateDepthBuffer) {
  1734. depthStencilBuffer = gl.createRenderbuffer();
  1735. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1736. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1737. }
  1738. // Create the framebuffer
  1739. var framebuffer = gl.createFramebuffer();
  1740. this.bindUnboundFramebuffer(framebuffer);
  1741. // Manage attachments
  1742. if (generateStencilBuffer) {
  1743. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1744. }
  1745. else if (generateDepthBuffer) {
  1746. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1747. }
  1748. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  1749. if (generateMipMaps) {
  1750. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1751. }
  1752. // Unbind
  1753. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1754. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1755. this.bindUnboundFramebuffer(null);
  1756. texture._framebuffer = framebuffer;
  1757. if (generateDepthBuffer) {
  1758. texture._depthBuffer = depthStencilBuffer;
  1759. }
  1760. texture._baseWidth = width;
  1761. texture._baseHeight = height;
  1762. texture._width = width;
  1763. texture._height = height;
  1764. texture.isReady = true;
  1765. texture.generateMipMaps = generateMipMaps;
  1766. texture.references = 1;
  1767. texture.samplingMode = samplingMode;
  1768. texture.type = type;
  1769. this.resetTextureCache();
  1770. this._loadedTexturesCache.push(texture);
  1771. return texture;
  1772. };
  1773. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  1774. var gl = this._gl;
  1775. var texture = gl.createTexture();
  1776. var generateMipMaps = true;
  1777. var generateDepthBuffer = true;
  1778. var generateStencilBuffer = false;
  1779. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1780. if (options !== undefined) {
  1781. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1782. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1783. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  1784. if (options.samplingMode !== undefined) {
  1785. samplingMode = options.samplingMode;
  1786. }
  1787. }
  1788. texture.isCube = true;
  1789. texture.references = 1;
  1790. texture.generateMipMaps = generateMipMaps;
  1791. texture.references = 1;
  1792. texture.samplingMode = samplingMode;
  1793. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1794. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1795. for (var face = 0; face < 6; face++) {
  1796. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  1797. }
  1798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  1799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  1800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1802. // Create the depth buffer
  1803. var depthStencilBuffer;
  1804. // Create the depth/stencil buffer
  1805. if (generateStencilBuffer) {
  1806. depthStencilBuffer = gl.createRenderbuffer();
  1807. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1808. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  1809. }
  1810. else if (generateDepthBuffer) {
  1811. depthStencilBuffer = gl.createRenderbuffer();
  1812. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  1813. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  1814. }
  1815. // Create the framebuffer
  1816. var framebuffer = gl.createFramebuffer();
  1817. this.bindUnboundFramebuffer(framebuffer);
  1818. // Manage attachments
  1819. if (generateStencilBuffer) {
  1820. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1821. }
  1822. else if (generateDepthBuffer) {
  1823. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  1824. }
  1825. // Mipmaps
  1826. if (texture.generateMipMaps) {
  1827. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1828. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1829. }
  1830. // Unbind
  1831. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1832. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1833. this.bindUnboundFramebuffer(null);
  1834. texture._framebuffer = framebuffer;
  1835. if (generateDepthBuffer) {
  1836. texture._depthBuffer = depthStencilBuffer;
  1837. }
  1838. texture._width = size;
  1839. texture._height = size;
  1840. texture.isReady = true;
  1841. this.resetTextureCache();
  1842. this._loadedTexturesCache.push(texture);
  1843. return texture;
  1844. };
  1845. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  1846. var _this = this;
  1847. var gl = this._gl;
  1848. var texture = gl.createTexture();
  1849. texture.isCube = true;
  1850. texture.url = rootUrl;
  1851. texture.references = 1;
  1852. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1853. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1854. if (isDDS) {
  1855. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  1856. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1857. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1858. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1859. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1860. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  1861. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1862. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1863. }
  1864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1866. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1867. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1868. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1869. _this.resetTextureCache();
  1870. texture._width = info.width;
  1871. texture._height = info.height;
  1872. texture.isReady = true;
  1873. }, null, null, true);
  1874. }
  1875. else {
  1876. cascadeLoad(rootUrl, scene, function (imgs) {
  1877. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  1878. var height = width;
  1879. _this._prepareWorkingCanvas();
  1880. _this._workingCanvas.width = width;
  1881. _this._workingCanvas.height = height;
  1882. var faces = [
  1883. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1884. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1885. ];
  1886. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1887. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1888. for (var index = 0; index < faces.length; index++) {
  1889. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1890. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  1891. }
  1892. if (!noMipmap) {
  1893. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1894. }
  1895. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1896. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1899. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1900. _this.resetTextureCache();
  1901. texture._width = width;
  1902. texture._height = height;
  1903. texture.isReady = true;
  1904. }, files);
  1905. }
  1906. return texture;
  1907. };
  1908. Engine.prototype.updateTextureSize = function (texture, width, height) {
  1909. texture._width = width;
  1910. texture._height = height;
  1911. texture._size = width * height;
  1912. texture._baseWidth = width;
  1913. texture._baseHeight = height;
  1914. };
  1915. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  1916. var _this = this;
  1917. var gl = this._gl;
  1918. var texture = gl.createTexture();
  1919. scene._addPendingData(texture);
  1920. texture.isCube = true;
  1921. texture.references = 1;
  1922. texture.url = url;
  1923. var internalFormat = this._getInternalFormat(format);
  1924. var textureType = gl.UNSIGNED_BYTE;
  1925. if (type === Engine.TEXTURETYPE_FLOAT) {
  1926. textureType = gl.FLOAT;
  1927. }
  1928. var width = size;
  1929. var height = width;
  1930. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  1931. texture._width = width;
  1932. texture._height = height;
  1933. var onerror = function () {
  1934. scene._removePendingData(texture);
  1935. };
  1936. var internalCallback = function (data) {
  1937. var rgbeDataArrays = callback(data);
  1938. var facesIndex = [
  1939. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1940. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1941. ];
  1942. width = texture._width;
  1943. height = texture._height;
  1944. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  1945. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1946. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1947. if (!noMipmap && isPot) {
  1948. if (mipmmapGenerator) {
  1949. var arrayTemp = [];
  1950. // Data are known to be in +X +Y +Z -X -Y -Z
  1951. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  1952. arrayTemp.push(rgbeDataArrays[0]); // +X
  1953. arrayTemp.push(rgbeDataArrays[3]); // -X
  1954. arrayTemp.push(rgbeDataArrays[1]); // +Y
  1955. arrayTemp.push(rgbeDataArrays[4]); // -Y
  1956. arrayTemp.push(rgbeDataArrays[2]); // +Z
  1957. arrayTemp.push(rgbeDataArrays[5]); // -Z
  1958. var mipData = mipmmapGenerator(arrayTemp);
  1959. for (var level = 0; level < mipData.length; level++) {
  1960. var mipSize = width >> level;
  1961. // mipData is order in +X -X +Y -Y +Z -Z
  1962. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  1963. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  1964. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  1965. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  1966. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  1967. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  1968. }
  1969. }
  1970. else {
  1971. // Data are known to be in +X +Y +Z -X -Y -Z
  1972. for (var index = 0; index < facesIndex.length; index++) {
  1973. var faceData = rgbeDataArrays[index];
  1974. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  1975. }
  1976. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1977. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  1978. // By following the webgl standard changes from Revision 7, 2014/11/24
  1979. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  1980. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  1981. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  1982. // Data are known to be in +X +Y +Z -X -Y -Z
  1983. for (var index = 0; index < facesIndex.length; index++) {
  1984. var faceData = rgbeDataArrays[index];
  1985. // Create a new RGBA Face.
  1986. var newFaceData = new Float32Array(width * height * 4);
  1987. for (var x = 0; x < width; x++) {
  1988. for (var y = 0; y < height; y++) {
  1989. var index_1 = (y * width + x) * 3;
  1990. var newIndex = (y * width + x) * 4;
  1991. // Map Old Value to new value.
  1992. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  1993. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  1994. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  1995. // Add fully opaque alpha channel.
  1996. newFaceData[newIndex + 3] = 1;
  1997. }
  1998. }
  1999. // Reupload the face.
  2000. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  2001. }
  2002. // Try to generate mipmap again.
  2003. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2004. }
  2005. }
  2006. }
  2007. else {
  2008. noMipmap = true;
  2009. }
  2010. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  2011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2012. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2013. }
  2014. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  2015. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2017. }
  2018. else {
  2019. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2020. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2021. }
  2022. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2023. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2024. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2025. texture.isReady = true;
  2026. _this.resetTextureCache();
  2027. scene._removePendingData(texture);
  2028. };
  2029. BABYLON.Tools.LoadFile(url, function (data) {
  2030. internalCallback(data);
  2031. }, onerror, scene.database, true);
  2032. return texture;
  2033. };
  2034. ;
  2035. Engine.prototype._releaseTexture = function (texture) {
  2036. var gl = this._gl;
  2037. if (texture._framebuffer) {
  2038. gl.deleteFramebuffer(texture._framebuffer);
  2039. }
  2040. if (texture._depthBuffer) {
  2041. gl.deleteRenderbuffer(texture._depthBuffer);
  2042. }
  2043. gl.deleteTexture(texture);
  2044. // Unbind channels
  2045. this.unbindAllTextures();
  2046. var index = this._loadedTexturesCache.indexOf(texture);
  2047. if (index !== -1) {
  2048. this._loadedTexturesCache.splice(index, 1);
  2049. }
  2050. };
  2051. Engine.prototype.setProgram = function (program) {
  2052. if (this._currentProgram !== program) {
  2053. this._gl.useProgram(program);
  2054. this._currentProgram = program;
  2055. }
  2056. };
  2057. Engine.prototype.bindSamplers = function (effect) {
  2058. this.setProgram(effect.getProgram());
  2059. var samplers = effect.getSamplers();
  2060. for (var index = 0; index < samplers.length; index++) {
  2061. var uniform = effect.getUniform(samplers[index]);
  2062. this._gl.uniform1i(uniform, index);
  2063. }
  2064. this._currentEffect = null;
  2065. };
  2066. Engine.prototype.activateTexture = function (texture) {
  2067. if (this._activeTexture !== texture) {
  2068. this._gl.activeTexture(texture);
  2069. this._activeTexture = texture;
  2070. }
  2071. };
  2072. Engine.prototype._bindTextureDirectly = function (target, texture) {
  2073. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  2074. this._gl.bindTexture(target, texture);
  2075. this._activeTexturesCache[this._activeTexture] = texture;
  2076. }
  2077. };
  2078. Engine.prototype._bindTexture = function (channel, texture) {
  2079. if (channel < 0) {
  2080. return;
  2081. }
  2082. this.activateTexture(this._gl["TEXTURE" + channel]);
  2083. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2084. };
  2085. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  2086. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  2087. };
  2088. Engine.prototype.unbindAllTextures = function () {
  2089. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  2090. this.activateTexture(this._gl["TEXTURE" + channel]);
  2091. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2092. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2093. }
  2094. };
  2095. Engine.prototype.setTexture = function (channel, uniform, texture) {
  2096. if (channel < 0) {
  2097. return;
  2098. }
  2099. this._gl.uniform1i(uniform, channel);
  2100. this._setTexture(channel, texture);
  2101. };
  2102. Engine.prototype._setTexture = function (channel, texture) {
  2103. // Not ready?
  2104. if (!texture || !texture.isReady()) {
  2105. if (this._activeTexturesCache[channel] != null) {
  2106. this.activateTexture(this._gl["TEXTURE" + channel]);
  2107. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2108. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2109. }
  2110. return;
  2111. }
  2112. // Video
  2113. var alreadyActivated = false;
  2114. if (texture instanceof BABYLON.VideoTexture) {
  2115. this.activateTexture(this._gl["TEXTURE" + channel]);
  2116. alreadyActivated = true;
  2117. texture.update();
  2118. }
  2119. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  2120. texture.delayLoad();
  2121. return;
  2122. }
  2123. var internalTexture = texture.getInternalTexture();
  2124. if (this._activeTexturesCache[channel] === internalTexture) {
  2125. return;
  2126. }
  2127. if (!alreadyActivated) {
  2128. this.activateTexture(this._gl["TEXTURE" + channel]);
  2129. }
  2130. if (internalTexture.isCube) {
  2131. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  2132. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  2133. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  2134. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  2135. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  2136. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  2137. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  2138. }
  2139. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  2140. }
  2141. else {
  2142. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  2143. if (internalTexture._cachedWrapU !== texture.wrapU) {
  2144. internalTexture._cachedWrapU = texture.wrapU;
  2145. switch (texture.wrapU) {
  2146. case BABYLON.Texture.WRAP_ADDRESSMODE:
  2147. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  2148. break;
  2149. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  2150. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  2151. break;
  2152. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  2153. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  2154. break;
  2155. }
  2156. }
  2157. if (internalTexture._cachedWrapV !== texture.wrapV) {
  2158. internalTexture._cachedWrapV = texture.wrapV;
  2159. switch (texture.wrapV) {
  2160. case BABYLON.Texture.WRAP_ADDRESSMODE:
  2161. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  2162. break;
  2163. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  2164. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  2165. break;
  2166. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  2167. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  2168. break;
  2169. }
  2170. }
  2171. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  2172. }
  2173. };
  2174. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  2175. if (channel < 0) {
  2176. return;
  2177. }
  2178. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  2179. this._textureUnits = new Int32Array(textures.length);
  2180. }
  2181. for (var i = 0; i < textures.length; i++) {
  2182. this._textureUnits[i] = channel + i;
  2183. }
  2184. this._gl.uniform1iv(uniform, this._textureUnits);
  2185. for (var index = 0; index < textures.length; index++) {
  2186. this._setTexture(channel + index, textures[index]);
  2187. }
  2188. };
  2189. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  2190. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  2191. var value = texture.anisotropicFilteringLevel;
  2192. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2193. value = 1;
  2194. }
  2195. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  2196. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  2197. texture._cachedAnisotropicFilteringLevel = value;
  2198. }
  2199. };
  2200. Engine.prototype.readPixels = function (x, y, width, height) {
  2201. var data = new Uint8Array(height * width * 4);
  2202. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  2203. return data;
  2204. };
  2205. /**
  2206. * Add an externaly attached data from its key.
  2207. * This method call will fail and return false, if such key already exists.
  2208. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  2209. * @param key the unique key that identifies the data
  2210. * @param data the data object to associate to the key for this Engine instance
  2211. * @return true if no such key were already present and the data was added successfully, false otherwise
  2212. */
  2213. Engine.prototype.addExternalData = function (key, data) {
  2214. return this._externalData.add(key, data);
  2215. };
  2216. /**
  2217. * Get an externaly attached data from its key
  2218. * @param key the unique key that identifies the data
  2219. * @return the associated data, if present (can be null), or undefined if not present
  2220. */
  2221. Engine.prototype.getExternalData = function (key) {
  2222. return this._externalData.get(key);
  2223. };
  2224. /**
  2225. * Get an externaly attached data from its key, create it using a factory if it's not already present
  2226. * @param key the unique key that identifies the data
  2227. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  2228. * @return the associated data, can be null if the factory returned null.
  2229. */
  2230. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  2231. return this._externalData.getOrAddWithFactory(key, factory);
  2232. };
  2233. /**
  2234. * Remove an externaly attached data from the Engine instance
  2235. * @param key the unique key that identifies the data
  2236. * @return true if the data was successfully removed, false if it doesn't exist
  2237. */
  2238. Engine.prototype.removeExternalData = function (key) {
  2239. return this._externalData.remove(key);
  2240. };
  2241. Engine.prototype.releaseInternalTexture = function (texture) {
  2242. if (!texture) {
  2243. return;
  2244. }
  2245. texture.references--;
  2246. // Final reference ?
  2247. if (texture.references === 0) {
  2248. var texturesCache = this.getLoadedTexturesCache();
  2249. var index = texturesCache.indexOf(texture);
  2250. if (index > -1) {
  2251. texturesCache.splice(index, 1);
  2252. }
  2253. this._releaseTexture(texture);
  2254. }
  2255. };
  2256. // Dispose
  2257. Engine.prototype.dispose = function () {
  2258. this.hideLoadingUI();
  2259. this.stopRenderLoop();
  2260. // Release scenes
  2261. while (this.scenes.length) {
  2262. this.scenes[0].dispose();
  2263. }
  2264. // Release audio engine
  2265. Engine.audioEngine.dispose();
  2266. // Release effects
  2267. for (var name in this._compiledEffects) {
  2268. this._gl.deleteProgram(this._compiledEffects[name]._program);
  2269. }
  2270. // Unbind
  2271. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  2272. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  2273. continue;
  2274. }
  2275. this._gl.disableVertexAttribArray(i);
  2276. }
  2277. this._gl = null;
  2278. // Events
  2279. window.removeEventListener("blur", this._onBlur);
  2280. window.removeEventListener("focus", this._onFocus);
  2281. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  2282. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  2283. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  2284. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  2285. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  2286. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  2287. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  2288. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  2289. };
  2290. // Loading screen
  2291. Engine.prototype.displayLoadingUI = function () {
  2292. this._loadingScreen.displayLoadingUI();
  2293. };
  2294. Engine.prototype.hideLoadingUI = function () {
  2295. this._loadingScreen.hideLoadingUI();
  2296. };
  2297. Object.defineProperty(Engine.prototype, "loadingScreen", {
  2298. get: function () {
  2299. return this._loadingScreen;
  2300. },
  2301. set: function (loadingScreen) {
  2302. this._loadingScreen = loadingScreen;
  2303. },
  2304. enumerable: true,
  2305. configurable: true
  2306. });
  2307. Object.defineProperty(Engine.prototype, "loadingUIText", {
  2308. set: function (text) {
  2309. this._loadingScreen.loadingUIText = text;
  2310. },
  2311. enumerable: true,
  2312. configurable: true
  2313. });
  2314. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  2315. set: function (color) {
  2316. this._loadingScreen.loadingUIBackgroundColor = color;
  2317. },
  2318. enumerable: true,
  2319. configurable: true
  2320. });
  2321. Engine.prototype.attachContextLostEvent = function (callback) {
  2322. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  2323. };
  2324. Engine.prototype.attachContextRestoredEvent = function (callback) {
  2325. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  2326. };
  2327. // FPS
  2328. Engine.prototype.getFps = function () {
  2329. return this.fps;
  2330. };
  2331. Engine.prototype.getDeltaTime = function () {
  2332. return this.deltaTime;
  2333. };
  2334. Engine.prototype._measureFps = function () {
  2335. this.previousFramesDuration.push(BABYLON.Tools.Now);
  2336. var length = this.previousFramesDuration.length;
  2337. if (length >= 2) {
  2338. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  2339. }
  2340. if (length >= this.fpsRange) {
  2341. if (length > this.fpsRange) {
  2342. this.previousFramesDuration.splice(0, 1);
  2343. length = this.previousFramesDuration.length;
  2344. }
  2345. var sum = 0;
  2346. for (var id = 0; id < length - 1; id++) {
  2347. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  2348. }
  2349. this.fps = 1000.0 / (sum / (length - 1));
  2350. }
  2351. };
  2352. Engine.prototype._canRenderToFloatTexture = function () {
  2353. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  2354. };
  2355. Engine.prototype._canRenderToHalfFloatTexture = function () {
  2356. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  2357. };
  2358. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  2359. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  2360. var tempcanvas = document.createElement("canvas");
  2361. tempcanvas.height = 16;
  2362. tempcanvas.width = 16;
  2363. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  2364. // extension.
  2365. var ext = gl.getExtension(extension);
  2366. if (!ext) {
  2367. return false;
  2368. }
  2369. // setup GLSL program
  2370. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  2371. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  2372. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  2373. gl.useProgram(program);
  2374. // look up where the vertex data needs to go.
  2375. var positionLocation = gl.getAttribLocation(program, "a_position");
  2376. var colorLoc = gl.getUniformLocation(program, "u_color");
  2377. // provide texture coordinates for the rectangle.
  2378. var positionBuffer = gl.createBuffer();
  2379. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  2380. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  2381. -1.0, -1.0,
  2382. 1.0, -1.0,
  2383. -1.0, 1.0,
  2384. -1.0, 1.0,
  2385. 1.0, -1.0,
  2386. 1.0, 1.0]), gl.STATIC_DRAW);
  2387. gl.enableVertexAttribArray(positionLocation);
  2388. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  2389. var whiteTex = gl.createTexture();
  2390. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  2391. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  2392. var tex = gl.createTexture();
  2393. gl.bindTexture(gl.TEXTURE_2D, tex);
  2394. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  2395. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2397. var fb = gl.createFramebuffer();
  2398. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  2399. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  2400. var cleanup = function () {
  2401. gl.deleteProgram(program);
  2402. gl.disableVertexAttribArray(positionLocation);
  2403. gl.deleteBuffer(positionBuffer);
  2404. gl.deleteFramebuffer(fb);
  2405. gl.deleteTexture(whiteTex);
  2406. gl.deleteTexture(tex);
  2407. };
  2408. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  2409. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  2410. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  2411. cleanup();
  2412. return false;
  2413. }
  2414. // Draw the rectangle.
  2415. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  2416. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  2417. gl.drawArrays(gl.TRIANGLES, 0, 6);
  2418. gl.bindTexture(gl.TEXTURE_2D, tex);
  2419. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  2420. gl.clearColor(1, 0, 0, 1);
  2421. gl.clear(gl.COLOR_BUFFER_BIT);
  2422. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  2423. gl.drawArrays(gl.TRIANGLES, 0, 6);
  2424. var pixel = new Uint8Array(4);
  2425. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  2426. if (pixel[0] !== 0 ||
  2427. pixel[1] < 248 ||
  2428. pixel[2] < 248 ||
  2429. pixel[3] < 254) {
  2430. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  2431. cleanup();
  2432. return false;
  2433. }
  2434. // Succesfully rendered to "format" texture.
  2435. cleanup();
  2436. return true;
  2437. };
  2438. // Statics
  2439. Engine.isSupported = function () {
  2440. try {
  2441. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  2442. if (navigator.isCocoonJS) {
  2443. return true;
  2444. }
  2445. var tempcanvas = document.createElement("canvas");
  2446. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  2447. return gl != null && !!window.WebGLRenderingContext;
  2448. }
  2449. catch (e) {
  2450. return false;
  2451. }
  2452. };
  2453. // Const statics
  2454. Engine._ALPHA_DISABLE = 0;
  2455. Engine._ALPHA_ADD = 1;
  2456. Engine._ALPHA_COMBINE = 2;
  2457. Engine._ALPHA_SUBTRACT = 3;
  2458. Engine._ALPHA_MULTIPLY = 4;
  2459. Engine._ALPHA_MAXIMIZED = 5;
  2460. Engine._ALPHA_ONEONE = 6;
  2461. Engine._DELAYLOADSTATE_NONE = 0;
  2462. Engine._DELAYLOADSTATE_LOADED = 1;
  2463. Engine._DELAYLOADSTATE_LOADING = 2;
  2464. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  2465. Engine._TEXTUREFORMAT_ALPHA = 0;
  2466. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  2467. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  2468. Engine._TEXTUREFORMAT_RGB = 4;
  2469. Engine._TEXTUREFORMAT_RGBA = 5;
  2470. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  2471. Engine._TEXTURETYPE_FLOAT = 1;
  2472. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  2473. // Updatable statics so stick with vars here
  2474. Engine.CollisionsEpsilon = 0.001;
  2475. Engine.CodeRepository = "src/";
  2476. Engine.ShadersRepository = "src/Shaders/";
  2477. return Engine;
  2478. })();
  2479. BABYLON.Engine = Engine;
  2480. })(BABYLON || (BABYLON = {}));