babylon.engine.js 52 KB

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