babylon.engine.js 92 KB

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