babylon.engine.js 91 KB

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