babylon.engine.js 52 KB

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