babylon.engine.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  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 !== undefined ? 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 cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish, extensions) {
  648. var img;
  649. var onload = function () {
  650. loadedImages.push(img);
  651. scene._removePendingData(img);
  652. if (index != extensions.length - 1) {
  653. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  654. } else {
  655. onfinish(loadedImages);
  656. }
  657. };
  658. var onerror = function () {
  659. scene._removePendingData(img);
  660. };
  661. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  662. scene._addPendingData(img);
  663. };
  664. BABYLON.Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions) {
  665. var gl = this._gl;
  666. var texture = gl.createTexture();
  667. texture.isCube = true;
  668. texture.url = rootUrl;
  669. texture.references = 1;
  670. this._loadedTexturesCache.push(texture);
  671. var that = this;
  672. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  673. var width = getExponantOfTwo(imgs[0].width, that._caps.maxCubemapTextureSize);
  674. var height = width;
  675. that._workingCanvas.width = width;
  676. that._workingCanvas.height = height;
  677. var faces = [
  678. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  679. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  680. ];
  681. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  682. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
  683. for (var index = 0; index < faces.length; index++) {
  684. that._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  685. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, that._workingCanvas);
  686. }
  687. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
  690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  692. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  693. that._activeTexturesCache = [];
  694. texture._width = width;
  695. texture._height = height;
  696. texture.isReady = true;
  697. }, extensions);
  698. return texture;
  699. };
  700. BABYLON.Engine.prototype._releaseTexture = function (texture) {
  701. var gl = this._gl;
  702. if (texture._framebuffer) {
  703. gl.deleteFramebuffer(texture._framebuffer);
  704. }
  705. if (texture._depthBuffer) {
  706. gl.deleteRenderbuffer(texture._depthBuffer);
  707. }
  708. gl.deleteTexture(texture);
  709. // Unbind channels
  710. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  711. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  712. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  713. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  714. this._activeTexturesCache[channel] = null;
  715. }
  716. var index = this._loadedTexturesCache.indexOf(texture);
  717. if (index !== -1) {
  718. this._loadedTexturesCache.splice(index, 1);
  719. }
  720. };
  721. BABYLON.Engine.prototype.bindSamplers = function (effect) {
  722. this._gl.useProgram(effect.getProgram());
  723. var samplers = effect.getSamplers();
  724. for (var index = 0; index < samplers.length; index++) {
  725. var uniform = effect.getUniform(samplers[index]);
  726. this._gl.uniform1i(uniform, index);
  727. }
  728. this._currentEffect = null;
  729. };
  730. BABYLON.Engine.prototype._bindTexture = function (channel, texture) {
  731. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  732. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  733. this._activeTexturesCache[channel] = null;
  734. };
  735. BABYLON.Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  736. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  737. };
  738. BABYLON.Engine.prototype.setTexture = function (channel, texture) {
  739. if (channel < 0) {
  740. return;
  741. }
  742. // Not ready?
  743. if (!texture || !texture.isReady()) {
  744. if (this._activeTexturesCache[channel] != null) {
  745. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  746. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  747. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  748. this._activeTexturesCache[channel] = null;
  749. }
  750. return;
  751. }
  752. // Video
  753. if (texture instanceof BABYLON.VideoTexture) {
  754. if (texture._update()) {
  755. this._activeTexturesCache[channel] = null;
  756. }
  757. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  758. texture.delayLoad();
  759. return;
  760. }
  761. if (this._activeTexturesCache[channel] == texture) {
  762. return;
  763. }
  764. this._activeTexturesCache[channel] = texture;
  765. var internalTexture = texture.getInternalTexture();
  766. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  767. if (internalTexture.isCube) {
  768. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  769. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  770. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  771. 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);
  772. 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);
  773. }
  774. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  775. } else {
  776. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  777. if (internalTexture._cachedWrapU !== texture.wrapU) {
  778. internalTexture._cachedWrapU = texture.wrapU;
  779. switch (texture.wrapU) {
  780. case BABYLON.Texture.WRAP_ADDRESSMODE:
  781. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  782. break;
  783. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  784. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  785. break;
  786. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  787. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  788. break;
  789. }
  790. }
  791. if (internalTexture._cachedWrapV !== texture.wrapV) {
  792. internalTexture._cachedWrapV = texture.wrapV;
  793. switch (texture.wrapV) {
  794. case BABYLON.Texture.WRAP_ADDRESSMODE:
  795. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  796. break;
  797. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  798. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  799. break;
  800. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  801. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  802. break;
  803. }
  804. }
  805. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  806. }
  807. };
  808. BABYLON.Engine.prototype._setAnisotropicLevel = function (key, texture) {
  809. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  810. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  811. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  812. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  813. }
  814. };
  815. // Dispose
  816. BABYLON.Engine.prototype.dispose = function () {
  817. // Release scenes
  818. while (this.scenes.length) {
  819. this.scenes[0].dispose();
  820. }
  821. // Release effects
  822. for (var name in this._compiledEffects.length) {
  823. this._gl.deleteProgram(this._compiledEffects[name]._program);
  824. }
  825. };
  826. // Statics
  827. BABYLON.Engine.ShadersRepository = "Babylon/Shaders/";
  828. BABYLON.Engine.ALPHA_DISABLE = 0;
  829. BABYLON.Engine.ALPHA_ADD = 1;
  830. BABYLON.Engine.ALPHA_COMBINE = 2;
  831. // Statics
  832. BABYLON.Engine.DELAYLOADSTATE_NONE = 0;
  833. BABYLON.Engine.DELAYLOADSTATE_LOADED = 1;
  834. BABYLON.Engine.DELAYLOADSTATE_LOADING = 2;
  835. BABYLON.Engine.DELAYLOADSTATE_NOTLOADED = 4;
  836. BABYLON.Engine.epsilon = 0.001;
  837. BABYLON.Engine.collisionsEpsilon = 0.001;
  838. BABYLON.Engine.isSupported = function () {
  839. try {
  840. var tempcanvas = document.createElement("canvas");
  841. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  842. return gl != null && !!window.WebGLRenderingContext;
  843. } catch (e) {
  844. return false;
  845. }
  846. };
  847. })();