babylon.engine.ts 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  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 _lastVertexAttribIndex = 0;
  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. public createVertexBuffer(vertices: number[]): WebGLBuffer {
  350. var vbo = this._gl.createBuffer();
  351. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  352. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  353. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  354. vbo.references = 1;
  355. return vbo;
  356. }
  357. public createDynamicVertexBuffer(capacity: number): WebGLBuffer {
  358. var vbo = this._gl.createBuffer();
  359. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  360. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  361. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  362. vbo.references = 1;
  363. return vbo;
  364. }
  365. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, length?: number): void {
  366. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  367. if (length && length != vertices.length) {
  368. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices, 0, length));
  369. } else {
  370. if (vertices instanceof Float32Array) {
  371. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  372. } else {
  373. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  374. }
  375. }
  376. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  377. }
  378. public createIndexBuffer(indices: number[]): WebGLBuffer {
  379. var vbo = this._gl.createBuffer();
  380. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  381. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  382. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  383. vbo.references = 1;
  384. return vbo;
  385. }
  386. public bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  387. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  388. this._cachedVertexBuffers = vertexBuffer;
  389. this._cachedEffectForVertexBuffers = effect;
  390. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  391. var offset = 0;
  392. for (var index = 0; index < vertexDeclaration.length; index++) {
  393. var order = effect.getAttribute(index);
  394. if (order >= 0) {
  395. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  396. }
  397. offset += vertexDeclaration[index] * 4;
  398. }
  399. }
  400. if (this._cachedIndexBuffer !== indexBuffer) {
  401. this._cachedIndexBuffer = indexBuffer;
  402. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  403. }
  404. }
  405. public bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void {
  406. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  407. this._cachedVertexBuffers = vertexBuffers;
  408. this._cachedEffectForVertexBuffers = effect;
  409. var attributes = effect.getAttributesNames();
  410. for (var index = 0; index < attributes.length; index++) {
  411. var order = effect.getAttribute(index);
  412. if (order >= 0) {
  413. var vertexBuffer = vertexBuffers[attributes[index]];
  414. var stride = vertexBuffer.getStrideSize();
  415. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  416. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  417. }
  418. }
  419. }
  420. if (this._cachedIndexBuffer !== indexBuffer) {
  421. this._cachedIndexBuffer = indexBuffer;
  422. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  423. }
  424. }
  425. public _releaseBuffer(buffer: WebGLBuffer): void {
  426. buffer.references--;
  427. if (buffer.references === 0) {
  428. this._gl.deleteBuffer(buffer);
  429. }
  430. }
  431. public draw(useTriangles: boolean, indexStart: number, indexCount: number): void {
  432. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  433. var error = this._gl.getError();
  434. if (error) {
  435. console.log(error);
  436. }
  437. }
  438. // Shaders
  439. public _releaseEffect(effect: Effect): void {
  440. if (this._compiledEffects[effect._key]) {
  441. delete this._compiledEffects[effect._key];
  442. if (effect.getProgram()) {
  443. this._gl.deleteProgram(effect.getProgram());
  444. }
  445. }
  446. }
  447. public createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, optionalDefines?: string[],
  448. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  449. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  450. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  451. var name = vertex + "+" + fragment + "@" + defines;
  452. if (this._compiledEffects[name]) {
  453. return this._compiledEffects[name];
  454. }
  455. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, optionalDefines, onCompiled, onError);
  456. effect._key = name;
  457. this._compiledEffects[name] = effect;
  458. return effect;
  459. }
  460. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram {
  461. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  462. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  463. var shaderProgram = this._gl.createProgram();
  464. this._gl.attachShader(shaderProgram, vertexShader);
  465. this._gl.attachShader(shaderProgram, fragmentShader);
  466. var linked = this._gl.linkProgram(shaderProgram);
  467. if (!linked) {
  468. var error = this._gl.getProgramInfoLog(shaderProgram);
  469. if (error) {
  470. throw new Error(error);
  471. }
  472. }
  473. this._gl.deleteShader(vertexShader);
  474. this._gl.deleteShader(fragmentShader);
  475. return shaderProgram;
  476. }
  477. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  478. var results = [];
  479. for (var index = 0; index < uniformsNames.length; index++) {
  480. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  481. }
  482. return results;
  483. }
  484. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  485. var results = [];
  486. for (var index = 0; index < attributesNames.length; index++) {
  487. try {
  488. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  489. } catch (e) {
  490. results.push(-1);
  491. }
  492. }
  493. return results;
  494. }
  495. public enableEffect(effect: Effect): void {
  496. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  497. return;
  498. }
  499. // Use program
  500. this._gl.useProgram(effect.getProgram());
  501. var currentCount = effect.getAttributesCount();
  502. var maxIndex = 0;
  503. for (var index = 0; index < currentCount; index++) {
  504. // Attributes
  505. var order = effect.getAttribute(index);
  506. if (order >= 0) {
  507. this._gl.enableVertexAttribArray(effect.getAttribute(index));
  508. maxIndex = Math.max(maxIndex, order);
  509. }
  510. }
  511. for (index = maxIndex + 1; index <= this._lastVertexAttribIndex; index++) {
  512. this._gl.disableVertexAttribArray(index);
  513. }
  514. this._lastVertexAttribIndex = maxIndex;
  515. this._currentEffect = effect;
  516. }
  517. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  518. if (!uniform)
  519. return;
  520. this._gl.uniform1fv(uniform, array);
  521. }
  522. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  523. if (!uniform)
  524. return;
  525. this._gl.uniformMatrix4fv(uniform, false, matrices);
  526. }
  527. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  528. if (!uniform)
  529. return;
  530. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  531. }
  532. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  533. if (!uniform)
  534. return;
  535. this._gl.uniform1f(uniform, value);
  536. }
  537. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  538. if (!uniform)
  539. return;
  540. this._gl.uniform2f(uniform, x, y);
  541. }
  542. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  543. if (!uniform)
  544. return;
  545. this._gl.uniform3f(uniform, x, y, z);
  546. }
  547. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  548. if (!uniform)
  549. return;
  550. this._gl.uniform1i(uniform, bool);
  551. }
  552. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  553. if (!uniform)
  554. return;
  555. this._gl.uniform4f(uniform, x, y, z, w);
  556. }
  557. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  558. if (!uniform)
  559. return;
  560. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  561. }
  562. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  563. if (!uniform)
  564. return;
  565. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  566. }
  567. // States
  568. public setState(culling: boolean): void {
  569. // Culling
  570. if (this._cullingState !== culling) {
  571. if (culling) {
  572. this._gl.cullFace(this.cullBackFaces ? this._gl.BACK : this._gl.FRONT);
  573. this._gl.enable(this._gl.CULL_FACE);
  574. } else {
  575. this._gl.disable(this._gl.CULL_FACE);
  576. }
  577. this._cullingState = culling;
  578. }
  579. }
  580. public setDepthBuffer(enable: boolean): void {
  581. if (enable) {
  582. this._gl.enable(this._gl.DEPTH_TEST);
  583. } else {
  584. this._gl.disable(this._gl.DEPTH_TEST);
  585. }
  586. }
  587. public setDepthWrite(enable: boolean): void {
  588. this._gl.depthMask(enable);
  589. this._depthMask = enable;
  590. }
  591. public setColorWrite(enable: boolean): void {
  592. this._gl.colorMask(enable, enable, enable, enable);
  593. }
  594. public setAlphaMode(mode: number): void {
  595. switch (mode) {
  596. case BABYLON.Engine.ALPHA_DISABLE:
  597. this.setDepthWrite(true);
  598. this._gl.disable(this._gl.BLEND);
  599. break;
  600. case BABYLON.Engine.ALPHA_COMBINE:
  601. this.setDepthWrite(false);
  602. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  603. this._gl.enable(this._gl.BLEND);
  604. break;
  605. case BABYLON.Engine.ALPHA_ADD:
  606. this.setDepthWrite(false);
  607. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  608. this._gl.enable(this._gl.BLEND);
  609. break;
  610. }
  611. }
  612. public setAlphaTesting(enable: boolean): void {
  613. this._alphaTest = enable;
  614. }
  615. public getAlphaTesting(): boolean {
  616. return this._alphaTest;
  617. }
  618. // Textures
  619. public wipeCaches(): void {
  620. this._activeTexturesCache = [];
  621. this._currentEffect = null;
  622. this._cullingState = null;
  623. this._cachedVertexBuffers = null;
  624. this._cachedIndexBuffer = null;
  625. this._cachedEffectForVertexBuffers = null;
  626. }
  627. public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene): WebGLTexture {
  628. var texture = this._gl.createTexture();
  629. var isDDS = this.getCaps().s3tc && (url.substr(url.length - 4, 4).toLowerCase() === ".dds");
  630. scene._addPendingData(texture);
  631. texture.url = url;
  632. texture.noMipmap = noMipmap;
  633. texture.references = 1;
  634. this._loadedTexturesCache.push(texture);
  635. if (isDDS) {
  636. BABYLON.Tools.LoadFile(url, data => {
  637. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  638. var loadMipmap = info.mipmapCount > 1 && !noMipmap;
  639. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, () => {
  640. BABYLON.Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, loadMipmap);
  641. });
  642. }, null, scene.database, true);
  643. } else {
  644. var onload = (img) => {
  645. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, (potWidth, potHeight) => {
  646. var isPot = (img.width == potWidth && img.height == potHeight);
  647. if (!isPot) {
  648. this._workingCanvas.width = potWidth;
  649. this._workingCanvas.height = potHeight;
  650. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  651. }
  652. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  653. });
  654. };
  655. var onerror = () => {
  656. scene._removePendingData(texture);
  657. };
  658. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  659. }
  660. return texture;
  661. }
  662. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean): WebGLTexture {
  663. var texture = this._gl.createTexture();
  664. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  665. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  666. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  667. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
  668. if (!generateMipMaps) {
  669. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
  670. } else {
  671. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR_MIPMAP_LINEAR);
  672. }
  673. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  674. this._activeTexturesCache = [];
  675. texture._baseWidth = width;
  676. texture._baseHeight = height;
  677. texture._width = width;
  678. texture._height = height;
  679. texture.isReady = false;
  680. texture.generateMipMaps = generateMipMaps;
  681. texture.references = 1;
  682. this._loadedTexturesCache.push(texture);
  683. return texture;
  684. }
  685. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  686. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  687. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  688. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  689. if (texture.generateMipMaps) {
  690. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  691. }
  692. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  693. this._activeTexturesCache = [];
  694. texture.isReady = true;
  695. }
  696. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  697. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  698. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  699. // Scale the video if it is a NPOT using the current working canvas
  700. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  701. if (!texture._workingCanvas) {
  702. texture._workingCanvas = document.createElement("canvas");
  703. texture._workingContext = texture._workingCanvas.getContext("2d");
  704. texture._workingCanvas.width = texture._width;
  705. texture._workingCanvas.height = texture._height;
  706. }
  707. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  708. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  709. } else {
  710. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  711. }
  712. if (texture.generateMipMaps) {
  713. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  714. }
  715. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  716. this._activeTexturesCache = [];
  717. texture.isReady = true;
  718. }
  719. public createRenderTargetTexture(size: any, options): WebGLTexture {
  720. // old version had a "generateMipMaps" arg instead of options.
  721. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  722. // in the same way, generateDepthBuffer is defaulted to true
  723. var generateMipMaps = false;
  724. var generateDepthBuffer = true;
  725. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  726. if (options !== undefined) {
  727. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  728. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  729. if (options.samplingMode !== undefined) {
  730. samplingMode = options.samplingMode;
  731. }
  732. }
  733. var gl = this._gl;
  734. var texture = gl.createTexture();
  735. gl.bindTexture(gl.TEXTURE_2D, texture);
  736. var width = size.width || size;
  737. var height = size.height || size;
  738. var magFilter = gl.NEAREST;
  739. var minFilter = gl.NEAREST;
  740. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  741. magFilter = gl.LINEAR;
  742. if (generateMipMaps) {
  743. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  744. } else {
  745. minFilter = gl.LINEAR;
  746. }
  747. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  748. magFilter = gl.LINEAR;
  749. if (generateMipMaps) {
  750. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  751. } else {
  752. minFilter = gl.LINEAR;
  753. }
  754. }
  755. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  756. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  757. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  758. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  759. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  760. var depthBuffer: WebGLRenderbuffer;
  761. // Create the depth buffer
  762. if (generateDepthBuffer) {
  763. depthBuffer = gl.createRenderbuffer();
  764. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  765. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  766. }
  767. // Create the framebuffer
  768. var framebuffer = gl.createFramebuffer();
  769. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  770. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  771. if (generateDepthBuffer) {
  772. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  773. }
  774. // Unbind
  775. gl.bindTexture(gl.TEXTURE_2D, null);
  776. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  777. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  778. texture._framebuffer = framebuffer;
  779. if (generateDepthBuffer) {
  780. texture._depthBuffer = depthBuffer;
  781. }
  782. texture._width = width;
  783. texture._height = height;
  784. texture.isReady = true;
  785. texture.generateMipMaps = generateMipMaps;
  786. texture.references = 1;
  787. this._activeTexturesCache = [];
  788. this._loadedTexturesCache.push(texture);
  789. return texture;
  790. }
  791. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  792. var gl = this._gl;
  793. var texture = gl.createTexture();
  794. texture.isCube = true;
  795. texture.url = rootUrl;
  796. texture.references = 1;
  797. this._loadedTexturesCache.push(texture);
  798. cascadeLoad(rootUrl, 0, [], scene, imgs => {
  799. var width = getExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  800. var height = width;
  801. this._workingCanvas.width = width;
  802. this._workingCanvas.height = height;
  803. var faces = [
  804. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  805. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  806. ];
  807. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  808. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  809. for (var index = 0; index < faces.length; index++) {
  810. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  811. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  812. }
  813. if (!noMipmap) {
  814. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  815. }
  816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  820. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  821. this._activeTexturesCache = [];
  822. texture._width = width;
  823. texture._height = height;
  824. texture.isReady = true;
  825. }, extensions);
  826. return texture;
  827. }
  828. public _releaseTexture(texture: WebGLTexture): void {
  829. var gl = this._gl;
  830. if (texture._framebuffer) {
  831. gl.deleteFramebuffer(texture._framebuffer);
  832. }
  833. if (texture._depthBuffer) {
  834. gl.deleteRenderbuffer(texture._depthBuffer);
  835. }
  836. gl.deleteTexture(texture);
  837. // Unbind channels
  838. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  839. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  840. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  841. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  842. this._activeTexturesCache[channel] = null;
  843. }
  844. var index = this._loadedTexturesCache.indexOf(texture);
  845. if (index !== -1) {
  846. this._loadedTexturesCache.splice(index, 1);
  847. }
  848. }
  849. public bindSamplers(effect: Effect): void {
  850. this._gl.useProgram(effect.getProgram());
  851. var samplers = effect.getSamplers();
  852. for (var index = 0; index < samplers.length; index++) {
  853. var uniform = effect.getUniform(samplers[index]);
  854. this._gl.uniform1i(uniform, index);
  855. }
  856. this._currentEffect = null;
  857. }
  858. public _bindTexture(channel: number, texture: WebGLTexture): void {
  859. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  860. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  861. this._activeTexturesCache[channel] = null;
  862. }
  863. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  864. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  865. }
  866. public setTexture(channel: number, texture: Texture): void {
  867. if (channel < 0) {
  868. return;
  869. }
  870. // Not ready?
  871. if (!texture || !texture.isReady()) {
  872. if (this._activeTexturesCache[channel] != null) {
  873. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  874. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  875. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  876. this._activeTexturesCache[channel] = null;
  877. }
  878. return;
  879. }
  880. // Video
  881. if (texture instanceof BABYLON.VideoTexture) {
  882. if ((<VideoTexture>texture).update()) {
  883. this._activeTexturesCache[channel] = null;
  884. }
  885. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  886. texture.delayLoad();
  887. return;
  888. }
  889. if (this._activeTexturesCache[channel] == texture) {
  890. return;
  891. }
  892. this._activeTexturesCache[channel] = texture;
  893. var internalTexture = texture.getInternalTexture();
  894. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  895. if (internalTexture.isCube) {
  896. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  897. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  898. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  899. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  900. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  901. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  902. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  903. }
  904. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  905. } else {
  906. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  907. if (internalTexture._cachedWrapU !== texture.wrapU) {
  908. internalTexture._cachedWrapU = texture.wrapU;
  909. switch (texture.wrapU) {
  910. case BABYLON.Texture.WRAP_ADDRESSMODE:
  911. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  912. break;
  913. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  914. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  915. break;
  916. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  917. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  918. break;
  919. }
  920. }
  921. if (internalTexture._cachedWrapV !== texture.wrapV) {
  922. internalTexture._cachedWrapV = texture.wrapV;
  923. switch (texture.wrapV) {
  924. case BABYLON.Texture.WRAP_ADDRESSMODE:
  925. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  926. break;
  927. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  928. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  929. break;
  930. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  931. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  932. break;
  933. }
  934. }
  935. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  936. }
  937. }
  938. public _setAnisotropicLevel(key: number, texture: Texture) {
  939. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  940. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  941. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  942. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  943. }
  944. }
  945. // Dispose
  946. public dispose(): void {
  947. // Release scenes
  948. while (this.scenes.length) {
  949. this.scenes[0].dispose();
  950. }
  951. // Release effects
  952. for (var name in this._compiledEffects) {
  953. this._gl.deleteProgram(this._compiledEffects[name]._program);
  954. }
  955. // Events
  956. window.removeEventListener("blur", this._onBlur);
  957. window.removeEventListener("focus", this._onFocus);
  958. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  959. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  960. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  961. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  962. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  963. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  964. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  965. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  966. }
  967. // Statics
  968. public static isSupported(): boolean {
  969. try {
  970. var tempcanvas = document.createElement("canvas");
  971. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  972. return gl != null && !!window.WebGLRenderingContext;
  973. } catch (e) {
  974. return false;
  975. }
  976. }
  977. }
  978. }