babylon.engine.ts 56 KB

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