babylon.engine.js 57 KB

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