babylon.engine.js 102 KB

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