babylon.engine.ts 49 KB

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