babylon.engine.ts 49 KB

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