babylon.engine.js 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var compileShader = function (gl, source, type, defines) {
  4. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6. gl.compileShader(shader);
  7. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8. throw new Error(gl.getShaderInfoLog(shader));
  9. }
  10. return shader;
  11. };
  12. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  13. var magFilter = gl.NEAREST;
  14. var minFilter = gl.NEAREST;
  15. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  16. magFilter = gl.LINEAR;
  17. if (generateMipMaps) {
  18. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  19. } else {
  20. minFilter = gl.LINEAR;
  21. }
  22. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  23. magFilter = gl.LINEAR;
  24. if (generateMipMaps) {
  25. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  26. } else {
  27. minFilter = gl.LINEAR;
  28. }
  29. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  30. magFilter = gl.NEAREST;
  31. if (generateMipMaps) {
  32. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  33. } else {
  34. minFilter = gl.NEAREST;
  35. }
  36. }
  37. return {
  38. min: minFilter,
  39. mag: magFilter
  40. };
  41. };
  42. var getExponantOfTwo = function (value, max) {
  43. var count = 1;
  44. do {
  45. count *= 2;
  46. } while(count < value);
  47. if (count > max)
  48. count = max;
  49. return count;
  50. };
  51. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  52. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53. var engine = scene.getEngine();
  54. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  55. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  56. gl.bindTexture(gl.TEXTURE_2D, texture);
  57. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  58. processFunction(potWidth, potHeight);
  59. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  60. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  61. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  62. if (!noMipmap && !isCompressed) {
  63. gl.generateMipmap(gl.TEXTURE_2D);
  64. }
  65. gl.bindTexture(gl.TEXTURE_2D, null);
  66. engine._activeTexturesCache = [];
  67. texture._baseWidth = width;
  68. texture._baseHeight = height;
  69. texture._width = potWidth;
  70. texture._height = potHeight;
  71. texture.isReady = true;
  72. scene._removePendingData(texture);
  73. };
  74. // ANY
  75. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  76. var img;
  77. var onload = function () {
  78. loadedImages.push(img);
  79. scene._removePendingData(img);
  80. if (index != extensions.length - 1) {
  81. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  82. } else {
  83. onfinish(loadedImages);
  84. }
  85. };
  86. var onerror = function () {
  87. scene._removePendingData(img);
  88. };
  89. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  90. scene._addPendingData(img);
  91. };
  92. var EngineCapabilities = (function () {
  93. function EngineCapabilities() {
  94. }
  95. return EngineCapabilities;
  96. })();
  97. BABYLON.EngineCapabilities = EngineCapabilities;
  98. var Engine = (function () {
  99. function Engine(canvas, antialias, options) {
  100. var _this = this;
  101. // Public members
  102. this.isFullscreen = false;
  103. this.isPointerLock = false;
  104. this.forceWireframe = false;
  105. this.cullBackFaces = true;
  106. this.renderEvenInBackground = true;
  107. this.scenes = new Array();
  108. this._windowIsBackground = false;
  109. this._runningLoop = false;
  110. // Cache
  111. this._loadedTexturesCache = new Array();
  112. this._activeTexturesCache = new Array();
  113. this._compiledEffects = {};
  114. this._depthMask = false;
  115. this._renderingCanvas = canvas;
  116. options = options || {};
  117. options.antialias = antialias;
  118. try {
  119. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  120. } catch (e) {
  121. throw new Error("WebGL not supported");
  122. }
  123. if (!this._gl) {
  124. throw new Error("WebGL not supported");
  125. }
  126. this._onBlur = function () {
  127. _this._windowIsBackground = true;
  128. };
  129. this._onFocus = function () {
  130. _this._windowIsBackground = false;
  131. };
  132. window.addEventListener("blur", this._onBlur);
  133. window.addEventListener("focus", this._onFocus);
  134. // Textures
  135. this._workingCanvas = document.createElement("canvas");
  136. this._workingContext = this._workingCanvas.getContext("2d");
  137. // Viewport
  138. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  139. this.resize();
  140. // Caps
  141. this._caps = new EngineCapabilities();
  142. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  143. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  144. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  145. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  146. // Extensions
  147. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  148. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  149. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  150. 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');
  151. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  152. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  153. // Depth buffer
  154. this.setDepthBuffer(true);
  155. this.setDepthFunctionToLessOrEqual();
  156. this.setDepthWrite(true);
  157. // Fullscreen
  158. this._onFullscreenChange = function () {
  159. if (document.fullscreen !== undefined) {
  160. _this.isFullscreen = document.fullscreen;
  161. } else if (document.mozFullScreen !== undefined) {
  162. _this.isFullscreen = document.mozFullScreen;
  163. } else if (document.webkitIsFullScreen !== undefined) {
  164. _this.isFullscreen = document.webkitIsFullScreen;
  165. } else if (document.msIsFullScreen !== undefined) {
  166. _this.isFullscreen = document.msIsFullScreen;
  167. }
  168. // Pointer lock
  169. if (_this.isFullscreen && _this._pointerLockRequested) {
  170. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  171. if (canvas.requestPointerLock) {
  172. canvas.requestPointerLock();
  173. }
  174. }
  175. };
  176. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  177. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  178. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  179. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  180. // Pointer lock
  181. this._onPointerLockChange = function () {
  182. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  183. };
  184. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  185. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  186. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  187. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  188. }
  189. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  190. get: function () {
  191. return Engine._ALPHA_DISABLE;
  192. },
  193. enumerable: true,
  194. configurable: true
  195. });
  196. Object.defineProperty(Engine, "ALPHA_ADD", {
  197. get: function () {
  198. return Engine._ALPHA_ADD;
  199. },
  200. enumerable: true,
  201. configurable: true
  202. });
  203. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  204. get: function () {
  205. return Engine._ALPHA_COMBINE;
  206. },
  207. enumerable: true,
  208. configurable: true
  209. });
  210. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  211. get: function () {
  212. return Engine._DELAYLOADSTATE_NONE;
  213. },
  214. enumerable: true,
  215. configurable: true
  216. });
  217. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  218. get: function () {
  219. return Engine._DELAYLOADSTATE_LOADED;
  220. },
  221. enumerable: true,
  222. configurable: true
  223. });
  224. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  225. get: function () {
  226. return Engine._DELAYLOADSTATE_LOADING;
  227. },
  228. enumerable: true,
  229. configurable: true
  230. });
  231. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  232. get: function () {
  233. return Engine._DELAYLOADSTATE_NOTLOADED;
  234. },
  235. enumerable: true,
  236. configurable: true
  237. });
  238. Engine.prototype.getAspectRatio = function (camera) {
  239. var viewport = camera.viewport;
  240. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  241. };
  242. Engine.prototype.getRenderWidth = function () {
  243. if (this._currentRenderTarget) {
  244. return this._currentRenderTarget._width;
  245. }
  246. return this._renderingCanvas.width;
  247. };
  248. Engine.prototype.getRenderHeight = function () {
  249. if (this._currentRenderTarget) {
  250. return this._currentRenderTarget._height;
  251. }
  252. return this._renderingCanvas.height;
  253. };
  254. Engine.prototype.getRenderingCanvas = function () {
  255. return this._renderingCanvas;
  256. };
  257. Engine.prototype.setHardwareScalingLevel = function (level) {
  258. this._hardwareScalingLevel = level;
  259. this.resize();
  260. };
  261. Engine.prototype.getHardwareScalingLevel = function () {
  262. return this._hardwareScalingLevel;
  263. };
  264. Engine.prototype.getLoadedTexturesCache = function () {
  265. return this._loadedTexturesCache;
  266. };
  267. Engine.prototype.getCaps = function () {
  268. return this._caps;
  269. };
  270. // Methods
  271. Engine.prototype.setDepthFunctionToGreater = function () {
  272. this._gl.depthFunc(this._gl.GREATER);
  273. };
  274. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  275. this._gl.depthFunc(this._gl.GEQUAL);
  276. };
  277. Engine.prototype.setDepthFunctionToLess = function () {
  278. this._gl.depthFunc(this._gl.LESS);
  279. };
  280. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  281. this._gl.depthFunc(this._gl.LEQUAL);
  282. };
  283. Engine.prototype.stopRenderLoop = function () {
  284. this._renderFunction = null;
  285. this._runningLoop = false;
  286. };
  287. Engine.prototype._renderLoop = function () {
  288. var _this = this;
  289. var shouldRender = true;
  290. if (!this.renderEvenInBackground && this._windowIsBackground) {
  291. shouldRender = false;
  292. }
  293. if (shouldRender) {
  294. // Start new frame
  295. this.beginFrame();
  296. if (this._renderFunction) {
  297. this._renderFunction();
  298. }
  299. // Present
  300. this.endFrame();
  301. }
  302. if (this._runningLoop) {
  303. // Register new frame
  304. BABYLON.Tools.QueueNewFrame(function () {
  305. _this._renderLoop();
  306. });
  307. }
  308. };
  309. Engine.prototype.runRenderLoop = function (renderFunction) {
  310. var _this = this;
  311. this._runningLoop = true;
  312. this._renderFunction = renderFunction;
  313. BABYLON.Tools.QueueNewFrame(function () {
  314. _this._renderLoop();
  315. });
  316. };
  317. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  318. if (this.isFullscreen) {
  319. BABYLON.Tools.ExitFullscreen();
  320. } else {
  321. this._pointerLockRequested = requestPointerLock;
  322. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  323. }
  324. };
  325. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  326. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  327. if (this._depthMask) {
  328. this._gl.clearDepth(1.0);
  329. }
  330. var mode = 0;
  331. if (backBuffer)
  332. mode |= this._gl.COLOR_BUFFER_BIT;
  333. if (depthStencil && this._depthMask)
  334. mode |= this._gl.DEPTH_BUFFER_BIT;
  335. this._gl.clear(mode);
  336. };
  337. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  338. var width = requiredWidth || this._renderingCanvas.width;
  339. var height = requiredHeight || this._renderingCanvas.height;
  340. var x = viewport.x || 0;
  341. var y = viewport.y || 0;
  342. this._cachedViewport = viewport;
  343. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  344. };
  345. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  346. this._cachedViewport = null;
  347. this._gl.viewport(x, y, width, height);
  348. };
  349. Engine.prototype.beginFrame = function () {
  350. BABYLON.Tools._MeasureFps();
  351. };
  352. Engine.prototype.endFrame = function () {
  353. this.flushFramebuffer();
  354. };
  355. Engine.prototype.resize = function () {
  356. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  357. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  358. };
  359. Engine.prototype.bindFramebuffer = function (texture) {
  360. this._currentRenderTarget = texture;
  361. var gl = this._gl;
  362. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  363. this._gl.viewport(0, 0, texture._width, texture._height);
  364. this.wipeCaches();
  365. };
  366. Engine.prototype.unBindFramebuffer = function (texture) {
  367. this._currentRenderTarget = null;
  368. if (texture.generateMipMaps) {
  369. var gl = this._gl;
  370. gl.bindTexture(gl.TEXTURE_2D, texture);
  371. gl.generateMipmap(gl.TEXTURE_2D);
  372. gl.bindTexture(gl.TEXTURE_2D, null);
  373. }
  374. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  375. };
  376. Engine.prototype.flushFramebuffer = function () {
  377. this._gl.flush();
  378. };
  379. Engine.prototype.restoreDefaultFramebuffer = function () {
  380. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  381. this.setViewport(this._cachedViewport);
  382. this.wipeCaches();
  383. };
  384. // VBOs
  385. Engine.prototype._resetVertexBufferBinding = function () {
  386. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  387. this._cachedVertexBuffers = null;
  388. };
  389. Engine.prototype.createVertexBuffer = function (vertices) {
  390. var vbo = this._gl.createBuffer();
  391. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  392. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  393. this._resetVertexBufferBinding();
  394. vbo.references = 1;
  395. return vbo;
  396. };
  397. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  398. var vbo = this._gl.createBuffer();
  399. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  400. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  401. this._resetVertexBufferBinding();
  402. vbo.references = 1;
  403. return vbo;
  404. };
  405. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  406. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  407. //if (length && length != vertices.length) {
  408. // this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices, 0, length));
  409. //} else {
  410. if (vertices instanceof Float32Array) {
  411. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  412. } else {
  413. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  414. }
  415. // }
  416. this._resetVertexBufferBinding();
  417. };
  418. Engine.prototype._resetIndexBufferBinding = function () {
  419. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  420. this._cachedIndexBuffer = null;
  421. };
  422. Engine.prototype.createIndexBuffer = function (indices) {
  423. var vbo = this._gl.createBuffer();
  424. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  425. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  426. this._resetIndexBufferBinding();
  427. vbo.references = 1;
  428. return vbo;
  429. };
  430. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  431. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  432. this._cachedVertexBuffers = vertexBuffer;
  433. this._cachedEffectForVertexBuffers = effect;
  434. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  435. var offset = 0;
  436. for (var index = 0; index < vertexDeclaration.length; index++) {
  437. var order = effect.getAttributeLocation(index);
  438. if (order >= 0) {
  439. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  440. }
  441. offset += vertexDeclaration[index] * 4;
  442. }
  443. }
  444. if (this._cachedIndexBuffer !== indexBuffer) {
  445. this._cachedIndexBuffer = indexBuffer;
  446. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  447. }
  448. };
  449. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  450. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  451. this._cachedVertexBuffers = vertexBuffers;
  452. this._cachedEffectForVertexBuffers = effect;
  453. var attributes = effect.getAttributesNames();
  454. for (var index = 0; index < attributes.length; index++) {
  455. var order = effect.getAttributeLocation(index);
  456. if (order >= 0) {
  457. var vertexBuffer = vertexBuffers[attributes[index]];
  458. if (!vertexBuffer) {
  459. continue;
  460. }
  461. var stride = vertexBuffer.getStrideSize();
  462. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  463. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  464. }
  465. }
  466. }
  467. if (this._cachedIndexBuffer !== indexBuffer) {
  468. this._cachedIndexBuffer = indexBuffer;
  469. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  470. }
  471. };
  472. Engine.prototype._releaseBuffer = function (buffer) {
  473. buffer.references--;
  474. if (buffer.references === 0) {
  475. this._gl.deleteBuffer(buffer);
  476. return true;
  477. }
  478. return false;
  479. };
  480. Engine.prototype.createInstancesBuffer = function (capacity) {
  481. var buffer = this._gl.createBuffer();
  482. buffer.capacity = capacity;
  483. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  484. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  485. return buffer;
  486. };
  487. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  488. this._gl.deleteBuffer(buffer);
  489. };
  490. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  491. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  492. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  493. for (var index = 0; index < 4; index++) {
  494. var offsetLocation = offsetLocations[index];
  495. this._gl.enableVertexAttribArray(offsetLocation);
  496. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  497. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  498. }
  499. };
  500. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  501. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  502. for (var index = 0; index < 4; index++) {
  503. var offsetLocation = offsetLocations[index];
  504. this._gl.disableVertexAttribArray(offsetLocation);
  505. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  506. }
  507. };
  508. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  509. if (instancesCount) {
  510. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  511. return;
  512. }
  513. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  514. };
  515. // Shaders
  516. Engine.prototype._releaseEffect = function (effect) {
  517. if (this._compiledEffects[effect._key]) {
  518. delete this._compiledEffects[effect._key];
  519. if (effect.getProgram()) {
  520. this._gl.deleteProgram(effect.getProgram());
  521. }
  522. }
  523. };
  524. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, optionalDefines, onCompiled, onError) {
  525. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  526. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  527. var name = vertex + "+" + fragment + "@" + defines;
  528. if (this._compiledEffects[name]) {
  529. return this._compiledEffects[name];
  530. }
  531. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, optionalDefines, onCompiled, onError);
  532. effect._key = name;
  533. this._compiledEffects[name] = effect;
  534. return effect;
  535. };
  536. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  537. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  538. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  539. var shaderProgram = this._gl.createProgram();
  540. this._gl.attachShader(shaderProgram, vertexShader);
  541. this._gl.attachShader(shaderProgram, fragmentShader);
  542. this._gl.linkProgram(shaderProgram);
  543. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  544. if (!linked) {
  545. var error = this._gl.getProgramInfoLog(shaderProgram);
  546. if (error) {
  547. throw new Error(error);
  548. }
  549. }
  550. this._gl.deleteShader(vertexShader);
  551. this._gl.deleteShader(fragmentShader);
  552. return shaderProgram;
  553. };
  554. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  555. var results = [];
  556. for (var index = 0; index < uniformsNames.length; index++) {
  557. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  558. }
  559. return results;
  560. };
  561. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  562. var results = [];
  563. for (var index = 0; index < attributesNames.length; index++) {
  564. try {
  565. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  566. } catch (e) {
  567. results.push(-1);
  568. }
  569. }
  570. return results;
  571. };
  572. Engine.prototype.enableEffect = function (effect) {
  573. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  574. return;
  575. }
  576. this._vertexAttribArrays = this._vertexAttribArrays || [];
  577. // Use program
  578. this._gl.useProgram(effect.getProgram());
  579. for (var i in this._vertexAttribArrays) {
  580. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  581. continue;
  582. }
  583. this._vertexAttribArrays[i] = false;
  584. this._gl.disableVertexAttribArray(i);
  585. }
  586. var attributesCount = effect.getAttributesCount();
  587. for (var index = 0; index < attributesCount; index++) {
  588. // Attributes
  589. var order = effect.getAttributeLocation(index);
  590. if (order >= 0) {
  591. this._vertexAttribArrays[order] = true;
  592. this._gl.enableVertexAttribArray(order);
  593. }
  594. }
  595. this._currentEffect = effect;
  596. };
  597. Engine.prototype.setArray = function (uniform, array) {
  598. if (!uniform)
  599. return;
  600. this._gl.uniform1fv(uniform, array);
  601. };
  602. Engine.prototype.setMatrices = function (uniform, matrices) {
  603. if (!uniform)
  604. return;
  605. this._gl.uniformMatrix4fv(uniform, false, matrices);
  606. };
  607. Engine.prototype.setMatrix = function (uniform, matrix) {
  608. if (!uniform)
  609. return;
  610. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  611. };
  612. Engine.prototype.setFloat = function (uniform, value) {
  613. if (!uniform)
  614. return;
  615. this._gl.uniform1f(uniform, value);
  616. };
  617. Engine.prototype.setFloat2 = function (uniform, x, y) {
  618. if (!uniform)
  619. return;
  620. this._gl.uniform2f(uniform, x, y);
  621. };
  622. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  623. if (!uniform)
  624. return;
  625. this._gl.uniform3f(uniform, x, y, z);
  626. };
  627. Engine.prototype.setBool = function (uniform, bool) {
  628. if (!uniform)
  629. return;
  630. this._gl.uniform1i(uniform, bool);
  631. };
  632. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  633. if (!uniform)
  634. return;
  635. this._gl.uniform4f(uniform, x, y, z, w);
  636. };
  637. Engine.prototype.setColor3 = function (uniform, color3) {
  638. if (!uniform)
  639. return;
  640. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  641. };
  642. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  643. if (!uniform)
  644. return;
  645. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  646. };
  647. // States
  648. Engine.prototype.setState = function (culling) {
  649. // Culling
  650. if (this._cullingState !== culling) {
  651. if (culling) {
  652. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  653. this._gl.enable(this._gl.CULL_FACE);
  654. } else {
  655. this._gl.disable(this._gl.CULL_FACE);
  656. }
  657. this._cullingState = culling;
  658. }
  659. };
  660. Engine.prototype.setDepthBuffer = function (enable) {
  661. if (enable) {
  662. this._gl.enable(this._gl.DEPTH_TEST);
  663. } else {
  664. this._gl.disable(this._gl.DEPTH_TEST);
  665. }
  666. };
  667. Engine.prototype.setDepthWrite = function (enable) {
  668. this._gl.depthMask(enable);
  669. this._depthMask = enable;
  670. };
  671. Engine.prototype.setColorWrite = function (enable) {
  672. this._gl.colorMask(enable, enable, enable, enable);
  673. };
  674. Engine.prototype.setAlphaMode = function (mode) {
  675. switch (mode) {
  676. case BABYLON.Engine.ALPHA_DISABLE:
  677. this.setDepthWrite(true);
  678. this._gl.disable(this._gl.BLEND);
  679. break;
  680. case BABYLON.Engine.ALPHA_COMBINE:
  681. this.setDepthWrite(false);
  682. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  683. this._gl.enable(this._gl.BLEND);
  684. break;
  685. case BABYLON.Engine.ALPHA_ADD:
  686. this.setDepthWrite(false);
  687. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  688. this._gl.enable(this._gl.BLEND);
  689. break;
  690. }
  691. };
  692. Engine.prototype.setAlphaTesting = function (enable) {
  693. this._alphaTest = enable;
  694. };
  695. Engine.prototype.getAlphaTesting = function () {
  696. return this._alphaTest;
  697. };
  698. // Textures
  699. Engine.prototype.wipeCaches = function () {
  700. this._activeTexturesCache = [];
  701. this._currentEffect = null;
  702. this._cullingState = null;
  703. this._cachedVertexBuffers = null;
  704. this._cachedIndexBuffer = null;
  705. this._cachedEffectForVertexBuffers = null;
  706. };
  707. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  708. var gl = this._gl;
  709. gl.bindTexture(gl.TEXTURE_2D, texture);
  710. var magFilter = gl.NEAREST;
  711. var minFilter = gl.NEAREST;
  712. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  713. magFilter = gl.LINEAR;
  714. minFilter = gl.LINEAR;
  715. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  716. magFilter = gl.LINEAR;
  717. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  718. }
  719. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  720. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  721. gl.bindTexture(gl.TEXTURE_2D, null);
  722. };
  723. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode) {
  724. var _this = this;
  725. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  726. var texture = this._gl.createTexture();
  727. var extension = url.substr(url.length - 4, 4).toLowerCase();
  728. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  729. var isTGA = (extension === ".tga");
  730. scene._addPendingData(texture);
  731. texture.url = url;
  732. texture.noMipmap = noMipmap;
  733. texture.references = 1;
  734. this._loadedTexturesCache.push(texture);
  735. if (isTGA) {
  736. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  737. var data = new Uint8Array(arrayBuffer);
  738. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  739. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  740. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  741. }, samplingMode);
  742. }, null, scene.database, true);
  743. } else if (isDDS) {
  744. BABYLON.Tools.LoadFile(url, function (data) {
  745. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  746. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) <= 4);
  747. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  748. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  749. }, samplingMode);
  750. }, null, scene.database, true);
  751. } else {
  752. var onload = function (img) {
  753. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  754. var isPot = (img.width == potWidth && img.height == potHeight);
  755. if (!isPot) {
  756. _this._workingCanvas.width = potWidth;
  757. _this._workingCanvas.height = potHeight;
  758. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  759. }
  760. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  761. }, samplingMode);
  762. };
  763. var onerror = function () {
  764. scene._removePendingData(texture);
  765. };
  766. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  767. }
  768. return texture;
  769. };
  770. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  771. var texture = this._gl.createTexture();
  772. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  773. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  774. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  775. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  776. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  777. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  778. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  779. this._activeTexturesCache = [];
  780. texture._baseWidth = width;
  781. texture._baseHeight = height;
  782. texture._width = width;
  783. texture._height = height;
  784. texture.isReady = false;
  785. texture.generateMipMaps = generateMipMaps;
  786. texture.references = 1;
  787. this._loadedTexturesCache.push(texture);
  788. return texture;
  789. };
  790. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  791. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  792. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  793. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  794. if (texture.generateMipMaps) {
  795. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  796. }
  797. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  798. this._activeTexturesCache = [];
  799. texture.isReady = true;
  800. };
  801. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  802. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  803. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  804. // Scale the video if it is a NPOT using the current working canvas
  805. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  806. if (!texture._workingCanvas) {
  807. texture._workingCanvas = document.createElement("canvas");
  808. texture._workingContext = texture._workingCanvas.getContext("2d");
  809. texture._workingCanvas.width = texture._width;
  810. texture._workingCanvas.height = texture._height;
  811. }
  812. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  813. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  814. } else {
  815. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  816. }
  817. if (texture.generateMipMaps) {
  818. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  819. }
  820. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  821. this._activeTexturesCache = [];
  822. texture.isReady = true;
  823. };
  824. Engine.prototype.createRenderTargetTexture = function (size, options) {
  825. // old version had a "generateMipMaps" arg instead of options.
  826. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  827. // in the same way, generateDepthBuffer is defaulted to true
  828. var generateMipMaps = false;
  829. var generateDepthBuffer = true;
  830. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  831. if (options !== undefined) {
  832. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  833. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  834. if (options.samplingMode !== undefined) {
  835. samplingMode = options.samplingMode;
  836. }
  837. }
  838. var gl = this._gl;
  839. var texture = gl.createTexture();
  840. gl.bindTexture(gl.TEXTURE_2D, texture);
  841. var width = size.width || size;
  842. var height = size.height || size;
  843. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  844. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  845. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  846. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  847. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  848. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  849. var depthBuffer;
  850. // Create the depth buffer
  851. if (generateDepthBuffer) {
  852. depthBuffer = gl.createRenderbuffer();
  853. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  854. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  855. }
  856. // Create the framebuffer
  857. var framebuffer = gl.createFramebuffer();
  858. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  859. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  860. if (generateDepthBuffer) {
  861. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  862. }
  863. // Unbind
  864. gl.bindTexture(gl.TEXTURE_2D, null);
  865. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  866. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  867. texture._framebuffer = framebuffer;
  868. if (generateDepthBuffer) {
  869. texture._depthBuffer = depthBuffer;
  870. }
  871. texture._width = width;
  872. texture._height = height;
  873. texture.isReady = true;
  874. texture.generateMipMaps = generateMipMaps;
  875. texture.references = 1;
  876. this._activeTexturesCache = [];
  877. this._loadedTexturesCache.push(texture);
  878. return texture;
  879. };
  880. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  881. var _this = this;
  882. var gl = this._gl;
  883. var texture = gl.createTexture();
  884. texture.isCube = true;
  885. texture.url = rootUrl;
  886. texture.references = 1;
  887. this._loadedTexturesCache.push(texture);
  888. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  889. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  890. if (isDDS) {
  891. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  892. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  893. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  894. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  895. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  896. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  897. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  898. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  899. }
  900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  904. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  905. _this._activeTexturesCache = [];
  906. texture._width = info.width;
  907. texture._height = info.height;
  908. texture.isReady = true;
  909. });
  910. } else {
  911. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  912. var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  913. var height = width;
  914. _this._workingCanvas.width = width;
  915. _this._workingCanvas.height = height;
  916. var faces = [
  917. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  918. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  919. ];
  920. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  921. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  922. for (var index = 0; index < faces.length; index++) {
  923. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  924. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  925. }
  926. if (!noMipmap) {
  927. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  928. }
  929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  930. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  933. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  934. _this._activeTexturesCache = [];
  935. texture._width = width;
  936. texture._height = height;
  937. texture.isReady = true;
  938. }, extensions);
  939. }
  940. return texture;
  941. };
  942. Engine.prototype._releaseTexture = function (texture) {
  943. var gl = this._gl;
  944. if (texture._framebuffer) {
  945. gl.deleteFramebuffer(texture._framebuffer);
  946. }
  947. if (texture._depthBuffer) {
  948. gl.deleteRenderbuffer(texture._depthBuffer);
  949. }
  950. gl.deleteTexture(texture);
  951. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  952. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  953. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  954. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  955. this._activeTexturesCache[channel] = null;
  956. }
  957. var index = this._loadedTexturesCache.indexOf(texture);
  958. if (index !== -1) {
  959. this._loadedTexturesCache.splice(index, 1);
  960. }
  961. };
  962. Engine.prototype.bindSamplers = function (effect) {
  963. this._gl.useProgram(effect.getProgram());
  964. var samplers = effect.getSamplers();
  965. for (var index = 0; index < samplers.length; index++) {
  966. var uniform = effect.getUniform(samplers[index]);
  967. this._gl.uniform1i(uniform, index);
  968. }
  969. this._currentEffect = null;
  970. };
  971. Engine.prototype._bindTexture = function (channel, texture) {
  972. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  973. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  974. this._activeTexturesCache[channel] = null;
  975. };
  976. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  977. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  978. };
  979. Engine.prototype.setTexture = function (channel, texture) {
  980. if (channel < 0) {
  981. return;
  982. }
  983. // Not ready?
  984. if (!texture || !texture.isReady()) {
  985. if (this._activeTexturesCache[channel] != null) {
  986. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  987. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  988. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  989. this._activeTexturesCache[channel] = null;
  990. }
  991. return;
  992. }
  993. // Video
  994. if (texture instanceof BABYLON.VideoTexture) {
  995. if (texture.update()) {
  996. this._activeTexturesCache[channel] = null;
  997. }
  998. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  999. texture.delayLoad();
  1000. return;
  1001. }
  1002. if (this._activeTexturesCache[channel] == texture) {
  1003. return;
  1004. }
  1005. this._activeTexturesCache[channel] = texture;
  1006. var internalTexture = texture.getInternalTexture();
  1007. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1008. if (internalTexture.isCube) {
  1009. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1010. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1011. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1012. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1013. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1014. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1015. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1016. }
  1017. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1018. } else {
  1019. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1020. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1021. internalTexture._cachedWrapU = texture.wrapU;
  1022. switch (texture.wrapU) {
  1023. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1024. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1025. break;
  1026. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1027. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1028. break;
  1029. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1030. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1031. break;
  1032. }
  1033. }
  1034. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1035. internalTexture._cachedWrapV = texture.wrapV;
  1036. switch (texture.wrapV) {
  1037. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1038. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1039. break;
  1040. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1041. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1042. break;
  1043. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1044. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1045. break;
  1046. }
  1047. }
  1048. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1049. }
  1050. };
  1051. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  1052. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1053. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1054. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1055. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1056. }
  1057. };
  1058. Engine.prototype.readPixels = function (x, y, width, height) {
  1059. var data = new Uint8Array(height * width * 4);
  1060. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1061. return data;
  1062. };
  1063. // Dispose
  1064. Engine.prototype.dispose = function () {
  1065. this.stopRenderLoop();
  1066. while (this.scenes.length) {
  1067. this.scenes[0].dispose();
  1068. }
  1069. for (var name in this._compiledEffects) {
  1070. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1071. }
  1072. // Events
  1073. window.removeEventListener("blur", this._onBlur);
  1074. window.removeEventListener("focus", this._onFocus);
  1075. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1076. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1077. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1078. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1079. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1080. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1081. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1082. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1083. };
  1084. // Statics
  1085. Engine.isSupported = function () {
  1086. try {
  1087. var tempcanvas = document.createElement("canvas");
  1088. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1089. return gl != null && !!window.WebGLRenderingContext;
  1090. } catch (e) {
  1091. return false;
  1092. }
  1093. };
  1094. Engine._ALPHA_DISABLE = 0;
  1095. Engine._ALPHA_ADD = 1;
  1096. Engine._ALPHA_COMBINE = 2;
  1097. Engine._DELAYLOADSTATE_NONE = 0;
  1098. Engine._DELAYLOADSTATE_LOADED = 1;
  1099. Engine._DELAYLOADSTATE_LOADING = 2;
  1100. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  1101. Engine.Epsilon = 0.001;
  1102. Engine.CollisionsEpsilon = 0.001;
  1103. Engine.ShadersRepository = "Babylon/Shaders/";
  1104. return Engine;
  1105. })();
  1106. BABYLON.Engine = Engine;
  1107. })(BABYLON || (BABYLON = {}));
  1108. //# sourceMappingURL=babylon.engine.js.map