babylon.engine.js 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952
  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 getWebGLTextureType = function (gl, type) {
  13. var textureType = gl.UNSIGNED_BYTE;
  14. if (type === Engine.TEXTURETYPE_FLOAT)
  15. textureType = gl.FLOAT;
  16. return textureType;
  17. };
  18. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  19. var magFilter = gl.NEAREST;
  20. var minFilter = gl.NEAREST;
  21. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  22. magFilter = gl.LINEAR;
  23. if (generateMipMaps) {
  24. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  25. }
  26. else {
  27. minFilter = gl.LINEAR;
  28. }
  29. }
  30. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  31. magFilter = gl.LINEAR;
  32. if (generateMipMaps) {
  33. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  34. }
  35. else {
  36. minFilter = gl.LINEAR;
  37. }
  38. }
  39. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  40. magFilter = gl.NEAREST;
  41. if (generateMipMaps) {
  42. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  43. }
  44. else {
  45. minFilter = gl.NEAREST;
  46. }
  47. }
  48. return {
  49. min: minFilter,
  50. mag: magFilter
  51. };
  52. };
  53. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  54. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55. var engine = scene.getEngine();
  56. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  57. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  58. gl.bindTexture(gl.TEXTURE_2D, texture);
  59. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  60. texture._baseWidth = width;
  61. texture._baseHeight = height;
  62. texture._width = potWidth;
  63. texture._height = potHeight;
  64. texture.isReady = true;
  65. processFunction(potWidth, potHeight);
  66. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  67. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  68. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  69. if (!noMipmap && !isCompressed) {
  70. gl.generateMipmap(gl.TEXTURE_2D);
  71. }
  72. gl.bindTexture(gl.TEXTURE_2D, null);
  73. engine.resetTextureCache();
  74. scene._removePendingData(texture);
  75. if (onLoad) {
  76. onLoad();
  77. }
  78. };
  79. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  80. var img;
  81. var onload = function () {
  82. loadedImages[index] = img;
  83. loadedImages._internalCount++;
  84. scene._removePendingData(img);
  85. if (loadedImages._internalCount === 6) {
  86. onfinish(loadedImages);
  87. }
  88. };
  89. var onerror = function () {
  90. scene._removePendingData(img);
  91. };
  92. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  93. scene._addPendingData(img);
  94. };
  95. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  96. var loadedImages = [];
  97. loadedImages._internalCount = 0;
  98. for (var index = 0; index < 6; index++) {
  99. partialLoad(files[index], index, loadedImages, scene, onfinish);
  100. }
  101. };
  102. var EngineCapabilities = (function () {
  103. function EngineCapabilities() {
  104. }
  105. return EngineCapabilities;
  106. })();
  107. BABYLON.EngineCapabilities = EngineCapabilities;
  108. /**
  109. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  110. */
  111. var Engine = (function () {
  112. /**
  113. * @constructor
  114. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  115. * @param {boolean} [antialias] - enable antialias
  116. * @param options - further options to be sent to the getContext function
  117. */
  118. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  119. var _this = this;
  120. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  121. // Public members
  122. this.isFullscreen = false;
  123. this.isPointerLock = false;
  124. this.cullBackFaces = true;
  125. this.renderEvenInBackground = true;
  126. // To enable/disable IDB support and avoid XHR on .manifest
  127. this.enableOfflineSupport = true;
  128. this.scenes = new Array();
  129. this._windowIsBackground = false;
  130. this._webGLVersion = "1.0";
  131. this._drawCalls = 0;
  132. this._renderingQueueLaunched = false;
  133. this._activeRenderLoops = [];
  134. // FPS
  135. this.fpsRange = 60;
  136. this.previousFramesDuration = [];
  137. this.fps = 60;
  138. this.deltaTime = 0;
  139. // States
  140. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  141. this._alphaState = new BABYLON.Internals._AlphaState();
  142. this._alphaMode = Engine.ALPHA_DISABLE;
  143. // Cache
  144. this._loadedTexturesCache = new Array();
  145. this._maxTextureChannels = 16;
  146. this._activeTexturesCache = new Array(this._maxTextureChannels);
  147. this._compiledEffects = {};
  148. this._uintIndicesCurrentlySet = false;
  149. this._renderingCanvas = canvas;
  150. options = options || {};
  151. options.antialias = antialias;
  152. if (options.preserveDrawingBuffer === undefined) {
  153. options.preserveDrawingBuffer = false;
  154. }
  155. // GL
  156. //try {
  157. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  158. // if (this._gl) {
  159. // this._webGLVersion = "2.0";
  160. // }
  161. //} catch (e) {
  162. // // Do nothing
  163. //}
  164. if (!this._gl) {
  165. try {
  166. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  167. }
  168. catch (e) {
  169. throw new Error("WebGL not supported");
  170. }
  171. }
  172. if (!this._gl) {
  173. throw new Error("WebGL not supported");
  174. }
  175. this._onBlur = function () {
  176. _this._windowIsBackground = true;
  177. };
  178. this._onFocus = function () {
  179. _this._windowIsBackground = false;
  180. };
  181. window.addEventListener("blur", this._onBlur);
  182. window.addEventListener("focus", this._onFocus);
  183. // Viewport
  184. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  185. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  186. this.resize();
  187. // Caps
  188. this._caps = new EngineCapabilities();
  189. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  190. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  191. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  192. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  193. // Infos
  194. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  195. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  196. if (rendererInfo != null) {
  197. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  198. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  199. }
  200. if (!this._glVendor) {
  201. this._glVendor = "Unknown vendor";
  202. }
  203. if (!this._glRenderer) {
  204. this._glRenderer = "Unknown renderer";
  205. }
  206. // Extensions
  207. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  208. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  209. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  210. 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');
  211. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  212. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  213. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  214. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  215. this._caps.highPrecisionShaderSupported = true;
  216. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  217. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  218. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  219. if (this._gl.getShaderPrecisionFormat) {
  220. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  221. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  222. }
  223. // Depth buffer
  224. this.setDepthBuffer(true);
  225. this.setDepthFunctionToLessOrEqual();
  226. this.setDepthWrite(true);
  227. // Fullscreen
  228. this._onFullscreenChange = function () {
  229. if (document.fullscreen !== undefined) {
  230. _this.isFullscreen = document.fullscreen;
  231. }
  232. else if (document.mozFullScreen !== undefined) {
  233. _this.isFullscreen = document.mozFullScreen;
  234. }
  235. else if (document.webkitIsFullScreen !== undefined) {
  236. _this.isFullscreen = document.webkitIsFullScreen;
  237. }
  238. else if (document.msIsFullScreen !== undefined) {
  239. _this.isFullscreen = document.msIsFullScreen;
  240. }
  241. // Pointer lock
  242. if (_this.isFullscreen && _this._pointerLockRequested) {
  243. canvas.requestPointerLock = canvas.requestPointerLock ||
  244. canvas.msRequestPointerLock ||
  245. canvas.mozRequestPointerLock ||
  246. canvas.webkitRequestPointerLock;
  247. if (canvas.requestPointerLock) {
  248. canvas.requestPointerLock();
  249. }
  250. }
  251. };
  252. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  253. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  254. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  255. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  256. // Pointer lock
  257. this._onPointerLockChange = function () {
  258. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  259. document.webkitPointerLockElement === canvas ||
  260. document.msPointerLockElement === canvas ||
  261. document.pointerLockElement === canvas);
  262. };
  263. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  264. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  265. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  266. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  267. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  268. Engine.audioEngine = new BABYLON.AudioEngine();
  269. }
  270. //default loading screen
  271. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  272. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  273. }
  274. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  275. get: function () {
  276. return Engine._ALPHA_DISABLE;
  277. },
  278. enumerable: true,
  279. configurable: true
  280. });
  281. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  282. get: function () {
  283. return Engine._ALPHA_ONEONE;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. Object.defineProperty(Engine, "ALPHA_ADD", {
  289. get: function () {
  290. return Engine._ALPHA_ADD;
  291. },
  292. enumerable: true,
  293. configurable: true
  294. });
  295. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  296. get: function () {
  297. return Engine._ALPHA_COMBINE;
  298. },
  299. enumerable: true,
  300. configurable: true
  301. });
  302. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  303. get: function () {
  304. return Engine._ALPHA_SUBTRACT;
  305. },
  306. enumerable: true,
  307. configurable: true
  308. });
  309. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  310. get: function () {
  311. return Engine._ALPHA_MULTIPLY;
  312. },
  313. enumerable: true,
  314. configurable: true
  315. });
  316. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  317. get: function () {
  318. return Engine._ALPHA_MAXIMIZED;
  319. },
  320. enumerable: true,
  321. configurable: true
  322. });
  323. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  324. get: function () {
  325. return Engine._DELAYLOADSTATE_NONE;
  326. },
  327. enumerable: true,
  328. configurable: true
  329. });
  330. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  331. get: function () {
  332. return Engine._DELAYLOADSTATE_LOADED;
  333. },
  334. enumerable: true,
  335. configurable: true
  336. });
  337. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  338. get: function () {
  339. return Engine._DELAYLOADSTATE_LOADING;
  340. },
  341. enumerable: true,
  342. configurable: true
  343. });
  344. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  345. get: function () {
  346. return Engine._DELAYLOADSTATE_NOTLOADED;
  347. },
  348. enumerable: true,
  349. configurable: true
  350. });
  351. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  352. get: function () {
  353. return Engine._TEXTUREFORMAT_ALPHA;
  354. },
  355. enumerable: true,
  356. configurable: true
  357. });
  358. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  359. get: function () {
  360. return Engine._TEXTUREFORMAT_LUMINANCE;
  361. },
  362. enumerable: true,
  363. configurable: true
  364. });
  365. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  366. get: function () {
  367. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  368. },
  369. enumerable: true,
  370. configurable: true
  371. });
  372. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  373. get: function () {
  374. return Engine._TEXTUREFORMAT_RGB;
  375. },
  376. enumerable: true,
  377. configurable: true
  378. });
  379. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  380. get: function () {
  381. return Engine._TEXTUREFORMAT_RGBA;
  382. },
  383. enumerable: true,
  384. configurable: true
  385. });
  386. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  387. get: function () {
  388. return Engine._TEXTURETYPE_UNSIGNED_INT;
  389. },
  390. enumerable: true,
  391. configurable: true
  392. });
  393. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  394. get: function () {
  395. return Engine._TEXTURETYPE_FLOAT;
  396. },
  397. enumerable: true,
  398. configurable: true
  399. });
  400. Object.defineProperty(Engine, "Version", {
  401. get: function () {
  402. return "2.4.0-alpha";
  403. },
  404. enumerable: true,
  405. configurable: true
  406. });
  407. Object.defineProperty(Engine.prototype, "webGLVersion", {
  408. get: function () {
  409. return this._webGLVersion;
  410. },
  411. enumerable: true,
  412. configurable: true
  413. });
  414. Engine.prototype._prepareWorkingCanvas = function () {
  415. if (this._workingCanvas) {
  416. return;
  417. }
  418. this._workingCanvas = document.createElement("canvas");
  419. this._workingContext = this._workingCanvas.getContext("2d");
  420. };
  421. Engine.prototype.resetTextureCache = function () {
  422. for (var index = 0; index < this._maxTextureChannels; index++) {
  423. this._activeTexturesCache[index] = null;
  424. }
  425. };
  426. Engine.prototype.getGlInfo = function () {
  427. return {
  428. vendor: this._glVendor,
  429. renderer: this._glRenderer,
  430. version: this._glVersion
  431. };
  432. };
  433. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  434. if (useScreen === void 0) { useScreen = false; }
  435. var viewport = camera.viewport;
  436. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  437. };
  438. Engine.prototype.getRenderWidth = function (useScreen) {
  439. if (useScreen === void 0) { useScreen = false; }
  440. if (!useScreen && this._currentRenderTarget) {
  441. return this._currentRenderTarget._width;
  442. }
  443. return this._renderingCanvas.width;
  444. };
  445. Engine.prototype.getRenderHeight = function (useScreen) {
  446. if (useScreen === void 0) { useScreen = false; }
  447. if (!useScreen && this._currentRenderTarget) {
  448. return this._currentRenderTarget._height;
  449. }
  450. return this._renderingCanvas.height;
  451. };
  452. Engine.prototype.getRenderingCanvas = function () {
  453. return this._renderingCanvas;
  454. };
  455. Engine.prototype.getRenderingCanvasClientRect = function () {
  456. return this._renderingCanvas.getBoundingClientRect();
  457. };
  458. Engine.prototype.setHardwareScalingLevel = function (level) {
  459. this._hardwareScalingLevel = level;
  460. this.resize();
  461. };
  462. Engine.prototype.getHardwareScalingLevel = function () {
  463. return this._hardwareScalingLevel;
  464. };
  465. Engine.prototype.getLoadedTexturesCache = function () {
  466. return this._loadedTexturesCache;
  467. };
  468. Engine.prototype.getCaps = function () {
  469. return this._caps;
  470. };
  471. Object.defineProperty(Engine.prototype, "drawCalls", {
  472. get: function () {
  473. return this._drawCalls;
  474. },
  475. enumerable: true,
  476. configurable: true
  477. });
  478. // Methods
  479. Engine.prototype.resetDrawCalls = function () {
  480. this._drawCalls = 0;
  481. };
  482. Engine.prototype.setDepthFunctionToGreater = function () {
  483. this._depthCullingState.depthFunc = this._gl.GREATER;
  484. };
  485. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  486. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  487. };
  488. Engine.prototype.setDepthFunctionToLess = function () {
  489. this._depthCullingState.depthFunc = this._gl.LESS;
  490. };
  491. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  492. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  493. };
  494. /**
  495. * stop executing a render loop function and remove it from the execution array
  496. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  497. */
  498. Engine.prototype.stopRenderLoop = function (renderFunction) {
  499. if (!renderFunction) {
  500. this._activeRenderLoops = [];
  501. return;
  502. }
  503. var index = this._activeRenderLoops.indexOf(renderFunction);
  504. if (index >= 0) {
  505. this._activeRenderLoops.splice(index, 1);
  506. }
  507. };
  508. Engine.prototype._renderLoop = function () {
  509. var shouldRender = true;
  510. if (!this.renderEvenInBackground && this._windowIsBackground) {
  511. shouldRender = false;
  512. }
  513. if (shouldRender) {
  514. // Start new frame
  515. this.beginFrame();
  516. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  517. var renderFunction = this._activeRenderLoops[index];
  518. renderFunction();
  519. }
  520. // Present
  521. this.endFrame();
  522. }
  523. if (this._activeRenderLoops.length > 0) {
  524. // Register new frame
  525. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  526. }
  527. else {
  528. this._renderingQueueLaunched = false;
  529. }
  530. };
  531. /**
  532. * Register and execute a render loop. The engine can have more than one render function.
  533. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  534. * @example
  535. * engine.runRenderLoop(function () {
  536. * scene.render()
  537. * })
  538. */
  539. Engine.prototype.runRenderLoop = function (renderFunction) {
  540. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  541. return;
  542. }
  543. this._activeRenderLoops.push(renderFunction);
  544. if (!this._renderingQueueLaunched) {
  545. this._renderingQueueLaunched = true;
  546. this._bindedRenderFunction = this._renderLoop.bind(this);
  547. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  548. }
  549. };
  550. /**
  551. * Toggle full screen mode.
  552. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  553. */
  554. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  555. if (this.isFullscreen) {
  556. BABYLON.Tools.ExitFullscreen();
  557. }
  558. else {
  559. this._pointerLockRequested = requestPointerLock;
  560. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  561. }
  562. };
  563. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  564. this.applyStates();
  565. if (backBuffer) {
  566. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  567. }
  568. if (depthStencil && this._depthCullingState.depthMask) {
  569. this._gl.clearDepth(1.0);
  570. }
  571. var mode = 0;
  572. if (backBuffer) {
  573. mode |= this._gl.COLOR_BUFFER_BIT;
  574. }
  575. if (depthStencil && this._depthCullingState.depthMask) {
  576. mode |= this._gl.DEPTH_BUFFER_BIT;
  577. }
  578. this._gl.clear(mode);
  579. };
  580. /**
  581. * Set the WebGL's viewport
  582. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  583. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  584. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  585. */
  586. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  587. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  588. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  589. var x = viewport.x || 0;
  590. var y = viewport.y || 0;
  591. this._cachedViewport = viewport;
  592. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  593. };
  594. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  595. this._cachedViewport = null;
  596. this._gl.viewport(x, y, width, height);
  597. };
  598. Engine.prototype.beginFrame = function () {
  599. this._measureFps();
  600. };
  601. Engine.prototype.endFrame = function () {
  602. //this.flushFramebuffer();
  603. };
  604. /**
  605. * resize the view according to the canvas' size.
  606. * @example
  607. * window.addEventListener("resize", function () {
  608. * engine.resize();
  609. * });
  610. */
  611. Engine.prototype.resize = function () {
  612. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  613. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  614. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  615. for (var index = 0; index < this.scenes.length; index++) {
  616. var scene = this.scenes[index];
  617. if (scene.debugLayer.isVisible()) {
  618. scene.debugLayer._syncPositions();
  619. }
  620. }
  621. };
  622. /**
  623. * force a specific size of the canvas
  624. * @param {number} width - the new canvas' width
  625. * @param {number} height - the new canvas' height
  626. */
  627. Engine.prototype.setSize = function (width, height) {
  628. this._renderingCanvas.width = width;
  629. this._renderingCanvas.height = height;
  630. for (var index = 0; index < this.scenes.length; index++) {
  631. var scene = this.scenes[index];
  632. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  633. var cam = scene.cameras[camIndex];
  634. cam._currentRenderId = 0;
  635. }
  636. }
  637. };
  638. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  639. this._currentRenderTarget = texture;
  640. var gl = this._gl;
  641. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  642. if (texture.isCube) {
  643. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  644. }
  645. else {
  646. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  647. }
  648. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  649. this.wipeCaches();
  650. };
  651. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  652. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  653. this._currentRenderTarget = null;
  654. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  655. var gl = this._gl;
  656. gl.bindTexture(gl.TEXTURE_2D, texture);
  657. gl.generateMipmap(gl.TEXTURE_2D);
  658. gl.bindTexture(gl.TEXTURE_2D, null);
  659. }
  660. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  661. };
  662. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  663. if (texture.generateMipMaps) {
  664. var gl = this._gl;
  665. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  666. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  667. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  668. }
  669. };
  670. Engine.prototype.flushFramebuffer = function () {
  671. this._gl.flush();
  672. };
  673. Engine.prototype.restoreDefaultFramebuffer = function () {
  674. this._currentRenderTarget = null;
  675. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  676. this.setViewport(this._cachedViewport);
  677. this.wipeCaches();
  678. };
  679. // VBOs
  680. Engine.prototype._resetVertexBufferBinding = function () {
  681. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  682. this._cachedVertexBuffers = null;
  683. };
  684. Engine.prototype.createVertexBuffer = function (vertices) {
  685. var vbo = this._gl.createBuffer();
  686. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  687. if (vertices instanceof Float32Array) {
  688. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  689. }
  690. else {
  691. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  692. }
  693. this._resetVertexBufferBinding();
  694. vbo.references = 1;
  695. return vbo;
  696. };
  697. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  698. var vbo = this._gl.createBuffer();
  699. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  700. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  701. this._resetVertexBufferBinding();
  702. vbo.references = 1;
  703. return vbo;
  704. };
  705. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  706. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  707. if (offset === undefined) {
  708. offset = 0;
  709. }
  710. if (vertices instanceof Float32Array) {
  711. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  712. }
  713. else {
  714. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  715. }
  716. this._resetVertexBufferBinding();
  717. };
  718. Engine.prototype._resetIndexBufferBinding = function () {
  719. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  720. this._cachedIndexBuffer = null;
  721. };
  722. Engine.prototype.createIndexBuffer = function (indices) {
  723. var vbo = this._gl.createBuffer();
  724. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  725. // Check for 32 bits indices
  726. var arrayBuffer;
  727. var need32Bits = false;
  728. if (this._caps.uintIndices) {
  729. for (var index = 0; index < indices.length; index++) {
  730. if (indices[index] > 65535) {
  731. need32Bits = true;
  732. break;
  733. }
  734. }
  735. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  736. }
  737. else {
  738. arrayBuffer = new Uint16Array(indices);
  739. }
  740. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  741. this._resetIndexBufferBinding();
  742. vbo.references = 1;
  743. vbo.is32Bits = need32Bits;
  744. return vbo;
  745. };
  746. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  747. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  748. this._cachedVertexBuffers = vertexBuffer;
  749. this._cachedEffectForVertexBuffers = effect;
  750. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  751. var offset = 0;
  752. for (var index = 0; index < vertexDeclaration.length; index++) {
  753. var order = effect.getAttributeLocation(index);
  754. if (order >= 0) {
  755. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  756. }
  757. offset += vertexDeclaration[index] * 4;
  758. }
  759. }
  760. if (this._cachedIndexBuffer !== indexBuffer) {
  761. this._cachedIndexBuffer = indexBuffer;
  762. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  763. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  764. }
  765. };
  766. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  767. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  768. this._cachedVertexBuffers = vertexBuffers;
  769. this._cachedEffectForVertexBuffers = effect;
  770. var attributes = effect.getAttributesNames();
  771. for (var index = 0; index < attributes.length; index++) {
  772. var order = effect.getAttributeLocation(index);
  773. if (order >= 0) {
  774. var vertexBuffer = vertexBuffers[attributes[index]];
  775. if (!vertexBuffer) {
  776. continue;
  777. }
  778. var stride = vertexBuffer.getStrideSize();
  779. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  780. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  781. }
  782. }
  783. }
  784. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  785. this._cachedIndexBuffer = indexBuffer;
  786. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  787. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  788. }
  789. };
  790. Engine.prototype._releaseBuffer = function (buffer) {
  791. buffer.references--;
  792. if (buffer.references === 0) {
  793. this._gl.deleteBuffer(buffer);
  794. return true;
  795. }
  796. return false;
  797. };
  798. Engine.prototype.createInstancesBuffer = function (capacity) {
  799. var buffer = this._gl.createBuffer();
  800. buffer.capacity = capacity;
  801. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  802. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  803. return buffer;
  804. };
  805. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  806. this._gl.deleteBuffer(buffer);
  807. };
  808. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  809. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  810. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  811. for (var index = 0; index < 4; index++) {
  812. var offsetLocation = offsetLocations[index];
  813. this._gl.enableVertexAttribArray(offsetLocation);
  814. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  815. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  816. }
  817. };
  818. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  819. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  820. for (var index = 0; index < 4; index++) {
  821. var offsetLocation = offsetLocations[index];
  822. this._gl.disableVertexAttribArray(offsetLocation);
  823. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  824. }
  825. };
  826. Engine.prototype.applyStates = function () {
  827. this._depthCullingState.apply(this._gl);
  828. this._alphaState.apply(this._gl);
  829. };
  830. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  831. // Apply states
  832. this.applyStates();
  833. this._drawCalls++;
  834. // Render
  835. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  836. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  837. if (instancesCount) {
  838. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  839. return;
  840. }
  841. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  842. };
  843. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  844. // Apply states
  845. this.applyStates();
  846. this._drawCalls++;
  847. if (instancesCount) {
  848. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  849. return;
  850. }
  851. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  852. };
  853. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  854. // Apply states
  855. this.applyStates();
  856. this._drawCalls++;
  857. if (instancesCount) {
  858. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  859. return;
  860. }
  861. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  862. };
  863. // Shaders
  864. Engine.prototype._releaseEffect = function (effect) {
  865. if (this._compiledEffects[effect._key]) {
  866. delete this._compiledEffects[effect._key];
  867. if (effect.getProgram()) {
  868. this._gl.deleteProgram(effect.getProgram());
  869. }
  870. }
  871. };
  872. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  873. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  874. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  875. var name = vertex + "+" + fragment + "@" + defines;
  876. if (this._compiledEffects[name]) {
  877. return this._compiledEffects[name];
  878. }
  879. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  880. effect._key = name;
  881. this._compiledEffects[name] = effect;
  882. return effect;
  883. };
  884. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  885. if (uniformsNames === void 0) { uniformsNames = []; }
  886. if (samplers === void 0) { samplers = []; }
  887. if (defines === void 0) { defines = ""; }
  888. return this.createEffect({
  889. vertex: "particles",
  890. fragmentElement: fragmentName
  891. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  892. };
  893. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  894. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  895. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  896. var shaderProgram = this._gl.createProgram();
  897. this._gl.attachShader(shaderProgram, vertexShader);
  898. this._gl.attachShader(shaderProgram, fragmentShader);
  899. this._gl.linkProgram(shaderProgram);
  900. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  901. if (!linked) {
  902. var error = this._gl.getProgramInfoLog(shaderProgram);
  903. if (error) {
  904. throw new Error(error);
  905. }
  906. }
  907. this._gl.deleteShader(vertexShader);
  908. this._gl.deleteShader(fragmentShader);
  909. return shaderProgram;
  910. };
  911. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  912. var results = [];
  913. for (var index = 0; index < uniformsNames.length; index++) {
  914. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  915. }
  916. return results;
  917. };
  918. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  919. var results = [];
  920. for (var index = 0; index < attributesNames.length; index++) {
  921. try {
  922. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  923. }
  924. catch (e) {
  925. results.push(-1);
  926. }
  927. }
  928. return results;
  929. };
  930. Engine.prototype.enableEffect = function (effect) {
  931. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  932. if (effect && effect.onBind) {
  933. effect.onBind(effect);
  934. }
  935. return;
  936. }
  937. this._vertexAttribArrays = this._vertexAttribArrays || [];
  938. // Use program
  939. this._gl.useProgram(effect.getProgram());
  940. for (var i in this._vertexAttribArrays) {
  941. //make sure this is a number)
  942. var iAsNumber = +i;
  943. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  944. continue;
  945. }
  946. this._vertexAttribArrays[iAsNumber] = false;
  947. this._gl.disableVertexAttribArray(iAsNumber);
  948. }
  949. var attributesCount = effect.getAttributesCount();
  950. for (var index = 0; index < attributesCount; index++) {
  951. // Attributes
  952. var order = effect.getAttributeLocation(index);
  953. if (order >= 0) {
  954. this._vertexAttribArrays[order] = true;
  955. this._gl.enableVertexAttribArray(order);
  956. }
  957. }
  958. this._currentEffect = effect;
  959. if (effect.onBind) {
  960. effect.onBind(effect);
  961. }
  962. };
  963. Engine.prototype.setArray = function (uniform, array) {
  964. if (!uniform)
  965. return;
  966. this._gl.uniform1fv(uniform, array);
  967. };
  968. Engine.prototype.setArray2 = function (uniform, array) {
  969. if (!uniform || array.length % 2 !== 0)
  970. return;
  971. this._gl.uniform2fv(uniform, array);
  972. };
  973. Engine.prototype.setArray3 = function (uniform, array) {
  974. if (!uniform || array.length % 3 !== 0)
  975. return;
  976. this._gl.uniform3fv(uniform, array);
  977. };
  978. Engine.prototype.setArray4 = function (uniform, array) {
  979. if (!uniform || array.length % 4 !== 0)
  980. return;
  981. this._gl.uniform4fv(uniform, array);
  982. };
  983. Engine.prototype.setMatrices = function (uniform, matrices) {
  984. if (!uniform)
  985. return;
  986. this._gl.uniformMatrix4fv(uniform, false, matrices);
  987. };
  988. Engine.prototype.setMatrix = function (uniform, matrix) {
  989. if (!uniform)
  990. return;
  991. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  992. };
  993. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  994. if (!uniform)
  995. return;
  996. this._gl.uniformMatrix3fv(uniform, false, matrix);
  997. };
  998. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  999. if (!uniform)
  1000. return;
  1001. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1002. };
  1003. Engine.prototype.setFloat = function (uniform, value) {
  1004. if (!uniform)
  1005. return;
  1006. this._gl.uniform1f(uniform, value);
  1007. };
  1008. Engine.prototype.setFloat2 = function (uniform, x, y) {
  1009. if (!uniform)
  1010. return;
  1011. this._gl.uniform2f(uniform, x, y);
  1012. };
  1013. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  1014. if (!uniform)
  1015. return;
  1016. this._gl.uniform3f(uniform, x, y, z);
  1017. };
  1018. Engine.prototype.setBool = function (uniform, bool) {
  1019. if (!uniform)
  1020. return;
  1021. this._gl.uniform1i(uniform, bool);
  1022. };
  1023. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  1024. if (!uniform)
  1025. return;
  1026. this._gl.uniform4f(uniform, x, y, z, w);
  1027. };
  1028. Engine.prototype.setColor3 = function (uniform, color3) {
  1029. if (!uniform)
  1030. return;
  1031. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1032. };
  1033. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  1034. if (!uniform)
  1035. return;
  1036. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1037. };
  1038. // States
  1039. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  1040. if (zOffset === void 0) { zOffset = 0; }
  1041. if (reverseSide === void 0) { reverseSide = false; }
  1042. // Culling
  1043. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1044. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1045. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1046. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1047. if (culling) {
  1048. this._depthCullingState.cullFace = cullFace;
  1049. this._depthCullingState.cull = true;
  1050. }
  1051. else {
  1052. this._depthCullingState.cull = false;
  1053. }
  1054. }
  1055. // Z offset
  1056. this._depthCullingState.zOffset = zOffset;
  1057. };
  1058. Engine.prototype.setDepthBuffer = function (enable) {
  1059. this._depthCullingState.depthTest = enable;
  1060. };
  1061. Engine.prototype.getDepthWrite = function () {
  1062. return this._depthCullingState.depthMask;
  1063. };
  1064. Engine.prototype.setDepthWrite = function (enable) {
  1065. this._depthCullingState.depthMask = enable;
  1066. };
  1067. Engine.prototype.setColorWrite = function (enable) {
  1068. this._gl.colorMask(enable, enable, enable, enable);
  1069. };
  1070. Engine.prototype.setAlphaMode = function (mode) {
  1071. if (this._alphaMode === mode) {
  1072. return;
  1073. }
  1074. switch (mode) {
  1075. case Engine.ALPHA_DISABLE:
  1076. this.setDepthWrite(true);
  1077. this._alphaState.alphaBlend = false;
  1078. break;
  1079. case Engine.ALPHA_COMBINE:
  1080. this.setDepthWrite(false);
  1081. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1082. this._alphaState.alphaBlend = true;
  1083. break;
  1084. case Engine.ALPHA_ONEONE:
  1085. this.setDepthWrite(false);
  1086. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1087. this._alphaState.alphaBlend = true;
  1088. break;
  1089. case Engine.ALPHA_ADD:
  1090. this.setDepthWrite(false);
  1091. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1092. this._alphaState.alphaBlend = true;
  1093. break;
  1094. case Engine.ALPHA_SUBTRACT:
  1095. this.setDepthWrite(false);
  1096. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1097. this._alphaState.alphaBlend = true;
  1098. break;
  1099. case Engine.ALPHA_MULTIPLY:
  1100. this.setDepthWrite(false);
  1101. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1102. this._alphaState.alphaBlend = true;
  1103. break;
  1104. case Engine.ALPHA_MAXIMIZED:
  1105. this.setDepthWrite(false);
  1106. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1107. this._alphaState.alphaBlend = true;
  1108. break;
  1109. }
  1110. this._alphaMode = mode;
  1111. };
  1112. Engine.prototype.getAlphaMode = function () {
  1113. return this._alphaMode;
  1114. };
  1115. Engine.prototype.setAlphaTesting = function (enable) {
  1116. this._alphaTest = enable;
  1117. };
  1118. Engine.prototype.getAlphaTesting = function () {
  1119. return this._alphaTest;
  1120. };
  1121. // Textures
  1122. Engine.prototype.wipeCaches = function () {
  1123. this.resetTextureCache();
  1124. this._currentEffect = null;
  1125. this._depthCullingState.reset();
  1126. this._alphaState.reset();
  1127. this._cachedVertexBuffers = null;
  1128. this._cachedIndexBuffer = null;
  1129. this._cachedEffectForVertexBuffers = null;
  1130. };
  1131. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  1132. var gl = this._gl;
  1133. gl.bindTexture(gl.TEXTURE_2D, texture);
  1134. var magFilter = gl.NEAREST;
  1135. var minFilter = gl.NEAREST;
  1136. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  1137. magFilter = gl.LINEAR;
  1138. minFilter = gl.LINEAR;
  1139. }
  1140. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  1141. magFilter = gl.LINEAR;
  1142. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  1143. }
  1144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  1145. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  1146. gl.bindTexture(gl.TEXTURE_2D, null);
  1147. texture.samplingMode = samplingMode;
  1148. };
  1149. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  1150. var _this = this;
  1151. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1152. if (onLoad === void 0) { onLoad = null; }
  1153. if (onError === void 0) { onError = null; }
  1154. if (buffer === void 0) { buffer = null; }
  1155. var texture = this._gl.createTexture();
  1156. var extension;
  1157. var fromData = false;
  1158. if (url.substr(0, 5) === "data:") {
  1159. fromData = true;
  1160. }
  1161. if (!fromData)
  1162. extension = url.substr(url.length - 4, 4).toLowerCase();
  1163. else {
  1164. var oldUrl = url;
  1165. fromData = oldUrl.split(':');
  1166. url = oldUrl;
  1167. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  1168. }
  1169. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1170. var isTGA = (extension === ".tga");
  1171. scene._addPendingData(texture);
  1172. texture.url = url;
  1173. texture.noMipmap = noMipmap;
  1174. texture.references = 1;
  1175. texture.samplingMode = samplingMode;
  1176. this._loadedTexturesCache.push(texture);
  1177. var onerror = function () {
  1178. scene._removePendingData(texture);
  1179. if (onError) {
  1180. onError();
  1181. }
  1182. };
  1183. var callback;
  1184. if (isTGA) {
  1185. callback = function (arrayBuffer) {
  1186. var data = new Uint8Array(arrayBuffer);
  1187. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  1188. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  1189. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  1190. }, onLoad, samplingMode);
  1191. };
  1192. if (!(fromData instanceof Array))
  1193. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  1194. callback(arrayBuffer);
  1195. }, onerror, scene.database, true);
  1196. else
  1197. callback(buffer);
  1198. }
  1199. else if (isDDS) {
  1200. callback = function (data) {
  1201. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1202. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  1203. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  1204. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  1205. }, onLoad, samplingMode);
  1206. };
  1207. if (!(fromData instanceof Array))
  1208. BABYLON.Tools.LoadFile(url, function (data) {
  1209. callback(data);
  1210. }, onerror, scene.database, true);
  1211. else
  1212. callback(buffer);
  1213. }
  1214. else {
  1215. var onload = function (img) {
  1216. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  1217. var isPot = (img.width === potWidth && img.height === potHeight);
  1218. if (!isPot) {
  1219. _this._prepareWorkingCanvas();
  1220. _this._workingCanvas.width = potWidth;
  1221. _this._workingCanvas.height = potHeight;
  1222. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  1223. _this._workingContext.imageSmoothingEnabled = false;
  1224. _this._workingContext.mozImageSmoothingEnabled = false;
  1225. _this._workingContext.oImageSmoothingEnabled = false;
  1226. _this._workingContext.webkitImageSmoothingEnabled = false;
  1227. _this._workingContext.msImageSmoothingEnabled = false;
  1228. }
  1229. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  1230. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  1231. _this._workingContext.imageSmoothingEnabled = true;
  1232. _this._workingContext.mozImageSmoothingEnabled = true;
  1233. _this._workingContext.oImageSmoothingEnabled = true;
  1234. _this._workingContext.webkitImageSmoothingEnabled = true;
  1235. _this._workingContext.msImageSmoothingEnabled = true;
  1236. }
  1237. }
  1238. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  1239. }, onLoad, samplingMode);
  1240. };
  1241. if (!(fromData instanceof Array))
  1242. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  1243. else
  1244. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  1245. }
  1246. return texture;
  1247. };
  1248. Engine.prototype._getInternalFormat = function (format) {
  1249. var internalFormat = this._gl.RGBA;
  1250. switch (format) {
  1251. case Engine.TEXTUREFORMAT_ALPHA:
  1252. internalFormat = this._gl.ALPHA;
  1253. break;
  1254. case Engine.TEXTUREFORMAT_LUMINANCE:
  1255. internalFormat = this._gl.LUMINANCE;
  1256. break;
  1257. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1258. internalFormat = this._gl.LUMINANCE_ALPHA;
  1259. break;
  1260. case Engine.TEXTUREFORMAT_RGB:
  1261. internalFormat = this._gl.RGB;
  1262. break;
  1263. case Engine.TEXTUREFORMAT_RGBA:
  1264. internalFormat = this._gl.RGBA;
  1265. break;
  1266. }
  1267. return internalFormat;
  1268. };
  1269. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  1270. if (compression === void 0) { compression = null; }
  1271. var internalFormat = this._getInternalFormat(format);
  1272. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1273. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  1274. if (compression) {
  1275. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  1276. }
  1277. else {
  1278. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  1279. }
  1280. if (texture.generateMipMaps) {
  1281. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1282. }
  1283. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1284. this.resetTextureCache();
  1285. texture.isReady = true;
  1286. };
  1287. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  1288. if (compression === void 0) { compression = null; }
  1289. var texture = this._gl.createTexture();
  1290. texture._baseWidth = width;
  1291. texture._baseHeight = height;
  1292. texture._width = width;
  1293. texture._height = height;
  1294. texture.references = 1;
  1295. this.updateRawTexture(texture, data, format, invertY, compression);
  1296. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1297. // Filters
  1298. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  1299. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1300. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1301. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1302. texture.samplingMode = samplingMode;
  1303. this._loadedTexturesCache.push(texture);
  1304. return texture;
  1305. };
  1306. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  1307. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  1308. var texture = this._gl.createTexture();
  1309. texture._baseWidth = width;
  1310. texture._baseHeight = height;
  1311. if (forceExponantOfTwo) {
  1312. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  1313. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  1314. }
  1315. this.resetTextureCache();
  1316. texture._width = width;
  1317. texture._height = height;
  1318. texture.isReady = false;
  1319. texture.generateMipMaps = generateMipMaps;
  1320. texture.references = 1;
  1321. texture.samplingMode = samplingMode;
  1322. this.updateTextureSamplingMode(samplingMode, texture);
  1323. this._loadedTexturesCache.push(texture);
  1324. return texture;
  1325. };
  1326. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  1327. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  1328. if (texture.isCube) {
  1329. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  1330. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1331. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1332. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1333. }
  1334. else {
  1335. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1336. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  1337. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  1338. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1339. }
  1340. };
  1341. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  1342. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1343. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  1344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  1345. if (texture.generateMipMaps) {
  1346. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1347. }
  1348. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1349. this.resetTextureCache();
  1350. texture.isReady = true;
  1351. };
  1352. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  1353. if (texture._isDisabled) {
  1354. return;
  1355. }
  1356. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1357. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  1358. try {
  1359. // Testing video texture support
  1360. if (this._videoTextureSupported === undefined) {
  1361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1362. if (this._gl.getError() !== 0) {
  1363. this._videoTextureSupported = false;
  1364. }
  1365. else {
  1366. this._videoTextureSupported = true;
  1367. }
  1368. }
  1369. // Copy video through the current working canvas if video texture is not supported
  1370. if (!this._videoTextureSupported) {
  1371. if (!texture._workingCanvas) {
  1372. texture._workingCanvas = document.createElement("canvas");
  1373. texture._workingContext = texture._workingCanvas.getContext("2d");
  1374. texture._workingCanvas.width = texture._width;
  1375. texture._workingCanvas.height = texture._height;
  1376. }
  1377. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  1378. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  1379. }
  1380. else {
  1381. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  1382. }
  1383. if (texture.generateMipMaps) {
  1384. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1385. }
  1386. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1387. this.resetTextureCache();
  1388. texture.isReady = true;
  1389. }
  1390. catch (ex) {
  1391. // Something unexpected
  1392. // Let's disable the texture
  1393. texture._isDisabled = true;
  1394. }
  1395. };
  1396. Engine.prototype.createRenderTargetTexture = function (size, options) {
  1397. // old version had a "generateMipMaps" arg instead of options.
  1398. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  1399. // in the same way, generateDepthBuffer is defaulted to true
  1400. var generateMipMaps = false;
  1401. var generateDepthBuffer = true;
  1402. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1403. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1404. if (options !== undefined) {
  1405. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1406. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1407. type = options.type === undefined ? type : options.type;
  1408. if (options.samplingMode !== undefined) {
  1409. samplingMode = options.samplingMode;
  1410. }
  1411. if (type === Engine.TEXTURETYPE_FLOAT) {
  1412. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  1413. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1414. }
  1415. }
  1416. var gl = this._gl;
  1417. var texture = gl.createTexture();
  1418. gl.bindTexture(gl.TEXTURE_2D, texture);
  1419. var width = size.width || size;
  1420. var height = size.height || size;
  1421. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1422. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  1423. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  1424. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  1425. }
  1426. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  1427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  1428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1429. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1430. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  1431. var depthBuffer;
  1432. // Create the depth buffer
  1433. if (generateDepthBuffer) {
  1434. depthBuffer = gl.createRenderbuffer();
  1435. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1436. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  1437. }
  1438. // Create the framebuffer
  1439. var framebuffer = gl.createFramebuffer();
  1440. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1441. if (generateDepthBuffer) {
  1442. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1443. }
  1444. if (generateMipMaps) {
  1445. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  1446. }
  1447. // Unbind
  1448. gl.bindTexture(gl.TEXTURE_2D, null);
  1449. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1450. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1451. texture._framebuffer = framebuffer;
  1452. if (generateDepthBuffer) {
  1453. texture._depthBuffer = depthBuffer;
  1454. }
  1455. texture._width = width;
  1456. texture._height = height;
  1457. texture.isReady = true;
  1458. texture.generateMipMaps = generateMipMaps;
  1459. texture.references = 1;
  1460. texture.samplingMode = samplingMode;
  1461. this.resetTextureCache();
  1462. this._loadedTexturesCache.push(texture);
  1463. return texture;
  1464. };
  1465. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  1466. var gl = this._gl;
  1467. var texture = gl.createTexture();
  1468. var generateMipMaps = true;
  1469. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1470. if (options !== undefined) {
  1471. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  1472. if (options.samplingMode !== undefined) {
  1473. samplingMode = options.samplingMode;
  1474. }
  1475. }
  1476. texture.isCube = true;
  1477. texture.references = 1;
  1478. texture.generateMipMaps = generateMipMaps;
  1479. texture.references = 1;
  1480. texture.samplingMode = samplingMode;
  1481. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  1482. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1483. for (var face = 0; face < 6; face++) {
  1484. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  1485. }
  1486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  1487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  1488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1490. // Create the depth buffer
  1491. var depthBuffer = gl.createRenderbuffer();
  1492. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  1493. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  1494. // Create the framebuffer
  1495. var framebuffer = gl.createFramebuffer();
  1496. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1497. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  1498. // Mipmaps
  1499. if (texture.generateMipMaps) {
  1500. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1501. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1502. }
  1503. // Unbind
  1504. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1505. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  1506. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1507. texture._framebuffer = framebuffer;
  1508. texture._depthBuffer = depthBuffer;
  1509. this.resetTextureCache();
  1510. texture._width = size;
  1511. texture._height = size;
  1512. texture.isReady = true;
  1513. return texture;
  1514. };
  1515. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  1516. var _this = this;
  1517. var gl = this._gl;
  1518. var texture = gl.createTexture();
  1519. texture.isCube = true;
  1520. texture.url = rootUrl;
  1521. texture.references = 1;
  1522. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  1523. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  1524. if (isDDS) {
  1525. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  1526. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  1527. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  1528. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1529. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  1530. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  1531. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  1532. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1533. }
  1534. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1535. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  1536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1538. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1539. _this.resetTextureCache();
  1540. texture._width = info.width;
  1541. texture._height = info.height;
  1542. texture.isReady = true;
  1543. }, null, null, true);
  1544. }
  1545. else {
  1546. cascadeLoad(rootUrl, scene, function (imgs) {
  1547. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  1548. var height = width;
  1549. _this._prepareWorkingCanvas();
  1550. _this._workingCanvas.width = width;
  1551. _this._workingCanvas.height = height;
  1552. var faces = [
  1553. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1554. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1555. ];
  1556. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1557. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1558. for (var index = 0; index < faces.length; index++) {
  1559. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  1560. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  1561. }
  1562. if (!noMipmap) {
  1563. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1564. }
  1565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1569. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1570. _this.resetTextureCache();
  1571. texture._width = width;
  1572. texture._height = height;
  1573. texture.isReady = true;
  1574. }, files);
  1575. }
  1576. return texture;
  1577. };
  1578. Engine.prototype.updateTextureSize = function (texture, width, height) {
  1579. texture._width = width;
  1580. texture._height = height;
  1581. };
  1582. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  1583. var _this = this;
  1584. var gl = this._gl;
  1585. var texture = gl.createTexture();
  1586. scene._addPendingData(texture);
  1587. texture.isCube = true;
  1588. texture.references = 1;
  1589. texture.url = url;
  1590. var internalFormat = this._getInternalFormat(format);
  1591. var textureType = gl.UNSIGNED_BYTE;
  1592. if (type === Engine.TEXTURETYPE_FLOAT) {
  1593. textureType = gl.FLOAT;
  1594. }
  1595. var width = size;
  1596. var height = width;
  1597. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  1598. texture._width = width;
  1599. texture._height = height;
  1600. var onerror = function () {
  1601. scene._removePendingData(texture);
  1602. };
  1603. var internalCallback = function (data) {
  1604. var rgbeDataArrays = callback(data);
  1605. var facesIndex = [
  1606. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  1607. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  1608. ];
  1609. width = texture._width;
  1610. height = texture._height;
  1611. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  1612. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  1613. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  1614. if (!noMipmap && isPot) {
  1615. if (mipmmapGenerator) {
  1616. var arrayTemp = [];
  1617. // Data are known to be in +X +Y +Z -X -Y -Z
  1618. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  1619. arrayTemp.push(rgbeDataArrays[0]); // +X
  1620. arrayTemp.push(rgbeDataArrays[3]); // -X
  1621. arrayTemp.push(rgbeDataArrays[1]); // +Y
  1622. arrayTemp.push(rgbeDataArrays[4]); // -Y
  1623. arrayTemp.push(rgbeDataArrays[2]); // +Z
  1624. arrayTemp.push(rgbeDataArrays[5]); // -Z
  1625. var mipData = mipmmapGenerator(arrayTemp);
  1626. for (var level = 0; level < mipData.length; level++) {
  1627. var mipSize = width >> level;
  1628. // mipData is order in +X -X +Y -Y +Z -Z
  1629. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  1630. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  1631. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  1632. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  1633. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  1634. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  1635. }
  1636. }
  1637. else {
  1638. // Data are known to be in +X +Y +Z -X -Y -Z
  1639. for (var index = 0; index < facesIndex.length; index++) {
  1640. var faceData = rgbeDataArrays[index];
  1641. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  1642. }
  1643. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1644. }
  1645. }
  1646. else {
  1647. noMipmap = true;
  1648. }
  1649. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  1650. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  1651. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  1652. }
  1653. else {
  1654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  1655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  1656. }
  1657. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1658. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1659. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1660. texture.isReady = true;
  1661. _this.resetTextureCache();
  1662. scene._removePendingData(texture);
  1663. };
  1664. BABYLON.Tools.LoadFile(url, function (data) {
  1665. internalCallback(data);
  1666. }, onerror, scene.database, true);
  1667. return texture;
  1668. };
  1669. ;
  1670. Engine.prototype._releaseTexture = function (texture) {
  1671. var gl = this._gl;
  1672. if (texture._framebuffer) {
  1673. gl.deleteFramebuffer(texture._framebuffer);
  1674. }
  1675. if (texture._depthBuffer) {
  1676. gl.deleteRenderbuffer(texture._depthBuffer);
  1677. }
  1678. gl.deleteTexture(texture);
  1679. // Unbind channels
  1680. this.unbindAllTextures();
  1681. var index = this._loadedTexturesCache.indexOf(texture);
  1682. if (index !== -1) {
  1683. this._loadedTexturesCache.splice(index, 1);
  1684. }
  1685. };
  1686. Engine.prototype.bindSamplers = function (effect) {
  1687. this._gl.useProgram(effect.getProgram());
  1688. var samplers = effect.getSamplers();
  1689. for (var index = 0; index < samplers.length; index++) {
  1690. var uniform = effect.getUniform(samplers[index]);
  1691. this._gl.uniform1i(uniform, index);
  1692. }
  1693. this._currentEffect = null;
  1694. };
  1695. Engine.prototype._bindTexture = function (channel, texture) {
  1696. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1697. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1698. this._activeTexturesCache[channel] = null;
  1699. };
  1700. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  1701. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1702. };
  1703. Engine.prototype.unbindAllTextures = function () {
  1704. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  1705. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1706. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1707. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1708. this._activeTexturesCache[channel] = null;
  1709. }
  1710. };
  1711. Engine.prototype.setTexture = function (channel, texture) {
  1712. if (channel < 0) {
  1713. return;
  1714. }
  1715. // Not ready?
  1716. if (!texture || !texture.isReady()) {
  1717. if (this._activeTexturesCache[channel] != null) {
  1718. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1719. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1720. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1721. this._activeTexturesCache[channel] = null;
  1722. }
  1723. return;
  1724. }
  1725. // Video
  1726. var alreadyActivated = false;
  1727. if (texture instanceof BABYLON.VideoTexture) {
  1728. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1729. alreadyActivated = true;
  1730. texture.update();
  1731. }
  1732. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  1733. texture.delayLoad();
  1734. return;
  1735. }
  1736. if (this._activeTexturesCache[channel] === texture) {
  1737. return;
  1738. }
  1739. this._activeTexturesCache[channel] = texture;
  1740. var internalTexture = texture.getInternalTexture();
  1741. if (!alreadyActivated) {
  1742. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1743. }
  1744. if (internalTexture.isCube) {
  1745. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1746. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1747. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1748. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1749. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1750. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1751. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1752. }
  1753. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1754. }
  1755. else {
  1756. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1757. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1758. internalTexture._cachedWrapU = texture.wrapU;
  1759. switch (texture.wrapU) {
  1760. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1761. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1762. break;
  1763. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1764. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1765. break;
  1766. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1767. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1768. break;
  1769. }
  1770. }
  1771. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1772. internalTexture._cachedWrapV = texture.wrapV;
  1773. switch (texture.wrapV) {
  1774. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1775. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1776. break;
  1777. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1778. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1779. break;
  1780. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1781. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1782. break;
  1783. }
  1784. }
  1785. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1786. }
  1787. };
  1788. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  1789. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1790. var value = texture.anisotropicFilteringLevel;
  1791. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  1792. value = 1;
  1793. }
  1794. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  1795. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  1796. texture._cachedAnisotropicFilteringLevel = value;
  1797. }
  1798. };
  1799. Engine.prototype.readPixels = function (x, y, width, height) {
  1800. var data = new Uint8Array(height * width * 4);
  1801. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1802. return data;
  1803. };
  1804. Engine.prototype.releaseInternalTexture = function (texture) {
  1805. if (!texture) {
  1806. return;
  1807. }
  1808. texture.references--;
  1809. // Final reference ?
  1810. if (texture.references === 0) {
  1811. var texturesCache = this.getLoadedTexturesCache();
  1812. var index = texturesCache.indexOf(texture);
  1813. if (index > -1) {
  1814. texturesCache.splice(index, 1);
  1815. }
  1816. this._releaseTexture(texture);
  1817. }
  1818. };
  1819. // Dispose
  1820. Engine.prototype.dispose = function () {
  1821. this.hideLoadingUI();
  1822. this.stopRenderLoop();
  1823. // Release scenes
  1824. while (this.scenes.length) {
  1825. this.scenes[0].dispose();
  1826. }
  1827. // Release audio engine
  1828. Engine.audioEngine.dispose();
  1829. // Release effects
  1830. for (var name in this._compiledEffects) {
  1831. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1832. }
  1833. // Unbind
  1834. for (var i in this._vertexAttribArrays) {
  1835. //making sure this is a string
  1836. var iAsNumber = +i;
  1837. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  1838. continue;
  1839. }
  1840. this._gl.disableVertexAttribArray(iAsNumber);
  1841. }
  1842. this._gl = null;
  1843. // Events
  1844. window.removeEventListener("blur", this._onBlur);
  1845. window.removeEventListener("focus", this._onFocus);
  1846. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1847. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1848. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1849. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1850. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1851. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1852. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1853. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1854. };
  1855. // Loading screen
  1856. Engine.prototype.displayLoadingUI = function () {
  1857. this._loadingScreen.displayLoadingUI();
  1858. };
  1859. Engine.prototype.hideLoadingUI = function () {
  1860. this._loadingScreen.hideLoadingUI();
  1861. };
  1862. Object.defineProperty(Engine.prototype, "loadingScreen", {
  1863. get: function () {
  1864. return this._loadingScreen;
  1865. },
  1866. set: function (loadingScreen) {
  1867. this._loadingScreen = loadingScreen;
  1868. },
  1869. enumerable: true,
  1870. configurable: true
  1871. });
  1872. Object.defineProperty(Engine.prototype, "loadingUIText", {
  1873. set: function (text) {
  1874. this._loadingScreen.loadingUIText = text;
  1875. },
  1876. enumerable: true,
  1877. configurable: true
  1878. });
  1879. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  1880. set: function (color) {
  1881. this._loadingScreen.loadingUIBackgroundColor = color;
  1882. },
  1883. enumerable: true,
  1884. configurable: true
  1885. });
  1886. // FPS
  1887. Engine.prototype.getFps = function () {
  1888. return this.fps;
  1889. };
  1890. Engine.prototype.getDeltaTime = function () {
  1891. return this.deltaTime;
  1892. };
  1893. Engine.prototype._measureFps = function () {
  1894. this.previousFramesDuration.push(BABYLON.Tools.Now);
  1895. var length = this.previousFramesDuration.length;
  1896. if (length >= 2) {
  1897. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  1898. }
  1899. if (length >= this.fpsRange) {
  1900. if (length > this.fpsRange) {
  1901. this.previousFramesDuration.splice(0, 1);
  1902. length = this.previousFramesDuration.length;
  1903. }
  1904. var sum = 0;
  1905. for (var id = 0; id < length - 1; id++) {
  1906. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  1907. }
  1908. this.fps = 1000.0 / (sum / (length - 1));
  1909. }
  1910. };
  1911. // Statics
  1912. Engine.isSupported = function () {
  1913. try {
  1914. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  1915. if (navigator.isCocoonJS) {
  1916. return true;
  1917. }
  1918. var tempcanvas = document.createElement("canvas");
  1919. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1920. return gl != null && !!window.WebGLRenderingContext;
  1921. }
  1922. catch (e) {
  1923. return false;
  1924. }
  1925. };
  1926. // Const statics
  1927. Engine._ALPHA_DISABLE = 0;
  1928. Engine._ALPHA_ADD = 1;
  1929. Engine._ALPHA_COMBINE = 2;
  1930. Engine._ALPHA_SUBTRACT = 3;
  1931. Engine._ALPHA_MULTIPLY = 4;
  1932. Engine._ALPHA_MAXIMIZED = 5;
  1933. Engine._ALPHA_ONEONE = 6;
  1934. Engine._DELAYLOADSTATE_NONE = 0;
  1935. Engine._DELAYLOADSTATE_LOADED = 1;
  1936. Engine._DELAYLOADSTATE_LOADING = 2;
  1937. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  1938. Engine._TEXTUREFORMAT_ALPHA = 0;
  1939. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  1940. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  1941. Engine._TEXTUREFORMAT_RGB = 4;
  1942. Engine._TEXTUREFORMAT_RGBA = 5;
  1943. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  1944. Engine._TEXTURETYPE_FLOAT = 1;
  1945. // Updatable statics so stick with vars here
  1946. Engine.CollisionsEpsilon = 0.001;
  1947. Engine.CodeRepository = "src/";
  1948. Engine.ShadersRepository = "src/Shaders/";
  1949. return Engine;
  1950. })();
  1951. BABYLON.Engine = Engine;
  1952. })(BABYLON || (BABYLON = {}));