babylon.engine.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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 === undefined) {
  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, 1.0);
  151. this._gl.clearDepth(1.0);
  152. var mode = 0;
  153. if (backBuffer || this.forceWireframe)
  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._size, texture._size);
  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) {
  211. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  212. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  213. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  214. };
  215. BABYLON.Engine.prototype.createIndexBuffer = function (indices) {
  216. var vbo = this._gl.createBuffer();
  217. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  218. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  219. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  220. vbo.references = 1;
  221. return vbo;
  222. };
  223. BABYLON.Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  224. this._cachedVertexBuffers = null;
  225. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  226. var offset = 0;
  227. for (var index = 0; index < vertexDeclaration.length; index++) {
  228. var order = effect.getAttribute(index);
  229. if (order >= 0) {
  230. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  231. }
  232. offset += vertexDeclaration[index] * 4;
  233. }
  234. if (this._cachedIndexBuffer !== indexBuffer) {
  235. this._cachedIndexBuffer = indexBuffer;
  236. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  237. }
  238. };
  239. BABYLON.Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  240. if (this._cachedVertexBuffers !== vertexBuffers) {
  241. this._cachedVertexBuffers = vertexBuffers;
  242. var attributes = effect.getAttributesNames();
  243. for (var index = 0; index < attributes.length; index++) {
  244. var order = effect.getAttribute(index);
  245. if (order >= 0) {
  246. var vertexBuffer = vertexBuffers[attributes[index]];
  247. var stride = vertexBuffer.getStrideSize();
  248. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer._buffer);
  249. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  250. }
  251. }
  252. }
  253. if (this._cachedIndexBuffer !== indexBuffer) {
  254. this._cachedIndexBuffer = indexBuffer;
  255. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  256. }
  257. };
  258. BABYLON.Engine.prototype._releaseBuffer = function (buffer) {
  259. buffer.references--;
  260. if (buffer.references === 0) {
  261. this._gl.deleteBuffer(buffer);
  262. }
  263. };
  264. BABYLON.Engine.prototype.draw = function (useTriangles, indexStart, indexCount) {
  265. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  266. };
  267. // Shaders
  268. BABYLON.Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines) {
  269. var name = baseName + "@" + defines;
  270. if (this._compiledEffects[name]) {
  271. return this._compiledEffects[name];
  272. }
  273. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines);
  274. this._compiledEffects[name] = effect;
  275. return effect;
  276. };
  277. var compileShader = function (gl, source, type, defines) {
  278. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  279. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  280. gl.compileShader(shader);
  281. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  282. throw new Error(gl.getShaderInfoLog(shader));
  283. }
  284. return shader;
  285. };
  286. BABYLON.Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  287. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  288. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  289. var shaderProgram = this._gl.createProgram();
  290. this._gl.attachShader(shaderProgram, vertexShader);
  291. this._gl.attachShader(shaderProgram, fragmentShader);
  292. this._gl.linkProgram(shaderProgram);
  293. var error = this._gl.getProgramInfoLog(shaderProgram);
  294. if (error) {
  295. throw new Error(error);
  296. }
  297. this._gl.deleteShader(vertexShader);
  298. this._gl.deleteShader(fragmentShader);
  299. return shaderProgram;
  300. };
  301. BABYLON.Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  302. var results = [];
  303. for (var index = 0; index < uniformsNames.length; index++) {
  304. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  305. }
  306. return results;
  307. };
  308. BABYLON.Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  309. var results = [];
  310. for (var index = 0; index < attributesNames.length; index++) {
  311. try {
  312. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  313. } catch (e) {
  314. results.push(-1);
  315. }
  316. }
  317. return results;
  318. };
  319. BABYLON.Engine.prototype.enableEffect = function (effect) {
  320. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  321. return;
  322. }
  323. // Use program
  324. this._gl.useProgram(effect.getProgram());
  325. for (var index = 0; index < effect.getAttributesCount() ; index++) {
  326. // Attributes
  327. var order = effect.getAttribute(index);
  328. if (order >= 0) {
  329. this._gl.enableVertexAttribArray(effect.getAttribute(index));
  330. }
  331. }
  332. this._currentEffect = effect;
  333. };
  334. BABYLON.Engine.prototype.setMatrix = function (uniform, matrix) {
  335. if (!uniform)
  336. return;
  337. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  338. };
  339. BABYLON.Engine.prototype.setVector2 = function (uniform, x, y) {
  340. if (!uniform)
  341. return;
  342. this._gl.uniform2f(uniform, x, y);
  343. };
  344. BABYLON.Engine.prototype.setVector3 = function (uniform, vector3) {
  345. if (!uniform)
  346. return;
  347. this._gl.uniform3f(uniform, vector3.x, vector3.y, vector3.z);
  348. };
  349. BABYLON.Engine.prototype.setFloat2 = function (uniform, x, y) {
  350. if (!uniform)
  351. return;
  352. this._gl.uniform2f(uniform, x, y);
  353. };
  354. BABYLON.Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  355. if (!uniform)
  356. return;
  357. this._gl.uniform3f(uniform, x, y, z);
  358. };
  359. BABYLON.Engine.prototype.setBool = function (uniform, bool) {
  360. if (!uniform)
  361. return;
  362. this._gl.uniform1i(uniform, bool);
  363. };
  364. BABYLON.Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  365. if (!uniform)
  366. return;
  367. this._gl.uniform4f(uniform, x, y, z, w);
  368. };
  369. BABYLON.Engine.prototype.setColor3 = function (uniform, color3) {
  370. if (!uniform)
  371. return;
  372. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  373. };
  374. BABYLON.Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  375. if (!uniform)
  376. return;
  377. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  378. };
  379. // States
  380. BABYLON.Engine.prototype.setState = function (culling) {
  381. // Culling
  382. if (this._currentState.culling !== culling) {
  383. if (culling) {
  384. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  385. this._gl.enable(this._gl.CULL_FACE);
  386. } else {
  387. this._gl.disable(this._gl.CULL_FACE);
  388. }
  389. this._currentState.culling = culling;
  390. }
  391. };
  392. BABYLON.Engine.prototype.setDepthBuffer = function (enable) {
  393. if (enable) {
  394. this._gl.enable(this._gl.DEPTH_TEST);
  395. } else {
  396. this._gl.disable(this._gl.DEPTH_TEST);
  397. }
  398. };
  399. BABYLON.Engine.prototype.setDepthWrite = function (enable) {
  400. this._gl.depthMask(enable);
  401. };
  402. BABYLON.Engine.prototype.setColorWrite = function (enable) {
  403. this._gl.colorMask(enable, enable, enable, enable);
  404. };
  405. BABYLON.Engine.prototype.setAlphaMode = function (mode) {
  406. switch (mode) {
  407. case BABYLON.Engine.ALPHA_DISABLE:
  408. this.setDepthWrite(true);
  409. this._gl.disable(this._gl.BLEND);
  410. break;
  411. case BABYLON.Engine.ALPHA_COMBINE:
  412. this.setDepthWrite(false);
  413. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ZERO, this._gl.ONE);
  414. this._gl.enable(this._gl.BLEND);
  415. break;
  416. case BABYLON.Engine.ALPHA_ADD:
  417. this.setDepthWrite(false);
  418. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  419. this._gl.enable(this._gl.BLEND);
  420. break;
  421. }
  422. };
  423. BABYLON.Engine.prototype.setAlphaTesting = function (enable) {
  424. this._alphaTest = enable;
  425. };
  426. BABYLON.Engine.prototype.getAlphaTesting = function () {
  427. return this._alphaTest;
  428. };
  429. // Textures
  430. BABYLON.Engine.prototype.wipeCaches = function () {
  431. this._activeTexturesCache = [];
  432. this._currentEffect = null;
  433. this._currentState = {
  434. culling: null
  435. };
  436. this._cachedVertexBuffers = null;
  437. this._cachedVertexBuffers = null;
  438. };
  439. var getExponantOfTwo = function (value, max) {
  440. var count = 1;
  441. do {
  442. count *= 2;
  443. } while (count < value);
  444. if (count > max)
  445. count = max;
  446. return count;
  447. };
  448. BABYLON.Engine.prototype.createTexture = function (url, noMipmap, invertY, scene) {
  449. var texture = this._gl.createTexture();
  450. var that = this;
  451. var img = new Image();
  452. img.onload = function () {
  453. that._workingCanvas.width = getExponantOfTwo(img.width, that._caps.maxTextureSize);
  454. that._workingCanvas.height = getExponantOfTwo(img.height, that._caps.maxTextureSize);
  455. that._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, that._workingCanvas.width, that._workingCanvas.height);
  456. that._gl.bindTexture(that._gl.TEXTURE_2D, texture);
  457. that._gl.pixelStorei(that._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? true : invertY);
  458. that._gl.texImage2D(that._gl.TEXTURE_2D, 0, that._gl.RGBA, that._gl.RGBA, that._gl.UNSIGNED_BYTE, that._workingCanvas);
  459. that._gl.texParameteri(that._gl.TEXTURE_2D, that._gl.TEXTURE_MAG_FILTER, that._gl.LINEAR);
  460. if (noMipmap) {
  461. that._gl.texParameteri(that._gl.TEXTURE_2D, that._gl.TEXTURE_MIN_FILTER, that._gl.LINEAR);
  462. } else {
  463. that._gl.texParameteri(that._gl.TEXTURE_2D, that._gl.TEXTURE_MIN_FILTER, that._gl.LINEAR_MIPMAP_LINEAR);
  464. that._gl.generateMipmap(that._gl.TEXTURE_2D);
  465. }
  466. that._gl.bindTexture(that._gl.TEXTURE_2D, null);
  467. that._activeTexturesCache = [];
  468. texture._baseWidth = img.width;
  469. texture._baseHeight = img.height;
  470. texture._width = that._workingCanvas.width;
  471. texture._height = that._workingCanvas.height;
  472. texture.isReady = true;
  473. scene._removePendingData(img);
  474. };
  475. img.onerror = function () {
  476. scene._removePendingData(img);
  477. };
  478. scene._addPendingData(img);
  479. img.src = url;
  480. texture.url = url;
  481. texture.noMipmap = noMipmap;
  482. texture.references = 1;
  483. this._loadedTexturesCache.push(texture);
  484. return texture;
  485. };
  486. BABYLON.Engine.prototype.createDynamicTexture = function (size, generateMipMaps) {
  487. var texture = this._gl.createTexture();
  488. var width = getExponantOfTwo(size, this._caps.maxTextureSize);
  489. var height = width;
  490. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  491. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
  492. if (!generateMipMaps) {
  493. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
  494. } else {
  495. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR_MIPMAP_LINEAR);
  496. }
  497. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  498. this._activeTexturesCache = [];
  499. texture._baseWidth = width;
  500. texture._baseHeight = height;
  501. texture._width = width;
  502. texture._height = height;
  503. texture.isReady = false;
  504. texture.generateMipMaps = generateMipMaps;
  505. texture.references = 1;
  506. this._loadedTexturesCache.push(texture);
  507. return texture;
  508. };
  509. BABYLON.Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  510. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  511. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY);
  512. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  513. if (texture.generateMipMaps) {
  514. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  515. }
  516. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  517. this._activeTexturesCache = [];
  518. texture.isReady = true;
  519. };
  520. BABYLON.Engine.prototype.updateVideoTexture = function (texture, video) {
  521. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  522. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, false);
  523. // Scale the video if it is a NPOT
  524. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  525. if (!texture._workingCanvas) {
  526. texture._workingCanvas = document.createElement("canvas");
  527. texture._workingContext = texture._workingCanvas.getContext("2d");
  528. texture._workingCanvas.width = texture._width;
  529. texture._workingCanvas.height = texture._height;
  530. }
  531. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  532. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  533. } else {
  534. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  535. }
  536. if (texture.generateMipMaps) {
  537. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  538. }
  539. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  540. this._activeTexturesCache = [];
  541. texture.isReady = true;
  542. };
  543. BABYLON.Engine.prototype.createRenderTargetTexture = function (size, generateMipMaps) {
  544. var gl = this._gl;
  545. var texture = gl.createTexture();
  546. gl.bindTexture(gl.TEXTURE_2D, texture);
  547. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  548. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, generateMipMaps ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  549. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  550. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  551. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  552. // Create the depth buffer
  553. var depthBuffer = gl.createRenderbuffer();
  554. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  555. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  556. // Create the framebuffer
  557. var framebuffer = gl.createFramebuffer();
  558. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  559. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  560. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  561. // Unbind
  562. gl.bindTexture(gl.TEXTURE_2D, null);
  563. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  564. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  565. texture._framebuffer = framebuffer;
  566. texture._depthBuffer = depthBuffer;
  567. texture._size = size;
  568. texture.isReady = true;
  569. texture.generateMipMaps = generateMipMaps;
  570. texture.references = 1;
  571. this._activeTexturesCache = [];
  572. this._loadedTexturesCache.push(texture);
  573. return texture;
  574. };
  575. var extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  576. var cascadeLoad = function (rootUrl, index, loadedImages, scene, onfinish) {
  577. var img = new Image();
  578. img.onload = function () {
  579. loadedImages.push(this);
  580. scene._removePendingData(img);
  581. if (index != extensions.length - 1) {
  582. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish);
  583. } else {
  584. onfinish(loadedImages);
  585. }
  586. };
  587. img.onerrror = function () {
  588. scene._removePendingData(img);
  589. };
  590. scene._addPendingData(img);
  591. img.src = rootUrl + extensions[index];
  592. };
  593. BABYLON.Engine.prototype.createCubeTexture = function (rootUrl, scene) {
  594. var gl = this._gl;
  595. var texture = gl.createTexture();
  596. texture.isCube = true;
  597. texture.url = rootUrl;
  598. texture.references = 1;
  599. this._loadedTexturesCache.push(texture);
  600. var that = this;
  601. cascadeLoad(rootUrl, 0, [], scene, function (imgs) {
  602. var width = getExponantOfTwo(imgs[0].width);
  603. var height = width;
  604. that._workingCanvas.width = width;
  605. that._workingCanvas.height = height;
  606. var faces = [
  607. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  608. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  609. ];
  610. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  611. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
  612. for (var index = 0; index < faces.length; index++) {
  613. that._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  614. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, that._workingCanvas);
  615. }
  616. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  617. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  618. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
  619. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  620. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  621. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  622. that._activeTexturesCache = [];
  623. texture._width = width;
  624. texture._height = height;
  625. texture.isReady = true;
  626. });
  627. return texture;
  628. };
  629. BABYLON.Engine.prototype._releaseTexture = function (texture) {
  630. var gl = this._gl;
  631. if (texture._framebuffer) {
  632. gl.deleteFramebuffer(texture._framebuffer);
  633. }
  634. if (texture._depthBuffer) {
  635. gl.deleteRenderbuffer(texture._depthBuffer);
  636. }
  637. gl.deleteTexture(texture);
  638. // Unbind channels
  639. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  640. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  641. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  642. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  643. this._activeTexturesCache[channel] = null;
  644. }
  645. };
  646. BABYLON.Engine.prototype.bindSamplers = function (effect) {
  647. this._gl.useProgram(effect.getProgram());
  648. var samplers = effect.getSamplers();
  649. for (var index = 0; index < samplers.length; index++) {
  650. var uniform = effect.getUniform(samplers[index]);
  651. this._gl.uniform1i(uniform, index);
  652. }
  653. this._currentEffect = null;
  654. };
  655. BABYLON.Engine.prototype.setTexture = function (channel, texture) {
  656. if (channel < 0) {
  657. return;
  658. }
  659. if (!texture || !texture.isReady()) {
  660. if (this._activeTexturesCache[channel] != null) {
  661. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  662. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  663. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  664. this._activeTexturesCache[channel] = null;
  665. }
  666. return;
  667. }
  668. if (texture instanceof BABYLON.VideoTexture) {
  669. if (texture._update()) {
  670. this._activeTexturesCache[channel] = null;
  671. }
  672. }
  673. if (this._activeTexturesCache[channel] == texture) {
  674. return;
  675. }
  676. this._activeTexturesCache[channel] = texture;
  677. var internalTexture = texture.getInternalTexture();
  678. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  679. if (internalTexture.isCube) {
  680. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  681. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  682. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  683. 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);
  684. 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);
  685. }
  686. } else {
  687. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  688. if (internalTexture._cachedWrapU !== texture.wrapU) {
  689. internalTexture._cachedWrapU = texture.wrapU;
  690. switch (texture.wrapU) {
  691. case BABYLON.Texture.WRAP_ADDRESSMODE:
  692. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  693. break;
  694. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  695. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  696. break;
  697. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  698. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  699. break;
  700. }
  701. }
  702. if (internalTexture._cachedWrapV !== texture.wrapV) {
  703. internalTexture._cachedWrapV = texture.wrapV;
  704. switch (texture.wrapV) {
  705. case BABYLON.Texture.WRAP_ADDRESSMODE:
  706. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  707. break;
  708. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  710. break;
  711. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  712. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  713. break;
  714. }
  715. }
  716. }
  717. };
  718. // Dispose
  719. BABYLON.Engine.prototype.dispose = function () {
  720. // Release scenes
  721. while (this.scenes.length) {
  722. this.scenes[0].dispose();
  723. }
  724. // Release effects
  725. for (var name in this._compiledEffects.length) {
  726. this._gl.deleteProgram(this._compiledEffects[name]._program);
  727. }
  728. };
  729. // Statics
  730. BABYLON.Engine.ShadersRepository = "Babylon/Shaders/";
  731. BABYLON.Engine.ALPHA_DISABLE = 0;
  732. BABYLON.Engine.ALPHA_ADD = 1;
  733. BABYLON.Engine.ALPHA_COMBINE = 2;
  734. BABYLON.Engine.epsilon = 0.001;
  735. BABYLON.Engine.collisionsEpsilon = 0.001;
  736. BABYLON.Engine.isSupported = function () {
  737. try {
  738. var tempcanvas = document.createElement("canvas");
  739. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  740. return gl != null && !!window.WebGLRenderingContext;
  741. } catch (e) {
  742. return false;
  743. }
  744. };
  745. })();