babylon.engine.js 40 KB

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