babylon.engine.ts 64 KB

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