babylon.engine.ts 49 KB

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