babylon.engine.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  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 = Texture.TRILINEAR_SAMPLINGMODE; }
  53. var engine = scene.getEngine();
  54. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  55. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  56. gl.bindTexture(gl.TEXTURE_2D, texture);
  57. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  58. processFunction(potWidth, potHeight);
  59. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  60. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  61. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  62. if (!noMipmap && !isCompressed) {
  63. gl.generateMipmap(gl.TEXTURE_2D);
  64. }
  65. gl.bindTexture(gl.TEXTURE_2D, null);
  66. engine._activeTexturesCache = [];
  67. texture._baseWidth = width;
  68. texture._baseHeight = height;
  69. texture._width = potWidth;
  70. texture._height = potHeight;
  71. texture.isReady = true;
  72. scene._removePendingData(texture);
  73. };
  74. // ANY
  75. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  76. var img;
  77. var onload = function () {
  78. loadedImages.push(img);
  79. scene._removePendingData(img);
  80. if (index != extensions.length - 1) {
  81. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  82. } else {
  83. onfinish(loadedImages);
  84. }
  85. };
  86. var onerror = function () {
  87. scene._removePendingData(img);
  88. };
  89. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  90. scene._addPendingData(img);
  91. };
  92. var EngineCapabilities = (function () {
  93. function EngineCapabilities() {
  94. }
  95. return EngineCapabilities;
  96. })();
  97. BABYLON.EngineCapabilities = EngineCapabilities;
  98. var Engine = (function () {
  99. function Engine(canvas, antialias, options) {
  100. var _this = this;
  101. // Public members
  102. this.isFullscreen = false;
  103. this.isPointerLock = false;
  104. this.forceWireframe = false;
  105. this.cullBackFaces = true;
  106. this.renderEvenInBackground = true;
  107. this.scenes = new Array();
  108. this._windowIsBackground = false;
  109. this._runningLoop = false;
  110. // Cache
  111. this._loadedTexturesCache = new Array();
  112. this._activeTexturesCache = new Array();
  113. this._compiledEffects = {};
  114. this._depthMask = false;
  115. this._renderingCanvas = canvas;
  116. 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.13.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) {
  661. // Culling
  662. if (this._cullingState !== culling) {
  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.setDepthWrite = function (enable) {
  680. this._gl.depthMask(enable);
  681. this._depthMask = enable;
  682. };
  683. Engine.prototype.setColorWrite = function (enable) {
  684. this._gl.colorMask(enable, enable, enable, enable);
  685. };
  686. Engine.prototype.setAlphaMode = function (mode) {
  687. switch (mode) {
  688. case BABYLON.Engine.ALPHA_DISABLE:
  689. this.setDepthWrite(true);
  690. this._gl.disable(this._gl.BLEND);
  691. break;
  692. case BABYLON.Engine.ALPHA_COMBINE:
  693. this.setDepthWrite(false);
  694. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  695. this._gl.enable(this._gl.BLEND);
  696. break;
  697. case BABYLON.Engine.ALPHA_ADD:
  698. this.setDepthWrite(false);
  699. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  700. this._gl.enable(this._gl.BLEND);
  701. break;
  702. }
  703. };
  704. Engine.prototype.setAlphaTesting = function (enable) {
  705. this._alphaTest = enable;
  706. };
  707. Engine.prototype.getAlphaTesting = function () {
  708. return this._alphaTest;
  709. };
  710. // Textures
  711. Engine.prototype.wipeCaches = function () {
  712. this._activeTexturesCache = [];
  713. this._currentEffect = null;
  714. this._cullingState = null;
  715. this._cachedVertexBuffers = null;
  716. this._cachedIndexBuffer = null;
  717. this._cachedEffectForVertexBuffers = null;
  718. };
  719. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  720. var gl = this._gl;
  721. gl.bindTexture(gl.TEXTURE_2D, texture);
  722. var magFilter = gl.NEAREST;
  723. var minFilter = gl.NEAREST;
  724. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  725. magFilter = gl.LINEAR;
  726. minFilter = gl.LINEAR;
  727. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  728. magFilter = gl.LINEAR;
  729. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  730. }
  731. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  732. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  733. gl.bindTexture(gl.TEXTURE_2D, null);
  734. };
  735. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode) {
  736. var _this = this;
  737. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  738. var texture = this._gl.createTexture();
  739. var extension = url.substr(url.length - 4, 4).toLowerCase();
  740. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  741. var isTGA = (extension === ".tga");
  742. scene._addPendingData(texture);
  743. texture.url = url;
  744. texture.noMipmap = noMipmap;
  745. texture.references = 1;
  746. this._loadedTexturesCache.push(texture);
  747. if (isTGA) {
  748. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  749. var data = new Uint8Array(arrayBuffer);
  750. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  751. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  752. Internals.TGATools.UploadContent(_this._gl, data);
  753. }, samplingMode);
  754. }, null, scene.database, true);
  755. } else if (isDDS) {
  756. BABYLON.Tools.LoadFile(url, function (data) {
  757. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  758. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  759. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  760. console.log("loading " + url);
  761. Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  762. }, samplingMode);
  763. }, null, scene.database, true);
  764. } else {
  765. var onload = function (img) {
  766. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  767. var isPot = (img.width == potWidth && img.height == potHeight);
  768. if (!isPot) {
  769. _this._workingCanvas.width = potWidth;
  770. _this._workingCanvas.height = potHeight;
  771. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  772. }
  773. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  774. }, samplingMode);
  775. };
  776. var onerror = function () {
  777. scene._removePendingData(texture);
  778. };
  779. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  780. }
  781. return texture;
  782. };
  783. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  784. var texture = this._gl.createTexture();
  785. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  786. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  787. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  788. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  789. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  790. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  791. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  792. this._activeTexturesCache = [];
  793. texture._baseWidth = width;
  794. texture._baseHeight = height;
  795. texture._width = width;
  796. texture._height = height;
  797. texture.isReady = false;
  798. texture.generateMipMaps = generateMipMaps;
  799. texture.references = 1;
  800. this._loadedTexturesCache.push(texture);
  801. return texture;
  802. };
  803. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  804. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  805. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  806. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  807. if (texture.generateMipMaps) {
  808. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  809. }
  810. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  811. this._activeTexturesCache = [];
  812. texture.isReady = true;
  813. };
  814. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  815. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  816. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  817. // Scale the video if it is a NPOT using the current working canvas
  818. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  819. if (!texture._workingCanvas) {
  820. texture._workingCanvas = document.createElement("canvas");
  821. texture._workingContext = texture._workingCanvas.getContext("2d");
  822. texture._workingCanvas.width = texture._width;
  823. texture._workingCanvas.height = texture._height;
  824. }
  825. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  826. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  827. } else {
  828. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  829. }
  830. if (texture.generateMipMaps) {
  831. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  832. }
  833. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  834. this._activeTexturesCache = [];
  835. texture.isReady = true;
  836. };
  837. Engine.prototype.createRenderTargetTexture = function (size, options) {
  838. // old version had a "generateMipMaps" arg instead of options.
  839. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  840. // in the same way, generateDepthBuffer is defaulted to true
  841. var generateMipMaps = false;
  842. var generateDepthBuffer = true;
  843. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  844. if (options !== undefined) {
  845. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  846. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  847. if (options.samplingMode !== undefined) {
  848. samplingMode = options.samplingMode;
  849. }
  850. }
  851. var gl = this._gl;
  852. var texture = gl.createTexture();
  853. gl.bindTexture(gl.TEXTURE_2D, texture);
  854. var width = size.width || size;
  855. var height = size.height || size;
  856. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  859. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  860. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  861. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  862. var depthBuffer;
  863. // Create the depth buffer
  864. if (generateDepthBuffer) {
  865. depthBuffer = gl.createRenderbuffer();
  866. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  867. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  868. }
  869. // Create the framebuffer
  870. var framebuffer = gl.createFramebuffer();
  871. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  872. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  873. if (generateDepthBuffer) {
  874. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  875. }
  876. // Unbind
  877. gl.bindTexture(gl.TEXTURE_2D, null);
  878. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  879. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  880. texture._framebuffer = framebuffer;
  881. if (generateDepthBuffer) {
  882. texture._depthBuffer = depthBuffer;
  883. }
  884. texture._width = width;
  885. texture._height = height;
  886. texture.isReady = true;
  887. texture.generateMipMaps = generateMipMaps;
  888. texture.references = 1;
  889. this._activeTexturesCache = [];
  890. this._loadedTexturesCache.push(texture);
  891. return texture;
  892. };
  893. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  894. var _this = this;
  895. var gl = this._gl;
  896. var texture = gl.createTexture();
  897. texture.isCube = true;
  898. texture.url = rootUrl;
  899. texture.references = 1;
  900. this._loadedTexturesCache.push(texture);
  901. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  902. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  903. if (isDDS) {
  904. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  905. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  906. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  907. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  908. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  909. Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  910. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  911. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  912. }
  913. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  914. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  915. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  917. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  918. _this._activeTexturesCache = [];
  919. texture._width = info.width;
  920. texture._height = info.height;
  921. texture.isReady = true;
  922. });
  923. } else {
  924. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  925. var width = getExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  926. var height = width;
  927. _this._workingCanvas.width = width;
  928. _this._workingCanvas.height = height;
  929. var faces = [
  930. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  931. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  932. ];
  933. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  934. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  935. for (var index = 0; index < faces.length; index++) {
  936. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  937. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  938. }
  939. if (!noMipmap) {
  940. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  941. }
  942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  943. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  944. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  945. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  946. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  947. _this._activeTexturesCache = [];
  948. texture._width = width;
  949. texture._height = height;
  950. texture.isReady = true;
  951. }, extensions);
  952. }
  953. return texture;
  954. };
  955. Engine.prototype._releaseTexture = function (texture) {
  956. var gl = this._gl;
  957. if (texture._framebuffer) {
  958. gl.deleteFramebuffer(texture._framebuffer);
  959. }
  960. if (texture._depthBuffer) {
  961. gl.deleteRenderbuffer(texture._depthBuffer);
  962. }
  963. gl.deleteTexture(texture);
  964. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  965. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  966. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  967. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  968. this._activeTexturesCache[channel] = null;
  969. }
  970. var index = this._loadedTexturesCache.indexOf(texture);
  971. if (index !== -1) {
  972. this._loadedTexturesCache.splice(index, 1);
  973. }
  974. };
  975. Engine.prototype.bindSamplers = function (effect) {
  976. this._gl.useProgram(effect.getProgram());
  977. var samplers = effect.getSamplers();
  978. for (var index = 0; index < samplers.length; index++) {
  979. var uniform = effect.getUniform(samplers[index]);
  980. this._gl.uniform1i(uniform, index);
  981. }
  982. this._currentEffect = null;
  983. };
  984. Engine.prototype._bindTexture = function (channel, texture) {
  985. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  986. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  987. this._activeTexturesCache[channel] = null;
  988. };
  989. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  990. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  991. };
  992. Engine.prototype.setTexture = function (channel, texture) {
  993. if (channel < 0) {
  994. return;
  995. }
  996. // Not ready?
  997. if (!texture || !texture.isReady()) {
  998. if (this._activeTexturesCache[channel] != null) {
  999. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1000. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1001. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1002. this._activeTexturesCache[channel] = null;
  1003. }
  1004. return;
  1005. }
  1006. // Video
  1007. if (texture instanceof BABYLON.VideoTexture) {
  1008. if (texture.update()) {
  1009. this._activeTexturesCache[channel] = null;
  1010. }
  1011. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  1012. texture.delayLoad();
  1013. return;
  1014. }
  1015. if (this._activeTexturesCache[channel] == texture) {
  1016. return;
  1017. }
  1018. this._activeTexturesCache[channel] = texture;
  1019. var internalTexture = texture.getInternalTexture();
  1020. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1021. if (internalTexture.isCube) {
  1022. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1023. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1024. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1025. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1026. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1027. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1028. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1029. }
  1030. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1031. } else {
  1032. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1033. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1034. internalTexture._cachedWrapU = texture.wrapU;
  1035. switch (texture.wrapU) {
  1036. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1037. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1038. break;
  1039. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1040. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1041. break;
  1042. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1043. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1044. break;
  1045. }
  1046. }
  1047. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1048. internalTexture._cachedWrapV = texture.wrapV;
  1049. switch (texture.wrapV) {
  1050. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1051. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1052. break;
  1053. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1054. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1055. break;
  1056. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1057. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1058. break;
  1059. }
  1060. }
  1061. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1062. }
  1063. };
  1064. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  1065. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1066. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1067. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1068. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1069. }
  1070. };
  1071. Engine.prototype.readPixels = function (x, y, width, height) {
  1072. var data = new Uint8Array(height * width * 4);
  1073. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1074. return data;
  1075. };
  1076. // Dispose
  1077. Engine.prototype.dispose = function () {
  1078. this.stopRenderLoop();
  1079. while (this.scenes.length) {
  1080. this.scenes[0].dispose();
  1081. }
  1082. for (var name in this._compiledEffects) {
  1083. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1084. }
  1085. for (var i in this._vertexAttribArrays) {
  1086. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1087. continue;
  1088. }
  1089. this._gl.disableVertexAttribArray(i);
  1090. }
  1091. // Events
  1092. window.removeEventListener("blur", this._onBlur);
  1093. window.removeEventListener("focus", this._onFocus);
  1094. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1095. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1096. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1097. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1098. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1099. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1100. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1101. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1102. };
  1103. // Statics
  1104. Engine.isSupported = function () {
  1105. try {
  1106. var tempcanvas = document.createElement("canvas");
  1107. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1108. return gl != null && !!window.WebGLRenderingContext;
  1109. } catch (e) {
  1110. return false;
  1111. }
  1112. };
  1113. Engine._ALPHA_DISABLE = 0;
  1114. Engine._ALPHA_ADD = 1;
  1115. Engine._ALPHA_COMBINE = 2;
  1116. Engine._DELAYLOADSTATE_NONE = 0;
  1117. Engine._DELAYLOADSTATE_LOADED = 1;
  1118. Engine._DELAYLOADSTATE_LOADING = 2;
  1119. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  1120. Engine.Epsilon = 0.001;
  1121. Engine.CollisionsEpsilon = 0.001;
  1122. Engine.ShadersRepository = "Babylon/Shaders/";
  1123. return Engine;
  1124. })();
  1125. BABYLON.Engine = Engine;
  1126. })(BABYLON || (BABYLON = {}));