babylon.engine.js 38 KB

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