babylon.engine.ts 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string): WebGLShader => {
  3. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5. gl.compileShader(shader);
  6. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7. throw new Error(gl.getShaderInfoLog(shader));
  8. }
  9. return shader;
  10. };
  11. var getExponantOfTwo = (value: number, max: number): number => {
  12. var count = 1;
  13. do {
  14. count *= 2;
  15. } while (count < value);
  16. if (count > max)
  17. count = max;
  18. return count;
  19. };
  20. var prepareWebGLTexture = (texture: WebGLTexture, gl: WebGLRenderingContext, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  21. processFunction: (width: number, height: number) => void) => {
  22. var engine = scene.getEngine();
  23. var potWidth = getExponantOfTwo(width, engine.getCaps().maxTextureSize);
  24. var potHeight = getExponantOfTwo(height, engine.getCaps().maxTextureSize);
  25. gl.bindTexture(gl.TEXTURE_2D, texture);
  26. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  27. processFunction(potWidth, potHeight);
  28. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  29. if (noMipmap) {
  30. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  31. } else {
  32. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
  33. if (!isCompressed) {
  34. gl.generateMipmap(gl.TEXTURE_2D);
  35. }
  36. }
  37. gl.bindTexture(gl.TEXTURE_2D, null);
  38. engine._activeTexturesCache = [];
  39. texture._baseWidth = width;
  40. texture._baseHeight = height;
  41. texture._width = potWidth;
  42. texture._height = potHeight;
  43. texture.isReady = true;
  44. scene._removePendingData(texture);
  45. };
  46. // ANY
  47. var cascadeLoad = (rootUrl: string, index: number, loadedImages: HTMLImageElement[], scene,
  48. onfinish: (images: HTMLImageElement[]) => void, extensions: string[]) => {
  49. var img: HTMLImageElement;
  50. var onload = () => {
  51. loadedImages.push(img);
  52. scene._removePendingData(img);
  53. if (index != extensions.length - 1) {
  54. cascadeLoad(rootUrl, index + 1, loadedImages, scene, onfinish, extensions);
  55. } else {
  56. onfinish(loadedImages);
  57. }
  58. };
  59. var onerror = () => {
  60. scene._removePendingData(img);
  61. };
  62. img = BABYLON.Tools.LoadImage(rootUrl + extensions[index], onload, onerror, scene.database);
  63. scene._addPendingData(img);
  64. };
  65. export class EngineCapabilities {
  66. public maxTexturesImageUnits: number;
  67. public maxTextureSize: number;
  68. public maxCubemapTextureSize: number;
  69. public maxRenderTextureSize: number;
  70. public standardDerivatives: boolean;
  71. public s3tc;
  72. public textureFloat: boolean;
  73. public textureAnisotropicFilterExtension;
  74. public maxAnisotropy: number;
  75. public instancedArrays;
  76. }
  77. export class Engine {
  78. // Const statics
  79. private static _ALPHA_DISABLE = 0;
  80. private static _ALPHA_ADD = 1;
  81. private static _ALPHA_COMBINE = 2;
  82. private static _DELAYLOADSTATE_NONE = 0;
  83. private static _DELAYLOADSTATE_LOADED = 1;
  84. private static _DELAYLOADSTATE_LOADING = 2;
  85. private static _DELAYLOADSTATE_NOTLOADED = 4;
  86. public static get ALPHA_DISABLE(): number {
  87. return Engine._ALPHA_DISABLE;
  88. }
  89. public static get ALPHA_ADD(): number {
  90. return Engine._ALPHA_ADD;
  91. }
  92. public static get ALPHA_COMBINE(): number {
  93. return Engine._ALPHA_COMBINE;
  94. }
  95. public static get DELAYLOADSTATE_NONE(): number {
  96. return Engine._DELAYLOADSTATE_NONE;
  97. }
  98. public static get DELAYLOADSTATE_LOADED(): number {
  99. return Engine._DELAYLOADSTATE_LOADED;
  100. }
  101. public static get DELAYLOADSTATE_LOADING(): number {
  102. return Engine._DELAYLOADSTATE_LOADING;
  103. }
  104. public static get DELAYLOADSTATE_NOTLOADED(): number {
  105. return Engine._DELAYLOADSTATE_NOTLOADED;
  106. }
  107. // Updatable statics so stick with vars here
  108. public static Epsilon = 0.001;
  109. public static CollisionsEpsilon = 0.001;
  110. public static ShadersRepository = "Babylon/Shaders/";
  111. // Public members
  112. public isFullscreen = false;
  113. public isPointerLock = false;
  114. public forceWireframe = false;
  115. public cullBackFaces = true;
  116. public renderEvenInBackground = true;
  117. public scenes = new Array<Scene>();
  118. // Private Members
  119. private _gl: WebGLRenderingContext;
  120. private _renderingCanvas: HTMLCanvasElement;
  121. private _windowIsBackground = false;
  122. private _onBlur: () => void;
  123. private _onFocus: () => void;
  124. private _onFullscreenChange: () => void;
  125. private _onPointerLockChange: () => void;
  126. private _hardwareScalingLevel: number;
  127. private _caps: EngineCapabilities;
  128. private _pointerLockRequested: boolean;
  129. private _alphaTest: boolean;
  130. private _runningLoop = false;
  131. private _renderFunction: () => void;
  132. // Cache
  133. private _loadedTexturesCache = new Array<WebGLTexture>();
  134. public _activeTexturesCache = new Array<BaseTexture>();
  135. private _currentEffect: Effect;
  136. private _cullingState: boolean;
  137. private _compiledEffects = {};
  138. private _vertexAttribArrays: boolean[];
  139. private _depthMask = false;
  140. private _cachedViewport: Viewport;
  141. private _cachedVertexBuffers: any;
  142. private _cachedIndexBuffer: WebGLBuffer;
  143. private _cachedEffectForVertexBuffers: Effect;
  144. private _currentRenderTarget: WebGLTexture;
  145. private _workingCanvas: HTMLCanvasElement;
  146. private _workingContext: CanvasRenderingContext2D;
  147. constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?) {
  148. this._renderingCanvas = canvas;
  149. options = options || {};
  150. options.antialias = antialias;
  151. // GL
  152. try {
  153. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  154. } catch (e) {
  155. throw new Error("WebGL not supported");
  156. }
  157. if (!this._gl) {
  158. throw new Error("WebGL not supported");
  159. }
  160. this._onBlur = () => {
  161. this._windowIsBackground = true;
  162. };
  163. this._onFocus = () => {
  164. this._windowIsBackground = false;
  165. };
  166. window.addEventListener("blur", this._onBlur);
  167. window.addEventListener("focus", this._onFocus);
  168. // Textures
  169. this._workingCanvas = document.createElement("canvas");
  170. this._workingContext = this._workingCanvas.getContext("2d");
  171. // Viewport
  172. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  173. this.resize();
  174. // Caps
  175. this._caps = new EngineCapabilities();
  176. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  177. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  178. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  179. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  180. // Extensions
  181. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  182. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  183. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  184. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  185. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  186. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  187. // Depth buffer
  188. this.setDepthBuffer(true);
  189. this.setDepthFunctionToLessOrEqual();
  190. this.setDepthWrite(true);
  191. // Fullscreen
  192. this._onFullscreenChange = () => {
  193. if (document.fullscreen !== undefined) {
  194. this.isFullscreen = document.fullscreen;
  195. } else if (document.mozFullScreen !== undefined) {
  196. this.isFullscreen = document.mozFullScreen;
  197. } else if (document.webkitIsFullScreen !== undefined) {
  198. this.isFullscreen = document.webkitIsFullScreen;
  199. } else if (document.msIsFullScreen !== undefined) {
  200. this.isFullscreen = document.msIsFullScreen;
  201. }
  202. // Pointer lock
  203. if (this.isFullscreen && this._pointerLockRequested) {
  204. canvas.requestPointerLock = canvas.requestPointerLock ||
  205. canvas.msRequestPointerLock ||
  206. canvas.mozRequestPointerLock ||
  207. canvas.webkitRequestPointerLock;
  208. if (canvas.requestPointerLock) {
  209. canvas.requestPointerLock();
  210. }
  211. }
  212. };
  213. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  214. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  215. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  216. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  217. // Pointer lock
  218. this._onPointerLockChange = () => {
  219. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  220. document.webkitPointerLockElement === canvas ||
  221. document.msPointerLockElement === canvas ||
  222. document.pointerLockElement === canvas
  223. );
  224. };
  225. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  226. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  227. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  228. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  229. }
  230. public getAspectRatio(camera: Camera): number {
  231. var viewport = camera.viewport;
  232. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  233. }
  234. public getRenderWidth(): number {
  235. if (this._currentRenderTarget) {
  236. return this._currentRenderTarget._width;
  237. }
  238. return this._renderingCanvas.width;
  239. }
  240. public getRenderHeight(): number {
  241. if (this._currentRenderTarget) {
  242. return this._currentRenderTarget._height;
  243. }
  244. return this._renderingCanvas.height;
  245. }
  246. public getRenderingCanvas(): HTMLCanvasElement {
  247. return this._renderingCanvas;
  248. }
  249. public setHardwareScalingLevel(level: number): void {
  250. this._hardwareScalingLevel = level;
  251. this.resize();
  252. }
  253. public getHardwareScalingLevel(): number {
  254. return this._hardwareScalingLevel;
  255. }
  256. public getLoadedTexturesCache(): WebGLTexture[] {
  257. return this._loadedTexturesCache;
  258. }
  259. public getCaps(): EngineCapabilities {
  260. return this._caps;
  261. }
  262. // Methods
  263. public setDepthFunctionToGreater(): void {
  264. this._gl.depthFunc(this._gl.GREATER);
  265. }
  266. public setDepthFunctionToGreaterOrEqual(): void {
  267. this._gl.depthFunc(this._gl.GEQUAL);
  268. }
  269. public setDepthFunctionToLess(): void {
  270. this._gl.depthFunc(this._gl.LESS);
  271. }
  272. public setDepthFunctionToLessOrEqual(): void {
  273. this._gl.depthFunc(this._gl.LEQUAL);
  274. }
  275. public stopRenderLoop(): void {
  276. this._renderFunction = null;
  277. this._runningLoop = false;
  278. }
  279. public _renderLoop(): void {
  280. var shouldRender = true;
  281. if (!this.renderEvenInBackground && this._windowIsBackground) {
  282. shouldRender = false;
  283. }
  284. if (shouldRender) {
  285. // Start new frame
  286. this.beginFrame();
  287. if (this._renderFunction) {
  288. this._renderFunction();
  289. }
  290. // Present
  291. this.endFrame();
  292. }
  293. if (this._runningLoop) {
  294. // Register new frame
  295. BABYLON.Tools.QueueNewFrame(() => {
  296. this._renderLoop();
  297. });
  298. }
  299. }
  300. public runRenderLoop(renderFunction: () => void): void {
  301. this._runningLoop = true;
  302. this._renderFunction = renderFunction;
  303. BABYLON.Tools.QueueNewFrame(() => {
  304. this._renderLoop();
  305. });
  306. }
  307. public switchFullscreen(requestPointerLock: boolean): void {
  308. if (this.isFullscreen) {
  309. BABYLON.Tools.ExitFullscreen();
  310. } else {
  311. this._pointerLockRequested = requestPointerLock;
  312. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  313. }
  314. }
  315. public clear(color: any, backBuffer: boolean, depthStencil: boolean): void {
  316. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  317. if (this._depthMask) {
  318. this._gl.clearDepth(1.0);
  319. }
  320. var mode = 0;
  321. if (backBuffer)
  322. mode |= this._gl.COLOR_BUFFER_BIT;
  323. if (depthStencil && this._depthMask)
  324. mode |= this._gl.DEPTH_BUFFER_BIT;
  325. this._gl.clear(mode);
  326. }
  327. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  328. var width = requiredWidth || this._renderingCanvas.width;
  329. var height = requiredHeight || this._renderingCanvas.height;
  330. var x = viewport.x || 0;
  331. var y = viewport.y || 0;
  332. this._cachedViewport = viewport;
  333. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  334. }
  335. public setDirectViewport(x: number, y: number, width: number, height: number): void {
  336. this._cachedViewport = null;
  337. this._gl.viewport(x, y, width, height);
  338. }
  339. public beginFrame(): void {
  340. BABYLON.Tools._MeasureFps();
  341. }
  342. public endFrame(): void {
  343. this.flushFramebuffer();
  344. }
  345. public resize(): void {
  346. this._renderingCanvas.width = this._renderingCanvas.clientWidth / this._hardwareScalingLevel;
  347. this._renderingCanvas.height = this._renderingCanvas.clientHeight / this._hardwareScalingLevel;
  348. }
  349. public bindFramebuffer(texture: WebGLTexture): void {
  350. this._currentRenderTarget = texture;
  351. var gl = this._gl;
  352. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  353. this._gl.viewport(0, 0, texture._width, texture._height);
  354. this.wipeCaches();
  355. }
  356. public unBindFramebuffer(texture: WebGLTexture): void {
  357. this._currentRenderTarget = null;
  358. if (texture.generateMipMaps) {
  359. var gl = this._gl;
  360. gl.bindTexture(gl.TEXTURE_2D, texture);
  361. gl.generateMipmap(gl.TEXTURE_2D);
  362. gl.bindTexture(gl.TEXTURE_2D, null);
  363. }
  364. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  365. }
  366. public flushFramebuffer(): void {
  367. this._gl.flush();
  368. }
  369. public restoreDefaultFramebuffer(): void {
  370. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  371. this.setViewport(this._cachedViewport);
  372. this.wipeCaches();
  373. }
  374. // VBOs
  375. private _resetVertexBufferBinding(): void {
  376. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  377. this._cachedVertexBuffers = null;
  378. }
  379. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  380. var vbo = this._gl.createBuffer();
  381. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  382. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  383. this._resetVertexBufferBinding();
  384. vbo.references = 1;
  385. return vbo;
  386. }
  387. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  388. var vbo = this._gl.createBuffer();
  389. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  390. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  391. this._resetVertexBufferBinding();
  392. vbo.references = 1;
  393. return vbo;
  394. }
  395. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, length?: number): void {
  396. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  397. //if (length && length != vertices.length) {
  398. // this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices, 0, length));
  399. //} else {
  400. if (vertices instanceof Float32Array) {
  401. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  402. } else {
  403. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  404. }
  405. // }
  406. this._resetVertexBufferBinding();
  407. }
  408. private _resetIndexBufferBinding(): void {
  409. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  410. this._cachedIndexBuffer = null;
  411. }
  412. public createIndexBuffer(indices: number[]): WebGLBuffer {
  413. var vbo = this._gl.createBuffer();
  414. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  415. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  416. this._resetIndexBufferBinding();
  417. vbo.references = 1;
  418. return vbo;
  419. }
  420. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  421. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  422. this._cachedVertexBuffers = vertexBuffer;
  423. this._cachedEffectForVertexBuffers = effect;
  424. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  425. var offset = 0;
  426. for (var index = 0; index < vertexDeclaration.length; index++) {
  427. var order = effect.getAttributeLocation(index);
  428. if (order >= 0) {
  429. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  430. }
  431. offset += vertexDeclaration[index] * 4;
  432. }
  433. }
  434. if (this._cachedIndexBuffer !== indexBuffer) {
  435. this._cachedIndexBuffer = indexBuffer;
  436. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  437. }
  438. }
  439. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  440. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  441. this._cachedVertexBuffers = vertexBuffers;
  442. this._cachedEffectForVertexBuffers = effect;
  443. var attributes = effect.getAttributesNames();
  444. for (var index = 0; index < attributes.length; index++) {
  445. var order = effect.getAttributeLocation(index);
  446. if (order >= 0) {
  447. var vertexBuffer = vertexBuffers[attributes[index]];
  448. if (!vertexBuffer) {
  449. continue;
  450. }
  451. var stride = vertexBuffer.getStrideSize();
  452. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  453. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  454. }
  455. }
  456. }
  457. if (this._cachedIndexBuffer !== indexBuffer) {
  458. this._cachedIndexBuffer = indexBuffer;
  459. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  460. }
  461. }
  462. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  463. buffer.references--;
  464. if (buffer.references === 0) {
  465. this._gl.deleteBuffer(buffer);
  466. return true;
  467. }
  468. return false;
  469. }
  470. public createInstancesBuffer(capacity: number): WebGLBuffer {
  471. var buffer = this._gl.createBuffer();
  472. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  473. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  474. return buffer;
  475. }
  476. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void {
  477. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  478. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  479. for (var index = 0; index < 4; index++) {
  480. var offsetLocation = offsetLocations[index];
  481. this._gl.enableVertexAttribArray(offsetLocation);
  482. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  483. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  484. }
  485. }
  486. public unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void {
  487. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  488. for (var index = 0; index < 4; index++) {
  489. var offsetLocation = offsetLocations[index];
  490. this._gl.disableVertexAttribArray(offsetLocation);
  491. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  492. }
  493. }
  494. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  495. if (instancesCount) {
  496. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  497. return;
  498. }
  499. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  500. }
  501. // Shaders
  502. public _releaseEffect(effect: Effect): void {
  503. if (this._compiledEffects[effect._key]) {
  504. delete this._compiledEffects[effect._key];
  505. if (effect.getProgram()) {
  506. this._gl.deleteProgram(effect.getProgram());
  507. }
  508. }
  509. }
  510. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, optionalDefines?: string[],
  511. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  512. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  513. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  514. var name = vertex + "+" + fragment + "@" + defines;
  515. if (this._compiledEffects[name]) {
  516. return this._compiledEffects[name];
  517. }
  518. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, optionalDefines, onCompiled, onError);
  519. effect._key = name;
  520. this._compiledEffects[name] = effect;
  521. return effect;
  522. }
  523. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  524. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  525. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  526. var shaderProgram = this._gl.createProgram();
  527. this._gl.attachShader(shaderProgram, vertexShader);
  528. this._gl.attachShader(shaderProgram, fragmentShader);
  529. this._gl.linkProgram(shaderProgram);
  530. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  531. if (!linked) {
  532. var error = this._gl.getProgramInfoLog(shaderProgram);
  533. if (error) {
  534. throw new Error(error);
  535. }
  536. }
  537. this._gl.deleteShader(vertexShader);
  538. this._gl.deleteShader(fragmentShader);
  539. return shaderProgram;
  540. }
  541. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  542. var results = [];
  543. for (var index = 0; index < uniformsNames.length; index++) {
  544. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  545. }
  546. return results;
  547. }
  548. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  549. var results = [];
  550. for (var index = 0; index < attributesNames.length; index++) {
  551. try {
  552. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  553. } catch (e) {
  554. results.push(-1);
  555. }
  556. }
  557. return results;
  558. }
  559. public enableEffect(effect: Effect): void {
  560. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  561. return;
  562. }
  563. this._vertexAttribArrays = this._vertexAttribArrays || [];
  564. // Use program
  565. this._gl.useProgram(effect.getProgram());
  566. for (var i in this._vertexAttribArrays) {
  567. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  568. continue;
  569. }
  570. this._vertexAttribArrays[i] = false;
  571. this._gl.disableVertexAttribArray(i);
  572. }
  573. var attributesCount = effect.getAttributesCount();
  574. for (var index = 0; index < attributesCount; index++) {
  575. // Attributes
  576. var order = effect.getAttributeLocation(index);
  577. if (order >= 0) {
  578. this._vertexAttribArrays[order] = true;
  579. this._gl.enableVertexAttribArray(order);
  580. }
  581. }
  582. this._currentEffect = effect;
  583. }
  584. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  585. if (!uniform)
  586. return;
  587. this._gl.uniform1fv(uniform, array);
  588. }
  589. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  590. if (!uniform)
  591. return;
  592. this._gl.uniformMatrix4fv(uniform, false, matrices);
  593. }
  594. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  595. if (!uniform)
  596. return;
  597. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  598. }
  599. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  600. if (!uniform)
  601. return;
  602. this._gl.uniform1f(uniform, value);
  603. }
  604. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  605. if (!uniform)
  606. return;
  607. this._gl.uniform2f(uniform, x, y);
  608. }
  609. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  610. if (!uniform)
  611. return;
  612. this._gl.uniform3f(uniform, x, y, z);
  613. }
  614. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  615. if (!uniform)
  616. return;
  617. this._gl.uniform1i(uniform, bool);
  618. }
  619. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  620. if (!uniform)
  621. return;
  622. this._gl.uniform4f(uniform, x, y, z, w);
  623. }
  624. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  625. if (!uniform)
  626. return;
  627. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  628. }
  629. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  630. if (!uniform)
  631. return;
  632. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  633. }
  634. // States
  635. public setState(culling: boolean): void {
  636. // Culling
  637. if (this._cullingState !== culling) {
  638. if (culling) {
  639. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  640. this._gl.enable(this._gl.CULL_FACE);
  641. } else {
  642. this._gl.disable(this._gl.CULL_FACE);
  643. }
  644. this._cullingState = culling;
  645. }
  646. }
  647. public setDepthBuffer(enable: boolean): void {
  648. if (enable) {
  649. this._gl.enable(this._gl.DEPTH_TEST);
  650. } else {
  651. this._gl.disable(this._gl.DEPTH_TEST);
  652. }
  653. }
  654. public setDepthWrite(enable: boolean): void {
  655. this._gl.depthMask(enable);
  656. this._depthMask = enable;
  657. }
  658. public setColorWrite(enable: boolean): void {
  659. this._gl.colorMask(enable, enable, enable, enable);
  660. }
  661. public setAlphaMode(mode: number): void {
  662. switch (mode) {
  663. case BABYLON.Engine.ALPHA_DISABLE:
  664. this.setDepthWrite(true);
  665. this._gl.disable(this._gl.BLEND);
  666. break;
  667. case BABYLON.Engine.ALPHA_COMBINE:
  668. this.setDepthWrite(false);
  669. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  670. this._gl.enable(this._gl.BLEND);
  671. break;
  672. case BABYLON.Engine.ALPHA_ADD:
  673. this.setDepthWrite(false);
  674. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  675. this._gl.enable(this._gl.BLEND);
  676. break;
  677. }
  678. }
  679. public setAlphaTesting(enable: boolean): void {
  680. this._alphaTest = enable;
  681. }
  682. public getAlphaTesting(): boolean {
  683. return this._alphaTest;
  684. }
  685. // Textures
  686. public wipeCaches(): void {
  687. this._activeTexturesCache = [];
  688. this._currentEffect = null;
  689. this._cullingState = null;
  690. this._cachedVertexBuffers = null;
  691. this._cachedIndexBuffer = null;
  692. this._cachedEffectForVertexBuffers = null;
  693. }
  694. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  695. var gl = this._gl;
  696. gl.bindTexture(gl.TEXTURE_2D, texture);
  697. var magFilter = gl.NEAREST;
  698. var minFilter = gl.NEAREST;
  699. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  700. magFilter = gl.LINEAR;
  701. minFilter = gl.LINEAR;
  702. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  703. magFilter = gl.LINEAR;
  704. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  705. }
  706. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  707. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  708. gl.bindTexture(gl.TEXTURE_2D, null);
  709. }
  710. public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene): WebGLTexture {
  711. var texture = this._gl.createTexture();
  712. var extension = url.substr(url.length - 4, 4).toLowerCase();
  713. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  714. var isTGA = (extension === ".tga");
  715. scene._addPendingData(texture);
  716. texture.url = url;
  717. texture.noMipmap = noMipmap;
  718. texture.references = 1;
  719. this._loadedTexturesCache.push(texture);
  720. if (isTGA) {
  721. BABYLON.Tools.LoadFile(url, arrayBuffer => {
  722. var data = new Uint8Array(arrayBuffer);
  723. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  724. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  725. Internals.TGATools.UploadContent(this._gl, data);
  726. });
  727. }, null, scene.database, true);
  728. } else if (isDDS) {
  729. BABYLON.Tools.LoadFile(url, data => {
  730. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  731. var loadMipmap = info.mipmapCount > 1 && !noMipmap;
  732. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, true, () => {
  733. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, loadMipmap);
  734. });
  735. }, null, scene.database, true);
  736. } else {
  737. var onload = (img) => {
  738. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  739. var isPot = (img.width == potWidth && img.height == potHeight);
  740. if (!isPot) {
  741. this._workingCanvas.width = potWidth;
  742. this._workingCanvas.height = potHeight;
  743. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  744. }
  745. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  746. });
  747. };
  748. var onerror = () => {
  749. scene._removePendingData(texture);
  750. };
  751. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  752. }
  753. return texture;
  754. }
  755. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean): WebGLTexture {
  756. var texture = this._gl.createTexture();
  757. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  758. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  759. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  760. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
  761. if (!generateMipMaps) {
  762. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
  763. } else {
  764. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR_MIPMAP_LINEAR);
  765. }
  766. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  767. this._activeTexturesCache = [];
  768. texture._baseWidth = width;
  769. texture._baseHeight = height;
  770. texture._width = width;
  771. texture._height = height;
  772. texture.isReady = false;
  773. texture.generateMipMaps = generateMipMaps;
  774. texture.references = 1;
  775. this._loadedTexturesCache.push(texture);
  776. return texture;
  777. }
  778. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  779. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  780. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  781. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  782. if (texture.generateMipMaps) {
  783. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  784. }
  785. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  786. this._activeTexturesCache = [];
  787. texture.isReady = true;
  788. }
  789. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  790. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  791. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  792. // Scale the video if it is a NPOT using the current working canvas
  793. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  794. if (!texture._workingCanvas) {
  795. texture._workingCanvas = document.createElement("canvas");
  796. texture._workingContext = texture._workingCanvas.getContext("2d");
  797. texture._workingCanvas.width = texture._width;
  798. texture._workingCanvas.height = texture._height;
  799. }
  800. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  801. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  802. } else {
  803. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  804. }
  805. if (texture.generateMipMaps) {
  806. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  807. }
  808. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  809. this._activeTexturesCache = [];
  810. texture.isReady = true;
  811. }
  812. public createRenderTargetTexture(size: any, options): WebGLTexture {
  813. // old version had a "generateMipMaps" arg instead of options.
  814. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  815. // in the same way, generateDepthBuffer is defaulted to true
  816. var generateMipMaps = false;
  817. var generateDepthBuffer = true;
  818. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  819. if (options !== undefined) {
  820. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  821. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  822. if (options.samplingMode !== undefined) {
  823. samplingMode = options.samplingMode;
  824. }
  825. }
  826. var gl = this._gl;
  827. var texture = gl.createTexture();
  828. gl.bindTexture(gl.TEXTURE_2D, texture);
  829. var width = size.width || size;
  830. var height = size.height || size;
  831. var magFilter = gl.NEAREST;
  832. var minFilter = gl.NEAREST;
  833. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  834. magFilter = gl.LINEAR;
  835. if (generateMipMaps) {
  836. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  837. } else {
  838. minFilter = gl.LINEAR;
  839. }
  840. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  841. magFilter = gl.LINEAR;
  842. if (generateMipMaps) {
  843. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  844. } else {
  845. minFilter = gl.LINEAR;
  846. }
  847. }
  848. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  849. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  850. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  851. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  852. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  853. var depthBuffer: WebGLRenderbuffer;
  854. // Create the depth buffer
  855. if (generateDepthBuffer) {
  856. depthBuffer = gl.createRenderbuffer();
  857. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  858. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  859. }
  860. // Create the framebuffer
  861. var framebuffer = gl.createFramebuffer();
  862. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  863. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  864. if (generateDepthBuffer) {
  865. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  866. }
  867. // Unbind
  868. gl.bindTexture(gl.TEXTURE_2D, null);
  869. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  870. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  871. texture._framebuffer = framebuffer;
  872. if (generateDepthBuffer) {
  873. texture._depthBuffer = depthBuffer;
  874. }
  875. texture._width = width;
  876. texture._height = height;
  877. texture.isReady = true;
  878. texture.generateMipMaps = generateMipMaps;
  879. texture.references = 1;
  880. this._activeTexturesCache = [];
  881. this._loadedTexturesCache.push(texture);
  882. return texture;
  883. }
  884. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  885. var gl = this._gl;
  886. var texture = gl.createTexture();
  887. texture.isCube = true;
  888. texture.url = rootUrl;
  889. texture.references = 1;
  890. this._loadedTexturesCache.push(texture);
  891. cascadeLoad(rootUrl, 0, [], scene, imgs => {
  892. var width = getExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  893. var height = width;
  894. this._workingCanvas.width = width;
  895. this._workingCanvas.height = height;
  896. var faces = [
  897. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  898. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  899. ];
  900. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  901. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  902. for (var index = 0; index < faces.length; index++) {
  903. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  904. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  905. }
  906. if (!noMipmap) {
  907. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  908. }
  909. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  910. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  911. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  912. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  913. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  914. this._activeTexturesCache = [];
  915. texture._width = width;
  916. texture._height = height;
  917. texture.isReady = true;
  918. }, extensions);
  919. return texture;
  920. }
  921. public _releaseTexture(texture: WebGLTexture): void {
  922. var gl = this._gl;
  923. if (texture._framebuffer) {
  924. gl.deleteFramebuffer(texture._framebuffer);
  925. }
  926. if (texture._depthBuffer) {
  927. gl.deleteRenderbuffer(texture._depthBuffer);
  928. }
  929. gl.deleteTexture(texture);
  930. // Unbind channels
  931. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  932. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  933. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  934. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  935. this._activeTexturesCache[channel] = null;
  936. }
  937. var index = this._loadedTexturesCache.indexOf(texture);
  938. if (index !== -1) {
  939. this._loadedTexturesCache.splice(index, 1);
  940. }
  941. }
  942. public bindSamplers(effect: Effect): void {
  943. this._gl.useProgram(effect.getProgram());
  944. var samplers = effect.getSamplers();
  945. for (var index = 0; index < samplers.length; index++) {
  946. var uniform = effect.getUniform(samplers[index]);
  947. this._gl.uniform1i(uniform, index);
  948. }
  949. this._currentEffect = null;
  950. }
  951. public _bindTexture(channel: number, texture: WebGLTexture): void {
  952. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  953. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  954. this._activeTexturesCache[channel] = null;
  955. }
  956. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  957. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  958. }
  959. public setTexture(channel: number, texture: BaseTexture): void {
  960. if (channel < 0) {
  961. return;
  962. }
  963. // Not ready?
  964. if (!texture || !texture.isReady()) {
  965. if (this._activeTexturesCache[channel] != null) {
  966. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  967. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  968. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  969. this._activeTexturesCache[channel] = null;
  970. }
  971. return;
  972. }
  973. // Video
  974. if (texture instanceof BABYLON.VideoTexture) {
  975. if ((<VideoTexture>texture).update()) {
  976. this._activeTexturesCache[channel] = null;
  977. }
  978. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  979. texture.delayLoad();
  980. return;
  981. }
  982. if (this._activeTexturesCache[channel] == texture) {
  983. return;
  984. }
  985. this._activeTexturesCache[channel] = texture;
  986. var internalTexture = texture.getInternalTexture();
  987. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  988. if (internalTexture.isCube) {
  989. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  990. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  991. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  992. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  993. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  994. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  995. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  996. }
  997. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  998. } else {
  999. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1000. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1001. internalTexture._cachedWrapU = texture.wrapU;
  1002. switch (texture.wrapU) {
  1003. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1004. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1005. break;
  1006. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1007. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1008. break;
  1009. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1010. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1011. break;
  1012. }
  1013. }
  1014. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1015. internalTexture._cachedWrapV = texture.wrapV;
  1016. switch (texture.wrapV) {
  1017. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1018. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1019. break;
  1020. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1021. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1022. break;
  1023. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1024. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1025. break;
  1026. }
  1027. }
  1028. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1029. }
  1030. }
  1031. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1032. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1033. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1034. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1035. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1036. }
  1037. }
  1038. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1039. var data = new Uint8Array(height * width * 4);
  1040. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1041. return data;
  1042. }
  1043. // Dispose
  1044. public dispose(): void {
  1045. this.stopRenderLoop();
  1046. // Release scenes
  1047. while (this.scenes.length) {
  1048. this.scenes[0].dispose();
  1049. }
  1050. // Release effects
  1051. for (var name in this._compiledEffects) {
  1052. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1053. }
  1054. // Events
  1055. window.removeEventListener("blur", this._onBlur);
  1056. window.removeEventListener("focus", this._onFocus);
  1057. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1058. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1059. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1060. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1061. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1062. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1063. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1064. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1065. }
  1066. // Statics
  1067. public static isSupported(): boolean {
  1068. try {
  1069. var tempcanvas = document.createElement("canvas");
  1070. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1071. return gl != null && !!window.WebGLRenderingContext;
  1072. } catch (e) {
  1073. return false;
  1074. }
  1075. }
  1076. }
  1077. }