babylon.engine.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  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. buffer.capacity = capacity;
  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.deleteInstancesBuffer = function (buffer) {
  460. this._gl.deleteBuffer(buffer);
  461. };
  462. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  463. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  464. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  465. for (var index = 0; index < 4; index++) {
  466. var offsetLocation = offsetLocations[index];
  467. this._gl.enableVertexAttribArray(offsetLocation);
  468. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  469. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  470. }
  471. };
  472. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  473. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  474. for (var index = 0; index < 4; index++) {
  475. var offsetLocation = offsetLocations[index];
  476. this._gl.disableVertexAttribArray(offsetLocation);
  477. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  478. }
  479. };
  480. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  481. if (instancesCount) {
  482. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  483. return;
  484. }
  485. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  486. };
  487. // Shaders
  488. Engine.prototype._releaseEffect = function (effect) {
  489. if (this._compiledEffects[effect._key]) {
  490. delete this._compiledEffects[effect._key];
  491. if (effect.getProgram()) {
  492. this._gl.deleteProgram(effect.getProgram());
  493. }
  494. }
  495. };
  496. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, optionalDefines, onCompiled, onError) {
  497. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  498. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  499. var name = vertex + "+" + fragment + "@" + defines;
  500. if (this._compiledEffects[name]) {
  501. return this._compiledEffects[name];
  502. }
  503. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, optionalDefines, onCompiled, onError);
  504. effect._key = name;
  505. this._compiledEffects[name] = effect;
  506. return effect;
  507. };
  508. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  509. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  510. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  511. var shaderProgram = this._gl.createProgram();
  512. this._gl.attachShader(shaderProgram, vertexShader);
  513. this._gl.attachShader(shaderProgram, fragmentShader);
  514. this._gl.linkProgram(shaderProgram);
  515. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  516. if (!linked) {
  517. var error = this._gl.getProgramInfoLog(shaderProgram);
  518. if (error) {
  519. throw new Error(error);
  520. }
  521. }
  522. this._gl.deleteShader(vertexShader);
  523. this._gl.deleteShader(fragmentShader);
  524. return shaderProgram;
  525. };
  526. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  527. var results = [];
  528. for (var index = 0; index < uniformsNames.length; index++) {
  529. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  530. }
  531. return results;
  532. };
  533. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  534. var results = [];
  535. for (var index = 0; index < attributesNames.length; index++) {
  536. try {
  537. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  538. } catch (e) {
  539. results.push(-1);
  540. }
  541. }
  542. return results;
  543. };
  544. Engine.prototype.enableEffect = function (effect) {
  545. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  546. return;
  547. }
  548. this._vertexAttribArrays = this._vertexAttribArrays || [];
  549. // Use program
  550. this._gl.useProgram(effect.getProgram());
  551. for (var i in this._vertexAttribArrays) {
  552. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  553. continue;
  554. }
  555. this._vertexAttribArrays[i] = false;
  556. this._gl.disableVertexAttribArray(i);
  557. }
  558. var attributesCount = effect.getAttributesCount();
  559. for (var index = 0; index < attributesCount; index++) {
  560. // Attributes
  561. var order = effect.getAttributeLocation(index);
  562. if (order >= 0) {
  563. this._vertexAttribArrays[order] = true;
  564. this._gl.enableVertexAttribArray(order);
  565. }
  566. }
  567. this._currentEffect = effect;
  568. };
  569. Engine.prototype.setArray = function (uniform, array) {
  570. if (!uniform)
  571. return;
  572. this._gl.uniform1fv(uniform, array);
  573. };
  574. Engine.prototype.setMatrices = function (uniform, matrices) {
  575. if (!uniform)
  576. return;
  577. this._gl.uniformMatrix4fv(uniform, false, matrices);
  578. };
  579. Engine.prototype.setMatrix = function (uniform, matrix) {
  580. if (!uniform)
  581. return;
  582. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  583. };
  584. Engine.prototype.setFloat = function (uniform, value) {
  585. if (!uniform)
  586. return;
  587. this._gl.uniform1f(uniform, value);
  588. };
  589. Engine.prototype.setFloat2 = function (uniform, x, y) {
  590. if (!uniform)
  591. return;
  592. this._gl.uniform2f(uniform, x, y);
  593. };
  594. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  595. if (!uniform)
  596. return;
  597. this._gl.uniform3f(uniform, x, y, z);
  598. };
  599. Engine.prototype.setBool = function (uniform, bool) {
  600. if (!uniform)
  601. return;
  602. this._gl.uniform1i(uniform, bool);
  603. };
  604. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  605. if (!uniform)
  606. return;
  607. this._gl.uniform4f(uniform, x, y, z, w);
  608. };
  609. Engine.prototype.setColor3 = function (uniform, color3) {
  610. if (!uniform)
  611. return;
  612. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  613. };
  614. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  615. if (!uniform)
  616. return;
  617. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  618. };
  619. // States
  620. Engine.prototype.setState = function (culling) {
  621. // Culling
  622. if (this._cullingState !== culling) {
  623. if (culling) {
  624. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  625. this._gl.enable(this._gl.CULL_FACE);
  626. } else {
  627. this._gl.disable(this._gl.CULL_FACE);
  628. }
  629. this._cullingState = culling;
  630. }
  631. };
  632. Engine.prototype.setDepthBuffer = function (enable) {
  633. if (enable) {
  634. this._gl.enable(this._gl.DEPTH_TEST);
  635. } else {
  636. this._gl.disable(this._gl.DEPTH_TEST);
  637. }
  638. };
  639. Engine.prototype.setDepthWrite = function (enable) {
  640. this._gl.depthMask(enable);
  641. this._depthMask = enable;
  642. };
  643. Engine.prototype.setColorWrite = function (enable) {
  644. this._gl.colorMask(enable, enable, enable, enable);
  645. };
  646. Engine.prototype.setAlphaMode = function (mode) {
  647. switch (mode) {
  648. case BABYLON.Engine.ALPHA_DISABLE:
  649. this.setDepthWrite(true);
  650. this._gl.disable(this._gl.BLEND);
  651. break;
  652. case BABYLON.Engine.ALPHA_COMBINE:
  653. this.setDepthWrite(false);
  654. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  655. this._gl.enable(this._gl.BLEND);
  656. break;
  657. case BABYLON.Engine.ALPHA_ADD:
  658. this.setDepthWrite(false);
  659. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  660. this._gl.enable(this._gl.BLEND);
  661. break;
  662. }
  663. };
  664. Engine.prototype.setAlphaTesting = function (enable) {
  665. this._alphaTest = enable;
  666. };
  667. Engine.prototype.getAlphaTesting = function () {
  668. return this._alphaTest;
  669. };
  670. // Textures
  671. Engine.prototype.wipeCaches = function () {
  672. this._activeTexturesCache = [];
  673. this._currentEffect = null;
  674. this._cullingState = null;
  675. this._cachedVertexBuffers = null;
  676. this._cachedIndexBuffer = null;
  677. this._cachedEffectForVertexBuffers = null;
  678. };
  679. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  680. var gl = this._gl;
  681. gl.bindTexture(gl.TEXTURE_2D, texture);
  682. var magFilter = gl.NEAREST;
  683. var minFilter = gl.NEAREST;
  684. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  685. magFilter = gl.LINEAR;
  686. minFilter = gl.LINEAR;
  687. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  688. magFilter = gl.LINEAR;
  689. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  690. }
  691. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  693. gl.bindTexture(gl.TEXTURE_2D, null);
  694. };
  695. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene) {
  696. var _this = this;
  697. var texture = this._gl.createTexture();
  698. var extension = url.substr(url.length - 4, 4).toLowerCase();
  699. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  700. var isTGA = (extension === ".tga");
  701. scene._addPendingData(texture);
  702. texture.url = url;
  703. texture.noMipmap = noMipmap;
  704. texture.references = 1;
  705. this._loadedTexturesCache.push(texture);
  706. if (isTGA) {
  707. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  708. var data = new Uint8Array(arrayBuffer);
  709. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  710. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  711. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  712. });
  713. }, null, scene.database, true);
  714. } else if (isDDS) {
  715. BABYLON.Tools.LoadFile(url, function (data) {
  716. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  717. var loadMipmap = info.mipmapCount > 1 && !noMipmap;
  718. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, true, function () {
  719. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, loadMipmap);
  720. });
  721. }, null, scene.database, true);
  722. } else {
  723. var onload = function (img) {
  724. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  725. var isPot = (img.width == potWidth && img.height == potHeight);
  726. if (!isPot) {
  727. _this._workingCanvas.width = potWidth;
  728. _this._workingCanvas.height = potHeight;
  729. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  730. }
  731. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  732. });
  733. };
  734. var onerror = function () {
  735. scene._removePendingData(texture);
  736. };
  737. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  738. }
  739. return texture;
  740. };
  741. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps) {
  742. var texture = this._gl.createTexture();
  743. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  744. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  745. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  746. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
  747. if (!generateMipMaps) {
  748. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
  749. } else {
  750. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR_MIPMAP_LINEAR);
  751. }
  752. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  753. this._activeTexturesCache = [];
  754. texture._baseWidth = width;
  755. texture._baseHeight = height;
  756. texture._width = width;
  757. texture._height = height;
  758. texture.isReady = false;
  759. texture.generateMipMaps = generateMipMaps;
  760. texture.references = 1;
  761. this._loadedTexturesCache.push(texture);
  762. return texture;
  763. };
  764. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  765. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  766. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  767. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  768. if (texture.generateMipMaps) {
  769. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  770. }
  771. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  772. this._activeTexturesCache = [];
  773. texture.isReady = true;
  774. };
  775. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  776. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  777. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  778. // Scale the video if it is a NPOT using the current working canvas
  779. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  780. if (!texture._workingCanvas) {
  781. texture._workingCanvas = document.createElement("canvas");
  782. texture._workingContext = texture._workingCanvas.getContext("2d");
  783. texture._workingCanvas.width = texture._width;
  784. texture._workingCanvas.height = texture._height;
  785. }
  786. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  787. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  788. } else {
  789. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  790. }
  791. if (texture.generateMipMaps) {
  792. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  793. }
  794. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  795. this._activeTexturesCache = [];
  796. texture.isReady = true;
  797. };
  798. Engine.prototype.createRenderTargetTexture = function (size, options) {
  799. // old version had a "generateMipMaps" arg instead of options.
  800. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  801. // in the same way, generateDepthBuffer is defaulted to true
  802. var generateMipMaps = false;
  803. var generateDepthBuffer = true;
  804. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  805. if (options !== undefined) {
  806. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  807. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  808. if (options.samplingMode !== undefined) {
  809. samplingMode = options.samplingMode;
  810. }
  811. }
  812. var gl = this._gl;
  813. var texture = gl.createTexture();
  814. gl.bindTexture(gl.TEXTURE_2D, texture);
  815. var width = size.width || size;
  816. var height = size.height || size;
  817. var magFilter = gl.NEAREST;
  818. var minFilter = gl.NEAREST;
  819. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  820. magFilter = gl.LINEAR;
  821. if (generateMipMaps) {
  822. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  823. } else {
  824. minFilter = gl.LINEAR;
  825. }
  826. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  827. magFilter = gl.LINEAR;
  828. if (generateMipMaps) {
  829. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  830. } else {
  831. minFilter = gl.LINEAR;
  832. }
  833. }
  834. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  835. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  836. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  837. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  838. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  839. var depthBuffer;
  840. // Create the depth buffer
  841. if (generateDepthBuffer) {
  842. depthBuffer = gl.createRenderbuffer();
  843. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  844. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  845. }
  846. // Create the framebuffer
  847. var framebuffer = gl.createFramebuffer();
  848. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  849. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  850. if (generateDepthBuffer) {
  851. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  852. }
  853. // Unbind
  854. gl.bindTexture(gl.TEXTURE_2D, null);
  855. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  856. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  857. texture._framebuffer = framebuffer;
  858. if (generateDepthBuffer) {
  859. texture._depthBuffer = depthBuffer;
  860. }
  861. texture._width = width;
  862. texture._height = height;
  863. texture.isReady = true;
  864. texture.generateMipMaps = generateMipMaps;
  865. texture.references = 1;
  866. this._activeTexturesCache = [];
  867. this._loadedTexturesCache.push(texture);
  868. return texture;
  869. };
  870. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  871. var _this = this;
  872. var gl = this._gl;
  873. var texture = gl.createTexture();
  874. texture.isCube = true;
  875. texture.url = rootUrl;
  876. texture.references = 1;
  877. this._loadedTexturesCache.push(texture);
  878. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  879. var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  880. var height = width;
  881. _this._workingCanvas.width = width;
  882. _this._workingCanvas.height = height;
  883. var faces = [
  884. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  885. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  886. ];
  887. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  888. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  889. for (var index = 0; index < faces.length; index++) {
  890. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  891. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  892. }
  893. if (!noMipmap) {
  894. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  895. }
  896. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  900. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  901. _this._activeTexturesCache = [];
  902. texture._width = width;
  903. texture._height = height;
  904. texture.isReady = true;
  905. }, extensions);
  906. return texture;
  907. };
  908. Engine.prototype._releaseTexture = function (texture) {
  909. var gl = this._gl;
  910. if (texture._framebuffer) {
  911. gl.deleteFramebuffer(texture._framebuffer);
  912. }
  913. if (texture._depthBuffer) {
  914. gl.deleteRenderbuffer(texture._depthBuffer);
  915. }
  916. gl.deleteTexture(texture);
  917. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  918. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  919. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  920. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  921. this._activeTexturesCache[channel] = null;
  922. }
  923. var index = this._loadedTexturesCache.indexOf(texture);
  924. if (index !== -1) {
  925. this._loadedTexturesCache.splice(index, 1);
  926. }
  927. };
  928. Engine.prototype.bindSamplers = function (effect) {
  929. this._gl.useProgram(effect.getProgram());
  930. var samplers = effect.getSamplers();
  931. for (var index = 0; index < samplers.length; index++) {
  932. var uniform = effect.getUniform(samplers[index]);
  933. this._gl.uniform1i(uniform, index);
  934. }
  935. this._currentEffect = null;
  936. };
  937. Engine.prototype._bindTexture = function (channel, texture) {
  938. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  939. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  940. this._activeTexturesCache[channel] = null;
  941. };
  942. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  943. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  944. };
  945. Engine.prototype.setTexture = function (channel, texture) {
  946. if (channel < 0) {
  947. return;
  948. }
  949. // Not ready?
  950. if (!texture || !texture.isReady()) {
  951. if (this._activeTexturesCache[channel] != null) {
  952. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  953. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  954. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  955. this._activeTexturesCache[channel] = null;
  956. }
  957. return;
  958. }
  959. // Video
  960. if (texture instanceof BABYLON.VideoTexture) {
  961. if (texture.update()) {
  962. this._activeTexturesCache[channel] = null;
  963. }
  964. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  965. texture.delayLoad();
  966. return;
  967. }
  968. if (this._activeTexturesCache[channel] == texture) {
  969. return;
  970. }
  971. this._activeTexturesCache[channel] = texture;
  972. var internalTexture = texture.getInternalTexture();
  973. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  974. if (internalTexture.isCube) {
  975. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  976. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  977. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  978. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  979. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  980. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  981. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  982. }
  983. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  984. } else {
  985. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  986. if (internalTexture._cachedWrapU !== texture.wrapU) {
  987. internalTexture._cachedWrapU = texture.wrapU;
  988. switch (texture.wrapU) {
  989. case BABYLON.Texture.WRAP_ADDRESSMODE:
  990. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  991. break;
  992. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  993. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  994. break;
  995. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  996. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  997. break;
  998. }
  999. }
  1000. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1001. internalTexture._cachedWrapV = texture.wrapV;
  1002. switch (texture.wrapV) {
  1003. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1004. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1005. break;
  1006. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1007. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1008. break;
  1009. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1010. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1011. break;
  1012. }
  1013. }
  1014. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1015. }
  1016. };
  1017. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  1018. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1019. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1020. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1021. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1022. }
  1023. };
  1024. Engine.prototype.readPixels = function (x, y, width, height) {
  1025. var data = new Uint8Array(height * width * 4);
  1026. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1027. return data;
  1028. };
  1029. // Dispose
  1030. Engine.prototype.dispose = function () {
  1031. this.stopRenderLoop();
  1032. while (this.scenes.length) {
  1033. this.scenes[0].dispose();
  1034. }
  1035. for (var name in this._compiledEffects) {
  1036. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1037. }
  1038. // Events
  1039. window.removeEventListener("blur", this._onBlur);
  1040. window.removeEventListener("focus", this._onFocus);
  1041. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1042. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1043. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1044. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1045. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1046. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1047. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1048. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1049. };
  1050. // Statics
  1051. Engine.isSupported = function () {
  1052. try {
  1053. var tempcanvas = document.createElement("canvas");
  1054. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1055. return gl != null && !!window.WebGLRenderingContext;
  1056. } catch (e) {
  1057. return false;
  1058. }
  1059. };
  1060. Engine._ALPHA_DISABLE = 0;
  1061. Engine._ALPHA_ADD = 1;
  1062. Engine._ALPHA_COMBINE = 2;
  1063. Engine._DELAYLOADSTATE_NONE = 0;
  1064. Engine._DELAYLOADSTATE_LOADED = 1;
  1065. Engine._DELAYLOADSTATE_LOADING = 2;
  1066. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  1067. Engine.Epsilon = 0.001;
  1068. Engine.CollisionsEpsilon = 0.001;
  1069. Engine.ShadersRepository = "Babylon/Shaders/";
  1070. return Engine;
  1071. })();
  1072. BABYLON.Engine = Engine;
  1073. })(BABYLON || (BABYLON = {}));
  1074. //# sourceMappingURL=babylon.engine.js.map