babylon.engine.ts 55 KB

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