babylon.engine.js 35 KB

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