babylon.engine.js 34 KB

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