babylon.engine.ts 55 KB

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