babylon.engine.ts 48 KB

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