babylon.engine.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. "use strict";
  2. var BABYLON = BABYLON || {};
  3. (function () {
  4. BABYLON.Engine = function (canvas, antialias) {
  5. this._renderingCanvas = canvas;
  6. // GL
  7. try {
  8. this._gl = canvas.getContext("webgl", { antialias: antialias }) || canvas.getContext("experimental-webgl", { antialias: antialias });
  9. } catch (e) {
  10. throw new Error("WebGL not supported");
  11. }
  12. if (!this._gl) {
  13. throw new Error("WebGL not supported");
  14. }
  15. // Options
  16. this.forceWireframe = false;
  17. this.cullBackFaces = true;
  18. // Scenes
  19. this.scenes = [];
  20. // Textures
  21. this._workingCanvas = document.createElement("canvas");
  22. this._workingContext = this._workingCanvas.getContext("2d");
  23. // Viewport
  24. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  25. this.resize();
  26. // Caps
  27. this._caps = {};
  28. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  29. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  30. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  31. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  32. // Extensions
  33. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  34. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') ;
  35. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  36. 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');
  37. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  38. // Cache
  39. this._loadedTexturesCache = [];
  40. this._activeTexturesCache = [];
  41. this._currentEffect = null;
  42. this._currentState = {
  43. culling: null
  44. };
  45. this._compiledEffects = {};
  46. this._gl.enable(this._gl.DEPTH_TEST);
  47. this._gl.depthFunc(this._gl.LEQUAL);
  48. // Fullscreen
  49. this.isFullscreen = false;
  50. var that = this;
  51. var onFullscreenChange = function () {
  52. if (document.fullscreen !== undefined) {
  53. that.isFullscreen = document.fullscreen;
  54. } else if (document.mozFullScreen !== undefined) {
  55. that.isFullscreen = document.mozFullScreen;
  56. } else if (document.webkitIsFullScreen !== undefined) {
  57. that.isFullscreen = document.webkitIsFullScreen;
  58. } else if (document.msIsFullScreen !== undefined) {
  59. that.isFullscreen = document.msIsFullScreen;
  60. }
  61. // Pointer lock
  62. if (that.isFullscreen && that._pointerLockRequested) {
  63. canvas.requestPointerLock = canvas.requestPointerLock ||
  64. canvas.msRequestPointerLock ||
  65. canvas.mozRequestPointerLock ||
  66. canvas.webkitRequestPointerLock;
  67. if (canvas.requestPointerLock) {
  68. canvas.requestPointerLock();
  69. }
  70. }
  71. };
  72. document.addEventListener("fullscreenchange", onFullscreenChange, false);
  73. document.addEventListener("mozfullscreenchange", onFullscreenChange, false);
  74. document.addEventListener("webkitfullscreenchange", onFullscreenChange, false);
  75. document.addEventListener("msfullscreenchange", onFullscreenChange, false);
  76. // Pointer lock
  77. this.isPointerLock = false;
  78. var onPointerLockChange = function () {
  79. that.isPointerLock = (document.mozPointerLockElement === canvas ||
  80. document.webkitPointerLockElement === canvas ||
  81. document.msPointerLockElement === canvas ||
  82. document.pointerLockElement === canvas
  83. );
  84. };
  85. document.addEventListener("pointerlockchange", onPointerLockChange, false);
  86. document.addEventListener("mspointerlockchange", onPointerLockChange, false);
  87. document.addEventListener("mozpointerlockchange", onPointerLockChange, false);
  88. document.addEventListener("webkitpointerlockchange", onPointerLockChange, false);
  89. };
  90. // Properties
  91. BABYLON.Engine.prototype.getAspectRatio = function (camera) {
  92. var viewport = camera.viewport;
  93. return (this._renderingCanvas.width * viewport.width) / (this._renderingCanvas.height * viewport.height);
  94. };
  95. BABYLON.Engine.prototype.getRenderWidth = function () {
  96. return this._renderingCanvas.width;
  97. };
  98. BABYLON.Engine.prototype.getRenderHeight = function () {
  99. return this._renderingCanvas.height;
  100. };
  101. BABYLON.Engine.prototype.getRenderingCanvas = function () {
  102. return this._renderingCanvas;
  103. };
  104. BABYLON.Engine.prototype.setHardwareScalingLevel = function (level) {
  105. this._hardwareScalingLevel = level;
  106. this.resize();
  107. };
  108. BABYLON.Engine.prototype.getHardwareScalingLevel = function () {
  109. return this._hardwareScalingLevel;
  110. };
  111. BABYLON.Engine.prototype.getLoadedTexturesCache = function () {
  112. return this._loadedTexturesCache;
  113. };
  114. BABYLON.Engine.prototype.getCaps = function () {
  115. return this._caps;
  116. };
  117. // Methods
  118. BABYLON.Engine.prototype.stopRenderLoop = function () {
  119. this._renderFunction = null;
  120. this._runningLoop = false;
  121. };
  122. BABYLON.Engine.prototype._renderLoop = function () {
  123. // Start new frame
  124. this.beginFrame();
  125. if (this._renderFunction) {
  126. this._renderFunction();
  127. }
  128. // Present
  129. this.endFrame();
  130. if (this._runningLoop) {
  131. // Register new frame
  132. var that = this;
  133. BABYLON.Tools.QueueNewFrame(function () {
  134. that._renderLoop();
  135. });
  136. }
  137. };
  138. BABYLON.Engine.prototype.runRenderLoop = function (renderFunction) {
  139. this._runningLoop = true;
  140. this._renderFunction = renderFunction;
  141. var that = this;
  142. BABYLON.Tools.QueueNewFrame(function () {
  143. that._renderLoop();
  144. });
  145. };
  146. BABYLON.Engine.prototype.switchFullscreen = function (requestPointerLock) {
  147. if (this.isFullscreen) {
  148. BABYLON.Tools.ExitFullscreen();
  149. } else {
  150. this._pointerLockRequested = requestPointerLock;
  151. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  152. }
  153. };
  154. BABYLON.Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  155. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  156. this._gl.clearDepth(1.0);
  157. var mode = 0;
  158. if (backBuffer)
  159. mode |= this._gl.COLOR_BUFFER_BIT;
  160. if (depthStencil)
  161. mode |= this._gl.DEPTH_BUFFER_BIT;
  162. this._gl.clear(mode);
  163. };
  164. BABYLON.Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  165. var width = requiredWidth || this._renderingCanvas.width;
  166. var height = requiredHeight || this._renderingCanvas.height;
  167. var x = viewport.x || 0;
  168. var y = viewport.y || 0;
  169. this._cachedViewport = viewport;
  170. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  171. };
  172. BABYLON.Engine.prototype.setDirectViewport = function (x, y, width, height) {
  173. this._cachedViewport = null;
  174. this._gl.viewport(x, y, width, height);
  175. };
  176. BABYLON.Engine.prototype.beginFrame = function () {
  177. BABYLON.Tools._MeasureFps();
  178. };
  179. BABYLON.Engine.prototype.endFrame = function () {
  180. this.flushFramebuffer();
  181. };
  182. BABYLON.Engine.prototype.resize = function () {
  183. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  184. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  185. };
  186. BABYLON.Engine.prototype.bindFramebuffer = function (texture) {
  187. var gl = this._gl;
  188. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  189. this._gl.viewport(0, 0, texture._width, texture._height);
  190. this.wipeCaches();
  191. };
  192. BABYLON.Engine.prototype.unBindFramebuffer = function (texture) {
  193. if (texture.generateMipMaps) {
  194. var gl = this._gl;
  195. gl.bindTexture(gl.TEXTURE_2D, texture);
  196. gl.generateMipmap(gl.TEXTURE_2D);
  197. gl.bindTexture(gl.TEXTURE_2D, null);
  198. }
  199. };
  200. BABYLON.Engine.prototype.flushFramebuffer = function () {
  201. this._gl.flush();
  202. };
  203. BABYLON.Engine.prototype.restoreDefaultFramebuffer = function () {
  204. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  205. this.setViewport(this._cachedViewport);
  206. this.wipeCaches();
  207. };
  208. // VBOs
  209. BABYLON.Engine.prototype.createVertexBuffer = function (vertices) {
  210. var vbo = this._gl.createBuffer();
  211. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  212. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  213. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  214. vbo.references = 1;
  215. return vbo;
  216. };
  217. BABYLON.Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  218. var vbo = this._gl.createBuffer();
  219. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  220. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  221. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  222. vbo.references = 1;
  223. return vbo;
  224. };
  225. BABYLON.Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  226. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  227. // Should be (vertices instanceof Float32Array ? vertices : new Float32Array(vertices)) but Chrome raises an Exception in this case :(
  228. if (length) {
  229. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices, 0, length));
  230. } else {
  231. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  232. }
  233. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  234. };
  235. BABYLON.Engine.prototype.createIndexBuffer = function (indices) {
  236. var vbo = this._gl.createBuffer();
  237. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  238. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  239. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  240. vbo.references = 1;
  241. return vbo;
  242. };
  243. BABYLON.Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  244. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  245. this._cachedVertexBuffers = vertexBuffer;
  246. this._cachedEffectForVertexBuffers = effect;
  247. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  248. var offset = 0;
  249. for (var index = 0; index < vertexDeclaration.length; index++) {
  250. var order = effect.getAttribute(index);
  251. if (order >= 0) {
  252. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  253. }
  254. offset += vertexDeclaration[index] * 4;
  255. }
  256. }
  257. if (this._cachedIndexBuffer !== indexBuffer) {
  258. this._cachedIndexBuffer = indexBuffer;
  259. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  260. }
  261. };
  262. BABYLON.Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  263. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  264. this._cachedVertexBuffers = vertexBuffers;
  265. this._cachedEffectForVertexBuffers = effect;
  266. var attributes = effect.getAttributesNames();
  267. for (var index = 0; index < attributes.length; index++) {
  268. var order = effect.getAttribute(index);
  269. if (order >= 0) {
  270. var vertexBuffer = vertexBuffers[attributes[index]];
  271. var stride = vertexBuffer.getStrideSize();
  272. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer._buffer);
  273. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  274. }
  275. }
  276. }
  277. if (this._cachedIndexBuffer !== indexBuffer) {
  278. this._cachedIndexBuffer = indexBuffer;
  279. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  280. }
  281. };
  282. BABYLON.Engine.prototype._releaseBuffer = function (buffer) {
  283. buffer.references--;
  284. if (buffer.references === 0) {
  285. this._gl.deleteBuffer(buffer);
  286. }
  287. };
  288. BABYLON.Engine.prototype.draw = function (useTriangles, indexStart, indexCount) {
  289. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  290. };
  291. // Shaders
  292. BABYLON.Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, optionalDefines) {
  293. var vertex = baseName.vertex || baseName;
  294. var fragment = baseName.fragment || baseName;
  295. var name = vertex + "+" + fragment + "@" + defines;
  296. if (this._compiledEffects[name]) {
  297. return this._compiledEffects[name];
  298. }
  299. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, optionalDefines);
  300. this._compiledEffects[name] = effect;
  301. return effect;
  302. };
  303. var compileShader = function (gl, source, type, defines) {
  304. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  305. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  306. gl.compileShader(shader);
  307. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  308. throw new Error(gl.getShaderInfoLog(shader));
  309. }
  310. return shader;
  311. };
  312. BABYLON.Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  313. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  314. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  315. var shaderProgram = this._gl.createProgram();
  316. this._gl.attachShader(shaderProgram, vertexShader);
  317. this._gl.attachShader(shaderProgram, fragmentShader);
  318. this._gl.linkProgram(shaderProgram);
  319. var error = this._gl.getProgramInfoLog(shaderProgram);
  320. if (error) {
  321. throw new Error(error);
  322. }
  323. this._gl.deleteShader(vertexShader);
  324. this._gl.deleteShader(fragmentShader);
  325. return shaderProgram;
  326. };
  327. BABYLON.Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  328. var results = [];
  329. for (var index = 0; index < uniformsNames.length; index++) {
  330. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  331. }
  332. return results;
  333. };
  334. BABYLON.Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  335. var results = [];
  336. for (var index = 0; index < attributesNames.length; index++) {
  337. try {
  338. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  339. } catch (e) {
  340. results.push(-1);
  341. }
  342. }
  343. return results;
  344. };
  345. BABYLON.Engine.prototype.enableEffect = function (effect) {
  346. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  347. return;
  348. }
  349. // Use program
  350. this._gl.useProgram(effect.getProgram());
  351. for (var index = 0; index < effect.getAttributesCount() ; index++) {
  352. // Attributes
  353. var order = effect.getAttribute(index);
  354. if (order >= 0) {
  355. this._gl.enableVertexAttribArray(effect.getAttribute(index));
  356. }
  357. }
  358. this._currentEffect = effect;
  359. };
  360. BABYLON.Engine.prototype.setMatrices = function (uniform, matrices) {
  361. if (!uniform)
  362. return;
  363. this._gl.uniformMatrix4fv(uniform, false, matrices);
  364. };
  365. BABYLON.Engine.prototype.setMatrix = function (uniform, matrix) {
  366. if (!uniform)
  367. return;
  368. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  369. };
  370. BABYLON.Engine.prototype.setFloat = function (uniform, value) {
  371. if (!uniform)
  372. return;
  373. this._gl.uniform1f(uniform, value);
  374. };
  375. BABYLON.Engine.prototype.setFloat2 = function (uniform, x, y) {
  376. if (!uniform)
  377. return;
  378. this._gl.uniform2f(uniform, x, y);
  379. };
  380. BABYLON.Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  381. if (!uniform)
  382. return;
  383. this._gl.uniform3f(uniform, x, y, z);
  384. };
  385. BABYLON.Engine.prototype.setBool = function (uniform, bool) {
  386. if (!uniform)
  387. return;
  388. this._gl.uniform1i(uniform, bool);
  389. };
  390. BABYLON.Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  391. if (!uniform)
  392. return;
  393. this._gl.uniform4f(uniform, x, y, z, w);
  394. };
  395. BABYLON.Engine.prototype.setColor3 = function (uniform, color3) {
  396. if (!uniform)
  397. return;
  398. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  399. };
  400. BABYLON.Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  401. if (!uniform)
  402. return;
  403. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  404. };
  405. // States
  406. BABYLON.Engine.prototype.setState = function (culling) {
  407. // Culling
  408. if (this._currentState.culling !== culling) {
  409. if (culling) {
  410. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  411. this._gl.enable(this._gl.CULL_FACE);
  412. } else {
  413. this._gl.disable(this._gl.CULL_FACE);
  414. }
  415. this._currentState.culling = culling;
  416. }
  417. };
  418. BABYLON.Engine.prototype.setDepthBuffer = function (enable) {
  419. if (enable) {
  420. this._gl.enable(this._gl.DEPTH_TEST);
  421. } else {
  422. this._gl.disable(this._gl.DEPTH_TEST);
  423. }
  424. };
  425. BABYLON.Engine.prototype.setDepthWrite = function (enable) {
  426. this._gl.depthMask(enable);
  427. };
  428. BABYLON.Engine.prototype.setColorWrite = function (enable) {
  429. this._gl.colorMask(enable, enable, enable, enable);
  430. };
  431. BABYLON.Engine.prototype.setAlphaMode = function (mode) {
  432. switch (mode) {
  433. case BABYLON.Engine.ALPHA_DISABLE:
  434. this.setDepthWrite(true);
  435. this._gl.disable(this._gl.BLEND);
  436. break;
  437. case BABYLON.Engine.ALPHA_COMBINE:
  438. this.setDepthWrite(false);
  439. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  440. this._gl.enable(this._gl.BLEND);
  441. break;
  442. case BABYLON.Engine.ALPHA_ADD:
  443. this.setDepthWrite(false);
  444. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  445. this._gl.enable(this._gl.BLEND);
  446. break;
  447. }
  448. };
  449. BABYLON.Engine.prototype.setAlphaTesting = function (enable) {
  450. this._alphaTest = enable;
  451. };
  452. BABYLON.Engine.prototype.getAlphaTesting = function () {
  453. return this._alphaTest;
  454. };
  455. // Textures
  456. BABYLON.Engine.prototype.wipeCaches = function () {
  457. this._activeTexturesCache = [];
  458. this._currentEffect = null;
  459. this._currentState = {
  460. culling: null
  461. };
  462. this._cachedVertexBuffers = null;
  463. this._cachedVertexBuffers = null;
  464. this._cachedEffectForVertexBuffers = null;
  465. };
  466. var getExponantOfTwo = function (value, max) {
  467. var count = 1;
  468. do {
  469. count *= 2;
  470. } while (count < value);
  471. if (count > max)
  472. count = max;
  473. return count;
  474. };
  475. var prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, processFunction) {
  476. var engine = scene.getEngine();
  477. var potWidth = getExponantOfTwo(width, engine._caps.maxTextureSize);
  478. var potHeight = getExponantOfTwo(height, engine._caps.maxTextureSize);
  479. engine._gl.bindTexture(engine._gl.TEXTURE_2D, texture);
  480. engine._gl.pixelStorei(engine._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? true : invertY);
  481. processFunction(potWidth, potHeight);
  482. engine._gl.texParameteri(engine._gl.TEXTURE_2D, engine._gl.TEXTURE_MAG_FILTER, engine._gl.LINEAR);
  483. if (noMipmap) {
  484. engine._gl.texParameteri(engine._gl.TEXTURE_2D, engine._gl.TEXTURE_MIN_FILTER, engine._gl.LINEAR);
  485. } else {
  486. engine._gl.texParameteri(engine._gl.TEXTURE_2D, engine._gl.TEXTURE_MIN_FILTER, engine._gl.LINEAR_MIPMAP_LINEAR);
  487. engine._gl.generateMipmap(engine._gl.TEXTURE_2D);
  488. }
  489. engine._gl.bindTexture(engine._gl.TEXTURE_2D, null);
  490. engine._activeTexturesCache = [];
  491. texture._baseWidth = width;
  492. texture._baseHeight = height;
  493. texture._width = potWidth;
  494. texture._height = potHeight;
  495. texture.isReady = true;
  496. scene._removePendingData(texture);
  497. };
  498. BABYLON.Engine.prototype.createTexture = function (url, noMipmap, invertY, scene) {
  499. var texture = this._gl.createTexture();
  500. var that = this;
  501. var isDDS = this.getCaps().s3tc && (url.substr(url.length - 4, 4).toLowerCase() === ".dds");
  502. scene._addPendingData(texture);
  503. texture.url = url;
  504. texture.noMipmap = noMipmap;
  505. texture.references = 1;
  506. this._loadedTexturesCache.push(texture);
  507. if (isDDS) {
  508. BABYLON.Tools.LoadFile(url, function (data) {
  509. var info = BABYLON.Tools.GetDDSInfo(data);
  510. var loadMipmap = info.mipmapCount > 1 && !noMipmap;
  511. prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, function (potWidth, potHeight) {
  512. BABYLON.Tools.UploadDDSLevels(that._gl, that.getCaps().s3tc, data, loadMipmap);
  513. });
  514. }, null, scene.database, true);
  515. } else {
  516. var onload = function(img) {
  517. prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, function (potWidth, potHeight) {
  518. var isPot = (img.width == potWidth && img.height == potHeight);
  519. if (!isPot) {
  520. that._workingCanvas.width = potWidth;
  521. that._workingCanvas.height = potHeight;
  522. that._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  523. }
  524. that._gl.texImage2D(that._gl.TEXTURE_2D, 0, that._gl.RGBA, that._gl.RGBA, that._gl.UNSIGNED_BYTE, isPot ? img : that._workingCanvas);
  525. });
  526. };
  527. var onerror = function() {
  528. scene._removePendingData(texture);
  529. };
  530. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  531. }
  532. return texture;
  533. };
  534. BABYLON.Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps) {
  535. var texture = this._gl.createTexture();
  536. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  537. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  538. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  539. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
  540. if (!generateMipMaps) {
  541. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
  542. } else {
  543. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR_MIPMAP_LINEAR);
  544. }
  545. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  546. this._activeTexturesCache = [];
  547. texture._baseWidth = width;
  548. texture._baseHeight = height;
  549. texture._width = width;
  550. texture._height = height;
  551. texture.isReady = false;
  552. texture.generateMipMaps = generateMipMaps;
  553. texture.references = 1;
  554. this._loadedTexturesCache.push(texture);
  555. return texture;
  556. };
  557. BABYLON.Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  558. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  559. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY);
  560. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  561. if (texture.generateMipMaps) {
  562. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  563. }
  564. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  565. this._activeTexturesCache = [];
  566. texture.isReady = true;
  567. };
  568. BABYLON.Engine.prototype.updateVideoTexture = function (texture, video) {
  569. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  570. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, false);
  571. // Scale the video if it is a NPOT
  572. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  573. if (!texture._workingCanvas) {
  574. texture._workingCanvas = document.createElement("canvas");
  575. texture._workingContext = texture._workingCanvas.getContext("2d");
  576. texture._workingCanvas.width = texture._width;
  577. texture._workingCanvas.height = texture._height;
  578. }
  579. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  580. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  581. } else {
  582. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  583. }
  584. if (texture.generateMipMaps) {
  585. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  586. }
  587. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  588. this._activeTexturesCache = [];
  589. texture.isReady = true;
  590. };
  591. BABYLON.Engine.prototype.createRenderTargetTexture = function (size, options) {
  592. // old version had a "generateMipMaps" arg instead of options.
  593. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  594. // in the same way, generateDepthBuffer is defaulted to true
  595. var generateMipMaps = false;
  596. var generateDepthBuffer = true;
  597. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  598. if (options !== undefined) {
  599. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  600. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  601. if (options.samplingMode !== undefined) {
  602. samplingMode = options.samplingMode;
  603. }
  604. }
  605. var gl = this._gl;
  606. var texture = gl.createTexture();
  607. gl.bindTexture(gl.TEXTURE_2D, texture);
  608. var width = size.width || size;
  609. var height = size.height || size;
  610. var magFilter = gl.NEAREST;
  611. var minFilter = gl.NEAREST;
  612. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  613. magFilter = gl.LINEAR;
  614. if (generateMipMaps) {
  615. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  616. } else {
  617. minFilter = gl.LINEAR;
  618. }
  619. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  620. magFilter = gl.LINEAR;
  621. if (generateMipMaps) {
  622. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  623. } else {
  624. minFilter = gl.LINEAR;
  625. }
  626. }
  627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  629. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  630. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  631. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  632. var depthBuffer;
  633. // Create the depth buffer
  634. if (generateDepthBuffer) {
  635. depthBuffer = gl.createRenderbuffer();
  636. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  637. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  638. }
  639. // Create the framebuffer
  640. var framebuffer = gl.createFramebuffer();
  641. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  642. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  643. if (generateDepthBuffer) {
  644. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  645. }
  646. // Unbind
  647. gl.bindTexture(gl.TEXTURE_2D, null);
  648. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  649. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  650. texture._framebuffer = framebuffer;
  651. if (generateDepthBuffer) {
  652. texture._depthBuffer = depthBuffer;
  653. }
  654. texture._width = width;
  655. texture._height = height;
  656. texture.isReady = true;
  657. texture.generateMipMaps = generateMipMaps;
  658. texture.references = 1;
  659. this._activeTexturesCache = [];
  660. this._loadedTexturesCache.push(texture);
  661. return texture;
  662. };
  663. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  664. var img;
  665. var onload = function () {
  666. loadedImages.push(img);
  667. scene._removePendingData(img);
  668. if (index != extensions.length - 1) {
  669. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  670. } else {
  671. onfinish(loadedImages);
  672. }
  673. };
  674. var onerror = function () {
  675. scene._removePendingData(img);
  676. };
  677. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  678. scene._addPendingData(img);
  679. };
  680. BABYLON.Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions) {
  681. var gl = this._gl;
  682. var texture = gl.createTexture();
  683. texture.isCube = true;
  684. texture.url = rootUrl;
  685. texture.references = 1;
  686. this._loadedTexturesCache.push(texture);
  687. var that = this;
  688. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  689. var width = getExponantOfTwo(imgs[0].width, that._caps.maxCubemapTextureSize);
  690. var height = width;
  691. that._workingCanvas.width = width;
  692. that._workingCanvas.height = height;
  693. var faces = [
  694. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  695. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  696. ];
  697. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  698. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
  699. for (var index = 0; index < faces.length; index++) {
  700. that._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  701. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, that._workingCanvas);
  702. }
  703. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
  706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  708. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  709. that._activeTexturesCache = [];
  710. texture._width = width;
  711. texture._height = height;
  712. texture.isReady = true;
  713. }, extensions);
  714. return texture;
  715. };
  716. BABYLON.Engine.prototype._releaseTexture = function (texture) {
  717. var gl = this._gl;
  718. if (texture._framebuffer) {
  719. gl.deleteFramebuffer(texture._framebuffer);
  720. }
  721. if (texture._depthBuffer) {
  722. gl.deleteRenderbuffer(texture._depthBuffer);
  723. }
  724. gl.deleteTexture(texture);
  725. // Unbind channels
  726. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  727. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  728. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  729. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  730. this._activeTexturesCache[channel] = null;
  731. }
  732. var index = this._loadedTexturesCache.indexOf(texture);
  733. if (index !== -1) {
  734. this._loadedTexturesCache.splice(index, 1);
  735. }
  736. };
  737. BABYLON.Engine.prototype.bindSamplers = function (effect) {
  738. this._gl.useProgram(effect.getProgram());
  739. var samplers = effect.getSamplers();
  740. for (var index = 0; index < samplers.length; index++) {
  741. var uniform = effect.getUniform(samplers[index]);
  742. this._gl.uniform1i(uniform, index);
  743. }
  744. this._currentEffect = null;
  745. };
  746. BABYLON.Engine.prototype._bindTexture = function (channel, texture) {
  747. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  748. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  749. this._activeTexturesCache[channel] = null;
  750. };
  751. BABYLON.Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  752. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  753. };
  754. BABYLON.Engine.prototype.setTexture = function (channel, texture) {
  755. if (channel < 0) {
  756. return;
  757. }
  758. // Not ready?
  759. if (!texture || !texture.isReady()) {
  760. if (this._activeTexturesCache[channel] != null) {
  761. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  762. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  763. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  764. this._activeTexturesCache[channel] = null;
  765. }
  766. return;
  767. }
  768. // Video
  769. if (texture instanceof BABYLON.VideoTexture) {
  770. if (texture._update()) {
  771. this._activeTexturesCache[channel] = null;
  772. }
  773. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  774. texture.delayLoad();
  775. return;
  776. }
  777. if (this._activeTexturesCache[channel] == texture) {
  778. return;
  779. }
  780. this._activeTexturesCache[channel] = texture;
  781. var internalTexture = texture.getInternalTexture();
  782. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  783. if (internalTexture.isCube) {
  784. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  785. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  786. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  787. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, texture.coordinatesMode !== BABYLON.CubeTexture.CUBIC_MODE ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE);
  788. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, texture.coordinatesMode !== BABYLON.CubeTexture.CUBIC_MODE ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE);
  789. }
  790. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  791. } else {
  792. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  793. if (internalTexture._cachedWrapU !== texture.wrapU) {
  794. internalTexture._cachedWrapU = texture.wrapU;
  795. switch (texture.wrapU) {
  796. case BABYLON.Texture.WRAP_ADDRESSMODE:
  797. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  798. break;
  799. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  800. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  801. break;
  802. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  803. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  804. break;
  805. }
  806. }
  807. if (internalTexture._cachedWrapV !== texture.wrapV) {
  808. internalTexture._cachedWrapV = texture.wrapV;
  809. switch (texture.wrapV) {
  810. case BABYLON.Texture.WRAP_ADDRESSMODE:
  811. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  812. break;
  813. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  814. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  815. break;
  816. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  817. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  818. break;
  819. }
  820. }
  821. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  822. }
  823. };
  824. BABYLON.Engine.prototype._setAnisotropicLevel = function (key, texture) {
  825. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  826. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  827. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  828. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  829. }
  830. };
  831. // Dispose
  832. BABYLON.Engine.prototype.dispose = function () {
  833. // Release scenes
  834. while (this.scenes.length) {
  835. this.scenes[0].dispose();
  836. }
  837. // Release effects
  838. for (var name in this._compiledEffects.length) {
  839. this._gl.deleteProgram(this._compiledEffects[name]._program);
  840. }
  841. };
  842. // Statics
  843. BABYLON.Engine.ShadersRepository = "Babylon/Shaders/";
  844. BABYLON.Engine.ALPHA_DISABLE = 0;
  845. BABYLON.Engine.ALPHA_ADD = 1;
  846. BABYLON.Engine.ALPHA_COMBINE = 2;
  847. // Statics
  848. BABYLON.Engine.DELAYLOADSTATE_NONE = 0;
  849. BABYLON.Engine.DELAYLOADSTATE_LOADED = 1;
  850. BABYLON.Engine.DELAYLOADSTATE_LOADING = 2;
  851. BABYLON.Engine.DELAYLOADSTATE_NOTLOADED = 4;
  852. BABYLON.Engine.epsilon = 0.001;
  853. BABYLON.Engine.collisionsEpsilon = 0.001;
  854. BABYLON.Engine.isSupported = function () {
  855. try {
  856. var tempcanvas = document.createElement("canvas");
  857. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  858. return gl != null && !!window.WebGLRenderingContext;
  859. } catch (e) {
  860. return false;
  861. }
  862. };
  863. })();