babylon.engine.js 36 KB

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