babylon.engine.js 40 KB

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