babylon.engine.js 38 KB

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