babylon.engine.ts 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  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 _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): void {
  676. // Culling
  677. if (this._cullingState !== culling) {
  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 setDepthWrite(enable: boolean): void {
  695. this._gl.depthMask(enable);
  696. this._depthMask = enable;
  697. }
  698. public setColorWrite(enable: boolean): void {
  699. this._gl.colorMask(enable, enable, enable, enable);
  700. }
  701. public setAlphaMode(mode: number): void {
  702. switch (mode) {
  703. case BABYLON.Engine.ALPHA_DISABLE:
  704. this.setDepthWrite(true);
  705. this._gl.disable(this._gl.BLEND);
  706. break;
  707. case BABYLON.Engine.ALPHA_COMBINE:
  708. this.setDepthWrite(false);
  709. this._gl.blendFuncSeparate(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  710. this._gl.enable(this._gl.BLEND);
  711. break;
  712. case BABYLON.Engine.ALPHA_ADD:
  713. this.setDepthWrite(false);
  714. this._gl.blendFuncSeparate(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  715. this._gl.enable(this._gl.BLEND);
  716. break;
  717. }
  718. }
  719. public setAlphaTesting(enable: boolean): void {
  720. this._alphaTest = enable;
  721. }
  722. public getAlphaTesting(): boolean {
  723. return this._alphaTest;
  724. }
  725. // Textures
  726. public wipeCaches(): void {
  727. this._activeTexturesCache = [];
  728. this._currentEffect = null;
  729. this._cullingState = null;
  730. this._cachedVertexBuffers = null;
  731. this._cachedIndexBuffer = null;
  732. this._cachedEffectForVertexBuffers = null;
  733. }
  734. public setSamplingMode(texture: WebGLTexture, samplingMode: number): void {
  735. var gl = this._gl;
  736. gl.bindTexture(gl.TEXTURE_2D, texture);
  737. var magFilter = gl.NEAREST;
  738. var minFilter = gl.NEAREST;
  739. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  740. magFilter = gl.LINEAR;
  741. minFilter = gl.LINEAR;
  742. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  743. magFilter = gl.LINEAR;
  744. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  745. }
  746. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  747. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  748. gl.bindTexture(gl.TEXTURE_2D, null);
  749. }
  750. public createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): WebGLTexture {
  751. var texture = this._gl.createTexture();
  752. var extension = url.substr(url.length - 4, 4).toLowerCase();
  753. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  754. var isTGA = (extension === ".tga");
  755. scene._addPendingData(texture);
  756. texture.url = url;
  757. texture.noMipmap = noMipmap;
  758. texture.references = 1;
  759. this._loadedTexturesCache.push(texture);
  760. if (isTGA) {
  761. BABYLON.Tools.LoadFile(url, arrayBuffer => {
  762. var data = new Uint8Array(arrayBuffer);
  763. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  764. prepareWebGLTexture(texture, this._gl, scene, header.width, header.height, invertY, noMipmap, false, () => {
  765. Internals.TGATools.UploadContent(this._gl, data);
  766. }, samplingMode);
  767. }, null, scene.database, true);
  768. } else if (isDDS) {
  769. BABYLON.Tools.LoadFile(url, data => {
  770. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  771. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount -1)) == 1);
  772. prepareWebGLTexture(texture, this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  773. console.log("loading " + url);
  774. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 1);
  775. }, samplingMode);
  776. }, null, scene.database, true);
  777. } else {
  778. var onload = (img) => {
  779. prepareWebGLTexture(texture, this._gl, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight) => {
  780. var isPot = (img.width == potWidth && img.height == potHeight);
  781. if (!isPot) {
  782. this._workingCanvas.width = potWidth;
  783. this._workingCanvas.height = potHeight;
  784. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  785. }
  786. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, isPot ? img : this._workingCanvas);
  787. }, samplingMode);
  788. };
  789. var onerror = () => {
  790. scene._removePendingData(texture);
  791. };
  792. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  793. }
  794. return texture;
  795. }
  796. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  797. var texture = this._gl.createTexture();
  798. width = getExponantOfTwo(width, this._caps.maxTextureSize);
  799. height = getExponantOfTwo(height, this._caps.maxTextureSize);
  800. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  801. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  802. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  803. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  804. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  805. this._activeTexturesCache = [];
  806. texture._baseWidth = width;
  807. texture._baseHeight = height;
  808. texture._width = width;
  809. texture._height = height;
  810. texture.isReady = false;
  811. texture.generateMipMaps = generateMipMaps;
  812. texture.references = 1;
  813. this._loadedTexturesCache.push(texture);
  814. return texture;
  815. }
  816. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void {
  817. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  818. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  819. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  820. if (texture.generateMipMaps) {
  821. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  822. }
  823. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  824. this._activeTexturesCache = [];
  825. texture.isReady = true;
  826. }
  827. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  828. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  829. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  830. // Scale the video if it is a NPOT using the current working canvas
  831. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  832. if (!texture._workingCanvas) {
  833. texture._workingCanvas = document.createElement("canvas");
  834. texture._workingContext = texture._workingCanvas.getContext("2d");
  835. texture._workingCanvas.width = texture._width;
  836. texture._workingCanvas.height = texture._height;
  837. }
  838. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  839. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  840. } else {
  841. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  842. }
  843. if (texture.generateMipMaps) {
  844. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  845. }
  846. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  847. this._activeTexturesCache = [];
  848. texture.isReady = true;
  849. }
  850. public createRenderTargetTexture(size: any, options): WebGLTexture {
  851. // old version had a "generateMipMaps" arg instead of options.
  852. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  853. // in the same way, generateDepthBuffer is defaulted to true
  854. var generateMipMaps = false;
  855. var generateDepthBuffer = true;
  856. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  857. if (options !== undefined) {
  858. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  859. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  860. if (options.samplingMode !== undefined) {
  861. samplingMode = options.samplingMode;
  862. }
  863. }
  864. var gl = this._gl;
  865. var texture = gl.createTexture();
  866. gl.bindTexture(gl.TEXTURE_2D, texture);
  867. var width = size.width || size;
  868. var height = size.height || size;
  869. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  872. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  874. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  875. var depthBuffer: WebGLRenderbuffer;
  876. // Create the depth buffer
  877. if (generateDepthBuffer) {
  878. depthBuffer = gl.createRenderbuffer();
  879. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  880. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  881. }
  882. // Create the framebuffer
  883. var framebuffer = gl.createFramebuffer();
  884. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  885. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  886. if (generateDepthBuffer) {
  887. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  888. }
  889. // Unbind
  890. gl.bindTexture(gl.TEXTURE_2D, null);
  891. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  892. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  893. texture._framebuffer = framebuffer;
  894. if (generateDepthBuffer) {
  895. texture._depthBuffer = depthBuffer;
  896. }
  897. texture._width = width;
  898. texture._height = height;
  899. texture.isReady = true;
  900. texture.generateMipMaps = generateMipMaps;
  901. texture.references = 1;
  902. this._activeTexturesCache = [];
  903. this._loadedTexturesCache.push(texture);
  904. return texture;
  905. }
  906. public createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture {
  907. var gl = this._gl;
  908. var texture = gl.createTexture();
  909. texture.isCube = true;
  910. texture.url = rootUrl;
  911. texture.references = 1;
  912. this._loadedTexturesCache.push(texture);
  913. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  914. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  915. if (isDDS) {
  916. BABYLON.Tools.LoadFile(rootUrl, data => {
  917. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  918. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  919. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  920. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  921. Internals.DDSTools.UploadDDSLevels(this._gl, this.getCaps().s3tc, data, info, loadMipmap, 6);
  922. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  923. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  924. }
  925. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  926. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  929. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  930. this._activeTexturesCache = [];
  931. texture._width = info.width;
  932. texture._height = info.height;
  933. texture.isReady = true;
  934. });
  935. } else {
  936. cascadeLoad(rootUrl, 0, [], scene, imgs => {
  937. var width = getExponantOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize);
  938. var height = width;
  939. this._workingCanvas.width = width;
  940. this._workingCanvas.height = height;
  941. var faces = [
  942. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  943. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  944. ];
  945. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  946. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  947. for (var index = 0; index < faces.length; index++) {
  948. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  949. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._workingCanvas);
  950. }
  951. if (!noMipmap) {
  952. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  953. }
  954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  957. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  958. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  959. this._activeTexturesCache = [];
  960. texture._width = width;
  961. texture._height = height;
  962. texture.isReady = true;
  963. }, extensions);
  964. }
  965. return texture;
  966. }
  967. public _releaseTexture(texture: WebGLTexture): void {
  968. var gl = this._gl;
  969. if (texture._framebuffer) {
  970. gl.deleteFramebuffer(texture._framebuffer);
  971. }
  972. if (texture._depthBuffer) {
  973. gl.deleteRenderbuffer(texture._depthBuffer);
  974. }
  975. gl.deleteTexture(texture);
  976. // Unbind channels
  977. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  978. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  979. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  980. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  981. this._activeTexturesCache[channel] = null;
  982. }
  983. var index = this._loadedTexturesCache.indexOf(texture);
  984. if (index !== -1) {
  985. this._loadedTexturesCache.splice(index, 1);
  986. }
  987. }
  988. public bindSamplers(effect: Effect): void {
  989. this._gl.useProgram(effect.getProgram());
  990. var samplers = effect.getSamplers();
  991. for (var index = 0; index < samplers.length; index++) {
  992. var uniform = effect.getUniform(samplers[index]);
  993. this._gl.uniform1i(uniform, index);
  994. }
  995. this._currentEffect = null;
  996. }
  997. public _bindTexture(channel: number, texture: WebGLTexture): void {
  998. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  999. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  1000. this._activeTexturesCache[channel] = null;
  1001. }
  1002. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  1003. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  1004. }
  1005. public setTexture(channel: number, texture: BaseTexture): void {
  1006. if (channel < 0) {
  1007. return;
  1008. }
  1009. // Not ready?
  1010. if (!texture || !texture.isReady()) {
  1011. if (this._activeTexturesCache[channel] != null) {
  1012. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1013. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  1014. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  1015. this._activeTexturesCache[channel] = null;
  1016. }
  1017. return;
  1018. }
  1019. // Video
  1020. if (texture instanceof BABYLON.VideoTexture) {
  1021. if ((<VideoTexture>texture).update()) {
  1022. this._activeTexturesCache[channel] = null;
  1023. }
  1024. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1025. texture.delayLoad();
  1026. return;
  1027. }
  1028. if (this._activeTexturesCache[channel] == texture) {
  1029. return;
  1030. }
  1031. this._activeTexturesCache[channel] = texture;
  1032. var internalTexture = texture.getInternalTexture();
  1033. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  1034. if (internalTexture.isCube) {
  1035. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  1036. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1037. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1038. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1039. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  1040. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  1041. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  1042. }
  1043. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  1044. } else {
  1045. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  1046. if (internalTexture._cachedWrapU !== texture.wrapU) {
  1047. internalTexture._cachedWrapU = texture.wrapU;
  1048. switch (texture.wrapU) {
  1049. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1050. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  1051. break;
  1052. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1053. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  1054. break;
  1055. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1056. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  1057. break;
  1058. }
  1059. }
  1060. if (internalTexture._cachedWrapV !== texture.wrapV) {
  1061. internalTexture._cachedWrapV = texture.wrapV;
  1062. switch (texture.wrapV) {
  1063. case BABYLON.Texture.WRAP_ADDRESSMODE:
  1064. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  1065. break;
  1066. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  1067. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  1068. break;
  1069. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  1070. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  1071. break;
  1072. }
  1073. }
  1074. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  1075. }
  1076. }
  1077. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  1078. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  1079. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  1080. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  1081. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  1082. }
  1083. }
  1084. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  1085. var data = new Uint8Array(height * width * 4);
  1086. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  1087. return data;
  1088. }
  1089. // Dispose
  1090. public dispose(): void {
  1091. this.stopRenderLoop();
  1092. // Release scenes
  1093. while (this.scenes.length) {
  1094. this.scenes[0].dispose();
  1095. }
  1096. // Release effects
  1097. for (var name in this._compiledEffects) {
  1098. this._gl.deleteProgram(this._compiledEffects[name]._program);
  1099. }
  1100. // Unbind
  1101. for (var i in this._vertexAttribArrays) {
  1102. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  1103. continue;
  1104. }
  1105. this._gl.disableVertexAttribArray(i);
  1106. }
  1107. // Events
  1108. window.removeEventListener("blur", this._onBlur);
  1109. window.removeEventListener("focus", this._onFocus);
  1110. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1111. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1112. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1113. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1114. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  1115. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  1116. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  1117. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  1118. }
  1119. // Statics
  1120. public static isSupported(): boolean {
  1121. try {
  1122. var tempcanvas = document.createElement("canvas");
  1123. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  1124. return gl != null && !!window.WebGLRenderingContext;
  1125. } catch (e) {
  1126. return false;
  1127. }
  1128. }
  1129. }
  1130. }